File size: 24,972 Bytes
48d903a
 
 
 
0daaa48
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c106f0
 
 
 
 
 
 
 
 
 
 
 
 
 
935df43
 
5c106f0
 
 
 
 
 
 
 
 
0b327f4
 
 
 
f137b9c
 
 
 
 
 
0b327f4
 
 
e31009b
0b327f4
 
48d903a
 
 
 
 
 
 
 
 
 
5a55e77
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a55e77
48d903a
5a55e77
48d903a
 
 
5a55e77
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a55e77
 
8646505
48d903a
 
 
 
 
 
85aaf7e
48d903a
 
 
 
 
 
 
 
 
 
85aaf7e
48d903a
 
 
85aaf7e
 
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8646505
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8646505
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8646505
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
5a55e77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8646505
5a55e77
 
 
 
 
 
 
 
 
 
 
 
48d903a
 
 
 
 
 
 
 
 
 
8646505
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8646505
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8646505
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8646505
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8646505
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8646505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85aaf7e
 
8646505
85aaf7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8646505
 
85aaf7e
8646505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48d903a
 
 
 
 
 
 
8646505
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
8646505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48d903a
 
 
 
 
 
 
 
 
8646505
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
5a55e77
 
 
48d903a
 
 
 
 
 
 
8646505
48d903a
 
 
 
 
 
 
 
 
 
5a55e77
48d903a
 
 
 
 
 
 
 
 
5a55e77
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
85aaf7e
48d903a
 
 
85aaf7e
 
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a55e77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48d903a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8646505
 
 
 
 
 
 
 
 
5a55e77
48d903a
 
 
 
5a55e77
 
 
48d903a
 
 
 
 
 
 
 
 
 
 
5a55e77
48d903a
 
 
 
 
 
 
 
8646505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85aaf7e
 
 
 
 
 
 
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
package handler

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"

	"github.com/google/uuid"

	"zai-proxy/internal/auth"
	"zai-proxy/internal/filter"
	"zai-proxy/internal/logger"
	"zai-proxy/internal/model"
	"zai-proxy/internal/upstream"
)

func HandleChatCompletions(w http.ResponseWriter, r *http.Request) {
	apiKey := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
	if apiKey == "" {
		apiKey = r.Header.Get("x-api-key")
	}
	if apiKey == "" {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}
	ok, reason := CheckAndTrack(apiKey, 0)
	if !ok {
		http.Error(w, reason, http.StatusTooManyRequests)
		return
	}
	token := apiKey
	// Estimación simple de tokens (4 chars = 1 token)
	defer func() { TrackUsage(apiKey, 100) }()
	if token == "free" || strings.HasPrefix(token, "RWPX-") {
		anonymousToken, err := auth.GetAnonymousToken()
		if err != nil {
			logger.LogError("Failed to get anonymous token: %v", err)
			http.Error(w, "Failed to get anonymous token", http.StatusInternalServerError)
			return
		}
		token = anonymousToken
	}
	body, _ := io.ReadAll(r.Body)
	r.Body = io.NopCloser(bytes.NewReader(body))
	var tempReq map[string]interface{}
	json.Unmarshal(body, &tempReq)
	if m, ok := tempReq["model"].(string); ok && IsDeepSeekModel(m) {
		ok2, reason := CheckAndTrack(apiKey, 0)
		if !ok2 { http.Error(w, reason, 429); return }
		HandleDeepSeek(w, r, body, apiKey)
		return
	}
	if m, ok := tempReq["model"].(string); ok && IsOpenRouterModel(m) {
		ok2, reason := CheckAndTrack(apiKey, 0)
		if !ok2 { http.Error(w, reason, 429); return }
		HandleOpenRouter(w, r, body, apiKey)
		return
	}
	var req model.ChatRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "Invalid request", http.StatusBadRequest)
		return
	}

	if req.Model == "" {
		req.Model = "GLM-4.6"
	}

	resp, modelName, err := upstream.MakeUpstreamRequest(token, req.Messages, req.Model, req.Tools, req.ToolChoice)
	if err != nil {
		logger.LogError("Upstream request failed: %v", err)
		http.Error(w, "Upstream error", http.StatusBadGateway)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		bodyStr := string(body)
		if len(bodyStr) > 500 {
			bodyStr = bodyStr[:500]
		}
		logger.LogError("Upstream error: status=%d, body=%s", resp.StatusCode, bodyStr)
		http.Error(w, "Upstream error", resp.StatusCode)
		return
	}

	completionID := fmt.Sprintf("chatcmpl-%s", uuid.New().String()[:29])

	if req.Stream {
		handleStreamResponse(w, resp.Body, completionID, modelName, req.Tools)
	} else {
		handleNonStreamResponse(w, resp.Body, completionID, modelName, req.Tools)
	}
}

func handleStreamResponse(w http.ResponseWriter, body io.ReadCloser, completionID, modelName string, tools []model.Tool) {
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")

	flusher, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "Streaming not supported", http.StatusInternalServerError)
		return
	}

	scanner := bufio.NewScanner(body)
	scanner.Buffer(make([]byte, 1024*1024), 1024*1024)
	hasContent := false
	searchRefFilter := filter.NewSearchRefFilter()
	thinkingFilter := &filter.ThinkingFilter{}
	pendingSourcesMarkdown := ""
	pendingImageSearchMarkdown := ""
	totalContentOutputLength := 0
	hasToolCalls := false
	var collectedToolCalls []model.ToolCall
	promptToolBuffer := "" // 用于 prompt 注入模式下缓冲 answer 文本以检测 <tool_call>

	for scanner.Scan() {
		line := scanner.Text()
		logger.LogDebug("[Upstream] %s", line)

		if !strings.HasPrefix(line, "data: ") {
			logger.LogInfo("[DEBUG-Stream] non-data line: %s", truncate(line, 200))
			continue
		}

		payload := strings.TrimPrefix(line, "data: ")
		if payload == "[DONE]" {
			break
		}

		var upstreamData model.UpstreamData
		if err := json.Unmarshal([]byte(payload), &upstreamData); err != nil {
			logger.LogInfo("[DEBUG-Stream] JSON parse error: %v, payload=%s", err, truncate(payload, 300))
			continue
		}

		logger.LogInfo("[DEBUG-Stream] phase=%s delta_content_len=%d edit_content_len=%d", upstreamData.Data.Phase, len(upstreamData.Data.DeltaContent), len(upstreamData.Data.EditContent))

		if upstreamData.Data.Phase == "done" {
			break
		}

		if upstreamData.Data.Phase == "thinking" && upstreamData.Data.DeltaContent != "" {
			isNewThinkingRound := false
			if thinkingFilter.LastPhase != "" && thinkingFilter.LastPhase != "thinking" {
				thinkingFilter.ResetForNewRound()
				thinkingFilter.ThinkingRoundCount++
				isNewThinkingRound = true
			}
			thinkingFilter.LastPhase = "thinking"

			reasoningContent := thinkingFilter.ProcessThinking(upstreamData.Data.DeltaContent)

			if isNewThinkingRound && thinkingFilter.ThinkingRoundCount > 1 && reasoningContent != "" {
				reasoningContent = "\n\n" + reasoningContent
			}

			if reasoningContent != "" {
				thinkingFilter.LastOutputChunk = reasoningContent
				reasoningContent = searchRefFilter.Process(reasoningContent)

				if reasoningContent != "" {
					hasContent = true
					chunk := model.ChatCompletionChunk{
						ID:      completionID,
						Object:  "chat.completion.chunk",
						Created: time.Now().Unix(),
						Model:   modelName,
						Choices: []model.Choice{{
							Index:        0,
							Delta:        &model.Delta{ReasoningContent: reasoningContent},
							FinishReason: nil,
						}},
					}
					data, _ := json.Marshal(chunk)
					fmt.Fprintf(w, "data: %s\n\n", data)
					flusher.Flush()
				}
			}
			continue
		}

		if upstreamData.Data.Phase != "" {
			thinkingFilter.LastPhase = upstreamData.Data.Phase
		}

		editContent := upstreamData.GetEditContent()
		if editContent != "" && filter.IsSearchResultContent(editContent) {
			if results := filter.ParseSearchResults(editContent); len(results) > 0 {
				searchRefFilter.AddSearchResults(results)
				pendingSourcesMarkdown = searchRefFilter.GetSearchResultsMarkdown()
			}
			continue
		}
		if editContent != "" && strings.Contains(editContent, `"search_image"`) {
			textBeforeBlock := filter.ExtractTextBeforeGlmBlock(editContent)
			if textBeforeBlock != "" {
				textBeforeBlock = searchRefFilter.Process(textBeforeBlock)
				if textBeforeBlock != "" {
					hasContent = true
					chunk := model.ChatCompletionChunk{
						ID:      completionID,
						Object:  "chat.completion.chunk",
						Created: time.Now().Unix(),
						Model:   modelName,
						Choices: []model.Choice{{
							Index:        0,
							Delta:        &model.Delta{Content: textBeforeBlock},
							FinishReason: nil,
						}},
					}
					data, _ := json.Marshal(chunk)
					fmt.Fprintf(w, "data: %s\n\n", data)
					flusher.Flush()
				}
			}
			if results := filter.ParseImageSearchResults(editContent); len(results) > 0 {
				pendingImageSearchMarkdown = filter.FormatImageSearchResults(results)
			}
			continue
		}
		if editContent != "" && strings.Contains(editContent, `"mcp"`) {
			textBeforeBlock := filter.ExtractTextBeforeGlmBlock(editContent)
			if textBeforeBlock != "" {
				textBeforeBlock = searchRefFilter.Process(textBeforeBlock)
				if textBeforeBlock != "" {
					hasContent = true
					chunk := model.ChatCompletionChunk{
						ID:      completionID,
						Object:  "chat.completion.chunk",
						Created: time.Now().Unix(),
						Model:   modelName,
						Choices: []model.Choice{{
							Index:        0,
							Delta:        &model.Delta{Content: textBeforeBlock},
							FinishReason: nil,
						}},
					}
					data, _ := json.Marshal(chunk)
					fmt.Fprintf(w, "data: %s\n\n", data)
					flusher.Flush()
				}
			}
			continue
		}
		if editContent != "" && filter.IsSearchToolCall(editContent, upstreamData.Data.Phase) {
			continue
		}
		// 检测用户定义的函数调用(tool_call 阶段,非 mcp/search)
		if upstreamData.Data.Phase == "tool_call" && editContent != "" {
			logger.LogInfo("[ToolCall] phase=%s edit_content=%s", upstreamData.Data.Phase, editContent)
		}
		if len(tools) > 0 && editContent != "" && filter.IsFunctionToolCall(editContent, upstreamData.Data.Phase) {
			if toolCalls := filter.ParseFunctionToolCalls(editContent); len(toolCalls) > 0 {
				for i := range toolCalls {
					if toolCalls[i].ID == "" {
						toolCalls[i].ID = fmt.Sprintf("call_%s", uuid.New().String()[:24])
					}
					toolCalls[i].Index = i
				}
				collectedToolCalls = toolCalls
				hasToolCalls = true

				for _, tc := range toolCalls {
					hasContent = true
					chunk := model.ChatCompletionChunk{
						ID:      completionID,
						Object:  "chat.completion.chunk",
						Created: time.Now().Unix(),
						Model:   modelName,
						Choices: []model.Choice{{
							Index: 0,
							Delta: &model.Delta{
								ToolCalls: []model.ToolCall{tc},
							},
							FinishReason: nil,
						}},
					}
					data, _ := json.Marshal(chunk)
					fmt.Fprintf(w, "data: %s\n\n", data)
					flusher.Flush()
				}
			}
			continue
		}

		if pendingSourcesMarkdown != "" {
			hasContent = true
			chunk := model.ChatCompletionChunk{
				ID:      completionID,
				Object:  "chat.completion.chunk",
				Created: time.Now().Unix(),
				Model:   modelName,
				Choices: []model.Choice{{
					Index:        0,
					Delta:        &model.Delta{Content: pendingSourcesMarkdown},
					FinishReason: nil,
				}},
			}
			data, _ := json.Marshal(chunk)
			fmt.Fprintf(w, "data: %s\n\n", data)
			flusher.Flush()
			pendingSourcesMarkdown = ""
		}
		if pendingImageSearchMarkdown != "" {
			hasContent = true
			chunk := model.ChatCompletionChunk{
				ID:      completionID,
				Object:  "chat.completion.chunk",
				Created: time.Now().Unix(),
				Model:   modelName,
				Choices: []model.Choice{{
					Index:        0,
					Delta:        &model.Delta{Content: pendingImageSearchMarkdown},
					FinishReason: nil,
				}},
			}
			data, _ := json.Marshal(chunk)
			fmt.Fprintf(w, "data: %s\n\n", data)
			flusher.Flush()
			pendingImageSearchMarkdown = ""
		}

		content := ""
		reasoningContent := ""

		if thinkingRemaining := thinkingFilter.Flush(); thinkingRemaining != "" {
			thinkingFilter.LastOutputChunk = thinkingRemaining
			processedRemaining := searchRefFilter.Process(thinkingRemaining)
			if processedRemaining != "" {
				hasContent = true
				chunk := model.ChatCompletionChunk{
					ID:      completionID,
					Object:  "chat.completion.chunk",
					Created: time.Now().Unix(),
					Model:   modelName,
					Choices: []model.Choice{{
						Index:        0,
						Delta:        &model.Delta{ReasoningContent: processedRemaining},
						FinishReason: nil,
					}},
				}
				data, _ := json.Marshal(chunk)
				fmt.Fprintf(w, "data: %s\n\n", data)
				flusher.Flush()
			}
		}

		if pendingSourcesMarkdown != "" && thinkingFilter.HasSeenFirstThinking {
			hasContent = true
			chunk := model.ChatCompletionChunk{
				ID:      completionID,
				Object:  "chat.completion.chunk",
				Created: time.Now().Unix(),
				Model:   modelName,
				Choices: []model.Choice{{
					Index:        0,
					Delta:        &model.Delta{ReasoningContent: pendingSourcesMarkdown},
					FinishReason: nil,
				}},
			}
			data, _ := json.Marshal(chunk)
			fmt.Fprintf(w, "data: %s\n\n", data)
			flusher.Flush()
			pendingSourcesMarkdown = ""
		}

		if upstreamData.Data.Phase == "answer" && upstreamData.Data.DeltaContent != "" {
			content = upstreamData.Data.DeltaContent
		} else if upstreamData.Data.Phase == "answer" && editContent != "" {
			if strings.Contains(editContent, "</details>") {
				reasoningContent = thinkingFilter.ExtractIncrementalThinking(editContent)

				if idx := strings.Index(editContent, "</details>"); idx != -1 {
					afterDetails := editContent[idx+len("</details>"):]
					if strings.HasPrefix(afterDetails, "\n") {
						content = afterDetails[1:]
					} else {
						content = afterDetails
					}
					totalContentOutputLength = len([]rune(content))
				}
			}
		} else if (upstreamData.Data.Phase == "other" || upstreamData.Data.Phase == "tool_call") && editContent != "" {
			fullContent := editContent
			fullContentRunes := []rune(fullContent)

			if len(fullContentRunes) > totalContentOutputLength {
				content = string(fullContentRunes[totalContentOutputLength:])
				totalContentOutputLength = len(fullContentRunes)
			} else {
				content = fullContent
			}
		}

		if reasoningContent != "" {
			reasoningContent = searchRefFilter.Process(reasoningContent) + searchRefFilter.Flush()
		}
		if reasoningContent != "" {
			hasContent = true
			chunk := model.ChatCompletionChunk{
				ID:      completionID,
				Object:  "chat.completion.chunk",
				Created: time.Now().Unix(),
				Model:   modelName,
				Choices: []model.Choice{{
					Index:        0,
					Delta:        &model.Delta{ReasoningContent: reasoningContent},
					FinishReason: nil,
				}},
			}
			data, _ := json.Marshal(chunk)
			fmt.Fprintf(w, "data: %s\n\n", data)
			flusher.Flush()
		}

		if content == "" {
			continue
		}

		content = searchRefFilter.Process(content)
		if content == "" {
			continue
		}

		hasContent = true
		if upstreamData.Data.Phase == "answer" && upstreamData.Data.DeltaContent != "" {
			totalContentOutputLength += len([]rune(content))
		}

		// prompt 注入模式:缓冲 answer 文本,检测 <tool_call> 块
		if len(tools) > 0 {
			promptToolBuffer += content
			// 循环提取完整的 <tool_call>...</tool_call> 块
			for {
				openIdx := strings.Index(promptToolBuffer, "<tool_call>")
				if openIdx == -1 {
					// 无 <tool_call> 标签,全部安全输出
					break
				}
				// 输出 <tool_call> 之前的安全文本
				if openIdx > 0 {
					safeContent := promptToolBuffer[:openIdx]
					promptToolBuffer = promptToolBuffer[openIdx:]
					if safeContent != "" {
						sendContentChunk(w, flusher, completionID, modelName, safeContent)
					}
				}
				// 查找闭合标签:</tool_call>、</think>、或下一个 <tool_call>
				afterOpen := promptToolBuffer[len("<tool_call>"):]
				closeIdx := strings.Index(promptToolBuffer, "</tool_call>")
				thinkCloseIdx := strings.Index(afterOpen, "</think>")
				nextOpenIdx := strings.Index(afterOpen, "<tool_call>")

				// 选择最近的闭合位置
				blockEnd := -1
				if closeIdx != -1 {
					blockEnd = closeIdx + len("</tool_call>")
				}
				if thinkCloseIdx != -1 {
					candidate := len("<tool_call>") + thinkCloseIdx + len("</think>")
					if blockEnd == -1 || candidate < blockEnd {
						blockEnd = candidate
					}
				}
				if nextOpenIdx != -1 {
					// 下一个 <tool_call> 隐式关闭当前块
					candidate := len("<tool_call>") + nextOpenIdx
					if blockEnd == -1 || candidate < blockEnd {
						blockEnd = candidate
					}
				}

				if blockEnd == -1 {
					// 未找到任何闭合标记,等待更多数据
					break
				}

				// 提取完整块
				block := promptToolBuffer[:blockEnd]
				promptToolBuffer = promptToolBuffer[blockEnd:]

				// 解析 tool call
				_, toolCalls := filter.ExtractPromptToolCalls(block)
				if len(toolCalls) > 0 {
					collectedToolCalls = append(collectedToolCalls, toolCalls...)
					hasToolCalls = true
					for _, tc := range toolCalls {
						chunk := model.ChatCompletionChunk{
							ID:      completionID,
							Object:  "chat.completion.chunk",
							Created: time.Now().Unix(),
							Model:   modelName,
							Choices: []model.Choice{{
								Index: 0,
								Delta: &model.Delta{
									ToolCalls: []model.ToolCall{tc},
								},
								FinishReason: nil,
							}},
						}
						data, _ := json.Marshal(chunk)
						fmt.Fprintf(w, "data: %s\n\n", data)
						flusher.Flush()
					}
				}
			}
			continue
		}

		chunk := model.ChatCompletionChunk{
			ID:      completionID,
			Object:  "chat.completion.chunk",
			Created: time.Now().Unix(),
			Model:   modelName,
			Choices: []model.Choice{{
				Index:        0,
				Delta:        &model.Delta{Content: content},
				FinishReason: nil,
			}},
		}

		data, _ := json.Marshal(chunk)
		fmt.Fprintf(w, "data: %s\n\n", data)
		flusher.Flush()
	}

	if err := scanner.Err(); err != nil {
		logger.LogError("[Upstream] scanner error: %v", err)
	}

	// prompt 注入模式:flush 缓冲区中剩余的文本
	if promptToolBuffer != "" {
		// 尝试最后一次提取 tool calls
		cleanContent, toolCalls := filter.ExtractPromptToolCalls(promptToolBuffer)
		if len(toolCalls) > 0 {
			collectedToolCalls = append(collectedToolCalls, toolCalls...)
			hasToolCalls = true
			for _, tc := range toolCalls {
				chunk := model.ChatCompletionChunk{
					ID:      completionID,
					Object:  "chat.completion.chunk",
					Created: time.Now().Unix(),
					Model:   modelName,
					Choices: []model.Choice{{
						Index: 0,
						Delta: &model.Delta{
							ToolCalls: []model.ToolCall{tc},
						},
						FinishReason: nil,
					}},
				}
				data, _ := json.Marshal(chunk)
				fmt.Fprintf(w, "data: %s\n\n", data)
				flusher.Flush()
			}
		}
		if cleanContent != "" {
			sendContentChunk(w, flusher, completionID, modelName, cleanContent)
			hasContent = true
		}
		promptToolBuffer = ""
	}

	if remaining := searchRefFilter.Flush(); remaining != "" {
		hasContent = true
		chunk := model.ChatCompletionChunk{
			ID:      completionID,
			Object:  "chat.completion.chunk",
			Created: time.Now().Unix(),
			Model:   modelName,
			Choices: []model.Choice{{
				Index:        0,
				Delta:        &model.Delta{Content: remaining},
				FinishReason: nil,
			}},
		}
		data, _ := json.Marshal(chunk)
		fmt.Fprintf(w, "data: %s\n\n", data)
		flusher.Flush()
	}

	if !hasContent {
		logger.LogError("Stream response 200 but no content received")
	}

	stopReason := "stop"
	if hasToolCalls && len(collectedToolCalls) > 0 {
		stopReason = "tool_calls"
	}
	finalChunk := model.ChatCompletionChunk{
		ID:      completionID,
		Object:  "chat.completion.chunk",
		Created: time.Now().Unix(),
		Model:   modelName,
		Choices: []model.Choice{{
			Index:        0,
			Delta:        &model.Delta{},
			FinishReason: &stopReason,
		}},
	}

	data, _ := json.Marshal(finalChunk)
	fmt.Fprintf(w, "data: %s\n\n", data)
	fmt.Fprintf(w, "data: [DONE]\n\n")
	flusher.Flush()
}

func handleNonStreamResponse(w http.ResponseWriter, body io.ReadCloser, completionID, modelName string, tools []model.Tool) {
	scanner := bufio.NewScanner(body)
	scanner.Buffer(make([]byte, 1024*1024), 1024*1024)
	var chunks []string
	var reasoningChunks []string
	thinkingFilter := &filter.ThinkingFilter{}
	searchRefFilter := filter.NewSearchRefFilter()
	hasThinking := false
	pendingSourcesMarkdown := ""
	pendingImageSearchMarkdown := ""
	var collectedToolCalls []model.ToolCall

	for scanner.Scan() {
		line := scanner.Text()
		if !strings.HasPrefix(line, "data: ") {
			continue
		}

		payload := strings.TrimPrefix(line, "data: ")
		if payload == "[DONE]" {
			break
		}

		var upstreamData model.UpstreamData
		if err := json.Unmarshal([]byte(payload), &upstreamData); err != nil {
			logger.LogInfo("[DEBUG-NonStream] JSON parse error: %v, payload=%s", err, truncate(payload, 200))
			continue
		}

		logger.LogInfo("[DEBUG-NonStream] phase=%s delta_content_len=%d edit_content_len=%d", upstreamData.Data.Phase, len(upstreamData.Data.DeltaContent), len(upstreamData.Data.EditContent))

		if upstreamData.Data.Phase == "done" {
			break
		}

		if upstreamData.Data.Phase == "thinking" && upstreamData.Data.DeltaContent != "" {
			if thinkingFilter.LastPhase != "" && thinkingFilter.LastPhase != "thinking" {
				thinkingFilter.ResetForNewRound()
				thinkingFilter.ThinkingRoundCount++
				if thinkingFilter.ThinkingRoundCount > 1 {
					reasoningChunks = append(reasoningChunks, "\n\n")
				}
			}
			thinkingFilter.LastPhase = "thinking"

			hasThinking = true
			reasoningContent := thinkingFilter.ProcessThinking(upstreamData.Data.DeltaContent)
			if reasoningContent != "" {
				thinkingFilter.LastOutputChunk = reasoningContent
				reasoningChunks = append(reasoningChunks, reasoningContent)
			}
			continue
		}

		if upstreamData.Data.Phase != "" {
			thinkingFilter.LastPhase = upstreamData.Data.Phase
		}

		editContent := upstreamData.GetEditContent()
		if editContent != "" && filter.IsSearchResultContent(editContent) {
			if results := filter.ParseSearchResults(editContent); len(results) > 0 {
				searchRefFilter.AddSearchResults(results)
				pendingSourcesMarkdown = searchRefFilter.GetSearchResultsMarkdown()
			}
			continue
		}
		if editContent != "" && strings.Contains(editContent, `"search_image"`) {
			textBeforeBlock := filter.ExtractTextBeforeGlmBlock(editContent)
			if textBeforeBlock != "" {
				chunks = append(chunks, textBeforeBlock)
			}
			if results := filter.ParseImageSearchResults(editContent); len(results) > 0 {
				pendingImageSearchMarkdown = filter.FormatImageSearchResults(results)
			}
			continue
		}
		if editContent != "" && strings.Contains(editContent, `"mcp"`) {
			textBeforeBlock := filter.ExtractTextBeforeGlmBlock(editContent)
			if textBeforeBlock != "" {
				chunks = append(chunks, textBeforeBlock)
			}
			continue
		}
		if editContent != "" && filter.IsSearchToolCall(editContent, upstreamData.Data.Phase) {
			continue
		}
		// 检测用户定义的函数调用
		if upstreamData.Data.Phase == "tool_call" && editContent != "" {
			logger.LogInfo("[ToolCall] phase=%s edit_content=%s", upstreamData.Data.Phase, editContent)
		}
		if len(tools) > 0 && editContent != "" && filter.IsFunctionToolCall(editContent, upstreamData.Data.Phase) {
			if toolCalls := filter.ParseFunctionToolCalls(editContent); len(toolCalls) > 0 {
				for i := range toolCalls {
					if toolCalls[i].ID == "" {
						toolCalls[i].ID = fmt.Sprintf("call_%s", uuid.New().String()[:24])
					}
					toolCalls[i].Index = i
				}
				collectedToolCalls = toolCalls
			}
			continue
		}

		if pendingSourcesMarkdown != "" {
			if hasThinking {
				reasoningChunks = append(reasoningChunks, pendingSourcesMarkdown)
			} else {
				chunks = append(chunks, pendingSourcesMarkdown)
			}
			pendingSourcesMarkdown = ""
		}
		if pendingImageSearchMarkdown != "" {
			chunks = append(chunks, pendingImageSearchMarkdown)
			pendingImageSearchMarkdown = ""
		}

		content := ""
		if upstreamData.Data.Phase == "answer" && upstreamData.Data.DeltaContent != "" {
			content = upstreamData.Data.DeltaContent
		} else if upstreamData.Data.Phase == "answer" && editContent != "" {
			if strings.Contains(editContent, "</details>") {
				reasoningContent := thinkingFilter.ExtractIncrementalThinking(editContent)
				if reasoningContent != "" {
					reasoningChunks = append(reasoningChunks, reasoningContent)
				}

				if idx := strings.Index(editContent, "</details>"); idx != -1 {
					afterDetails := editContent[idx+len("</details>"):]
					if strings.HasPrefix(afterDetails, "\n") {
						content = afterDetails[1:]
					} else {
						content = afterDetails
					}
				}
			}
		} else if (upstreamData.Data.Phase == "other" || upstreamData.Data.Phase == "tool_call") && editContent != "" {
			content = editContent
		}

		if content != "" {
			chunks = append(chunks, content)
		}
	}

	fullContent := strings.Join(chunks, "")
	fullContent = searchRefFilter.Process(fullContent) + searchRefFilter.Flush()
	fullReasoning := strings.Join(reasoningChunks, "")
	fullReasoning = searchRefFilter.Process(fullReasoning) + searchRefFilter.Flush()

	// prompt 注入模式:从 answer 文本中提取 <tool_call> 块
	if len(tools) > 0 && len(collectedToolCalls) == 0 {
		cleanContent, promptToolCalls := filter.ExtractPromptToolCalls(fullContent)
		if len(promptToolCalls) > 0 {
			collectedToolCalls = promptToolCalls
			fullContent = cleanContent
		}
	}

	if fullContent == "" && len(collectedToolCalls) == 0 {
		logger.LogError("Non-stream response 200 but no content received")
	}

	stopReason := "stop"
	if len(collectedToolCalls) > 0 {
		stopReason = "tool_calls"
	}
	response := model.ChatCompletionResponse{
		ID:      completionID,
		Object:  "chat.completion",
		Created: time.Now().Unix(),
		Model:   modelName,
		Choices: []model.Choice{{
			Index: 0,
			Message: &model.MessageResp{
				Role:             "assistant",
				Content:          fullContent,
				ReasoningContent: fullReasoning,
				ToolCalls:        collectedToolCalls,
			},
			FinishReason: &stopReason,
		}},
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}

// sendContentChunk 发送一个 content SSE chunk
func sendContentChunk(w http.ResponseWriter, flusher http.Flusher, completionID, modelName, content string) {
	chunk := model.ChatCompletionChunk{
		ID:      completionID,
		Object:  "chat.completion.chunk",
		Created: time.Now().Unix(),
		Model:   modelName,
		Choices: []model.Choice{{
			Index:        0,
			Delta:        &model.Delta{Content: content},
			FinishReason: nil,
		}},
	}
	data, _ := json.Marshal(chunk)
	fmt.Fprintf(w, "data: %s\n\n", data)
	flusher.Flush()
}

func truncate(s string, maxLen int) string {
	if len(s) <= maxLen {
		return s
	}
	return s[:maxLen] + "..."
}