Skip to content

Commit

Permalink
改进 ChatGPT 服务初始化和认证机制
Browse files Browse the repository at this point in the history
- 在 ChatService 初始化时增加环境变量配置检查,提醒配置 OPENAI_API_URL 和 OPENAI_API_KEY
- 改进 getChatGPTAuth 函数,增加返回值 enable 表示服务是否可用
- 在使用 ChatGPT 接口前检查服务是否启用,避免不必要的调用
-优化代码结构,提高可读性和可维护性
  • Loading branch information
weibaohui committed Oct 16, 2024
1 parent d1a0c4f commit 1e76ad4
Showing 1 changed file with 18 additions and 9 deletions.
27 changes: 18 additions & 9 deletions pkg/service/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ import (

// Init 设置一个自检提示
func init() {
getChatGPTAuth()
apiKey, apiURL, _ := getChatGPTAuth()
if apiKey == "" || apiURL == "" {
// 前端不显示,后端提示
log.Println("ChatService:请配置环境变量,设置OPENAI_API_URL、OPENAI_API_KEY")
return
}
}

var model = "Qwen/Qwen2.5-Coder-7B-Instruct"
Expand All @@ -23,7 +28,11 @@ type ChatService struct {
}

func (c *ChatService) GetChatStream(chat string) (*http.Response, error) {
key, apiURL := getChatGPTAuth()
key, apiURL, enable := getChatGPTAuth()
if !enable {
return nil, fmt.Errorf("chatGPT not enable")
}

// url := "https://api.siliconflow.cn/v1/chat/completions"
url := fmt.Sprintf("%s/chat/completions", apiURL)

Expand Down Expand Up @@ -67,8 +76,10 @@ func (c *ChatService) GetChatStream(chat string) (*http.Response, error) {
return resp, err
}
func (c *ChatService) Chat(chat string) string {
apiKey, apiURL := getChatGPTAuth()

apiKey, apiURL, enable := getChatGPTAuth()
if !enable {
return ""
}
// 初始化OpenAI客户端
cfg := openai.DefaultConfig(apiKey)
cfg.BaseURL = apiURL
Expand Down Expand Up @@ -96,14 +107,12 @@ func (c *ChatService) Chat(chat string) string {
return result
}

func getChatGPTAuth() (apiKey string, apiURL string) {
func getChatGPTAuth() (apiKey string, apiURL string, enable bool) {
// 从环境变量读取OpenAI API Key和API URL
apiKey = os.Getenv("OPENAI_API_KEY")
apiURL = os.Getenv("OPENAI_API_URL")
if apiKey == "" || apiURL == "" {
// 前端不显示,后端提示
log.Println("ChatService:请配置环境变量,设置OPENAI_API_URL、OPENAI_API_KEY")
return
if apiKey != "" && apiURL != "" {
enable = true
}
return
}

0 comments on commit 1e76ad4

Please sign in to comment.