|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+package factory
|
|
|
2
|
+
|
|
|
3
|
+import (
|
|
|
4
|
+ "context"
|
|
|
5
|
+ "encoding/json"
|
|
|
6
|
+ "fmt"
|
|
|
7
|
+ "io"
|
|
|
8
|
+ "net/http"
|
|
|
9
|
+ "strings"
|
|
|
10
|
+ "time"
|
|
|
11
|
+)
|
|
|
12
|
+
|
|
|
13
|
+// 极简HTTP客户端实现
|
|
|
14
|
+type SimpleHTTPClient struct {
|
|
|
15
|
+ config *ModelConfig
|
|
|
16
|
+ client *http.Client
|
|
|
17
|
+}
|
|
|
18
|
+
|
|
|
19
|
+// NewSimpleHTTPClient 创建客户端(每次请求创建新的)
|
|
|
20
|
+func NewSimpleHTTPClient(config *ModelConfig) *SimpleHTTPClient {
|
|
|
21
|
+ return &SimpleHTTPClient{
|
|
|
22
|
+ config: config,
|
|
|
23
|
+ client: &http.Client{
|
|
|
24
|
+ Timeout: time.Duration(config.Timeout) * time.Second,
|
|
|
25
|
+ },
|
|
|
26
|
+ }
|
|
|
27
|
+}
|
|
|
28
|
+
|
|
|
29
|
+// Chat 一次性返回(阻塞式)
|
|
|
30
|
+func (c *SimpleHTTPClient) Chat(ctx context.Context, messages []ChatMessage) (string, error) {
|
|
|
31
|
+ // 构建请求
|
|
|
32
|
+ reqBody := map[string]interface{}{
|
|
|
33
|
+ "model": c.config.Model,
|
|
|
34
|
+ "messages": messages,
|
|
|
35
|
+ "max_tokens": c.config.MaxTokens,
|
|
|
36
|
+ "temperature": c.config.Temperature,
|
|
|
37
|
+ "stream": false,
|
|
|
38
|
+ }
|
|
|
39
|
+
|
|
|
40
|
+ // 根据不同提供商调整请求格式
|
|
|
41
|
+ reqBody = c.adjustRequestForProvider(reqBody)
|
|
|
42
|
+
|
|
|
43
|
+ // 发送请求
|
|
|
44
|
+ resp, err := c.doRequest(ctx, reqBody)
|
|
|
45
|
+ if err != nil {
|
|
|
46
|
+ return "", err
|
|
|
47
|
+ }
|
|
|
48
|
+ defer resp.Body.Close()
|
|
|
49
|
+
|
|
|
50
|
+ // 解析响应
|
|
|
51
|
+ var result map[string]interface{}
|
|
|
52
|
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
|
|
53
|
+ return "", fmt.Errorf("解析响应失败: %v", err)
|
|
|
54
|
+ }
|
|
|
55
|
+
|
|
|
56
|
+ // 提取回复内容
|
|
|
57
|
+ return c.extractContent(result), nil
|
|
|
58
|
+}
|
|
|
59
|
+
|
|
|
60
|
+// ChatStream 流式返回
|
|
|
61
|
+func (c *SimpleHTTPClient) ChatStream(ctx context.Context, messages []ChatMessage) (<-chan string, error) {
|
|
|
62
|
+ ch := make(chan string)
|
|
|
63
|
+
|
|
|
64
|
+ go func() {
|
|
|
65
|
+ defer close(ch)
|
|
|
66
|
+
|
|
|
67
|
+ // 构建请求
|
|
|
68
|
+ reqBody := map[string]interface{}{
|
|
|
69
|
+ "model": c.config.Model,
|
|
|
70
|
+ "messages": messages,
|
|
|
71
|
+ "max_tokens": c.config.MaxTokens,
|
|
|
72
|
+ "temperature": c.config.Temperature,
|
|
|
73
|
+ "stream": true,
|
|
|
74
|
+ }
|
|
|
75
|
+
|
|
|
76
|
+ reqBody = c.adjustRequestForProvider(reqBody)
|
|
|
77
|
+
|
|
|
78
|
+ // 发送请求
|
|
|
79
|
+ resp, err := c.doRequest(ctx, reqBody)
|
|
|
80
|
+ if err != nil {
|
|
|
81
|
+ ch <- fmt.Sprintf("错误: %v", err)
|
|
|
82
|
+ return
|
|
|
83
|
+ }
|
|
|
84
|
+ defer resp.Body.Close()
|
|
|
85
|
+
|
|
|
86
|
+ // 流式读取
|
|
|
87
|
+ reader := c.createStreamReader(resp.Body)
|
|
|
88
|
+ for {
|
|
|
89
|
+ select {
|
|
|
90
|
+ case <-ctx.Done():
|
|
|
91
|
+ return
|
|
|
92
|
+ default:
|
|
|
93
|
+ line, err := reader()
|
|
|
94
|
+ if err != nil {
|
|
|
95
|
+ if err != io.EOF {
|
|
|
96
|
+ ch <- fmt.Sprintf("读取错误: %v", err)
|
|
|
97
|
+ }
|
|
|
98
|
+ return
|
|
|
99
|
+ }
|
|
|
100
|
+ if line != "" {
|
|
|
101
|
+ ch <- line
|
|
|
102
|
+ }
|
|
|
103
|
+ }
|
|
|
104
|
+ }
|
|
|
105
|
+ }()
|
|
|
106
|
+
|
|
|
107
|
+ return ch, nil
|
|
|
108
|
+}
|
|
|
109
|
+
|
|
|
110
|
+// doRequest 执行HTTP请求
|
|
|
111
|
+func (c *SimpleHTTPClient) doRequest(ctx context.Context, body map[string]interface{}) (*http.Response, error) {
|
|
|
112
|
+ // 序列化请求体
|
|
|
113
|
+ jsonData, err := json.Marshal(body)
|
|
|
114
|
+ if err != nil {
|
|
|
115
|
+ return nil, fmt.Errorf("序列化请求失败: %v", err)
|
|
|
116
|
+ }
|
|
|
117
|
+
|
|
|
118
|
+ // 确定端点URL
|
|
|
119
|
+ endpoint := c.getEndpointURL()
|
|
|
120
|
+
|
|
|
121
|
+ // 创建请求
|
|
|
122
|
+ req, err := http.NewRequestWithContext(ctx, "POST", endpoint, strings.NewReader(string(jsonData)))
|
|
|
123
|
+ if err != nil {
|
|
|
124
|
+ return nil, fmt.Errorf("创建请求失败: %v", err)
|
|
|
125
|
+ }
|
|
|
126
|
+
|
|
|
127
|
+ // 设置请求头
|
|
|
128
|
+ c.setHeaders(req)
|
|
|
129
|
+
|
|
|
130
|
+ // 发送请求
|
|
|
131
|
+ resp, err := c.client.Do(req)
|
|
|
132
|
+ if err != nil {
|
|
|
133
|
+ return nil, fmt.Errorf("请求失败: %v", err)
|
|
|
134
|
+ }
|
|
|
135
|
+
|
|
|
136
|
+ // 检查状态码
|
|
|
137
|
+ if resp.StatusCode != http.StatusOK {
|
|
|
138
|
+ body, _ := io.ReadAll(resp.Body)
|
|
|
139
|
+ resp.Body.Close()
|
|
|
140
|
+ return nil, fmt.Errorf("API错误: %s, 响应: %s", resp.Status, string(body))
|
|
|
141
|
+ }
|
|
|
142
|
+
|
|
|
143
|
+ return resp, nil
|
|
|
144
|
+}
|
|
|
145
|
+
|
|
|
146
|
+// getEndpointURL 获取API端点URL
|
|
|
147
|
+func (c *SimpleHTTPClient) getEndpointURL() string {
|
|
|
148
|
+ switch c.config.Provider {
|
|
|
149
|
+ case "openai":
|
|
|
150
|
+ return c.config.BaseURL + "/chat/completions"
|
|
|
151
|
+ case "deepseek":
|
|
|
152
|
+ return c.config.BaseURL + "/chat/completions"
|
|
|
153
|
+ case "claude":
|
|
|
154
|
+ return c.config.BaseURL + "/messages"
|
|
|
155
|
+ default:
|
|
|
156
|
+ return c.config.BaseURL + "/chat/completions"
|
|
|
157
|
+ }
|
|
|
158
|
+}
|
|
|
159
|
+
|
|
|
160
|
+// setHeaders 设置请求头
|
|
|
161
|
+func (c *SimpleHTTPClient) setHeaders(req *http.Request) {
|
|
|
162
|
+ req.Header.Set("Content-Type", "application/json")
|
|
|
163
|
+ req.Header.Set("Authorization", "Bearer "+c.config.APIKey)
|
|
|
164
|
+
|
|
|
165
|
+ // 提供商特定头
|
|
|
166
|
+ switch c.config.Provider {
|
|
|
167
|
+ case "claude":
|
|
|
168
|
+ req.Header.Set("x-api-key", c.config.APIKey)
|
|
|
169
|
+ req.Header.Set("anthropic-version", "2023-06-01")
|
|
|
170
|
+ case "openai", "deepseek":
|
|
|
171
|
+ // 标准头
|
|
|
172
|
+ }
|
|
|
173
|
+}
|
|
|
174
|
+
|
|
|
175
|
+// adjustRequestForProvider 调整请求格式
|
|
|
176
|
+func (c *SimpleHTTPClient) adjustRequestForProvider(reqBody map[string]interface{}) map[string]interface{} {
|
|
|
177
|
+ switch c.config.Provider {
|
|
|
178
|
+ case "claude":
|
|
|
179
|
+ // Claude使用不同的格式
|
|
|
180
|
+ return map[string]interface{}{
|
|
|
181
|
+ "model": c.config.Model,
|
|
|
182
|
+ "messages": reqBody["messages"],
|
|
|
183
|
+ "max_tokens": c.config.MaxTokens,
|
|
|
184
|
+ }
|
|
|
185
|
+ default:
|
|
|
186
|
+ return reqBody
|
|
|
187
|
+ }
|
|
|
188
|
+}
|
|
|
189
|
+
|
|
|
190
|
+// extractContent 从响应中提取内容
|
|
|
191
|
+func (c *SimpleHTTPClient) extractContent(resp map[string]interface{}) string {
|
|
|
192
|
+ switch c.config.Provider {
|
|
|
193
|
+ case "openai", "deepseek":
|
|
|
194
|
+ if choices, ok := resp["choices"].([]interface{}); ok && len(choices) > 0 {
|
|
|
195
|
+ if choice, ok := choices[0].(map[string]interface{}); ok {
|
|
|
196
|
+ if message, ok := choice["message"].(map[string]interface{}); ok {
|
|
|
197
|
+ if content, ok := message["content"].(string); ok {
|
|
|
198
|
+ return content
|
|
|
199
|
+ }
|
|
|
200
|
+ }
|
|
|
201
|
+ }
|
|
|
202
|
+ }
|
|
|
203
|
+ case "claude":
|
|
|
204
|
+ if content, ok := resp["content"].([]interface{}); ok && len(content) > 0 {
|
|
|
205
|
+ if first, ok := content[0].(map[string]interface{}); ok {
|
|
|
206
|
+ if text, ok := first["text"].(string); ok {
|
|
|
207
|
+ return text
|
|
|
208
|
+ }
|
|
|
209
|
+ }
|
|
|
210
|
+ }
|
|
|
211
|
+ }
|
|
|
212
|
+ return ""
|
|
|
213
|
+}
|
|
|
214
|
+
|
|
|
215
|
+// createStreamReader 创建流式读取器
|
|
|
216
|
+func (c *SimpleHTTPClient) createStreamReader(body io.Reader) func() (string, error) {
|
|
|
217
|
+ buf := make([]byte, 4096)
|
|
|
218
|
+ var leftover []byte
|
|
|
219
|
+
|
|
|
220
|
+ return func() (string, error) {
|
|
|
221
|
+ // 读取数据
|
|
|
222
|
+ n, err := body.Read(buf)
|
|
|
223
|
+ if err != nil {
|
|
|
224
|
+ return "", err
|
|
|
225
|
+ }
|
|
|
226
|
+
|
|
|
227
|
+ data := append(leftover, buf[:n]...)
|
|
|
228
|
+ lines := strings.Split(string(data), "\n")
|
|
|
229
|
+
|
|
|
230
|
+ // 处理完整的行
|
|
|
231
|
+ var result strings.Builder
|
|
|
232
|
+ for i, line := range lines {
|
|
|
233
|
+ if i == len(lines)-1 {
|
|
|
234
|
+ // 最后一行可能不完整,留到下次
|
|
|
235
|
+ leftover = []byte(line)
|
|
|
236
|
+ continue
|
|
|
237
|
+ }
|
|
|
238
|
+
|
|
|
239
|
+ line = strings.TrimSpace(line)
|
|
|
240
|
+ if line == "" || !strings.HasPrefix(line, "data: ") {
|
|
|
241
|
+ continue
|
|
|
242
|
+ }
|
|
|
243
|
+
|
|
|
244
|
+ // 去除"data: "前缀
|
|
|
245
|
+ line = line[6:]
|
|
|
246
|
+ if line == "[DONE]" {
|
|
|
247
|
+ return "", io.EOF
|
|
|
248
|
+ }
|
|
|
249
|
+
|
|
|
250
|
+ // 解析JSON
|
|
|
251
|
+ var chunk map[string]interface{}
|
|
|
252
|
+ if err := json.Unmarshal([]byte(line), &chunk); err != nil {
|
|
|
253
|
+ continue
|
|
|
254
|
+ }
|
|
|
255
|
+
|
|
|
256
|
+ // 提取内容
|
|
|
257
|
+ content := c.extractStreamContent(chunk)
|
|
|
258
|
+ if content != "" {
|
|
|
259
|
+ result.WriteString(content)
|
|
|
260
|
+ }
|
|
|
261
|
+ }
|
|
|
262
|
+
|
|
|
263
|
+ return result.String(), nil
|
|
|
264
|
+ }
|
|
|
265
|
+}
|
|
|
266
|
+
|
|
|
267
|
+// extractStreamContent 提取流式响应内容
|
|
|
268
|
+func (c *SimpleHTTPClient) extractStreamContent(chunk map[string]interface{}) string {
|
|
|
269
|
+ switch c.config.Provider {
|
|
|
270
|
+ case "openai", "deepseek":
|
|
|
271
|
+ if choices, ok := chunk["choices"].([]interface{}); ok && len(choices) > 0 {
|
|
|
272
|
+ if choice, ok := choices[0].(map[string]interface{}); ok {
|
|
|
273
|
+ if delta, ok := choice["delta"].(map[string]interface{}); ok {
|
|
|
274
|
+ if content, ok := delta["content"].(string); ok {
|
|
|
275
|
+ return content
|
|
|
276
|
+ }
|
|
|
277
|
+ }
|
|
|
278
|
+ }
|
|
|
279
|
+ }
|
|
|
280
|
+ case "claude":
|
|
|
281
|
+ if content, ok := chunk["content"].([]interface{}); ok && len(content) > 0 {
|
|
|
282
|
+ if first, ok := content[0].(map[string]interface{}); ok {
|
|
|
283
|
+ if text, ok := first["text"].(string); ok {
|
|
|
284
|
+ return text
|
|
|
285
|
+ }
|
|
|
286
|
+ }
|
|
|
287
|
+ }
|
|
|
288
|
+ }
|
|
|
289
|
+ return ""
|
|
|
290
|
+}
|
|
|
291
|
+
|
|
|
292
|
+// ==================== 工厂函数 ====================
|
|
|
293
|
+
|
|
|
294
|
+// CreateClient 工厂函数:根据配置创建客户端
|
|
|
295
|
+func CreateClient(configKey string) (AIClient, error) {
|
|
|
296
|
+ // 这里模拟从"数据库"读取配置
|
|
|
297
|
+ // 实际项目中应该从数据库/配置中心读取
|
|
|
298
|
+ config, err := GetConfigFromMockDB(configKey)
|
|
|
299
|
+ if err != nil {
|
|
|
300
|
+ return nil, err
|
|
|
301
|
+ }
|
|
|
302
|
+
|
|
|
303
|
+ return NewSimpleHTTPClient(config), nil
|
|
|
304
|
+}
|
|
|
305
|
+
|
|
|
306
|
+// GetConfigFromMockDB 模拟从数据库获取配置
|
|
|
307
|
+func GetConfigFromMockDB(configKey string) (*ModelConfig, error) {
|
|
|
308
|
+ // 这里调用模拟数据库
|
|
|
309
|
+ // 实际应该调用数据库查询
|
|
|
310
|
+ return &ModelConfig{
|
|
|
311
|
+ Provider: "openai",
|
|
|
312
|
+ BaseURL: "https://api.openai.com/v1",
|
|
|
313
|
+ APIKey: "fake-key-for-demo",
|
|
|
314
|
+ Model: "gpt-3.5-turbo",
|
|
|
315
|
+ MaxTokens: 1000,
|
|
|
316
|
+ Temperature: 0.7,
|
|
|
317
|
+ Timeout: 30,
|
|
|
318
|
+ }, nil
|
|
|
319
|
+}
|