diff --git a/workers/ai.go b/workers/ai.go index 994a10f..e998a58 100644 --- a/workers/ai.go +++ b/workers/ai.go @@ -4,6 +4,7 @@ import ( "fmt" "log" "strings" + "time" "github.com/goccy/go-json" "github.com/parnurzeal/gorequest" @@ -62,8 +63,8 @@ func getConfig() (string, string, string) { if cfg["MODEL"] != nil { MODEL = cfg["MODEL"].(string) } else { - log.Println("模型 未配置,使用默认chatglm_pro模型") - MODEL = "chatglm_pro" + log.Println("模型 未配置,使用默认 gpt-4o 模型") + MODEL = "gpt-4o" } return OPENAI_API_KEY, OPENAI_BaseURL, MODEL @@ -125,36 +126,45 @@ func handleChatRequest(OPENAI_API_KEY, OPENAI_BaseURL, MODEL, rawMsg, UID string }, {"role": "user", "content": rawMsg[strings.Index(rawMsg, " ")+1:]}, }, - "temperature": 0.7, + "temperature": 0.7, + "presence_penalty": 0, + "frequency_penalty": 0, + "top_p": 1, } - request := gorequest.New() - resp, body, errs := request.Post(OPENAI_BaseURL). - Set("Content-Type", "application/json"). - Set("Authorization", "Bearer "+OPENAI_API_KEY). - Send(requestBody). - End() + const maxRetry = 2 + for retries := 0; retries <= maxRetry; retries++ { + request := gorequest.New() + resp, body, errs := request.Post(OPENAI_BaseURL). + Set("Content-Type", "application/json"). + Set("Authorization", "Bearer "+OPENAI_API_KEY). + Send(requestBody). + End() - if errs != nil { - log.Println(errs) - return "请求失败" - } - println(resp.StatusCode) - if resp.StatusCode == 200 { - var responseBody map[string]interface{} - if err := json.Unmarshal([]byte(body), &responseBody); err != nil { - log.Println(err) - return "解析失败" + if errs != nil { + log.Println(errs) + return "请求失败" } - choices := responseBody["choices"].([]interface{}) - if len(choices) > 0 { - choice := choices[0].(map[string]interface{}) - msg := choice["message"].(map[string]interface{})["content"].(string) - return fmt.Sprintf("[CQ:at,qq=%s] %s", UID, msg) + println(resp.StatusCode) + if resp.StatusCode == 200 { + var responseBody map[string]interface{} + if err := json.Unmarshal([]byte(body), &responseBody); err != nil { + log.Println(err) + return "解析失败" + } + choices := responseBody["choices"].([]interface{}) + if len(choices) > 0 { + choice := choices[0].(map[string]interface{}) + msg := choice["message"].(map[string]interface{})["content"].(string) + return fmt.Sprintf("[CQ:at,qq=%s] %s", UID, msg) + } else { + log.Println("choices为空") + return "api解析失败" + } } else { - log.Println("choices为空") - return "api解析失败" + log.Printf("请求失败,状态码:%d,重试中...(%d/%d)\n", resp.StatusCode, retries+1, maxRetry) + time.Sleep(time.Second * 1) + // return "请求失败: " + fmt.Sprintf("%d", resp.StatusCode) } - } else { - return "请求失败: " + string(resp.StatusCode) } + return "请求失败!" }