package provider import ( "bufio" "bytes" "context" "encoding/json" "fmt" "log" "net/url" "os" "strings" "example.com/ueino/internal/opt" "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 原样发送上层组装的消息,通过通道返回文本片段。 // 流开始后的错误记录日志并关闭通道。 // 调用方应持续读取通道,提前停止时取消 ctx。 func (c *_chat) ChatCompletion(ctx context.Context, messages []model.ChatMessage) (<-chan string, error) { if len(messages) == 0 { return nil, fmt.Errorf("至少需要一条消息") } body := model.ChatCompletionRequest{Model: c.opt.modelName, Messages: messages, Stream: true} 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 } if !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") { resp.Body.Close() return nil, fmt.Errorf("模型接口未返回流式响应") } out := make(chan string, opt.RESPONSE_CHAN_SIZE) go func() { defer close(out) defer resp.Body.Close() scanner := bufio.NewScanner(resp.Body) scanner.Buffer(make([]byte, 4096), 1024*1024) for scanner.Scan() { data, ok := bytes.CutPrefix(scanner.Bytes(), []byte("data:")) if !ok { continue } data = bytes.TrimSpace(data) if bytes.Equal(data, []byte("[DONE]")) { return } var chunk model.ChatCompletionResponse if err := json.Unmarshal(data, &chunk); err != nil { log.Printf("解析模型流式响应失败: %v", err) return } if len(chunk.Choices) == 0 || chunk.Choices[0].Delta.Content == "" { continue } select { case out <- chunk.Choices[0].Delta.Content: case <-ctx.Done(): return } } if ctx.Err() == nil { log.Printf("模型响应流未正常结束: %v", scanner.Err()) } }() return out, nil }