-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2060 lines (1749 loc) · 94.7 KB
/
Copy pathmain.py
File metadata and controls
2060 lines (1749 loc) · 94.7 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
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Toolify: Empower any LLM with function calling capabilities.
# Copyright (C) 2025 FunnyCups (https://github.com/funnycups)
"""
Main FastAPI application for Toolify middleware.
Refactored for better modularity and maintainability.
"""
import os
import json
import uuid
import httpx
import traceback
import time
import logging
import yaml
from typing import List, Dict, Any, Optional
from fastapi import FastAPI, Request, Header, HTTPException, Depends, status
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from pydantic import ValidationError
# Toolify modules
from toolify_core.models import ChatCompletionRequest, AnthropicMessage, GeminiRequest, Tool, ToolFunction
from toolify_core.token_counter import TokenCounter
from config_loader import config_loader, AppConfig
from admin_auth import (
LoginRequest, LoginResponse, verify_admin_token,
verify_password, create_access_token, get_admin_credentials
)
from toolify_core.function_calling import (
generate_function_prompt,
generate_random_trigger_signal,
parse_function_calls_xml
)
from toolify_core.tool_mapping import store_tool_call_mapping
# Format converters (new unified system)
from toolify_core.converters import (
ConverterFactory,
OpenAIConverter,
AnthropicConverter,
GeminiConverter
)
# Capability detection
from toolify_core.capability_detector import (
DetectorFactory,
OpenAICapabilityDetector,
AnthropicCapabilityDetector,
GeminiCapabilityDetector
)
# Backward compatibility - keep old adapter functions
from toolify_core.anthropic_adapter import (
anthropic_to_openai_request,
openai_to_anthropic_response,
stream_openai_to_anthropic
)
from toolify_core.message_processor import (
preprocess_messages,
validate_message_structure,
safe_process_tool_choice
)
from toolify_core.upstream_router import find_upstream
from toolify_core.streaming_proxy import stream_proxy_with_fc_transform
logger = logging.getLogger(__name__)
def build_upstream_url(base_url: str, endpoint: str) -> str:
"""
智能构建上游URL,自动处理 /v1 路径
Args:
base_url: 上游基础URL
endpoint: 端点路径(如 /chat/completions, /messages)
Returns:
完整的URL
"""
# 移除尾部斜杠
base_url = base_url.rstrip('/')
# 如果 endpoint 不以 / 开头,添加
if not endpoint.startswith('/'):
endpoint = '/' + endpoint
# 智能处理 /v1 前缀
# 如果 base_url 已经包含 /v1, /v1beta 等,直接拼接
if any(base_url.endswith(suffix) for suffix in ['/v1', '/v1beta', '/v1alpha']):
return base_url + endpoint
# 如果 endpoint 需要 /v1 但 base_url 没有,自动添加
# OpenAI 端点
if endpoint in ['/chat/completions', '/completions', '/models', '/embeddings']:
if '/v1' not in base_url:
return base_url + '/v1' + endpoint
# Anthropic 端点 - 已经包含 /v1/messages
if endpoint.startswith('/v1/'):
return base_url + endpoint
# 默认直接拼接
return base_url + endpoint
async def convert_anthropic_stream_to_gemini(line_iterator, model: str):
"""将 Anthropic SSE 流转换为 Gemini SSE 格式"""
accumulated_text = ""
async for line in line_iterator:
if not line or not line.strip():
continue
# Anthropic 使用 event: 和 data: 格式
if line.startswith("event:"):
event_type = line[6:].strip()
logger.debug(f"🔧 Anthropic event: {event_type}")
continue
if line.startswith("data:"):
data_str = line[5:].strip()
try:
data = json.loads(data_str)
event_type = data.get("type")
# 处理 content_block_delta 事件(包含文本内容)
if event_type == "content_block_delta":
delta = data.get("delta", {})
if delta.get("type") == "text_delta":
text = delta.get("text", "")
accumulated_text += text
# 发送 Gemini 格式的chunk
gemini_chunk = {
"candidates": [{
"content": {
"parts": [{"text": text}],
"role": "model"
},
"index": 0
}]
}
yield f"data: {json.dumps(gemini_chunk, ensure_ascii=False)}\n\n"
# 处理 message_stop 事件(流结束)
elif event_type == "message_stop":
# 发送最后的 chunk 带 finishReason
gemini_final = {
"candidates": [{
"content": {
"parts": [{"text": ""}],
"role": "model"
},
"finishReason": "STOP",
"index": 0
}]
}
yield f"data: {json.dumps(gemini_final, ensure_ascii=False)}\n\n"
logger.debug(f"🔧 Anthropic → Gemini stream completed, total text: {len(accumulated_text)} chars")
break
except json.JSONDecodeError:
logger.debug(f"🔧 Skipping non-JSON line: {line[:100]}")
continue
async def convert_openai_stream_to_gemini(line_iterator, model: str):
"""将 OpenAI SSE 流转换为 Gemini SSE 格式"""
accumulated_text = ""
async for line in line_iterator:
if not line or not line.strip():
continue
if line.startswith("data:"):
data_str = line[5:].strip()
if data_str == "[DONE]":
# OpenAI 流结束
gemini_final = {
"candidates": [{
"content": {
"parts": [{"text": ""}],
"role": "model"
},
"finishReason": "STOP",
"index": 0
}]
}
yield f"data: {json.dumps(gemini_final, ensure_ascii=False)}\n\n"
logger.debug(f"🔧 OpenAI → Gemini stream completed, total text: {len(accumulated_text)} chars")
break
try:
data = json.loads(data_str)
choices = data.get("choices", [])
if choices:
choice = choices[0]
delta = choice.get("delta", {})
content = delta.get("content", "")
if content:
accumulated_text += content
# 发送 Gemini 格式的chunk
gemini_chunk = {
"candidates": [{
"content": {
"parts": [{"text": content}],
"role": "model"
},
"index": 0
}]
}
yield f"data: {json.dumps(gemini_chunk, ensure_ascii=False)}\n\n"
# 处理 finish_reason
finish_reason = choice.get("finish_reason")
if finish_reason:
gemini_reason = "STOP" if finish_reason == "stop" else "MAX_TOKENS"
gemini_final = {
"candidates": [{
"content": {
"parts": [{"text": ""}],
"role": "model"
},
"finishReason": gemini_reason,
"index": 0
}]
}
yield f"data: {json.dumps(gemini_final, ensure_ascii=False)}\n\n"
except json.JSONDecodeError:
logger.debug(f"🔧 Skipping non-JSON line: {line[:100]}")
continue
# Global variables
app_config: AppConfig = None
MODEL_TO_SERVICE_MAPPING: Dict[str, List[Dict[str, Any]]] = {}
ALIAS_MAPPING: Dict[str, List[str]] = {}
DEFAULT_SERVICE: Dict[str, Any] = {}
ALLOWED_CLIENT_KEYS: List[str] = []
GLOBAL_TRIGGER_SIGNAL: str = ""
token_counter = TokenCounter()
def load_runtime_config(reload: bool = False):
"""Load or reload runtime configuration and derived globals."""
global app_config, MODEL_TO_SERVICE_MAPPING, ALIAS_MAPPING, DEFAULT_SERVICE
global ALLOWED_CLIENT_KEYS, GLOBAL_TRIGGER_SIGNAL
if reload:
app_config = config_loader.reload_config()
logger.info("🔄 Reloaded configuration from disk")
else:
app_config = config_loader.load_config()
log_level_str = app_config.features.log_level
if log_level_str == "DISABLED":
log_level = logging.CRITICAL + 1
else:
log_level = getattr(logging, log_level_str, logging.INFO)
# Configure logging (avoid adding duplicate handlers on reload)
root_logger = logging.getLogger()
if not root_logger.handlers:
logging.basicConfig(
level=log_level,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
else:
root_logger.setLevel(log_level)
logger.info(f"✅ Configuration loaded successfully: {config_loader.config_path}")
logger.info(f"📊 Configured {len(app_config.upstream_services)} upstream services")
logger.info(f"🔑 Configured {len(app_config.client_authentication.allowed_keys)} client keys")
MODEL_TO_SERVICE_MAPPING, ALIAS_MAPPING = config_loader.get_model_to_service_mapping()
DEFAULT_SERVICE = config_loader.get_default_service()
ALLOWED_CLIENT_KEYS = config_loader.get_allowed_client_keys()
GLOBAL_TRIGGER_SIGNAL = generate_random_trigger_signal()
logger.info(f"🎯 Configured {len(MODEL_TO_SERVICE_MAPPING)} model mappings")
if ALIAS_MAPPING:
logger.info(f"🔄 Configured {len(ALIAS_MAPPING)} model aliases: {list(ALIAS_MAPPING.keys())}")
logger.info(f"🔄 Default service: {DEFAULT_SERVICE['name']}")
# Initialize FastAPI app (don't load config at module level for better IDE support)
app = FastAPI()
http_client = httpx.AsyncClient()
# Register converters
ConverterFactory.register_converter("openai", OpenAIConverter)
ConverterFactory.register_converter("anthropic", AnthropicConverter)
ConverterFactory.register_converter("gemini", GeminiConverter)
logger.info("✅ Registered format converters: OpenAI, Anthropic, Gemini")
# Register capability detectors
DetectorFactory.register_detector("openai", OpenAICapabilityDetector)
DetectorFactory.register_detector("anthropic", AnthropicCapabilityDetector)
DetectorFactory.register_detector("gemini", GeminiCapabilityDetector)
logger.info("✅ Registered capability detectors: OpenAI, Anthropic, Gemini")
# Flag to track if configuration is loaded
_config_loaded = False
def ensure_config_loaded():
"""Ensure configuration is loaded before handling requests."""
global _config_loaded
if not _config_loaded:
try:
load_runtime_config()
_config_loaded = True
logger.info("✅ Configuration loaded successfully on first request")
except Exception as e:
logger.error(f"❌ Configuration loading failed: {type(e).__name__}")
logger.error(f"❌ Error details: {str(e)}")
logger.error("💡 Please ensure config.yaml file exists and is properly formatted")
raise HTTPException(
status_code=500,
detail=f"Server configuration error: {str(e)}"
)
# Add CORS middleware for development
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000", "http://localhost:5173"], # Vite dev server
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.middleware("http")
async def debug_middleware(request: Request, call_next):
"""Middleware for debugging - logs response status."""
response = await call_next(request)
if response.status_code == 422:
logger.error(f"🔍 ❌ Validation failed for {request.method} {request.url.path}")
logger.error(f"🔍 Response status code: 422 (Pydantic validation failure)")
logger.error(f"🔍 Check the detailed error logs above for validation details")
return response
@app.exception_handler(ValidationError)
async def validation_exception_handler(request: Request, exc: ValidationError):
"""Handle Pydantic validation errors with detailed error information."""
logger.error("=" * 80)
logger.error("❌ PYDANTIC VALIDATION ERROR DETAILS")
logger.error("=" * 80)
logger.error(f"📍 Request URL: {request.url}")
logger.error(f"📍 Request Method: {request.method}")
logger.error(f"📍 Model being validated: {exc.title if hasattr(exc, 'title') else 'Unknown'}")
# Log request headers
logger.error(f"📋 Request Headers:")
for header_name, header_value in request.headers.items():
if header_name.lower() in ["authorization", "x-api-key"]:
masked_value = "***" + header_value[-8:] if len(header_value) > 8 else "***"
logger.error(f" {header_name}: {masked_value}")
else:
logger.error(f" {header_name}: {header_value}")
# Try to read and log the raw request body
try:
body_bytes = await request.body()
body_text = body_bytes.decode('utf-8')
logger.error(f"📦 Raw Request Body (first 2000 chars):")
logger.error(body_text[:2000])
if len(body_text) > 2000:
logger.error(f" ... (total {len(body_text)} chars)")
# Try to parse as JSON for better readability
try:
import json
body_json = json.loads(body_text)
logger.error(f"📦 Parsed Request JSON:")
logger.error(f" Keys: {list(body_json.keys())}")
logger.error(f" Model: {body_json.get('model', 'N/A')}")
logger.error(f" Messages count: {len(body_json.get('messages', []))}")
logger.error(f" Max tokens: {body_json.get('max_tokens', 'NOT PROVIDED')}")
logger.error(f" Stream: {body_json.get('stream', 'N/A')}")
logger.error(f" Tools: {len(body_json.get('tools', []))} tools")
except:
pass
except Exception as e:
logger.error(f"⚠️ Could not read request body: {e}")
logger.error(f"🔴 Validation Errors ({len(exc.errors())} error(s)):")
for i, error in enumerate(exc.errors(), 1):
logger.error(f" Error {i}:")
logger.error(f" Location: {' -> '.join(str(loc) for loc in error.get('loc', []))}")
logger.error(f" Message: {error.get('msg')}")
logger.error(f" Type: {error.get('type')}")
if 'input' in error:
input_repr = repr(error['input'])
logger.error(f" Input: {input_repr[:300]}{'...' if len(input_repr) > 300 else ''}")
logger.error("=" * 80)
# Build user-friendly error message
error_messages = []
for error in exc.errors():
field = ' -> '.join(str(loc) for loc in error.get('loc', []))
msg = error.get('msg', 'Validation error')
error_messages.append(f"{field}: {msg}")
return JSONResponse(
status_code=422,
content={
"error": {
"message": "Request validation failed: " + "; ".join(error_messages[:3]),
"type": "invalid_request_error",
"code": "invalid_request",
"details": exc.errors()
}
}
)
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
"""Handle all uncaught exceptions."""
logger.error(f"❌ Unhandled exception: {exc}")
logger.error(f"❌ Request URL: {request.url}")
logger.error(f"❌ Exception type: {type(exc).__name__}")
logger.error(f"❌ Error stack: {traceback.format_exc()}")
return JSONResponse(
status_code=500,
content={
"error": {
"message": "Internal server error",
"type": "server_error",
"code": "internal_error"
}
}
)
async def verify_api_key(authorization: str = Header(...)):
"""Dependency: verify client API key."""
logger.debug(f"🔐 API Key Verification")
logger.debug(f" Authorization header: {authorization[:20]}...{authorization[-8:] if len(authorization) > 20 else authorization}")
if not authorization:
logger.error("❌ Missing Authorization header")
raise HTTPException(status_code=401, detail="Missing Authorization header")
# Extract key
if authorization.startswith("Bearer "):
client_key = authorization[7:]
else:
# Some clients might not include "Bearer " prefix
client_key = authorization
logger.debug(f" Extracted key: ***{client_key[-8:] if len(client_key) > 8 else '***'}")
if app_config.features.key_passthrough:
logger.debug(f" Mode: Key passthrough (validation skipped)")
return client_key
logger.debug(f" Mode: Validating against {len(ALLOWED_CLIENT_KEYS)} allowed keys")
logger.debug(f" Allowed keys: {[f'***{k[-8:]}' for k in ALLOWED_CLIENT_KEYS]}")
if client_key not in ALLOWED_CLIENT_KEYS:
logger.error(f"❌ Unauthorized key: ***{client_key[-8:]}")
raise HTTPException(status_code=401, detail="Unauthorized")
logger.debug(f"✅ Key validated successfully")
return client_key
@app.get("/")
def read_root():
"""Root endpoint showing service status."""
ensure_config_loaded()
return {
"status": "OpenAI Function Call Middleware is running",
"config": {
"upstream_services_count": len(app_config.upstream_services),
"client_keys_count": len(app_config.client_authentication.allowed_keys),
"models_count": len(MODEL_TO_SERVICE_MAPPING),
"features": {
"function_calling": app_config.features.enable_function_calling,
"log_level": app_config.features.log_level,
"convert_developer_to_system": app_config.features.convert_developer_to_system,
"random_trigger": True
}
}
}
@app.post("/v1/chat/completions")
async def chat_completions(
request: Request,
body: ChatCompletionRequest,
_api_key: str = Depends(verify_api_key)
):
"""Main chat completion endpoint, proxy and inject function calling capabilities."""
ensure_config_loaded()
start_time = time.time()
# Count input tokens
prompt_tokens = token_counter.count_tokens(body.messages, body.model)
logger.info(f"📊 Request to {body.model} - Input tokens: {prompt_tokens}")
try:
logger.debug(f"🔧 Received request, model: {body.model}")
logger.debug(f"🔧 Number of messages: {len(body.messages)}")
logger.debug(f"🔧 Number of tools: {len(body.tools) if body.tools else 0}")
logger.debug(f"🔧 Streaming: {body.stream}")
upstreams, actual_model = find_upstream(
body.model,
MODEL_TO_SERVICE_MAPPING,
ALIAS_MAPPING,
DEFAULT_SERVICE,
app_config.features.model_passthrough,
app_config.upstream_services
)
logger.debug(f"🔧 Found {len(upstreams)} upstream service(s) for model {body.model}")
for i, srv in enumerate(upstreams):
logger.debug(f"🔧 Service {i + 1}: {srv['name']} (priority: {srv.get('priority', 0)})")
logger.debug(f"🔧 Starting message preprocessing, original message count: {len(body.messages)}")
processed_messages = preprocess_messages(
body.messages,
GLOBAL_TRIGGER_SIGNAL,
app_config.features.convert_developer_to_system
)
logger.debug(f"🔧 Preprocessing completed, processed message count: {len(processed_messages)}")
if not validate_message_structure(processed_messages, app_config.features.convert_developer_to_system):
logger.error(f"❌ Message structure validation failed, but continuing processing")
request_body_dict = body.model_dump(exclude_unset=True)
request_body_dict["model"] = actual_model
request_body_dict["messages"] = processed_messages
is_fc_enabled = app_config.features.enable_function_calling
has_tools_in_request = bool(body.tools)
has_function_call = is_fc_enabled and has_tools_in_request
logger.debug(f"🔧 Request body constructed, message count: {len(processed_messages)}")
except Exception as e:
logger.error(f"❌ Request preprocessing failed: {str(e)}")
logger.error(f"❌ Error type: {type(e).__name__}")
if hasattr(app_config, 'debug') and app_config.debug:
logger.error(f"❌ Error stack: {traceback.format_exc()}")
return JSONResponse(
status_code=422,
content={
"error": {
"message": "Invalid request format",
"type": "invalid_request_error",
"code": "invalid_request"
}
}
)
if has_function_call:
logger.debug(f"🔧 Using global trigger signal for this request: {GLOBAL_TRIGGER_SIGNAL}")
# Check if function calling injection is enabled for this upstream
upstream_fc_enabled = upstreams[0].get('inject_function_calling')
if upstream_fc_enabled is None:
# Inherit from global setting
upstream_fc_enabled = app_config.features.enable_function_calling
if not upstream_fc_enabled:
logger.info(f"🔧 Function calling injection disabled for upstream '{upstreams[0]['name']}', passing through tools to native API")
# Don't inject, let upstream handle tools natively
has_function_call = False
else:
function_prompt, _ = generate_function_prompt(
body.tools,
GLOBAL_TRIGGER_SIGNAL,
app_config.features.prompt_template
)
tool_choice_prompt = safe_process_tool_choice(body.tool_choice)
if tool_choice_prompt:
function_prompt += tool_choice_prompt
# 打印 prompt 大小信息
prompt_chars = len(function_prompt)
estimated_tokens = prompt_chars // 4 # 粗略估算
logger.info("=" * 80)
logger.info(f"📏 Function Calling Prompt Size:")
logger.info(f" Upstream: {upstreams[0]['name']}")
logger.info(f" Tools count: {len(body.tools)}")
logger.info(f" Prompt characters: {prompt_chars:,}")
logger.info(f" Estimated tokens: ~{estimated_tokens:,}")
logger.info(f" Original messages: {len(body.messages)}")
logger.info("=" * 80)
system_message = {"role": "system", "content": function_prompt}
request_body_dict["messages"].insert(0, system_message)
# 计算注入后的总大小
total_chars = sum(len(str(m.get('content', ''))) for m in request_body_dict["messages"])
logger.info(f"📏 Total request size after injection: {total_chars:,} characters (~{total_chars//4:,} tokens)")
logger.info(f"📏 Total messages after injection: {len(request_body_dict['messages'])}")
if "tools" in request_body_dict:
del request_body_dict["tools"]
if "tool_choice" in request_body_dict:
del request_body_dict["tool_choice"]
elif has_tools_in_request and not is_fc_enabled:
logger.info(f"🔧 Function calling is disabled by configuration, ignoring 'tools' and 'tool_choice' in request.")
if "tools" in request_body_dict:
del request_body_dict["tools"]
if "tool_choice" in request_body_dict:
del request_body_dict["tool_choice"]
# Try each upstream service by priority until one succeeds
last_error = None
if not body.stream:
# Non-streaming: try each upstream with failover
for upstream_idx, upstream in enumerate(upstreams):
upstream_url = build_upstream_url(upstream['base_url'], '/chat/completions')
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {_api_key}" if app_config.features.key_passthrough else f"Bearer {upstream['api_key']}",
"Accept": "application/json"
}
logger.info(
f"📝 Attempting upstream {upstream_idx + 1}/{len(upstreams)}: {upstream['name']} (priority: {upstream.get('priority', 0)})")
logger.info(
f"📝 Model: {request_body_dict.get('model', 'unknown')}, Messages: {len(request_body_dict.get('messages', []))}")
try:
logger.debug(f"🔧 Sending upstream request to: {upstream_url}")
logger.debug(f"🔧 has_function_call: {has_function_call}")
logger.debug(f"🔧 Request body contains tools: {bool(body.tools)}")
upstream_response = await http_client.post(
upstream_url, json=request_body_dict, headers=headers, timeout=app_config.server.timeout
)
upstream_response.raise_for_status()
# 添加响应内容检查,防止空响应或非JSON响应
response_text = upstream_response.text
print(f"\n{'='*80}")
print(f"🔍 UPSTREAM NON-STREAMING RESPONSE")
print(f"{'='*80}")
print(f"Status: {upstream_response.status_code}")
print(f"Headers: {dict(upstream_response.headers)}")
print(f"Body length: {len(response_text)} bytes")
print(f"Body (first 1000 chars):\n{response_text[:1000]}")
if len(response_text) > 1000:
print(f"... (total {len(response_text)} bytes)")
print(f"{'='*80}\n")
logger.debug(f"🔧 Upstream response status code: {upstream_response.status_code}")
logger.debug(f"🔧 Upstream response length: {len(response_text)} bytes")
if not response_text or response_text.strip() == "":
logger.error(f"❌ Upstream {upstream['name']} returned empty response body with 200 status")
raise ValueError("Empty response from upstream service")
try:
response_json = upstream_response.json()
except json.JSONDecodeError as json_err:
logger.error(f"❌ Failed to parse JSON from {upstream['name']}")
logger.error(f"❌ Response content (first 500 chars): {response_text[:500]}")
logger.error(f"❌ Content-Type: {upstream_response.headers.get('content-type', 'unknown')}")
raise ValueError(f"Invalid JSON response: {json_err}")
# Count output tokens and handle usage
completion_text = ""
if response_json.get("choices") and len(response_json["choices"]) > 0:
content = response_json["choices"][0].get("message", {}).get("content")
if content:
completion_text = content
# Calculate our estimated tokens
estimated_completion_tokens = token_counter.count_text_tokens(completion_text,
body.model) if completion_text else 0
estimated_prompt_tokens = prompt_tokens
estimated_total_tokens = estimated_prompt_tokens + estimated_completion_tokens
elapsed_time = time.time() - start_time
# Check if upstream provided usage and respect it
upstream_usage = response_json.get("usage", {})
if upstream_usage:
# Preserve upstream's usage structure and only replace zero values
final_usage = upstream_usage.copy()
# Replace zero or missing values with our estimates
if not final_usage.get("prompt_tokens") or final_usage.get("prompt_tokens") == 0:
final_usage["prompt_tokens"] = estimated_prompt_tokens
logger.debug(f"🔧 Replaced zero/missing prompt_tokens with estimate: {estimated_prompt_tokens}")
if not final_usage.get("completion_tokens") or final_usage.get("completion_tokens") == 0:
final_usage["completion_tokens"] = estimated_completion_tokens
logger.debug(
f"🔧 Replaced zero/missing completion_tokens with estimate: {estimated_completion_tokens}")
if not final_usage.get("total_tokens") or final_usage.get("total_tokens") == 0:
final_usage["total_tokens"] = final_usage.get("prompt_tokens",
estimated_prompt_tokens) + final_usage.get(
"completion_tokens", estimated_completion_tokens)
logger.debug(
f"🔧 Replaced zero/missing total_tokens with calculated value: {final_usage['total_tokens']}")
response_json["usage"] = final_usage
logger.debug(f"🔧 Preserved upstream usage with replacements: {final_usage}")
else:
# No upstream usage, provide our estimates
response_json["usage"] = {
"prompt_tokens": estimated_prompt_tokens,
"completion_tokens": estimated_completion_tokens,
"total_tokens": estimated_total_tokens
}
logger.debug(f"🔧 No upstream usage found, using estimates")
# Log token statistics
actual_usage = response_json["usage"]
logger.info("=" * 60)
logger.info(f"📊 Token Usage Statistics - Model: {body.model}")
logger.info(f" Input Tokens: {actual_usage.get('prompt_tokens', 0)}")
logger.info(f" Output Tokens: {actual_usage.get('completion_tokens', 0)}")
logger.info(f" Total Tokens: {actual_usage.get('total_tokens', 0)}")
logger.info(f" Duration: {elapsed_time:.2f}s")
logger.info("=" * 60)
if has_function_call:
content = response_json["choices"][0]["message"]["content"]
logger.debug(f"🔧 Complete response content: {repr(content)}")
parsed_tools = parse_function_calls_xml(content, GLOBAL_TRIGGER_SIGNAL)
logger.debug(f"🔧 XML parsing result: {parsed_tools}")
if parsed_tools:
logger.debug(f"🔧 Successfully parsed {len(parsed_tools)} tool calls")
tool_calls = []
for tool in parsed_tools:
tool_call_id = f"call_{uuid.uuid4().hex}"
store_tool_call_mapping(
tool_call_id,
tool["name"],
tool["args"],
f"Calling tool {tool['name']}"
)
tool_calls.append({
"id": tool_call_id,
"type": "function",
"function": {
"name": tool["name"],
"arguments": json.dumps(tool["args"])
}
})
logger.debug(f"🔧 Converted tool_calls: {tool_calls}")
response_json["choices"][0]["message"] = {
"role": "assistant",
"content": None,
"tool_calls": tool_calls,
}
response_json["choices"][0]["finish_reason"] = "tool_calls"
logger.debug(f"🔧 Function call conversion completed")
else:
logger.debug(f"🔧 No tool calls detected, returning original content (including think blocks)")
else:
logger.debug(f"🔧 No function calls detected or conversion conditions not met")
return JSONResponse(content=response_json)
except httpx.HTTPStatusError as e:
logger.warning(f"⚠️ Upstream {upstream['name']} failed: status_code={e.response.status_code}")
logger.debug(f"🔧 Error details: {e.response.text}")
last_error = e
# Check if we should retry with next upstream
# Don't retry for client errors (400, 401, 403) - these won't succeed with different upstream
if e.response.status_code in [400, 401, 403]:
logger.error(f"❌ Client error from {upstream['name']}, not retrying other upstreams")
if e.response.status_code == 400:
error_response = {
"error": {"message": "Invalid request parameters", "type": "invalid_request_error",
"code": "bad_request"}}
elif e.response.status_code == 401:
error_response = {"error": {"message": "Authentication failed", "type": "authentication_error",
"code": "unauthorized"}}
elif e.response.status_code == 403:
error_response = {
"error": {"message": "Access forbidden", "type": "permission_error", "code": "forbidden"}}
return JSONResponse(content=error_response, status_code=e.response.status_code)
# For 429 and 5xx errors, try next upstream if available
if upstream_idx < len(upstreams) - 1:
logger.info(f"🔄 Trying next upstream service (failover)...")
continue
else:
# All upstreams failed
logger.error(f"❌ All {len(upstreams)} upstream services failed")
if e.response.status_code == 429:
error_response = {
"error": {"message": "Rate limit exceeded on all upstreams", "type": "rate_limit_error",
"code": "rate_limit_exceeded"}}
elif e.response.status_code >= 500:
error_response = {"error": {"message": "All upstream services temporarily unavailable",
"type": "service_error", "code": "upstream_error"}}
else:
error_response = {
"error": {"message": "Request processing failed on all upstreams", "type": "api_error",
"code": "unknown_error"}}
return JSONResponse(content=error_response, status_code=e.response.status_code)
except ValueError as e:
# 捕获空响应或JSON解析错误
logger.error(f"❌ Invalid response from {upstream['name']}: {e}")
last_error = e
if upstream_idx < len(upstreams) - 1:
logger.info(f"🔄 Trying next upstream service...")
continue
else:
logger.error(f"❌ All upstreams failed - invalid responses")
return JSONResponse(
status_code=502,
content={"error": {"message": "All upstream services returned invalid responses",
"type": "bad_gateway", "code": "invalid_upstream_response"}}
)
except Exception as e:
logger.error(f"❌ Unexpected error with {upstream['name']}: {type(e).__name__}: {e}")
logger.error(f"❌ Error traceback: {traceback.format_exc()}")
last_error = e
if upstream_idx < len(upstreams) - 1:
logger.info(f"🔄 Trying next upstream service...")
continue
else:
logger.error(f"❌ All upstreams failed with errors")
return JSONResponse(
status_code=500,
content={"error": {"message": "All upstream services failed", "type": "service_error",
"code": "all_upstreams_failed"}}
)
else:
# Streaming: use the highest priority upstream (first in list)
upstream = upstreams[0]
upstream_url = build_upstream_url(upstream['base_url'], '/chat/completions')
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {_api_key}" if app_config.features.key_passthrough else f"Bearer {upstream['api_key']}",
"Accept": "text/event-stream"
}
logger.info(f"📝 Streaming to upstream: {upstream['name']} (priority: {upstream.get('priority', 0)})")
async def stream_with_token_count():
completion_tokens = 0
completion_text = ""
done_received = False
upstream_usage_chunk = None
async for chunk in stream_proxy_with_fc_transform(
upstream_url,
request_body_dict,
headers,
body.model,
has_function_call,
GLOBAL_TRIGGER_SIGNAL,
http_client,
app_config.server.timeout
):
# Check if this is the [DONE] marker
if chunk.startswith(b"data: "):
try:
line_data = chunk[6:].decode('utf-8').strip()
if line_data == "[DONE]":
done_received = True
# Don't yield the [DONE] marker yet, we'll send it after usage info
break
elif line_data:
chunk_json = json.loads(line_data)
# Check if this chunk contains usage information
if "usage" in chunk_json:
upstream_usage_chunk = chunk_json
logger.debug(f"🔧 Detected upstream usage chunk: {chunk_json['usage']}")
# Don't yield upstream usage chunk yet, we'll process it
continue
# Process regular content chunks
if "choices" in chunk_json and len(chunk_json["choices"]) > 0:
delta = chunk_json["choices"][0].get("delta", {})
content = delta.get("content", "")
if content:
completion_text += content
except (json.JSONDecodeError, KeyError, UnicodeDecodeError) as e:
logger.debug(f"Failed to parse chunk for token counting: {e}")
pass
yield chunk
# Calculate our estimated tokens
estimated_completion_tokens = token_counter.count_text_tokens(completion_text,
body.model) if completion_text else 0
estimated_prompt_tokens = prompt_tokens
estimated_total_tokens = estimated_prompt_tokens + estimated_completion_tokens
elapsed_time = time.time() - start_time
# Determine final usage
final_usage = None
if upstream_usage_chunk and "usage" in upstream_usage_chunk:
# Respect upstream usage, but replace zero values
upstream_usage = upstream_usage_chunk["usage"]
final_usage = upstream_usage.copy()
if not final_usage.get("prompt_tokens") or final_usage.get("prompt_tokens") == 0:
final_usage["prompt_tokens"] = estimated_prompt_tokens
logger.debug(f"🔧 Replaced zero/missing prompt_tokens with estimate: {estimated_prompt_tokens}")
if not final_usage.get("completion_tokens") or final_usage.get("completion_tokens") == 0:
final_usage["completion_tokens"] = estimated_completion_tokens
logger.debug(
f"🔧 Replaced zero/missing completion_tokens with estimate: {estimated_completion_tokens}")
if not final_usage.get("total_tokens") or final_usage.get("total_tokens") == 0:
final_usage["total_tokens"] = final_usage.get("prompt_tokens",
estimated_prompt_tokens) + final_usage.get(
"completion_tokens", estimated_completion_tokens)
logger.debug(
f"🔧 Replaced zero/missing total_tokens with calculated value: {final_usage['total_tokens']}")
logger.debug(f"🔧 Using upstream usage with replacements: {final_usage}")
else:
# No upstream usage, use our estimates
final_usage = {
"prompt_tokens": estimated_prompt_tokens,
"completion_tokens": estimated_completion_tokens,
"total_tokens": estimated_total_tokens
}
logger.debug(f"🔧 No upstream usage found, using estimates")
# Log token statistics
logger.info("=" * 60)
logger.info(f"📊 Token Usage Statistics - Model: {body.model}")
logger.info(f" Input Tokens: {final_usage['prompt_tokens']}")
logger.info(f" Output Tokens: {final_usage['completion_tokens']}")
logger.info(f" Total Tokens: {final_usage['total_tokens']}")
logger.info(f" Duration: {elapsed_time:.2f}s")
logger.info("=" * 60)
# Send usage information if requested via stream_options OR if upstream provided usage
if (body.stream_options and body.stream_options.get("include_usage", False)) or upstream_usage_chunk:
usage_chunk_to_send = {
"id": f"chatcmpl-{uuid.uuid4().hex}",
"object": "chat.completion.chunk",
"created": int(time.time()),
"model": body.model,
"choices": [],
"usage": final_usage
}
# If upstream provided additional fields in the usage chunk, preserve them
if upstream_usage_chunk:
for key in upstream_usage_chunk:
if key not in ["usage", "choices"] and key not in usage_chunk_to_send:
usage_chunk_to_send[key] = upstream_usage_chunk[key]
yield f"data: {json.dumps(usage_chunk_to_send)}\n\n".encode('utf-8')
logger.debug(f"🔧 Sent usage chunk in stream: {usage_chunk_to_send['usage']}")
# Send [DONE] marker if it was received
if done_received:
yield b"data: [DONE]\n\n"
return StreamingResponse(
stream_with_token_count(),
media_type="text/event-stream"
)