miaopanel
1package ai
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "io"
11 "net/http"
12 "sort"
13 "strings"
14 "time"
15)
16
17// Provider speaks the OpenAI Chat Completions protocol. It always asks the
18// upstream for a stream and also tolerates providers that ignore `stream` and
19// answer with a single JSON document.
20type Provider struct {
21 client *http.Client
22}
23
24func newProvider() *Provider {
25 return &Provider{client: &http.Client{
26 Transport: &http.Transport{
27 Proxy: http.ProxyFromEnvironment,
28 ResponseHeaderTimeout: 30 * time.Second,
29 IdleConnTimeout: 90 * time.Second,
30 },
31 }}
32}
33
34type chatPayload struct {
35 Model string `json:"model"`
36 Messages []ChatMessage `json:"messages"`
37 Tools []ToolDef `json:"tools,omitempty"`
38 Temperature float64 `json:"temperature"`
39 Stream bool `json:"stream"`
40 MaxTokens int `json:"max_tokens,omitempty"`
41}
42
43type streamChunk struct {
44 Choices []struct {
45 Delta struct {
46 Content string `json:"content"`
47 ToolCalls []struct {
48 Index int `json:"index"`
49 ID string `json:"id"`
50 Type string `json:"type"`
51 Function struct {
52 Name string `json:"name"`
53 Arguments string `json:"arguments"`
54 } `json:"function"`
55 } `json:"tool_calls"`
56 } `json:"delta"`
57 FinishReason string `json:"finish_reason"`
58 } `json:"choices"`
59 Usage *Usage `json:"usage"`
60}
61
62type apiMessage struct {
63 Content string `json:"content"`
64 ToolCalls []ToolCall `json:"tool_calls"`
65}
66
67type apiResponse struct {
68 Choices []struct {
69 Message apiMessage `json:"message"`
70 FinishReason string `json:"finish_reason"`
71 } `json:"choices"`
72 Usage *Usage `json:"usage"`
73 Error *struct {
74 Message string `json:"message"`
75 } `json:"error"`
76}
77
78// Chat performs one completion. onDelta receives incremental text.
79func (p *Provider) Chat(ctx context.Context, st Settings, req ChatRequest, onDelta func(string)) (*ChatResult, error) {
80 if strings.TrimSpace(st.APIKey) == "" {
81 return nil, errors.New("尚未配置 AI API Key")
82 }
83 if strings.TrimSpace(req.Model) == "" {
84 return nil, errors.New("尚未配置模型")
85 }
86 payload := chatPayload{
87 Model: req.Model,
88 Messages: req.Messages,
89 Tools: req.Tools,
90 Temperature: req.Temperature,
91 Stream: true,
92 MaxTokens: req.MaxTokens,
93 }
94 body, err := json.Marshal(payload)
95 if err != nil {
96 return nil, err
97 }
98 endpoint := chatEndpoint(st.BaseURL)
99
100 var lastErr error
101 emitted := false
102 wrap := func(delta string) {
103 if delta == "" {
104 return
105 }
106 emitted = true
107 if onDelta != nil {
108 onDelta(delta)
109 }
110 }
111 // One retry is enough for transient connection failures; once tokens have
112 // reached the client a retry would duplicate output.
113 for attempt := 0; attempt < 2; attempt++ {
114 res, err := p.once(ctx, endpoint, st.APIKey, body, wrap)
115 if err == nil {
116 return res, nil
117 }
118 lastErr = err
119 if emitted || ctx.Err() != nil {
120 return nil, err
121 }
122 }
123 return nil, lastErr
124}
125
126func chatEndpoint(base string) string {
127 b := strings.TrimRight(strings.TrimSpace(base), "/")
128 if strings.Contains(b, "/chat/completions") {
129 return b
130 }
131 return b + "/chat/completions"
132}
133
134func (p *Provider) once(ctx context.Context, endpoint, apiKey string, body []byte, onDelta func(string)) (*ChatResult, error) {
135 httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
136 if err != nil {
137 return nil, err
138 }
139 httpReq.Header.Set("Content-Type", "application/json")
140 httpReq.Header.Set("Accept", "text/event-stream")
141 httpReq.Header.Set("Authorization", "Bearer "+apiKey)
142 httpReq.Header.Set("User-Agent", "MiaoPanel-AI")
143
144 resp, err := p.client.Do(httpReq)
145 if err != nil {
146 return nil, fmt.Errorf("连接 AI 服务失败: %w", err)
147 }
148 defer resp.Body.Close()
149
150 if resp.StatusCode != http.StatusOK {
151 msg := readErrorBody(resp.Body)
152 if msg == "" {
153 msg = fmt.Sprintf("AI 服务返回 HTTP %d", resp.StatusCode)
154 }
155 return nil, errors.New(msg)
156 }
157 if strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") {
158 return readStream(resp.Body, onDelta)
159 }
160 return readJSON(resp.Body, onDelta)
161}
162
163func readErrorBody(body io.Reader) string {
164 raw, _ := io.ReadAll(io.LimitReader(body, 4096))
165 var env struct {
166 Error *struct {
167 Message string `json:"message"`
168 } `json:"error"`
169 Message string `json:"message"`
170 }
171 if err := json.Unmarshal(raw, &env); err == nil {
172 if env.Error != nil && env.Error.Message != "" {
173 return env.Error.Message
174 }
175 if env.Message != "" {
176 return env.Message
177 }
178 }
179 text := strings.TrimSpace(string(raw))
180 if len(text) > 300 {
181 text = text[:300]
182 }
183 return text
184}
185
186func readJSON(body io.Reader, onDelta func(string)) (*ChatResult, error) {
187 var res apiResponse
188 if err := json.NewDecoder(io.LimitReader(body, 8<<20)).Decode(&res); err != nil {
189 return nil, fmt.Errorf("解析 AI 响应失败: %w", err)
190 }
191 if res.Error != nil && res.Error.Message != "" {
192 return nil, errors.New(res.Error.Message)
193 }
194 if len(res.Choices) == 0 {
195 return nil, errors.New("AI 服务没有返回任何结果")
196 }
197 choice := res.Choices[0]
198 if choice.Message.Content != "" && onDelta != nil {
199 onDelta(choice.Message.Content)
200 }
201 return &ChatResult{
202 Message: ChatMessage{
203 Role: "assistant",
204 Content: choice.Message.Content,
205 ToolCalls: choice.Message.ToolCalls,
206 },
207 FinishReason: choice.FinishReason,
208 Usage: res.Usage,
209 }, nil
210}
211
212func readStream(body io.Reader, onDelta func(string)) (*ChatResult, error) {
213 scanner := bufio.NewScanner(body)
214 scanner.Buffer(make([]byte, 64<<10), 4<<20)
215 var content strings.Builder
216 finish := ""
217 var usage *Usage
218 calls := map[int]*ToolCall{}
219 var order []int
220
221 for scanner.Scan() {
222 line := strings.TrimSpace(scanner.Text())
223 if !strings.HasPrefix(line, "data:") {
224 continue
225 }
226 data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
227 if data == "" || data == "[DONE]" {
228 if data == "[DONE]" {
229 break
230 }
231 continue
232 }
233 var chunk streamChunk
234 if err := json.Unmarshal([]byte(data), &chunk); err != nil {
235 // Some providers send keepalive comments or vendor events.
236 continue
237 }
238 if chunk.Usage != nil {
239 usage = chunk.Usage
240 }
241 if len(chunk.Choices) == 0 {
242 continue
243 }
244 choice := chunk.Choices[0]
245 if choice.Delta.Content != "" {
246 content.WriteString(choice.Delta.Content)
247 if onDelta != nil {
248 onDelta(choice.Delta.Content)
249 }
250 }
251 for _, d := range choice.Delta.ToolCalls {
252 cur, ok := calls[d.Index]
253 if !ok {
254 cur = &ToolCall{Type: "function"}
255 calls[d.Index] = cur
256 order = append(order, d.Index)
257 }
258 if d.ID != "" {
259 cur.ID = d.ID
260 }
261 if d.Type != "" {
262 cur.Type = d.Type
263 }
264 cur.Function.Name += d.Function.Name
265 cur.Function.Arguments += d.Function.Arguments
266 }
267 if choice.FinishReason != "" {
268 finish = choice.FinishReason
269 }
270 }
271 if err := scanner.Err(); err != nil {
272 return nil, fmt.Errorf("读取 AI 流失败: %w", err)
273 }
274
275 toolCalls := make([]ToolCall, 0, len(calls))
276 sort.Ints(order)
277 for _, idx := range order {
278 tc := calls[idx]
279 if tc.ID == "" {
280 continue
281 }
282 toolCalls = append(toolCalls, *tc)
283 }
284 return &ChatResult{
285 Message: ChatMessage{
286 Role: "assistant",
287 Content: content.String(),
288 ToolCalls: toolCalls,
289 },
290 FinishReason: finish,
291 Usage: usage,
292 }, nil
293}