-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_proxy.py
More file actions
1857 lines (1729 loc) · 76.4 KB
/
Copy pathtest_proxy.py
File metadata and controls
1857 lines (1729 loc) · 76.4 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""proxy.py 的自测:用本地 mock 上游验证改写与透传逻辑。"""
from __future__ import annotations
import http.client
import json
import logging
import socket
import threading
import time
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import proxy as proxy_module
from proxy import (
ProxyHandler,
ProxyServer,
_BadRequest,
_log_safe,
_redact_secrets,
build_chat_path,
build_upstream_path,
extract_upstream_error,
infer_request_agent,
normalize_agent_messages,
)
from responses_chat import (
ChatUpstreamError,
ChatToResponsesStream,
chat_json_to_sse_events,
chat_to_responses,
model_needs_chat_conversion,
responses_to_chat_request,
)
class MockUpstream(ThreadingHTTPServer):
daemon_threads = True
allow_reuse_address = True
def __init__(self, addr):
super().__init__(addr, MockUpstreamHandler)
self.status = 200
self.response_payload = {"ok": True}
self.extra_headers = {}
self.mode = "json"
self.last = None
self.sse_chunks = []
self.sse_done = True
class MockUpstreamHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_POST(self):
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length)
server = self.server
server.last = {
"method": self.command,
"path": self.path,
"headers": dict(self.headers.items()),
"body": body,
}
if server.mode == "sse":
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
event = b'data: {"type":"response.output_text.delta","delta":"hello"}\n\n'
parts = [event[:13], event[13:]]
for part in parts:
self.wfile.write(("%x\r\n" % len(part)).encode("ascii") + part + b"\r\n")
self.wfile.flush()
self.wfile.write(b"0\r\n\r\n")
self.wfile.flush()
return
if server.mode == "close_sse":
# close-delimited 流式响应:无 Content-Length、无 chunked,
# 发送一个事件后保持连接一段时间再关闭。
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Connection", "close")
self.end_headers()
event = b'data: {"type":"response.output_text.delta","delta":"hi"}\n\n'
self.wfile.write(event)
self.wfile.flush()
time.sleep(3)
return
if server.mode == "chat_sse":
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
for chunk in server.sse_chunks:
event = ("data: " + json.dumps(chunk) + "\n\n").encode("utf-8")
self.wfile.write(("%x\r\n" % len(event)).encode("ascii") + event + b"\r\n")
self.wfile.flush()
if server.sse_done:
done = b"data: [DONE]\n\n"
self.wfile.write(("%x\r\n" % len(done)).encode("ascii") + done + b"\r\n")
self.wfile.write(b"0\r\n\r\n")
self.wfile.flush()
return
if server.mode == "chat_bad_json":
payload = b"this is not json"
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
return
if server.mode == "chat_sse_invalid":
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
event = b"data: not-json\n\n"
self.wfile.write(("%x\r\n" % len(event)).encode("ascii") + event + b"\r\n")
self.wfile.write(b"0\r\n\r\n")
self.wfile.flush()
return
if server.mode == "binary_error":
payload = b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03binary-garbage-\xff\xfe"
self.send_response(server.status)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
return
payload = json.dumps(server.response_payload).encode("utf-8")
self.send_response(server.status)
for key, value in server.extra_headers.items():
self.send_header(key, value)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def log_message(self, fmt, *args):
pass
class ProxyTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.upstream = MockUpstream(("127.0.0.1", 0))
cls.upstream_port = cls.upstream.server_address[1]
threading.Thread(target=cls.upstream.serve_forever, daemon=True).start()
cls.upstream_url = f"http://127.0.0.1:{cls.upstream_port}"
cls.proxy = ProxyServer(
("127.0.0.1", 0),
argparse_namespace(
upstream=cls.upstream_url,
chat_models=[],
chat_upstream=None,
fix_agent_message=False,
timeout=10,
client_timeout=10,
max_connections=64,
log_body=False,
),
)
cls.proxy_port = cls.proxy.server_address[1]
threading.Thread(target=cls.proxy.serve_forever, daemon=True).start()
cls.fix_proxy = ProxyServer(
("127.0.0.1", 0),
argparse_namespace(
upstream=cls.upstream_url,
chat_models=[],
chat_upstream=None,
fix_agent_message=True,
timeout=10,
client_timeout=10,
max_connections=64,
log_body=False,
),
)
cls.fix_proxy_port = cls.fix_proxy.server_address[1]
threading.Thread(target=cls.fix_proxy.serve_forever, daemon=True).start()
cls.chat_proxy = ProxyServer(
("127.0.0.1", 0),
argparse_namespace(
upstream=cls.upstream_url,
chat_models=["deepseek", "mimo"],
chat_upstream=None,
fix_agent_message=False,
timeout=10,
client_timeout=10,
max_connections=64,
log_body=False,
),
)
cls.chat_proxy_port = cls.chat_proxy.server_address[1]
threading.Thread(target=cls.chat_proxy.serve_forever, daemon=True).start()
cls.mimo_proxy = ProxyServer(
("127.0.0.1", 0),
argparse_namespace(
upstream=cls.upstream_url,
chat_models=["mimo"],
chat_upstream=None,
fix_agent_message=True,
timeout=10,
client_timeout=10,
max_connections=64,
log_body=False,
),
)
cls.mimo_proxy_port = cls.mimo_proxy.server_address[1]
threading.Thread(target=cls.mimo_proxy.serve_forever, daemon=True).start()
@classmethod
def tearDownClass(cls):
cls.proxy.shutdown()
cls.proxy.server_close()
cls.fix_proxy.shutdown()
cls.fix_proxy.server_close()
cls.chat_proxy.shutdown()
cls.chat_proxy.server_close()
cls.mimo_proxy.shutdown()
cls.mimo_proxy.server_close()
cls.upstream.shutdown()
cls.upstream.server_close()
def post(self, path, payload, headers=None, proxy_port=None):
conn = http.client.HTTPConnection(
"127.0.0.1", proxy_port or self.proxy_port, timeout=10
)
body = json.dumps(payload).encode("utf-8")
req_headers = {"Authorization": "Bearer test-key-123"}
if headers:
req_headers.update(headers)
if not any(key.lower() == "content-type" for key in req_headers):
req_headers["Content-Type"] = "application/json"
conn.request("POST", path, body=body, headers=req_headers)
resp = conn.getresponse()
data = resp.read()
conn.close()
return resp.status, data
def test_agent_message_rewritten(self):
payload = {
"model": "deepseek-v4-flash",
"input": [
{"type": "message", "role": "user",
"content": [{"type": "input_text", "text": "hello"}]},
{
"type": "agent_message",
"id": "amsg_123",
"author": "/root",
"recipient": "/root/worker",
"content": [
{"type": "input_text",
"text": "Message Type: NEW_TASK\nTask name: /root/worker\nSender: /root\nPayload:\n"},
{"type": "encrypted_content",
"encrypted_content": "REPRO-TOKEN-1234"},
],
},
],
"stream": False,
}
status, data = self.post(
"/v1/responses", payload, proxy_port=self.fix_proxy_port
)
self.assertEqual(status, 200)
last = self.upstream.last
self.assertIsNotNone(last)
self.assertEqual(last["path"], "/responses")
self.assertEqual(last["headers"].get("Authorization"), "Bearer test-key-123")
body = json.loads(last["body"])
items = body["input"]
self.assertEqual(items[0], payload["input"][0])
self.assertEqual(items[1]["type"], "message")
self.assertEqual(items[1]["role"], "user")
self.assertEqual(items[1]["id"], "amsg_123")
self.assertNotIn("author", items[1])
self.assertNotIn("recipient", items[1])
self.assertEqual(
items[1]["content"],
[
{"type": "input_text",
"text": "Message Type: NEW_TASK\nTask name: /root/worker\nSender: /root\nPayload:\n"},
{"type": "input_text", "text": "REPRO-TOKEN-1234"},
],
)
raw = last["body"].decode()
self.assertNotIn("agent_message", raw)
self.assertNotIn("encrypted_content", raw)
def test_default_passthrough_keeps_agent_message(self):
"""裸启动(无任何开关)时 agent_message 原样透传,不做改写。"""
payload = {
"model": "deepseek-v4-flash",
"input": [
{
"type": "agent_message",
"id": "amsg_keep",
"author": "/root",
"recipient": "/root/worker",
"content": [
{"type": "encrypted_content", "encrypted_content": "SECRET-TASK"},
],
}
],
}
status, data = self.post("/v1/responses", payload)
self.assertEqual(status, 200)
raw = self.upstream.last["body"].decode()
self.assertIn("agent_message", raw)
self.assertIn("SECRET-TASK", raw)
def test_chat_conversion_implicitly_normalizes_agent_message(self):
"""只开 chat 转换、不开 --fix-agent-message 时,agent_message 仍被改写。"""
self.upstream.mode = "chat_json"
self.upstream.response_payload = {
"id": "chatcmpl-1",
"choices": [{"finish_reason": "stop",
"message": {"role": "assistant", "content": "ok"}}],
}
try:
payload = {
"model": "deepseek-v4-flash",
"input": [
{
"type": "agent_message",
"id": "amsg_1",
"content": [
{"type": "input_text", "text": "task header"},
{"type": "encrypted_content", "encrypted_content": "task body"},
],
}
],
}
status, data = self.post(
"/v1/responses", payload, proxy_port=self.chat_proxy_port
)
self.assertEqual(status, 200)
last = self.upstream.last
self.assertEqual(last["path"], "/chat/completions")
sent = json.loads(last["body"])
self.assertEqual(sent["messages"][0]["role"], "user")
self.assertEqual(sent["messages"][0]["content"], "task headertask body")
finally:
self.upstream.mode = "json"
self.upstream.response_payload = {"ok": True}
def test_mimo_only_chat_conversion(self):
"""--chat-models mimo + --fix-agent-message:mimo 转换,deepseek 仅改写透传。"""
self.upstream.mode = "chat_json"
self.upstream.response_payload = {
"id": "chatcmpl-mimo",
"created": 1700000000,
"model": "mimo-v2.5",
"choices": [{"finish_reason": "stop",
"message": {"role": "assistant", "content": "hi from mimo"}}],
}
try:
status, data = self.post(
"/v1/responses",
{"model": "mimo-v2.5", "input": "hello"},
proxy_port=self.mimo_proxy_port,
)
self.assertEqual(status, 200)
self.assertEqual(self.upstream.last["path"], "/chat/completions")
deepseek_payload = {
"model": "deepseek-v4-flash",
"input": [
{"type": "agent_message", "content": [
{"type": "encrypted_content", "encrypted_content": "ds-task"},
]},
],
}
status, data = self.post(
"/v1/responses", deepseek_payload, proxy_port=self.mimo_proxy_port
)
self.assertEqual(status, 200)
self.assertEqual(self.upstream.last["path"], "/responses")
raw = self.upstream.last["body"].decode()
self.assertNotIn("agent_message", raw)
self.assertIn("ds-task", raw)
finally:
self.upstream.mode = "json"
self.upstream.response_payload = {"ok": True}
def test_request_log_shows_rewrite_and_proto(self):
request_logger = logging.getLogger("responses-proxy")
with self.assertLogs(request_logger, level="DEBUG") as captured:
self.post(
"/v1/responses",
{
"model": "m",
"input": [
{"type": "agent_message", "author": "/root",
"recipient": "/root/worker", "content": [
{"type": "encrypted_content", "encrypted_content": "task"},
]},
],
},
proxy_port=self.fix_proxy_port,
)
lines = "\n".join(captured.output)
self.assertIn("agent=/root/worker", lines)
self.assertIn("proto=responses", lines)
self.upstream.mode = "chat_json"
self.upstream.response_payload = {
"id": "chatcmpl-log",
"created": 1700000000,
"model": "deepseek-v4-flash",
"choices": [{"finish_reason": "stop",
"message": {"role": "assistant", "content": "ok"}}],
}
try:
with self.assertLogs(request_logger, level="DEBUG") as captured:
self.post(
"/v1/responses",
{"model": "deepseek-v4-flash", "input": "hi"},
proxy_port=self.chat_proxy_port,
)
lines = "\n".join(captured.output)
self.assertIn("agent=main", lines)
self.assertIn("proto=chat", lines)
finally:
self.upstream.mode = "json"
self.upstream.response_payload = {"ok": True}
def test_infer_request_agent(self):
self.assertEqual(
infer_request_agent({"input": [
{"type": "agent_message", "author": "/root/worker",
"recipient": "/root"},
]}),
"main",
)
self.assertEqual(
infer_request_agent({"input": [
{"type": "agent_message", "author": "/root",
"recipient": "/root/worker"},
]}),
"/root/worker",
)
self.assertEqual(
infer_request_agent({"input": [
{"type": "agent_message", "author": "/root",
"recipient": "/root/worker"},
{"type": "agent_message", "author": "/root/worker",
"recipient": "/root/worker/deep"},
]}),
"/root/worker/deep",
)
self.assertEqual(infer_request_agent({"input": []}), "main")
def test_path_without_v1_prefix(self):
self.post("/responses", {"model": "m", "input": []})
self.assertEqual(self.upstream.last["path"], "/responses")
def test_normal_request_unchanged(self):
payload = {
"model": "deepseek-v4-flash",
"input": [
{"type": "message", "role": "user",
"content": [{"type": "input_text", "text": "ping"}]}
],
}
self.post("/v1/responses", payload)
self.assertEqual(json.loads(self.upstream.last["body"]), payload)
def test_lowercase_content_type_not_duplicated(self):
payload = {"model": "m", "input": [{"type": "message", "role": "user",
"content": [{"type": "input_text", "text": "hi"}]}]}
self.post("/v1/responses", payload, headers={"content-type": "application/json"})
content_types = [
value
for key, value in self.upstream.last["headers"].items()
if key.lower() == "content-type"
]
self.assertEqual(content_types, ["application/json"])
def test_sse_stream_passthrough(self):
self.upstream.mode = "sse"
try:
conn = http.client.HTTPConnection("127.0.0.1", self.proxy_port, timeout=10)
conn.request(
"POST",
"/v1/responses",
body=json.dumps({"model": "m", "input": [], "stream": True}).encode(),
headers={"Content-Type": "application/json"},
)
resp = conn.getresponse()
data = resp.read()
conn.close()
self.assertEqual(resp.status, 200)
self.assertEqual(resp.getheader("Content-Type"), "text/event-stream")
self.assertIn(b"hello", data)
finally:
self.upstream.mode = "json"
def test_upstream_error_passthrough(self):
self.upstream.status = 400
self.upstream.response_payload = {
"error": {"message": "bad request", "type": "invalid_request_error"}
}
try:
status, data = self.post("/v1/responses", {"model": "m", "input": []})
self.assertEqual(status, 400)
self.assertIn(b"invalid_request_error", data)
finally:
self.upstream.status = 200
self.upstream.response_payload = {"ok": True}
def test_build_upstream_path(self):
self.assertEqual(build_upstream_path("/zen/go/v1", "/v1/responses"), "/zen/go/v1/responses")
self.assertEqual(build_upstream_path("/zen/go/v1", "/responses"), "/zen/go/v1/responses")
self.assertEqual(build_upstream_path("/v1", "/v1/responses"), "/v1/responses")
self.assertEqual(build_upstream_path("/v1", "/responses"), "/v1/responses")
self.assertEqual(build_upstream_path("/zen/go/v1", "/zen/go/v1/responses"), "/zen/go/v1/responses")
def test_build_upstream_path_prefix_boundary(self):
"""base 前缀必须按路径段匹配,不能把 /v10 误当成 /v1。"""
self.assertEqual(
build_upstream_path("/v1", "/v10/responses"), "/v1/v10/responses"
)
def test_build_chat_path(self):
self.assertEqual(build_chat_path("/zen/go/v1"), "/zen/go/v1/chat/completions")
self.assertEqual(build_chat_path("/v1"), "/v1/chat/completions")
self.assertEqual(build_chat_path(""), "/chat/completions")
self.assertEqual(
build_chat_path("https://api.deepseek.com/v1/chat/completions"),
"https://api.deepseek.com/v1/chat/completions",
)
def test_model_needs_chat_conversion(self):
self.assertTrue(model_needs_chat_conversion("deepseek-v4-flash", ["deepseek", "mimo"]))
self.assertTrue(model_needs_chat_conversion("MIMO-v2.5", ["deepseek", "mimo"]))
self.assertFalse(model_needs_chat_conversion("gpt-5.6", ["deepseek", "mimo"]))
self.assertFalse(model_needs_chat_conversion(None, ["deepseek"]))
self.assertFalse(model_needs_chat_conversion("deepseek-v4-flash", []))
def test_normalize_unit(self):
original = {
"type": "agent_message",
"id": "amsg_1",
"author": "a",
"recipient": "b",
"content": [{"type": "encrypted_content", "encrypted_content": "task"}],
}
normalized = normalize_agent_messages(original)
self.assertEqual(
normalized,
{
"type": "message",
"role": "user",
"id": "amsg_1",
"content": [{"type": "input_text", "text": "task"}],
},
)
def test_responses_to_chat_request(self):
payload = {
"model": "deepseek-v4-flash",
"instructions": [{"type": "input_text", "text": "be helpful"}],
"input": [
{"type": "message", "role": "user",
"content": [{"type": "input_text", "text": "hi"}]},
{"type": "reasoning",
"content": [{"type": "reasoning_text", "text": "think first"}]},
{"type": "function_call", "call_id": "call_1", "name": "get_weather",
"arguments": '{"city":"shanghai"}'},
{"type": "function_call", "call_id": "call_2", "name": "get_time",
"arguments": '{"city":"shanghai"}'},
{"type": "function_call_output", "call_id": "call_1", "output": "22c"},
{"type": "message", "role": "developer",
"content": [{"type": "input_text", "text": "dev rule"}]},
],
"tools": [
{"type": "function", "function": {"name": "get_weather",
"description": "weather", "parameters": {"type": "object"}}},
{"type": "custom", "name": "apply_patch", "description": "patch"},
{"type": "web_search", "name": "web_search"},
],
"tool_choice": {"type": "function", "name": "get_weather"},
"max_output_tokens": 2048,
"reasoning": {"effort": "high"},
"stream": True,
"store": True,
"metadata": {"k": "v"},
}
out = responses_to_chat_request(payload)
self.assertEqual(out["model"], "deepseek-v4-flash")
self.assertEqual(out["max_tokens"], 2048)
self.assertEqual(out["reasoning_effort"], "high")
self.assertEqual(out["thinking"], {"type": "enabled"})
self.assertEqual(out["stream_options"], {"include_usage": True})
self.assertNotIn("store", out)
self.assertNotIn("metadata", out)
self.assertNotIn("max_output_tokens", out)
self.assertEqual(out["tool_choice"], {"type": "function", "function": {"name": "get_weather"}})
self.assertEqual(len(out["tools"]), 2)
self.assertEqual(out["tools"][0]["function"]["name"], "get_weather")
self.assertEqual(out["tools"][1]["function"]["name"], "apply_patch")
self.assertEqual(out["messages"][0], {"role": "system", "content": "be helpful"})
self.assertEqual(out["messages"][1], {"role": "user", "content": "hi"})
assistant = out["messages"][2]
self.assertEqual(assistant["role"], "assistant")
self.assertEqual(assistant["reasoning_content"], "think first")
self.assertEqual(len(assistant["tool_calls"]), 2)
self.assertEqual(assistant["tool_calls"][0]["id"], "call_1")
self.assertEqual(assistant["tool_calls"][1]["id"], "call_2")
self.assertEqual(out["messages"][3], {"role": "tool", "tool_call_id": "call_1", "content": "22c"})
self.assertEqual(out["messages"][4], {"role": "system", "content": "dev rule"})
self.assertNotIn("n", out)
def test_n_dropped_and_input_file_mapped(self):
out = responses_to_chat_request({
"model": "m",
"n": 2,
"input": [
{"type": "message", "role": "user", "content": [
{"type": "input_text", "text": "look at "},
{"type": "input_file", "file_id": "file-abc", "filename": "a.txt"},
]},
],
})
self.assertNotIn("n", out)
self.assertEqual(
out["messages"][0]["content"],
[
{"type": "text", "text": "look at "},
{"type": "file", "file": {"file_id": "file-abc", "filename": "a.txt"}},
],
)
def test_empty_input_gets_fallback_message(self):
out = responses_to_chat_request({"model": "m", "input": []})
self.assertEqual(out["messages"], [{"role": "user", "content": ""}])
def test_flat_responses_function_tools(self):
out = responses_to_chat_request({
"model": "deepseek-v4-flash",
"input": "hi",
"tools": [
{"type": "function", "name": "get_weather",
"description": "weather",
"parameters": {"type": "object",
"properties": {"q": {"type": "string"}}},
"strict": False},
{"type": "function", "name": "get_time"},
],
"tool_choice": {"type": "function", "name": "get_weather"},
})
self.assertEqual(len(out["tools"]), 2)
self.assertEqual(out["tools"][0]["function"]["name"], "get_weather")
self.assertEqual(out["tools"][0]["function"]["strict"], False)
self.assertEqual(out["tools"][1]["function"]["name"], "get_time")
self.assertEqual(
out["tools"][1]["function"]["parameters"],
{"type": "object", "properties": {}},
)
self.assertEqual(
out["tool_choice"],
{"type": "function", "function": {"name": "get_weather"}},
)
def test_reasoning_content_merged_into_tool_call_assistant(self):
"""DeepSeek 同回合 reasoning + content + tool_calls 必须合并成一条 assistant。"""
out = responses_to_chat_request({
"model": "deepseek-v4-flash",
"input": [
{"type": "message", "role": "user",
"content": [{"type": "input_text", "text": "hi"}]},
{"type": "reasoning",
"content": [{"type": "reasoning_text", "text": "think A"}]},
{"type": "message", "role": "assistant",
"content": [{"type": "output_text", "text": "I will check"}]},
{"type": "function_call", "call_id": "call_1",
"name": "get_weather", "arguments": "{}"},
{"type": "function_call_output", "call_id": "call_1", "output": "22c"},
],
})
self.assertEqual(
[m["role"] for m in out["messages"]], ["user", "assistant", "tool"]
)
assistant = out["messages"][1]
self.assertEqual(assistant["content"], "I will check")
self.assertEqual(assistant["reasoning_content"], "think A")
self.assertEqual(len(assistant["tool_calls"]), 1)
self.assertEqual(assistant["tool_calls"][0]["id"], "call_1")
def test_reasoning_blocks_accumulate(self):
"""多个 reasoning 块必须累加回传,不能覆盖丢失。"""
out = responses_to_chat_request({
"model": "deepseek-v4-flash",
"input": [
{"type": "message", "role": "user", "content": "hi"},
{"type": "reasoning", "content": [{"type": "reasoning_text", "text": "r1"}]},
{"type": "function_call", "call_id": "c1", "name": "f1", "arguments": "{}"},
{"type": "reasoning", "content": [{"type": "reasoning_text", "text": "r2"}]},
{"type": "function_call", "call_id": "c2", "name": "f2", "arguments": "{}"},
{"type": "function_call_output", "call_id": "c1", "output": "x"},
],
})
assistants = [m for m in out["messages"] if m["role"] == "assistant"]
self.assertEqual(len(assistants), 1)
self.assertEqual(assistants[0]["reasoning_content"], "r1r2")
self.assertEqual(
[c["function"]["name"] for c in assistants[0]["tool_calls"]], ["f1", "f2"]
)
def test_arguments_dict_encoded(self):
"""function_call 的 arguments 为对象时直接序列化本体,不能包成 {"input": null}。"""
out = responses_to_chat_request({
"model": "deepseek-v4-flash",
"input": [
{"type": "function_call", "call_id": "c1", "name": "apply_patch",
"arguments": {"patch": "x"}},
{"type": "function_call_output", "call_id": "c1", "output": "ok"},
],
})
self.assertEqual(
out["messages"][0]["tool_calls"][0]["function"]["arguments"],
'{"patch": "x"}',
)
def test_tool_search_items_dropped(self):
"""tool_search 工具被丢弃,输入里的 call/output 也应跳过,不能变空名函数。"""
out = responses_to_chat_request({
"model": "deepseek-v4-flash",
"input": [
{"type": "tool_search_call", "call_id": "ts1",
"name": "tool_search", "arguments": "{}"},
{"type": "tool_search_output", "call_id": "ts1", "output": "x"},
],
})
self.assertEqual(out["messages"], [{"role": "user", "content": ""}])
self.assertNotIn("tool_calls", out["messages"][0])
def test_dropped_tools_and_fields_aggregated_log(self):
"""同一请求里被丢弃的工具和字段各自聚合,不逐条刷屏。"""
request_logger = logging.getLogger("responses-proxy")
with self.assertLogs(request_logger, level="DEBUG") as captured:
responses_to_chat_request({
"model": "deepseek-v4-flash",
"input": "hi",
"tools": [
{"type": "namespace", "name": "n"},
{"type": "tool_search"},
{"type": "namespace", "name": "n2"},
{"type": "function", "name": "f", "parameters": {}},
{"type": "web_search"},
],
"include": ["reasoning"],
"store": False,
})
tool_lines = [
line for line in captured.output
if "丢弃 Chat 不支持的 tool" in line
]
field_lines = [
line for line in captured.output
if "丢弃 Chat 协议不支持的字段" in line
]
self.assertEqual(len(tool_lines), 1)
self.assertEqual(len(field_lines), 1)
self.assertIn("namespace、tool_search、web_search", tool_lines[0])
self.assertIn("include、store", field_lines[0])
def test_custom_tool_without_name_skipped(self):
"""custom 工具没有 name 时与 function 分支一致跳过,不能生成空名函数。"""
out = responses_to_chat_request({
"model": "deepseek-v4-flash",
"input": "hi",
"tools": [
{"type": "custom", "description": "no name"},
{"type": "custom", "name": "apply_patch", "description": "patch"},
],
})
self.assertEqual(len(out["tools"]), 1)
self.assertEqual(out["tools"][0]["function"]["name"], "apply_patch")
def test_text_format_strict_only_when_explicit(self):
"""text.format 未显式给 strict 时不能静默强制 strict=True。"""
out = responses_to_chat_request({
"model": "deepseek-v4-flash",
"input": "hi",
"text": {"format": {"type": "json_schema", "name": "s", "schema": {}}},
})
json_schema = out["response_format"]["json_schema"]
self.assertNotIn("strict", json_schema)
out = responses_to_chat_request({
"model": "deepseek-v4-flash",
"input": "hi",
"text": {"format": {"type": "json_schema", "name": "s",
"schema": {}, "strict": False}},
})
self.assertIs(out["response_format"]["json_schema"]["strict"], False)
def test_empty_choices_not_masked_as_completed(self):
"""200 但无 choices 是异常响应,不能伪装成 completed。"""
with self.assertRaises(ChatUpstreamError):
chat_to_responses({"id": "x", "choices": []}, request_model="deepseek-v4-flash")
events = chat_json_to_sse_events(
{"id": "x", "choices": []}, request_model="deepseek-v4-flash"
)
last = json.loads(events[-1].decode("utf-8").split("data: ", 1)[1])
self.assertEqual(last["type"], "response.failed")
self.assertEqual(last["response"]["error"]["code"], "invalid_upstream_response")
def test_normalize_string_content_and_encrypted_content(self):
"""agent_message 字符串 content 不能丢;encrypted_content 非字符串也要处理。"""
normalized = normalize_agent_messages({
"type": "agent_message",
"id": "a",
"content": "直接字符串任务内容",
})
self.assertEqual(
normalized["content"],
[{"type": "input_text", "text": "直接字符串任务内容"}],
)
normalized = normalize_agent_messages(
{"type": "encrypted_content", "encrypted_content": 12345}
)
self.assertEqual(normalized, {"type": "input_text", "text": "12345"})
normalized = normalize_agent_messages({"type": "encrypted_content"})
self.assertEqual(normalized, {"type": "input_text", "text": ""})
def test_normalize_nesting_too_deep(self):
"""深嵌套请求不能触发 RecursionError,应显式 400。"""
nested = {"leaf": True}
for _ in range(150):
nested = {"child": nested}
with self.assertRaises(_BadRequest):
normalize_agent_messages(nested)
def test_log_safe_and_redact_secrets(self):
self.assertEqual(_log_safe("a\nb\rc"), "a\\nb\\rc")
self.assertEqual(_log_safe("bad \ufffd byte"), "bad \\ufffd byte")
self.assertEqual(
_redact_secrets("error: Bearer sk-abcdef123456"), "error: Bearer ***"
)
self.assertNotIn("sk-abcdef123456", _redact_secrets("token=sk-abcdef123456"))
def test_extract_upstream_error_binary_body(self):
raw = b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\xff\x01\x02\x03"
message = extract_upstream_error(404, raw)
self.assertIn("HTTP 404", message)
self.assertIn("gzip-compressed body", message)
self.assertIn("14 bytes", message)
self.assertNotIn("\ufffd", message)
def test_binary_error_body_logged_as_summary(self):
request_logger = logging.getLogger("responses-proxy")
self.upstream.mode = "binary_error"
self.upstream.status = 404
try:
with self.assertLogs(request_logger, level="DEBUG") as captured:
self.post(
"/robots.txt",
{"model": "m", "input": []},
)
lines = "\n".join(captured.output)
self.assertIn("error=upstream returned HTTP 404 (gzip-compressed body", lines)
self.assertNotIn("\ufffd", lines)
finally:
self.upstream.mode = "json"
self.upstream.status = 200
self.upstream.response_payload = {"ok": True}
def test_chat_json_fallback_keeps_multiple_tool_calls(self):
"""上游忽略 stream=true 返回整段 JSON 时,多个 tool_calls 不能塌陷成一个。"""
chat = {
"id": "chatcmpl-multi",
"model": "deepseek-v4-flash",
"choices": [{
"finish_reason": "tool_calls",
"message": {"role": "assistant", "content": "", "tool_calls": [
{"id": "call_1", "type": "function",
"function": {"name": "get_weather", "arguments": '{"q":"sh"}'}},
{"id": "call_2", "type": "function",
"function": {"name": "get_time", "arguments": '{"city":"sh"}'}},
]},
}],
}
events = chat_json_to_sse_events(chat, request_model="deepseek-v4-flash")
calls = []
for event in events:
data = json.loads(event.decode("utf-8").split("data: ", 1)[1])
if data["type"] == "response.output_item.done" and \
data.get("item", {}).get("type") == "function_call":
item = data["item"]
calls.append((item["name"], item["arguments"]))
self.assertEqual(
calls,
[("get_weather", '{"q":"sh"}'), ("get_time", '{"city":"sh"}')],
)
def test_stream_tool_calls_without_index_continue_single_tool(self):
"""流式 tool delta 无 index 时,无标识续片接续最近打开的调用。"""
t = ChatToResponsesStream("deepseek-v4-flash")
events = t.feed_chunk({
"choices": [{"delta": {"tool_calls": [
{"id": "call_a", "type": "function",
"function": {"name": "f1", "arguments": "{"}}
]}, "finish_reason": None}]
})
events += t.feed_chunk({
"choices": [{"delta": {"tool_calls": [
{"type": "function", "function": {"arguments": '"a":1}'}}
]}, "finish_reason": "tool_calls"}]
})
events += t.finish()
calls = []
for event in events:
data = json.loads(event.decode("utf-8").split("data: ", 1)[1])
if data["type"] == "response.output_item.done" and \
data.get("item", {}).get("type") == "function_call":
item = data["item"]
calls.append((item["name"], item["arguments"]))
self.assertEqual(calls, [("f1", '{"a":1}')])
def test_translator_output_cap_fails(self):
"""累积输出超过上限时发 response.failed,不伪装成功。"""
t = ChatToResponsesStream("deepseek-v4-flash", max_output_bytes=10)
events = t.feed_chunk({
"choices": [{"delta": {"content": "x" * 11}, "finish_reason": None}]
})
types = [
json.loads(event.decode("utf-8").split("data: ", 1)[1])["type"]
for event in events
]
self.assertEqual(types[-1], "response.failed")
self.assertIn("output_too_large", events[-1].decode("utf-8"))
self.assertNotIn("response.completed", events[-1].decode("utf-8"))
def test_stream_tool_call_id_preserved(self):
"""流式 tool delta 显式给出 id 时,function_call 的 call_id 应沿用上游 id。"""
t = ChatToResponsesStream("deepseek-v4-flash")
events = t.feed_chunk({
"choices": [{"delta": {"tool_calls": [
{"index": 0, "id": "call_upstream_1", "type": "function",
"function": {"name": "f1", "arguments": "{}"}}
]}, "finish_reason": "tool_calls"}]
})
events += t.finish()
call_ids = []
for event in events:
data = json.loads(event.decode("utf-8").split("data: ", 1)[1])
if data["type"] == "response.output_item.done" and \
data.get("item", {}).get("type") == "function_call":
call_ids.append(data["item"]["call_id"])
self.assertEqual(call_ids, ["call_upstream_1"])
def test_message_after_tool_closes_tool(self):
"""content 出现在 tool_calls 之后时,先关闭 tool 再开 message,不能同时 in_progress。"""
t = ChatToResponsesStream("deepseek-v4-flash")
events = t.feed_chunk({
"choices": [{"delta": {"tool_calls": [
{"index": 0, "id": "call_a", "function": {"name": "f1", "arguments": "{}"}}
]}, "finish_reason": None}]
})
events += t.feed_chunk({
"choices": [{"delta": {"content": "after tool"}, "finish_reason": None}]
})
opened = []
done = []
for event in events:
data = json.loads(event.decode("utf-8").split("data: ", 1)[1])
if data["type"] == "response.output_item.added":
opened.append(data["item"]["type"])
elif data["type"] == "response.output_item.done":
done.append(data["item"]["type"])
self.assertEqual(opened, ["function_call", "message"])
self.assertEqual(done, ["function_call"])
def test_failed_event_includes_partial_output(self):
"""流中途 fail 时,已产生的部分输出要进入 failed 快照。"""