-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathproxy.py
More file actions
4617 lines (4136 loc) · 207 KB
/
Copy pathproxy.py
File metadata and controls
4617 lines (4136 loc) · 207 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
"""
DeepSeek 网页 → API 代理(纯 HTTP 转发,无浏览器依赖)
用法: python proxy.py → 打开 http://localhost:8000/admin → 粘贴 cURL → 保存 → 用
"""
import asyncio, json, os, shlex, time, uuid, webbrowser, base64, re, secrets
from pathlib import Path
from typing import Any
from fastapi import FastAPI, HTTPException, Request, Depends
from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse
from fastapi.security import HTTPBasicCredentials
from fastapi.middleware.cors import CORSMiddleware
import tiktoken
from curl_cffi import requests as cffi_requests
from app.batch import init_batch_storage as anthropic_init_batch_storage
# ── Tokenizer ───────────────────────────────────
_enc = tiktoken.get_encoding("cl100k_base")
def _count_tokens(text: str) -> int:
return len(_enc.encode(text or ""))
# ── 用量统计 ───────────────────────────────────
from usage_store import add_usage, get_usage, clear_usage
from session_store import needs_renewal, on_new_session, add_tokens, get_usage_status, get_expired_sessions, remove_old_session
from response_store import save_response_record, get_response_record, delete_response_record, update_response_record
# ── 工具调用处理模块 ─────────────────────────────────
from tool_call import (
extract_tool_call,
get_tool_names,
convert_messages_for_deepseek,
clean_tool_text,
)
# ── 流式筛分 + DSML 解析 ────────────────────────────
from tool_sieve import StreamSieve, SieveEvent
from tool_dsml import parse_dsml_tool_calls as _parse_dsml, sanitize_leaked_output
# ── PoW (Proof of Work) Solver — 纯 Python 实现(无 WASM 依赖)────────
from pow_native import DeepSeekPOW
# Initialize PoW solver
pow_solver = DeepSeekPOW()
BASE_DIR = Path(__file__).parent
CONFIG_FILE = BASE_DIR / "config.json"
# 多账号管理
from app.config import config_manager, DsAccount
from app.auth import verify_admin
VISION_LOG = BASE_DIR / "vision.log"
_DEBUG = os.getenv("DS_DEBUG", "").lower() in ("1", "true", "yes")
# ── DeepSeek API 通用 Headers ─────────────────────
DS_HEADERS = {
"content-type": "application/json",
"origin": "https://chat.deepseek.com",
"referer": "https://chat.deepseek.com/",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/134.0.0.0 Safari/537.36",
"x-client-version": "2.0.2",
"x-client-platform": "web",
}
def _vlog(msg: str):
"""Log vision-related messages. File logging only when DS_DEBUG=1."""
ts = time.strftime("%H:%M:%S")
if _DEBUG:
with open(VISION_LOG, "a") as f:
f.write(f"[{ts}] {msg}\n")
print(f"[Vision] {msg}", flush=True)
PROXY_PORT = int(os.getenv("PROXY_PORT", "8000"))
def _gen_response_id() -> str:
return f"resp_{uuid.uuid4().hex}"
def _ensure_list(value: Any) -> list:
if value is None:
return []
return value if isinstance(value, list) else [value]
def _safe_json_loads(text: Any, default: Any):
if not isinstance(text, str):
return default
try:
return json.loads(text)
except (json.JSONDecodeError, ValueError, TypeError):
return default
def _response_status_from_finish_reason(finish_reason: str) -> str:
if finish_reason in ("stop", "tool_calls"):
return "completed"
if finish_reason in ("length", "content_filter"):
return "incomplete"
return "completed"
def _response_incomplete_details(finish_reason: str) -> dict | None:
if finish_reason in ("length", "content_filter"):
return {"reason": finish_reason}
return None
def _response_terminal_event_type(status: str) -> str:
if status == "failed":
return "response.failed"
if status == "incomplete":
return "response.incomplete"
if status == "cancelled":
return "response.cancelled"
return "response.completed"
def _build_response_usage(usage: dict | None) -> dict:
usage = usage or {}
input_tokens = int(usage.get("prompt_tokens", 0) or 0)
output_tokens = int(usage.get("completion_tokens", 0) or 0)
total_tokens = int(usage.get("total_tokens", input_tokens + output_tokens) or 0)
return {
"input_tokens": input_tokens,
"input_tokens_details": {"cached_tokens": 0},
"output_tokens": output_tokens,
"output_tokens_details": {"reasoning_tokens": 0},
"total_tokens": total_tokens,
}
def _response_text_item(text: str, item_id: str | None = None) -> dict:
return {
"id": item_id or f"msg_{uuid.uuid4().hex[:24]}",
"type": "message",
"status": "completed",
"role": "assistant",
"content": [{
"type": "output_text",
"text": text or "",
"annotations": [],
}],
}
def _response_refusal_item(refusal_text: str, item_id: str | None = None) -> dict:
return {
"id": item_id or f"rf_{uuid.uuid4().hex[:24]}",
"type": "refusal",
"status": "completed",
"content": [{
"type": "output_text",
"text": refusal_text or "",
"annotations": [],
}],
}
def _response_reasoning_item(summary_text: str, item_id: str | None = None) -> dict:
return {
"id": item_id or f"rs_{uuid.uuid4().hex[:24]}",
"type": "reasoning",
"status": "completed",
"summary": [{
"type": "summary_text",
"text": summary_text or "",
}],
}
def _response_function_call_item(tool_call: dict, call_id: str | None = None) -> dict:
fn = tool_call.get("function", {}) if isinstance(tool_call, dict) else {}
return {
"id": f"fc_{uuid.uuid4().hex[:24]}",
"type": "function_call",
"call_id": call_id or tool_call.get("id") or f"call_{uuid.uuid4().hex[:24]}",
"name": fn.get("name", ""),
"arguments": fn.get("arguments", "{}"),
"status": "completed",
}
def _response_text_config(body: dict) -> dict:
text = body.get("text")
if isinstance(text, dict):
cfg = dict(text)
fmt = cfg.get("format")
if isinstance(fmt, dict):
cfg["format"] = dict(fmt)
elif isinstance(fmt, str):
cfg["format"] = {"type": fmt}
else:
cfg["format"] = {"type": "text"}
return cfg
return {"format": {"type": "text"}}
def _extract_structured_json_text(output_text: str) -> tuple[str, Any] | tuple[None, None]:
if not output_text:
return None, None
candidate = output_text.strip()
if candidate.startswith("```"):
candidate = re.sub(r"^```(?:json)?\s*", "", candidate, flags=re.IGNORECASE)
candidate = re.sub(r"\s*```$", "", candidate)
start_candidates = [i for i in (candidate.find("{"), candidate.find("[")) if i != -1]
if start_candidates:
start = min(start_candidates)
end_candidates = [candidate.rfind("}"), candidate.rfind("]")]
end = max(end_candidates)
if end > start:
candidate = candidate[start:end + 1]
try:
parsed = json.loads(candidate)
return json.dumps(parsed, ensure_ascii=False), parsed
except (json.JSONDecodeError, ValueError, TypeError):
return None, None
def _normalize_structured_output_text(output_text: str, text_config: dict | None) -> str:
if not output_text or not isinstance(text_config, dict):
return output_text
fmt = text_config.get("format")
if not isinstance(fmt, dict):
return output_text
fmt_type = fmt.get("type")
if fmt_type not in ("json_object", "json_schema"):
return output_text
normalized, _ = _extract_structured_json_text(output_text)
return normalized if normalized is not None else output_text
def _json_schema_from_text_config(text_config: dict | None) -> dict | None:
fmt = text_config.get("format") if isinstance(text_config, dict) else None
if not isinstance(fmt, dict) or fmt.get("type") != "json_schema":
return None
schema = fmt.get("schema")
if isinstance(schema, dict):
return schema
json_schema = fmt.get("json_schema")
if isinstance(json_schema, dict):
nested = json_schema.get("schema")
return nested if isinstance(nested, dict) else json_schema
return None
def _schema_type_matches(value: Any, expected: str) -> bool:
if expected == "object":
return isinstance(value, dict)
if expected == "array":
return isinstance(value, list)
if expected == "string":
return isinstance(value, str)
if expected == "integer":
return isinstance(value, int) and not isinstance(value, bool)
if expected == "number":
return (isinstance(value, int) or isinstance(value, float)) and not isinstance(value, bool)
if expected == "boolean":
return isinstance(value, bool)
if expected == "null":
return value is None
return True
def _validate_json_schema_subset(value: Any, schema: dict | None, path: str = "$") -> str | None:
if not isinstance(schema, dict):
return None
expected_type = schema.get("type")
if isinstance(expected_type, list):
if not any(_schema_type_matches(value, t) for t in expected_type if isinstance(t, str)):
return f"{path} does not match any allowed type"
elif isinstance(expected_type, str) and not _schema_type_matches(value, expected_type):
return f"{path} must be {expected_type}"
if isinstance(value, dict):
required = schema.get("required")
if isinstance(required, list):
for key in required:
if isinstance(key, str) and key not in value:
return f"{path}.{key} is required"
properties = schema.get("properties")
if isinstance(properties, dict):
for key, prop_schema in properties.items():
if key in value and isinstance(prop_schema, dict):
error = _validate_json_schema_subset(value[key], prop_schema, f"{path}.{key}")
if error:
return error
additional = schema.get("additionalProperties")
if additional is False and isinstance(properties, dict):
extra = [key for key in value.keys() if key not in properties]
if extra:
return f"{path}.{extra[0]} is not allowed"
elif isinstance(additional, dict):
properties = properties if isinstance(properties, dict) else {}
for key, item in value.items():
if key not in properties:
error = _validate_json_schema_subset(item, additional, f"{path}.{key}")
if error:
return error
if isinstance(value, list):
item_schema = schema.get("items")
if isinstance(item_schema, dict):
for idx, item in enumerate(value):
error = _validate_json_schema_subset(item, item_schema, f"{path}[{idx}]")
if error:
return error
return None
def _structured_output_error(output_text: str, text_config: dict | None) -> dict | None:
fmt = text_config.get("format") if isinstance(text_config, dict) else None
if not isinstance(fmt, dict):
return None
fmt_type = fmt.get("type")
if fmt_type not in ("json_object", "json_schema"):
return None
normalized, parsed = _extract_structured_json_text(output_text)
if normalized is None:
return {"message": "response output_text is not valid JSON", "type": "invalid_response_format", "code": "invalid_json"}
if fmt_type == "json_schema":
schema_error = _validate_json_schema_subset(parsed, _json_schema_from_text_config(text_config))
if schema_error:
return {"message": f"response output_text does not match json_schema: {schema_error}", "type": "invalid_response_format", "code": "schema_validation_failed"}
return None
def _extract_output_text(output: list[dict]) -> str:
texts: list[str] = []
for item in output or []:
if item.get("type") == "message":
for content in item.get("content", []) or []:
if content.get("type") == "output_text":
texts.append(content.get("text", "") or "")
return "".join(texts)
def _normalize_response_tool_output(output: Any) -> str:
if isinstance(output, str):
return output
if output is None:
return ""
return json.dumps(output, ensure_ascii=False)
def _normalize_response_tool(tool: Any) -> dict | None:
if not isinstance(tool, dict):
return None
ttype = tool.get("type")
if ttype == "web_search_preview":
return None
fn = tool.get("function") if isinstance(tool.get("function"), dict) else {}
name = tool.get("name") or fn.get("name")
if ttype == "function" or name:
normalized_fn = {
"name": name or "",
"description": tool.get("description") or fn.get("description", ""),
"parameters": tool.get("parameters") or fn.get("parameters") or {"type": "object", "properties": {}},
}
if "strict" in tool:
normalized_fn["strict"] = tool.get("strict")
elif "strict" in fn:
normalized_fn["strict"] = fn.get("strict")
return {"type": "function", "function": normalized_fn}
return None
def _normalize_input_file_part(part: dict) -> dict:
if part.get("file_data") or part.get("data"):
return {
"type": "input_file",
"filename": part.get("filename") or "file.txt",
"file_data": part.get("file_data") or part.get("data") or "",
}
out = {"type": "input_file"}
if part.get("file_id"):
out["file_id"] = part.get("file_id")
if part.get("filename"):
out["filename"] = part.get("filename")
return out
def _normalize_response_input_item(item: Any) -> dict | None:
if isinstance(item, str):
return {
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": item}],
}
if not isinstance(item, dict):
return None
item_type = item.get("type")
role = item.get("role")
if item_type in ("input_text", "text"):
return {"type": "input_text", "text": item.get("text", "")}
if item_type == "function_call_output":
normalized = {
"type": "function_call_output",
"call_id": item.get("call_id") or item.get("id") or "",
"output": _normalize_response_tool_output(item.get("output")),
}
if item.get("id"):
normalized["id"] = item.get("id")
return normalized
if item_type == "function_call":
normalized = {
"type": "function_call",
"call_id": item.get("call_id") or item.get("id") or f"call_{uuid.uuid4().hex[:24]}",
"name": item.get("name", ""),
"arguments": item.get("arguments", "{}") if isinstance(item.get("arguments", "{}"), str)
else json.dumps(item.get("arguments", {}), ensure_ascii=False),
}
if item.get("id"):
normalized["id"] = item.get("id")
if "parameters" in item:
normalized["parameters"] = item.get("parameters")
if "description" in item:
normalized["description"] = item.get("description")
return normalized
if item_type == "message" or role in ("system", "user", "assistant", "tool"):
normalized = {
"type": "message",
"role": role or item.get("role", "user"),
}
content = item.get("content", "")
normalized_parts = []
if isinstance(content, list):
for part in content:
if not isinstance(part, dict):
continue
ptype = part.get("type")
if ptype in ("input_text", "output_text", "text"):
normalized_parts.append({"type": "input_text", "text": part.get("text", "")})
elif ptype == "input_image":
image_url = part.get("image_url") or part.get("url") or ""
item_part = {"type": "input_image"}
if isinstance(image_url, dict):
item_part["image_url"] = image_url.get("url", "")
if image_url.get("detail"):
item_part["detail"] = image_url.get("detail")
elif image_url:
item_part["image_url"] = image_url
if part.get("file_id"):
item_part["file_id"] = part.get("file_id")
normalized_parts.append(item_part)
elif ptype == "input_file":
normalized_parts.append(_normalize_input_file_part(part))
elif ptype == "function_call" and normalized["role"] == "assistant":
normalized_parts.append({
"type": "function_call",
"call_id": part.get("call_id") or part.get("id") or f"call_{uuid.uuid4().hex[:24]}",
"name": part.get("name", ""),
"arguments": part.get("arguments", "{}") if isinstance(part.get("arguments", "{}"), str)
else json.dumps(part.get("arguments", {}), ensure_ascii=False),
})
elif isinstance(content, str):
normalized_parts.append({"type": "input_text", "text": content})
normalized["content"] = normalized_parts
return normalized
return item
def _normalize_response_input_items(input_items: Any) -> list[dict]:
items = _ensure_list(input_items)
normalized: list[dict] = []
for item in items:
normalized_item = _normalize_response_input_item(item)
if normalized_item is not None:
normalized.append(normalized_item)
return normalized
def _assign_response_input_item_ids(items: list[dict], response_id: str) -> list[dict]:
assigned: list[dict] = []
for idx, item in enumerate(items or []):
if not isinstance(item, dict):
continue
copy = dict(item)
if not copy.get("id"):
copy["id"] = f"{response_id}_in_{idx}"
assigned.append(copy)
return assigned
def _response_instructions_item(instructions: str) -> dict:
return {
"type": "message",
"role": "system",
"content": [{"type": "input_text", "text": instructions}],
}
def _stored_input_items(body: dict) -> list[dict]:
items = _normalize_response_input_items(body.get("input"))
instructions = body.get("instructions")
if isinstance(instructions, str) and instructions.strip():
items = [_response_instructions_item(instructions)] + items
return _assign_response_input_item_ids(items, body.get("_response_id", f"resp_{uuid.uuid4().hex}"))
def _paginate_response_input_items(items: list[dict], *, limit: int, after: str | None, before: str | None, order: str) -> tuple[list[dict], bool]:
ordered = list(items or [])
if order == "desc":
ordered = list(reversed(ordered))
if after:
idx = next((i for i, item in enumerate(ordered) if item.get("id") == after), -1)
ordered = ordered[idx + 1:] if idx != -1 else []
if before:
idx = next((i for i, item in enumerate(ordered) if item.get("id") == before), -1)
ordered = ordered[:idx] if idx != -1 else []
has_more = len(ordered) > limit
return ordered[:limit], has_more
def _response_object_payload(record: dict, *, status: str | None = None, usage: dict | None = None,
completed_at: int | None | object = Ellipsis, output: list[dict] | None = None,
error: dict | None | object = Ellipsis, incomplete_details: dict | None | object = Ellipsis,
output_text: str | None = None) -> dict:
payload = dict(_public_response_record(record))
if status is not None:
payload["status"] = status
if usage is not None or "usage" in payload:
payload["usage"] = usage
if completed_at is not Ellipsis:
payload["completed_at"] = completed_at
if output is not None:
payload["output"] = output
if error is not Ellipsis:
payload["error"] = error
if incomplete_details is not Ellipsis:
payload["incomplete_details"] = incomplete_details
if output_text is not None:
payload["output_text"] = output_text
return payload
def _response_failed_payload(response_id: str, created: int, model_name: str, body: dict,
previous_response_id: str | None, error: dict, output_text: str = "") -> dict:
text_cfg = _response_text_config(body)
return {
"id": response_id,
"object": "response",
"created_at": created,
"completed_at": None,
"status": "failed",
"error": error,
"incomplete_details": None,
"instructions": body.get("instructions"),
"max_output_tokens": body.get("max_output_tokens"),
"model": model_name,
"output": [],
"parallel_tool_calls": True,
"previous_response_id": previous_response_id,
"reasoning": {"effort": body.get("reasoning", {}).get("effort")} if isinstance(body.get("reasoning"), dict) and body.get("reasoning", {}).get("effort") else None,
"store": True if body.get("store", True) else False,
"temperature": body.get("temperature"),
"text": text_cfg,
"tool_choice": body.get("tool_choice", "auto"),
"tools": body.get("tools", []),
"top_p": body.get("top_p"),
"truncation": body.get("truncation", "disabled"),
"usage": None,
"user": body.get("user"),
"metadata": body.get("metadata", {}),
"output_text": _normalize_structured_output_text(output_text, text_cfg),
}
def _extract_response_messages_and_tools(input_items: Any) -> tuple[list[dict], list[dict] | None]:
items = _ensure_list(input_items)
messages: list[dict] = []
tools_from_input: list[dict] = []
for item in items:
if isinstance(item, str):
messages.append({"role": "user", "content": item})
continue
if not isinstance(item, dict):
continue
item_type = item.get("type")
role = item.get("role")
if role in ("system", "user", "assistant", "tool"):
content = item.get("content", "")
if isinstance(content, list):
parts = []
assistant_tool_calls = []
for part in content:
if not isinstance(part, dict):
continue
ptype = part.get("type")
if ptype in ("input_text", "output_text", "text"):
parts.append({"type": "text", "text": part.get("text", "")})
elif ptype == "input_image":
image_url = part.get("image_url") or part.get("url") or ""
if image_url:
parts.append({"type": "image_url", "image_url": {"url": image_url}})
elif ptype == "input_file":
file_obj = {
"filename": part.get("filename") or "file.txt",
"file_data": part.get("file_data") or part.get("data") or "",
}
parts.append({"type": "file", "file": file_obj})
elif ptype == "function_call" and role == "assistant":
assistant_tool_calls.append({
"id": part.get("call_id") or part.get("id") or f"call_{uuid.uuid4().hex[:24]}",
"type": "function",
"function": {
"name": part.get("name", ""),
"arguments": part.get("arguments", "{}") if isinstance(part.get("arguments", "{}"), str)
else json.dumps(part.get("arguments", {}), ensure_ascii=False),
}
})
msg = {"role": role, "content": parts if parts else ""}
if assistant_tool_calls:
msg["tool_calls"] = assistant_tool_calls
if not parts:
msg["content"] = None
messages.append(msg)
else:
msg = {"role": role, "content": content}
if role == "assistant" and item_type == "function_call":
msg["tool_calls"] = [{
"id": item.get("call_id") or item.get("id") or f"call_{uuid.uuid4().hex[:24]}",
"type": "function",
"function": {
"name": item.get("name", ""),
"arguments": item.get("arguments", "{}") if isinstance(item.get("arguments", "{}"), str)
else json.dumps(item.get("arguments", {}), ensure_ascii=False),
}
}]
if content in ("", None):
msg["content"] = None
messages.append(msg)
continue
if item_type == "message":
content = item.get("content", [])
role = item.get("role", "user")
normalized_parts = []
assistant_tool_calls = []
if isinstance(content, list):
for part in content:
if not isinstance(part, dict):
continue
ptype = part.get("type")
if ptype in ("input_text", "output_text", "text"):
normalized_parts.append({"type": "text", "text": part.get("text", "")})
elif ptype == "input_image":
image_url = part.get("image_url") or part.get("url") or ""
if image_url:
normalized_parts.append({"type": "image_url", "image_url": {"url": image_url}})
elif ptype == "input_file":
normalized_parts.append({
"type": "file",
"file": {
"filename": part.get("filename") or "file.txt",
"file_data": part.get("file_data") or part.get("data") or "",
}
})
elif ptype == "function_call" and role == "assistant":
assistant_tool_calls.append({
"id": part.get("call_id") or part.get("id") or f"call_{uuid.uuid4().hex[:24]}",
"type": "function",
"function": {
"name": part.get("name", ""),
"arguments": part.get("arguments", "{}") if isinstance(part.get("arguments", "{}"), str)
else json.dumps(part.get("arguments", {}), ensure_ascii=False),
}
})
msg = {"role": role, "content": normalized_parts if normalized_parts else ""}
if assistant_tool_calls:
msg["tool_calls"] = assistant_tool_calls
if not normalized_parts:
msg["content"] = None
messages.append(msg)
continue
if item_type == "function_call_output":
output = _normalize_response_tool_output(item.get("output"))
tool_message = {"role": "tool", "content": output}
if item.get("call_id"):
tool_message["tool_call_id"] = item.get("call_id")
messages.append(tool_message)
continue
if item_type == "function_call":
if item.get("name") and ("parameters" in item or "description" in item):
tools_from_input.append({
"type": "function",
"function": {
"name": item.get("name", ""),
"description": item.get("description", ""),
"parameters": item.get("parameters", {"type": "object", "properties": {}}),
}
})
else:
messages.append({
"role": "assistant",
"content": None,
"tool_calls": [{
"id": item.get("call_id") or item.get("id") or f"call_{uuid.uuid4().hex[:24]}",
"type": "function",
"function": {
"name": item.get("name", ""),
"arguments": item.get("arguments", "{}") if isinstance(item.get("arguments", "{}"), str)
else json.dumps(item.get("arguments", {}), ensure_ascii=False),
}
}]
})
continue
if item_type in ("input_text", "text"):
messages.append({"role": "user", "content": item.get("text", "")})
return messages, (tools_from_input or None)
def _merge_previous_response_context(messages: list[dict], previous_response_id: str | None) -> list[dict]:
if not previous_response_id:
return messages
prev = get_response_record(previous_response_id)
if not prev:
raise HTTPException(404, detail={"error": {"message": f"response {previous_response_id} not found", "type": "invalid_request_error"}})
previous_messages = prev.get("_messages", [])
if not isinstance(previous_messages, list):
previous_messages = []
else:
previous_messages = list(previous_messages)
if messages and messages[0].get("role") == "system":
while previous_messages and isinstance(previous_messages[0], dict) and previous_messages[0].get("role") == "system":
previous_messages.pop(0)
return previous_messages + messages
def _normalize_response_tools(body: dict, parsed_tools: list[dict] | None) -> list[dict] | None:
tools = body.get("tools")
merged: list[dict] = []
seen: set[str] = set()
for source in (parsed_tools or []) + (tools if isinstance(tools, list) else []):
normalized = _normalize_response_tool(source)
if not normalized:
continue
name = normalized.get("function", {}).get("name", "")
if name and name in seen:
continue
if name:
seen.add(name)
merged.append(normalized)
return merged or None
def _has_web_search_tool(body: dict) -> bool:
tools = body.get("tools")
if not isinstance(tools, list):
return False
for tool in tools:
if isinstance(tool, dict) and tool.get("type") == "web_search_preview":
return True
return False
def _resolve_responses_model(body: dict) -> str:
model = body.get("model", "deepseek-default")
if not _has_web_search_tool(body) or "search" in model:
return model
candidates = []
if model.endswith("-reasoner"):
candidates.append(f"{model}-search")
candidates.append(f"{model}-search")
if model == "deepseek-default":
candidates.append("deepseek-search")
if model == "deepseek-reasoner":
candidates.append("deepseek-reasoner-search")
models = get_models()
for candidate in candidates:
if candidate in models:
return candidate
return model
def _messages_from_responses_request(body: dict) -> tuple[list[dict], list[dict] | None]:
input_items = body.get("input", [])
if isinstance(input_items, str):
messages, tools = [{"role": "user", "content": input_items}], None
else:
messages, tools = _extract_response_messages_and_tools(input_items)
instructions = body.get("instructions")
if isinstance(instructions, str) and instructions.strip():
messages = [{"role": "system", "content": instructions}] + messages
return messages, tools
def _build_responses_record(
response_id: str,
body: dict,
model: str,
created: int,
completed_at: int | None,
output: list[dict],
usage: dict,
messages: list[dict],
status: str = "completed",
incomplete_details: dict | None = None,
) -> dict:
text_config = _response_text_config(body)
text = _normalize_structured_output_text(_extract_output_text(output), text_config)
record = {
"id": response_id,
"object": "response",
"created_at": created,
"completed_at": completed_at,
"status": status,
"error": None,
"incomplete_details": incomplete_details,
"instructions": body.get("instructions"),
"max_output_tokens": body.get("max_output_tokens"),
"model": model,
"output": output,
"parallel_tool_calls": True,
"previous_response_id": body.get("previous_response_id"),
"reasoning": {"effort": body.get("reasoning", {}).get("effort")} if isinstance(body.get("reasoning"), dict) and body.get("reasoning", {}).get("effort") else None,
"store": True if body.get("store", True) else False,
"temperature": body.get("temperature"),
"text": text_config,
"tool_choice": body.get("tool_choice", "auto"),
"tools": body.get("tools", []),
"top_p": body.get("top_p"),
"truncation": body.get("truncation", "disabled"),
"usage": _build_response_usage(usage),
"user": body.get("user"),
"metadata": body.get("metadata", {}),
"output_text": text,
"_messages": messages,
"_input": _stored_input_items(body),
}
return record
_RESPONSE_PUBLIC_DEFAULTS = {
"object": "response",
"completed_at": None,
"error": None,
"incomplete_details": None,
"instructions": None,
"max_output_tokens": None,
"parallel_tool_calls": True,
"previous_response_id": None,
"reasoning": None,
"store": True,
"temperature": None,
"text": {"format": {"type": "text"}},
"tool_choice": "auto",
"tools": [],
"top_p": None,
"truncation": "disabled",
"usage": None,
"user": None,
"metadata": {},
"output": [],
"output_text": "",
}
def _normalized_response_output_item(item: Any) -> dict:
if not isinstance(item, dict):
return _response_text_item("")
item_type = item.get("type")
if item_type == "message":
normalized = dict(item)
normalized.setdefault("id", f"msg_{uuid.uuid4().hex[:24]}")
normalized.setdefault("status", "completed")
normalized.setdefault("role", "assistant")
content = []
for part in normalized.get("content", []) or []:
if not isinstance(part, dict):
continue
p = dict(part)
p.setdefault("type", "output_text")
if p.get("type") == "output_text":
p.setdefault("text", "")
p.setdefault("annotations", [])
content.append(p)
normalized["content"] = content
return normalized
if item_type == "reasoning":
normalized = dict(item)
normalized.setdefault("id", f"rs_{uuid.uuid4().hex[:24]}")
normalized.setdefault("summary", [])
return normalized
if item_type == "refusal":
normalized = dict(item)
normalized.setdefault("id", f"rf_{uuid.uuid4().hex[:24]}")
normalized.setdefault("status", "completed")
normalized.setdefault("content", [])
return normalized
if item_type == "function_call":
normalized = dict(item)
normalized.setdefault("id", normalized.get("call_id") or f"fc_{uuid.uuid4().hex[:24]}")
normalized.setdefault("call_id", normalized.get("id"))
normalized.setdefault("name", "")
normalized.setdefault("arguments", "{}")
normalized.setdefault("status", "completed")
return normalized
return dict(item)
def _sync_output_text_to_message_items(output: list[dict], output_text: str) -> list[dict]:
synced: list[dict] = []
replaced = False
for item in output or []:
normalized = _normalized_response_output_item(item)
if normalized.get("type") == "message" and not replaced:
for part in normalized.get("content", []) or []:
if part.get("type") == "output_text":
part["text"] = output_text or ""
replaced = True
break
synced.append(normalized)
return synced
def _public_response_record(record: dict) -> dict:
payload = {k: v for k, v in record.items() if not k.startswith("_")}
for key, value in _RESPONSE_PUBLIC_DEFAULTS.items():
if key not in payload:
payload[key] = dict(value) if isinstance(value, dict) else list(value) if isinstance(value, list) else value
payload["object"] = "response"
payload["output"] = [_normalized_response_output_item(item) for item in _ensure_list(payload.get("output"))]
if not isinstance(payload.get("metadata"), dict):
payload["metadata"] = {}
if payload.get("reasoning") is not None and not isinstance(payload.get("reasoning"), dict):
payload["reasoning"] = {}
if not isinstance(payload.get("text"), dict):
payload["text"] = {"format": {"type": "text"}}
if payload.get("usage") is not None and not isinstance(payload.get("usage"), dict):
payload["usage"] = None
payload["output_text"] = payload.get("output_text") or _extract_output_text(payload["output"])
return payload
def _apply_structured_output_contract(record: dict) -> dict:
text_config = record.get("text") if isinstance(record.get("text"), dict) else {"format": {"type": "text"}}
output_text = _extract_output_text(record.get("output", []))
normalized_text = _normalize_structured_output_text(output_text, text_config)
record = dict(record)
record["output_text"] = normalized_text
record["output"] = _sync_output_text_to_message_items(record.get("output", []), normalized_text)
error = _structured_output_error(normalized_text, text_config)
if error and record.get("status") == "completed":
record["status"] = "failed"
record["completed_at"] = None
record["error"] = error
record["incomplete_details"] = None
return record
def _response_output_from_chat_message(msg: dict) -> list[dict]:
output: list[dict] = []
reasoning = msg.get("reasoning_content", "")
if reasoning:
output.append(_response_reasoning_item(reasoning))
refusal = msg.get("refusal", "")
if isinstance(refusal, str) and refusal:
output.append(_response_refusal_item(refusal))
content = msg.get("content", "")
if isinstance(content, str) and content:
# 安全防护:剥除 content 中残留的 <think> 标签(SSE 解析可能遗漏)
content = re.sub(r'<think>.*?</think>', '', content, flags=re.DOTALL).strip()
if content:
output.append(_response_text_item(content))
tool_calls = msg.get("tool_calls") or []
for tc in tool_calls:
output.append(_response_function_call_item(tc))
if not output:
output.append(_response_text_item(""))
return output
def _assistant_message_from_chat_message(msg: dict) -> dict:
assistant = {
"role": "assistant",
"content": msg.get("content"),
}