-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathwo2api.go
More file actions
2367 lines (2011 loc) · 68.1 KB
/
wo2api.go
File metadata and controls
2367 lines (2011 loc) · 68.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"regexp"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
)
// 配置结构体用于存储命令行参数
type Config struct {
Port string // 代理服务器监听端口
Address string // 代理服务器监听地址
LogLevel string // 日志级别
DevMode bool // 开发模式标志
DiagnosticLevel string // 诊断级别:none, basic, full
SaveResponses bool // 是否保存所有响应
MaxRetries int // 最大重试次数
Timeout int // 请求超时时间(秒)
}
// WoCloud API 目标URL,硬编码
const (
TargetURL = "https://panservice.mail.wo.cn"
ClientID = "1001000035"
Version = "1.1.0" // 版本号
)
// 日志级别
const (
LogLevelDebug = "debug"
LogLevelInfo = "info"
LogLevelWarn = "warn"
LogLevelError = "error"
)
// 解析命令行参数并返回 Config 实例
func parseFlags() *Config {
cfg := &Config{}
flag.StringVar(&cfg.Port, "port", "5858", "Port to listen on")
flag.StringVar(&cfg.Address, "address", "localhost", "Address to listen on")
flag.StringVar(&cfg.LogLevel, "log-level", LogLevelInfo, "Log level (debug, info, warn, error)")
flag.BoolVar(&cfg.DevMode, "dev", false, "Enable development mode with enhanced logging")
flag.StringVar(&cfg.DiagnosticLevel, "diag", "none", "Diagnostic level: none, basic, full")
flag.BoolVar(&cfg.SaveResponses, "save-responses", false, "Save all responses for analysis")
flag.IntVar(&cfg.MaxRetries, "max-retries", 3, "Maximum number of retries for failed requests")
flag.IntVar(&cfg.Timeout, "timeout", 300, "Request timeout in seconds")
flag.Parse()
// 如果开发模式开启,自动设置日志级别为debug
if cfg.DevMode && cfg.LogLevel != LogLevelDebug {
cfg.LogLevel = LogLevelDebug
fmt.Println("开发模式已启用,日志级别设置为debug")
}
return cfg
}
// 全局配置变量
var (
appConfig *Config
)
// 性能指标
var (
requestCounter int64
successCounter int64
errorCounter int64
parseErrorCounter int64
avgResponseTime int64
latencyHistogram [10]int64 // 0-100ms, 100-200ms, ... >1s
statusMetrics sync.Map // 记录不同状态码的计数
)
// 日志记录器
var (
logger *log.Logger
logLevel string
logMutex sync.Mutex
)
// 日志初始化
func initLogger(level string) {
logger = log.New(os.Stdout, "[Wo2API] ", log.LstdFlags)
logLevel = level
}
// 根据日志级别记录日志
func logDebug(format string, v ...interface{}) {
if logLevel == LogLevelDebug {
logMutex.Lock()
logger.Printf("[DEBUG] "+format, v...)
logMutex.Unlock()
}
}
func logInfo(format string, v ...interface{}) {
if logLevel == LogLevelDebug || logLevel == LogLevelInfo {
logMutex.Lock()
logger.Printf("[INFO] "+format, v...)
logMutex.Unlock()
}
}
func logWarn(format string, v ...interface{}) {
if logLevel == LogLevelDebug || logLevel == LogLevelInfo || logLevel == LogLevelWarn {
logMutex.Lock()
logger.Printf("[WARN] "+format, v...)
logMutex.Unlock()
}
}
func logError(format string, v ...interface{}) {
logMutex.Lock()
logger.Printf("[ERROR] "+format, v...)
logMutex.Unlock()
// 错误计数
atomic.AddInt64(&errorCounter, 1)
}
// OpenAI/DeepSeek 消息格式
type APIMessage struct {
Role string `json:"role"`
Content interface{} `json:"content"` // 使用interface{}以支持各种类型
}
// OpenAI/DeepSeek 请求格式
type APIRequest struct {
Model string `json:"model"`
Messages []APIMessage `json:"messages"`
Stream bool `json:"stream"`
Temperature float64 `json:"temperature,omitempty"`
MaxTokens int `json:"max_tokens,omitempty"`
}
// WoCloud 历史记录格式
type WoCloudHistory struct {
Query string `json:"query"`
RewriteQuery string `json:"rewriteQuery"`
UploadFileUrl string `json:"uploadFileUrl"`
Response string `json:"response"`
ReasoningContent string `json:"reasoningContent"`
State string `json:"state"`
Key string `json:"key"`
}
// WoCloud 请求格式
type WoCloudRequest struct {
ModelId int `json:"modelId"`
Input string `json:"input"`
History []WoCloudHistory `json:"history"`
}
// WoCloud 响应格式 - 增强版
type WoCloudResponse struct {
Code int `json:"code"`
Message interface{} `json:"message"`
Response string `json:"response"`
ReasoningContent string `json:"reasoningContent"`
Finish int `json:"finish"`
// 添加新字段增强兼容性
Content string `json:"content,omitempty"` // 兼容可能使用的另一种字段名
Result string `json:"result,omitempty"` // 兼容可能使用的另一种字段名
Think string `json:"think,omitempty"` // 兼容可能使用的思考内容字段
Extra map[string]interface{} `json:"-"`
}
// 自定义UnmarshalJSON方法,增强容错性
func (r *WoCloudResponse) UnmarshalJSON(data []byte) error {
// 标准字段
type StandardResponse WoCloudResponse
// 临时结构,用于捕获所有字段
var temp struct {
StandardResponse
Extra map[string]interface{} `json:"-"`
}
// 尝试标准解析
if err := json.Unmarshal(data, &temp.StandardResponse); err != nil {
// 尝试解析为map
var rawMap map[string]interface{}
if mapErr := json.Unmarshal(data, &rawMap); mapErr != nil {
// 清除可能的BOM
cleanData := bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))
if cleanErr := json.Unmarshal(cleanData, &rawMap); cleanErr != nil {
reqID := generateRequestID()
logDebug("[reqID:%s] JSON解析失败: %v, 内容: %s", reqID, err, string(data[:min(len(data), 200)]))
return err
}
}
// 从map中提取关键字段
for key, value := range rawMap {
switch strings.ToLower(key) {
case "code":
switch v := value.(type) {
case float64:
temp.Code = int(v)
case int:
temp.Code = v
case string:
if c, err := strconv.Atoi(v); err == nil {
temp.Code = c
}
}
case "response", "content", "result":
if str, ok := value.(string); ok && str != "" {
temp.Response = str
}
case "reasoningcontent", "reasoning_content", "thinking", "think":
if str, ok := value.(string); ok && str != "" {
temp.ReasoningContent = str
}
case "finish", "done", "completed":
switch v := value.(type) {
case float64:
temp.Finish = int(v)
case int:
temp.Finish = v
case bool:
if v {
temp.Finish = 1
}
case string:
if f, err := strconv.Atoi(v); err == nil {
temp.Finish = f
} else if v == "true" || v == "yes" {
temp.Finish = 1
}
}
}
}
temp.Extra = rawMap
}
// 复制回原结构
*r = WoCloudResponse(temp.StandardResponse)
r.Extra = temp.Extra
// 优先级处理:如果 Response 为空但其他字段有值
if r.Response == "" {
if r.Content != "" {
r.Response = r.Content
} else if r.Result != "" {
r.Response = r.Result
}
}
// 如果 ReasoningContent 为空但 Think 有值
if r.ReasoningContent == "" && r.Think != "" {
r.ReasoningContent = r.Think
}
return nil
}
// DeepSeek 流式响应格式 - 修改以支持reasoning_content
type StreamChunk struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []struct {
Index int `json:"index"`
FinishReason *string `json:"finish_reason,omitempty"`
Delta struct {
Role string `json:"role,omitempty"`
Content string `json:"content,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"` // 使用reasoning_content而非think标签
} `json:"delta"`
} `json:"choices"`
}
// DeepSeek 非流式响应格式 - 修改以支持reasoning_content
type CompletionResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []struct {
Index int `json:"index"`
FinishReason string `json:"finish_reason"`
Message struct {
Role string `json:"role"`
Content string `json:"content"`
ReasoningContent string `json:"reasoning_content,omitempty"` // 使用reasoning_content
} `json:"message"`
} `json:"choices"`
Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
} `json:"usage"`
}
// WoCloud错误响应
type WoCloudError struct {
Code string `json:"code"`
Message string `json:"message"`
}
// 请求计数和互斥锁,用于监控
var (
requestCount uint64 = 0
countMutex sync.Mutex
)
// 启动指标报告器
func startMetricsReporter(interval time.Duration) {
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
<-ticker.C
reqCount := atomic.LoadInt64(&requestCounter)
successCount := atomic.LoadInt64(&successCounter)
errCount := atomic.LoadInt64(&errorCounter)
parseErrCount := atomic.LoadInt64(&parseErrorCounter)
// 仅当有请求时才输出指标
if reqCount > 0 {
avgTime := atomic.LoadInt64(&avgResponseTime)
// 修复类型不匹配问题,确保使用相同类型计算成功率
successRate := float64(0)
if reqCount > 0 {
successRate = float64(successCount) / float64(reqCount) * 100
}
logInfo("性能指标 - 请求总数: %d, 成功: %d (%.2f%%), 错误: %d, 解析错误: %d, 平均响应时间: %dms",
reqCount, successCount, successRate, errCount, parseErrCount, avgTime/max(reqCount, 1))
// 输出延迟直方图
var latencyReport strings.Builder
latencyReport.WriteString("延迟分布 - ")
for i, count := range latencyHistogram {
if count > 0 {
if i < 9 {
latencyReport.WriteString(fmt.Sprintf("%d-%dms: %d, ", i*100, (i+1)*100, count))
} else {
latencyReport.WriteString(fmt.Sprintf(">900ms: %d, ", count))
}
}
}
logInfo(strings.TrimSuffix(latencyReport.String(), ", "))
}
}
}()
}
// 主入口函数
func main() {
// 解析配置
appConfig = parseFlags()
// 初始化日志
initLogger(appConfig.LogLevel)
logInfo("启动服务: TargetURL=%s, Address=%s, Port=%s, Version=%s, LogLevel=%s",
TargetURL, appConfig.Address, appConfig.Port, Version, appConfig.LogLevel)
// 配置更高的并发处理能力
http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 100
http.DefaultTransport.(*http.Transport).MaxIdleConns = 100
http.DefaultTransport.(*http.Transport).IdleConnTimeout = 90 * time.Second
// 创建自定义服务器,支持更高并发
server := &http.Server{
Addr: appConfig.Address + ":" + appConfig.Port,
ReadTimeout: time.Duration(appConfig.Timeout) * time.Second,
WriteTimeout: time.Duration(appConfig.Timeout) * time.Second,
IdleTimeout: 120 * time.Second,
Handler: nil, // 使用默认的ServeMux
}
// 创建处理器
http.HandleFunc("/v1/models", func(w http.ResponseWriter, r *http.Request) {
handleModelsRequest(w, r)
})
http.HandleFunc("/v1/chat/completions", func(w http.ResponseWriter, r *http.Request) {
// 设置超时上下文
ctx, cancel := context.WithTimeout(r.Context(), time.Duration(appConfig.Timeout)*time.Second)
defer cancel()
// 包含超时上下文的请求
r = r.WithContext(ctx)
// 添加恢复机制,防止panic
defer func() {
if r := recover(); r != nil {
logError("处理请求时发生panic: %v\n%s", r, debug.Stack())
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}()
// 计数器增加
countMutex.Lock()
requestCount++
currentCount := requestCount
countMutex.Unlock()
logInfo("收到新请求 #%d", currentCount)
// 请求计数
atomic.AddInt64(&requestCounter, 1)
// 处理请求
handleChatCompletionRequest(w, r)
})
// 添加健康检查端点
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
countMutex.Lock()
count := requestCount
countMutex.Unlock()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf(`{"status":"ok","version":"%s","requests":%d}`, Version, count)))
})
// 添加版本端点
http.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf(`{"version":"%s"}`, Version)))
})
// 添加诊断端点
http.HandleFunc("/diagnostics", func(w http.ResponseWriter, r *http.Request) {
if !appConfig.DevMode {
http.Error(w, "Diagnostics only available in development mode", http.StatusForbidden)
return
}
reqCount := atomic.LoadInt64(&requestCounter)
successCount := atomic.LoadInt64(&successCounter)
errCount := atomic.LoadInt64(&errorCounter)
parseErrCount := atomic.LoadInt64(&parseErrorCounter)
// 计算成功率
successRate := float64(0)
if reqCount > 0 {
successRate = float64(successCount) / float64(reqCount) * 100
}
diagnosticInfo := map[string]interface{}{
"version": Version,
"start_time": time.Now().Format(time.RFC3339),
"requests": reqCount,
"success": successCount,
"errors": errCount,
"parse_errors": parseErrCount,
"success_rate": fmt.Sprintf("%.2f%%", successRate),
"avg_response_ms": atomic.LoadInt64(&avgResponseTime) / max(reqCount, 1),
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(diagnosticInfo)
})
// 启动指标报告
if appConfig.DevMode {
startMetricsReporter(1 * time.Minute)
}
// 创建停止通道
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
// 在goroutine中启动服务器
go func() {
logInfo("Starting proxy server on %s", server.Addr)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logError("Failed to start server: %v", err)
os.Exit(1)
}
}()
// 等待停止信号
<-stop
// 创建上下文用于优雅关闭
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// 优雅关闭服务器
logInfo("Server is shutting down...")
if err := server.Shutdown(ctx); err != nil {
logError("Server shutdown failed: %v", err)
}
logInfo("Server gracefully stopped")
}
// 验证消息格式
func validateMessages(messages []APIMessage) (bool, string) {
reqID := generateRequestID()
logDebug("[reqID:%s] 验证消息格式", reqID)
if messages == nil || len(messages) == 0 {
return false, "Messages array is required"
}
for _, msg := range messages {
if msg.Role == "" || msg.Content == nil {
return false, "Invalid message format: each message must have role and content"
}
}
return true, ""
}
// 从请求头中提取令牌
func extractToken(r *http.Request) (string, error) {
// 获取 Authorization 头部
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
return "", fmt.Errorf("missing Authorization header")
}
// 验证格式并提取令牌
if !strings.HasPrefix(authHeader, "Bearer ") {
return "", fmt.Errorf("invalid Authorization header format, must start with 'Bearer '")
}
// 提取令牌值
token := strings.TrimPrefix(authHeader, "Bearer ")
if token == "" {
return "", fmt.Errorf("empty token in Authorization header")
}
return token, nil
}
// 转换任意类型的内容为字符串
func contentToString(content interface{}) string {
if content == nil {
return ""
}
switch v := content.(type) {
case string:
return v
default:
jsonBytes, err := json.Marshal(v)
if err != nil {
logWarn("将内容转换为JSON失败: %v", err)
return ""
}
return string(jsonBytes)
}
}
// 从 OpenAI/DeepSeek 消息中提取用户消息和历史记录
func extractMessages(messages []APIMessage) (string, []WoCloudHistory) {
reqID := generateRequestID()
logDebug("[reqID:%s] 提取消息和历史记录", reqID)
// 获取最后一条用户消息
userMessage := ""
for i := len(messages) - 1; i >= 0; i-- {
if messages[i].Role == "user" {
userMessage = contentToString(messages[i].Content)
userMessage = strings.TrimSpace(userMessage)
break
}
}
// 构建历史记录
var history []WoCloudHistory
for i := 0; i < len(messages)-1; i++ {
if messages[i].Role == "user" && i+1 < len(messages) && messages[i+1].Role == "assistant" {
query := contentToString(messages[i].Content)
response := contentToString(messages[i+1].Content)
query = strings.TrimSpace(query)
response = strings.TrimSpace(response)
history = append(history, WoCloudHistory{
Query: query,
RewriteQuery: query,
UploadFileUrl: "",
Response: response,
ReasoningContent: "", // 无法从标准消息中提取推理内容
State: "finish",
Key: fmt.Sprintf("%d", time.Now().UnixNano()),
})
}
}
logDebug("[reqID:%s] 提取的用户消息长度: %d", reqID, len(userMessage))
logDebug("[reqID:%s] 提取的历史记录数量: %d", reqID, len(history))
return userMessage, history
}
// 增强的WoCloud错误处理函数
func handleWoError(resp *http.Response) (*WoCloudError, error) {
reqID := generateRequestID() // 为错误处理生成唯一ID
logDebug("[reqID:%s] 处理WoCloud错误响应", reqID)
contentType := resp.Header.Get("Content-Type")
// 先读取整个响应体
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("读取错误响应失败: %v", err)
}
bodyStr := string(bodyBytes)
logDebug("[reqID:%s] 错误响应内容: %s", reqID, bodyStr)
if strings.Contains(contentType, "text/event-stream") {
// 流式响应中的错误
lines := strings.Split(bodyStr, "\n")
for _, line := range lines {
if strings.HasPrefix(line, "data:") {
jsonStr := strings.TrimPrefix(line, "data:")
jsonStr = strings.TrimSpace(jsonStr)
if jsonStr == "[DONE]" {
continue
}
var errorData WoCloudError
if err := json.Unmarshal([]byte(jsonStr), &errorData); err != nil {
logDebug("[reqID:%s] 解析流式错误行失败: %v", reqID, err)
continue
}
if errorData.Code != "" && errorData.Code != "0" {
return &errorData, nil
}
}
}
// 如果没有找到具体错误信息,返回默认错误
return &WoCloudError{
Code: fmt.Sprintf("HTTP_%d", resp.StatusCode),
Message: fmt.Sprintf("Stream error with status code: %d", resp.StatusCode),
}, nil
} else {
// 尝试解析为JSON错误
var errorData WoCloudError
if err := json.Unmarshal(bodyBytes, &errorData); err != nil {
// 清理可能的BOM
cleanBody := bytes.TrimPrefix(bodyBytes, []byte("\xef\xbb\xbf"))
if err := json.Unmarshal(cleanBody, &errorData); err != nil {
// 尝试用更宽松的方式解析
var mapData map[string]interface{}
if mapErr := json.Unmarshal(cleanBody, &mapData); mapErr == nil {
// 从map中提取错误信息
if code, ok := mapData["code"]; ok {
switch v := code.(type) {
case string:
errorData.Code = v
case float64:
errorData.Code = fmt.Sprintf("%d", int(v))
case int:
errorData.Code = fmt.Sprintf("%d", v)
}
}
if message, ok := mapData["message"]; ok {
switch v := message.(type) {
case string:
errorData.Message = v
default:
errorData.Message = fmt.Sprintf("%v", v)
}
}
return &errorData, nil
}
// 返回基于HTTP状态码的错误
return &WoCloudError{
Code: fmt.Sprintf("HTTP_%d", resp.StatusCode),
Message: fmt.Sprintf("Error with status code: %d and content: %s", resp.StatusCode, bodyStr),
}, nil
}
}
return &errorData, nil
}
}
// 处理模型列表请求
func handleModelsRequest(w http.ResponseWriter, r *http.Request) {
logInfo("处理模型列表请求")
// 返回模型列表
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
modelsList := map[string]interface{}{
"object": "list",
"data": []map[string]interface{}{
{
"id": "DeepSeek-R1",
"object": "model",
"created": time.Now().Unix(),
"owned_by": "ChinaUnicom",
"capabilities": []string{"chat", "completions"},
},
},
}
json.NewEncoder(w).Encode(modelsList)
}
// 创建角色块 - 使用reasoning_content
func createRoleChunk(id string, created int64) []byte {
chunk := StreamChunk{
ID: id,
Object: "chat.completion.chunk",
Created: created,
Model: "DeepSeek-R1",
Choices: []struct {
Index int `json:"index"`
FinishReason *string `json:"finish_reason,omitempty"`
Delta struct {
Role string `json:"role,omitempty"`
Content string `json:"content,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
} `json:"delta"`
}{
{
Index: 0,
Delta: struct {
Role string `json:"role,omitempty"`
Content string `json:"content,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
}{
Role: "assistant",
},
},
},
}
data, _ := json.Marshal(chunk)
return data
}
// 创建推理内容块 - 使用reasoning_content
func createReasoningChunk(id string, created int64, reasoningContent string) []byte {
chunk := StreamChunk{
ID: id,
Object: "chat.completion.chunk",
Created: created,
Model: "DeepSeek-R1",
Choices: []struct {
Index int `json:"index"`
FinishReason *string `json:"finish_reason,omitempty"`
Delta struct {
Role string `json:"role,omitempty"`
Content string `json:"content,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
} `json:"delta"`
}{
{
Index: 0,
Delta: struct {
Role string `json:"role,omitempty"`
Content string `json:"content,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
}{
ReasoningContent: reasoningContent,
},
},
},
}
data, _ := json.Marshal(chunk)
return data
}
// 创建内容块
func createContentChunk(id string, created int64, content string) []byte {
chunk := StreamChunk{
ID: id,
Object: "chat.completion.chunk",
Created: created,
Model: "DeepSeek-R1",
Choices: []struct {
Index int `json:"index"`
FinishReason *string `json:"finish_reason,omitempty"`
Delta struct {
Role string `json:"role,omitempty"`
Content string `json:"content,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
} `json:"delta"`
}{
{
Index: 0,
Delta: struct {
Role string `json:"role,omitempty"`
Content string `json:"content,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
}{
Content: content,
},
},
},
}
data, _ := json.Marshal(chunk)
return data
}
// 创建完成块
func createDoneChunk(id string, created int64, reason string) []byte {
finishReason := reason
chunk := StreamChunk{
ID: id,
Object: "chat.completion.chunk",
Created: created,
Model: "DeepSeek-R1",
Choices: []struct {
Index int `json:"index"`
FinishReason *string `json:"finish_reason,omitempty"`
Delta struct {
Role string `json:"role,omitempty"`
Content string `json:"content,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
} `json:"delta"`
}{
{
Index: 0,
FinishReason: &finishReason,
Delta: struct {
Role string `json:"role,omitempty"`
Content string `json:"content,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
}{},
},
},
}
data, _ := json.Marshal(chunk)
return data
}
// 创建错误块
func createErrorChunk(id string, created int64, errorMsg string) []byte {
chunk := map[string]interface{}{
"error": map[string]interface{}{
"message": errorMsg,
"type": "api_error",
},
}
data, _ := json.Marshal(chunk)
return data
}
// 处理聊天补全请求
func handleChatCompletionRequest(w http.ResponseWriter, r *http.Request) {
reqID := generateRequestID()
startTime := time.Now()
logInfo("[reqID:%s] 处理聊天补全请求", reqID)
// 从请求头中提取令牌
token, err := extractToken(r)
if err != nil {
logError("[reqID:%s] 提取令牌失败: %v", reqID, err)
http.Error(w, fmt.Sprintf("Authorization error: %v", err), http.StatusUnauthorized)
return
}
// 解析请求体
var apiReq APIRequest
if err := json.NewDecoder(r.Body).Decode(&apiReq); err != nil {
logError("[reqID:%s] 解析请求失败: %v", reqID, err)
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// 验证消息格式
valid, errMsg := validateMessages(apiReq.Messages)
if !valid {
logError("[reqID:%s] 消息格式验证失败: %s", reqID, errMsg)
http.Error(w, errMsg, http.StatusBadRequest)
return
}
// 获取最后一条用户消息和历史记录
userMessage, history := extractMessages(apiReq.Messages)
if userMessage == "" {
logError("[reqID:%s] 未找到有效的用户消息", reqID)
http.Error(w, "No valid user message found", http.StatusBadRequest)
return
}
// 转发请求到 WoCloud API
var responseErr error
if apiReq.Stream {
responseErr = handleStreamingRequest(w, r, userMessage, history, token, reqID)
} else {
responseErr = handleNonStreamingRequest(w, r, userMessage, history, token, reqID)
}
// 请求处理完成,更新指标
elapsed := time.Since(startTime).Milliseconds()
// 更新延迟直方图
bucketIndex := min(int(elapsed/100), 9)
atomic.AddInt64(&latencyHistogram[bucketIndex], 1)
// 更新平均响应时间
atomic.AddInt64(&avgResponseTime, elapsed)
if responseErr == nil {
// 成功计数增加
atomic.AddInt64(&successCounter, 1)
logInfo("[reqID:%s] 请求处理成功,耗时: %dms", reqID, elapsed)
} else {
logError("[reqID:%s] 请求处理失败: %v, 耗时: %dms", reqID, responseErr, elapsed)
}
}
// 重试机制的HTTP请求函数
func doRequestWithRetry(req *http.Request, client *http.Client, maxRetries int) (*http.Response, error) {
var resp *http.Response
var err error
reqID := generateRequestID()
for i := 0; i < maxRetries; i++ {
resp, err = client.Do(req)
if err == nil && resp.StatusCode == http.StatusOK {
logDebug("[reqID:%s] HTTP请求成功", reqID)
return resp, nil
}
if resp != nil {
resp.Body.Close()
}
logWarn("[reqID:%s] HTTP请求失败(尝试%d/%d): %v", reqID, i+1, maxRetries, err)
// 避免最后一次失败后等待
if i < maxRetries-1 {
// 指数退避
backoffTime := time.Duration(100*(1<<i)) * time.Millisecond
logDebug("[reqID:%s] 等待 %v 后重试", reqID, backoffTime)
time.Sleep(backoffTime)
}
}
// 返回适当的错误信息
if err != nil {
return nil, fmt.Errorf("在%d次尝试后HTTP请求仍然失败: %v", maxRetries, err)
}
return nil, fmt.Errorf("在%d次尝试后HTTP请求返回非200状态码: %d", maxRetries, resp.StatusCode)
}
// 清理JSON字符串,去除可能导致JSON编码失败的字符
func sanitizeJsonString(input string, reqID string) string {
if input == "" {
return input
}
// 记录原始长度
originalLen := len(input)
// 移除控制字符(除了常见的换行、回车、制表符)
cleanStr := strings.Map(func(r rune) rune {
if r < 32 && r != '\n' && r != '\r' && r != '\t' {
return -1 // 删除字符
}
return r
}, input)
// 处理不成对的引号和转义字符
var result strings.Builder
inBackslash := false