package provider import ( "context" "fmt" "net/url" "os" "strings" "example.com/ueino/pkg/model" ) type option struct { baseURL string modelName string apiKey string } type ChatOption func(*option) func ChatBaseURL(baseURL string) ChatOption { return func(o *option) { if _, err := url.Parse(baseURL); err == nil { o.baseURL = strings.TrimRight(baseURL, "/") } } } func ChatModel(modelName string) ChatOption { return func(o *option) { if modelName != "" { o.modelName = modelName } } } func ChatApiKey(apiKey string) ChatOption { return func(o *option) { o.apiKey = apiKey } } func ChatApiKeyByEnv(env string) ChatOption { return func(o *option) { if val := os.Getenv(env); val != "" { o.apiKey = val } } } type _chat struct { opt *option } func NewChat(options ...ChatOption) *_chat { o := &option{ modelName: "gpt-4o", baseURL: "https://api.openai.com/v1", apiKey: "", } for _, fn := range options { fn(o) } return &_chat{ opt: o, } } // ChatCompletion 通过回调输出文字,完整接收后返回助手消息;失败时直接返回错误。 func (c *_chat) ChatCompletion(ctx context.Context, messages []model.ChatMessage, tools []model.ToolDefinition, onText func(string)) (*model.ChatMessage, error) { if len(messages) == 0 { return nil, fmt.Errorf("至少需要一条消息") } body := model.ChatCompletionRequest{Model: c.opt.modelName, Messages: messages, Stream: true, Tools: tools} headers := map[string]string{"Accept": "text/event-stream"} if c.opt.apiKey != "" { headers["Authorization"] = "Bearer " + c.opt.apiKey } endpoint := c.opt.baseURL + "/chat/completions" resp, err := PostJSONResponse(ctx, endpoint, headers, body) if err != nil { return nil, err } defer resp.Body.Close() if !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") { return nil, fmt.Errorf("模型接口未返回流式响应") } return readStream(ctx, resp.Body, onText) }