package ai import ( "bufio" "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "sort" "strings" "time" ) // Provider speaks the OpenAI Chat Completions protocol. It always asks the // upstream for a stream and also tolerates providers that ignore `stream` and // answer with a single JSON document. type Provider struct { client *http.Client } func newProvider() *Provider { return &Provider{client: &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, ResponseHeaderTimeout: 30 * time.Second, IdleConnTimeout: 90 * time.Second, }, }} } type chatPayload struct { Model string `json:"model"` Messages []ChatMessage `json:"messages"` Tools []ToolDef `json:"tools,omitempty"` Temperature float64 `json:"temperature"` Stream bool `json:"stream"` MaxTokens int `json:"max_tokens,omitempty"` } type streamChunk struct { Choices []struct { Delta struct { Content string `json:"content"` ToolCalls []struct { Index int `json:"index"` ID string `json:"id"` Type string `json:"type"` Function struct { Name string `json:"name"` Arguments string `json:"arguments"` } `json:"function"` } `json:"tool_calls"` } `json:"delta"` FinishReason string `json:"finish_reason"` } `json:"choices"` Usage *Usage `json:"usage"` } type apiMessage struct { Content string `json:"content"` ToolCalls []ToolCall `json:"tool_calls"` } type apiResponse struct { Choices []struct { Message apiMessage `json:"message"` FinishReason string `json:"finish_reason"` } `json:"choices"` Usage *Usage `json:"usage"` Error *struct { Message string `json:"message"` } `json:"error"` } // Chat performs one completion. onDelta receives incremental text. func (p *Provider) Chat(ctx context.Context, st Settings, req ChatRequest, onDelta func(string)) (*ChatResult, error) { if strings.TrimSpace(st.APIKey) == "" { return nil, errors.New("尚未配置 AI API Key") } if strings.TrimSpace(req.Model) == "" { return nil, errors.New("尚未配置模型") } payload := chatPayload{ Model: req.Model, Messages: req.Messages, Tools: req.Tools, Temperature: req.Temperature, Stream: true, MaxTokens: req.MaxTokens, } body, err := json.Marshal(payload) if err != nil { return nil, err } endpoint := chatEndpoint(st.BaseURL) var lastErr error emitted := false wrap := func(delta string) { if delta == "" { return } emitted = true if onDelta != nil { onDelta(delta) } } // One retry is enough for transient connection failures; once tokens have // reached the client a retry would duplicate output. for attempt := 0; attempt < 2; attempt++ { res, err := p.once(ctx, endpoint, st.APIKey, body, wrap) if err == nil { return res, nil } lastErr = err if emitted || ctx.Err() != nil { return nil, err } } return nil, lastErr } func chatEndpoint(base string) string { b := strings.TrimRight(strings.TrimSpace(base), "/") if strings.Contains(b, "/chat/completions") { return b } return b + "/chat/completions" } func (p *Provider) once(ctx context.Context, endpoint, apiKey string, body []byte, onDelta func(string)) (*ChatResult, error) { httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) if err != nil { return nil, err } httpReq.Header.Set("Content-Type", "application/json") httpReq.Header.Set("Accept", "text/event-stream") httpReq.Header.Set("Authorization", "Bearer "+apiKey) httpReq.Header.Set("User-Agent", "MiaoPanel-AI") resp, err := p.client.Do(httpReq) if err != nil { return nil, fmt.Errorf("连接 AI 服务失败: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { msg := readErrorBody(resp.Body) if msg == "" { msg = fmt.Sprintf("AI 服务返回 HTTP %d", resp.StatusCode) } return nil, errors.New(msg) } if strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") { return readStream(resp.Body, onDelta) } return readJSON(resp.Body, onDelta) } func readErrorBody(body io.Reader) string { raw, _ := io.ReadAll(io.LimitReader(body, 4096)) var env struct { Error *struct { Message string `json:"message"` } `json:"error"` Message string `json:"message"` } if err := json.Unmarshal(raw, &env); err == nil { if env.Error != nil && env.Error.Message != "" { return env.Error.Message } if env.Message != "" { return env.Message } } text := strings.TrimSpace(string(raw)) if len(text) > 300 { text = text[:300] } return text } func readJSON(body io.Reader, onDelta func(string)) (*ChatResult, error) { var res apiResponse if err := json.NewDecoder(io.LimitReader(body, 8<<20)).Decode(&res); err != nil { return nil, fmt.Errorf("解析 AI 响应失败: %w", err) } if res.Error != nil && res.Error.Message != "" { return nil, errors.New(res.Error.Message) } if len(res.Choices) == 0 { return nil, errors.New("AI 服务没有返回任何结果") } choice := res.Choices[0] if choice.Message.Content != "" && onDelta != nil { onDelta(choice.Message.Content) } return &ChatResult{ Message: ChatMessage{ Role: "assistant", Content: choice.Message.Content, ToolCalls: choice.Message.ToolCalls, }, FinishReason: choice.FinishReason, Usage: res.Usage, }, nil } func readStream(body io.Reader, onDelta func(string)) (*ChatResult, error) { scanner := bufio.NewScanner(body) scanner.Buffer(make([]byte, 64<<10), 4<<20) var content strings.Builder finish := "" var usage *Usage calls := map[int]*ToolCall{} var order []int for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) if !strings.HasPrefix(line, "data:") { continue } data := strings.TrimSpace(strings.TrimPrefix(line, "data:")) if data == "" || data == "[DONE]" { if data == "[DONE]" { break } continue } var chunk streamChunk if err := json.Unmarshal([]byte(data), &chunk); err != nil { // Some providers send keepalive comments or vendor events. continue } if chunk.Usage != nil { usage = chunk.Usage } if len(chunk.Choices) == 0 { continue } choice := chunk.Choices[0] if choice.Delta.Content != "" { content.WriteString(choice.Delta.Content) if onDelta != nil { onDelta(choice.Delta.Content) } } for _, d := range choice.Delta.ToolCalls { cur, ok := calls[d.Index] if !ok { cur = &ToolCall{Type: "function"} calls[d.Index] = cur order = append(order, d.Index) } if d.ID != "" { cur.ID = d.ID } if d.Type != "" { cur.Type = d.Type } cur.Function.Name += d.Function.Name cur.Function.Arguments += d.Function.Arguments } if choice.FinishReason != "" { finish = choice.FinishReason } } if err := scanner.Err(); err != nil { return nil, fmt.Errorf("读取 AI 流失败: %w", err) } toolCalls := make([]ToolCall, 0, len(calls)) sort.Ints(order) for _, idx := range order { tc := calls[idx] if tc.ID == "" { continue } toolCalls = append(toolCalls, *tc) } return &ChatResult{ Message: ChatMessage{ Role: "assistant", Content: content.String(), ToolCalls: toolCalls, }, FinishReason: finish, Usage: usage, }, nil }