python-codex 0.5.2__py3-none-any.whl → 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. pycodex/__init__.py +22 -12
  2. pycodex/agent.py +89 -74
  3. pycodex/bootstrap.py +37 -251
  4. pycodex/cli.py +19 -28
  5. pycodex/config.py +36 -0
  6. pycodex/context.py +368 -51
  7. pycodex/events.py +14 -187
  8. pycodex/model.py +197 -95
  9. pycodex/multi_agents.py +401 -0
  10. pycodex/portable/__init__.py +8 -6
  11. pycodex/portable/client.py +24 -39
  12. pycodex/portable/protocol.py +28 -0
  13. pycodex/portable/server.py +3 -3
  14. pycodex/prompts/developer_messages.json +13 -0
  15. pycodex/prompts/goals/budget_limit.md +19 -0
  16. pycodex/prompts/goals/continuation.md +56 -0
  17. pycodex/prompts/models.json +1143 -200
  18. pycodex/protocol.py +81 -15
  19. pycodex/runtime.py +370 -226
  20. pycodex/tools/__init__.py +102 -10
  21. pycodex/tools/agent_tool_schemas.py +0 -38
  22. pycodex/tools/apply_patch_tool.py +17 -34
  23. pycodex/tools/base_tool.py +63 -35
  24. pycodex/tools/clock_manager.py +182 -0
  25. pycodex/tools/clock_tool.py +58 -187
  26. pycodex/tools/code_mode_manager.py +165 -246
  27. pycodex/tools/exec_command_tool.py +0 -18
  28. pycodex/tools/exec_runtime.py +332 -0
  29. pycodex/tools/exec_tool.py +74 -31
  30. pycodex/tools/followup_task_tool.py +44 -0
  31. pycodex/tools/goal_manager.py +205 -0
  32. pycodex/tools/goal_tool.py +126 -0
  33. pycodex/tools/interrupt_agent_tool.py +48 -0
  34. pycodex/tools/list_agents_tool.py +66 -0
  35. pycodex/tools/python_tool_schema.py +141 -0
  36. pycodex/tools/request_permissions_tool.py +1 -0
  37. pycodex/tools/runtime_services.py +122 -450
  38. pycodex/tools/send_message_tool.py +42 -0
  39. pycodex/tools/spawn_agent_tool.py +55 -94
  40. pycodex/tools/unified_exec_manager.py +26 -35
  41. pycodex/tools/wait_agent_tool.py +46 -66
  42. pycodex/tools/wait_tool.py +24 -13
  43. pycodex/tools/web_search_tool.py +1 -0
  44. pycodex/utils/codex_config.py +105 -0
  45. pycodex/utils/compactor.py +4 -0
  46. pycodex/utils/compat.py +43 -2
  47. pycodex/utils/doctor.py +5 -4
  48. pycodex/utils/dotenv.py +0 -7
  49. pycodex/utils/event_helpers.py +143 -13
  50. pycodex/utils/history.py +59 -0
  51. pycodex/utils/session_persist.py +104 -48
  52. python_codex-0.6.1.dist-info/METADATA +201 -0
  53. python_codex-0.6.1.dist-info/RECORD +106 -0
  54. responses_server/__init__.py +2 -0
  55. responses_server/app.py +10 -7
  56. responses_server/config.py +6 -12
  57. responses_server/gemini_api.py +333 -0
  58. responses_server/messages_api.py +9 -1
  59. responses_server/payload_processors.py +4 -4
  60. responses_server/request_translation.py +486 -0
  61. responses_server/server.py +31 -24
  62. responses_server/stream_events.py +124 -0
  63. responses_server/stream_router.py +48 -830
  64. responses_server/tools/custom_adapter.py +29 -29
  65. responses_server/tools/web_search.py +3 -0
  66. responses_server/transport.py +388 -0
  67. pycodex/tools/close_agent_tool.py +0 -60
  68. pycodex/tools/exec_runtime.js +0 -161
  69. pycodex/tools/request_user_input_tool.py +0 -102
  70. pycodex/tools/resume_agent_tool.py +0 -54
  71. pycodex/tools/send_input_tool.py +0 -110
  72. python_codex-0.5.2.dist-info/METADATA +0 -262
  73. python_codex-0.5.2.dist-info/RECORD +0 -90
  74. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/WHEEL +0 -0
  75. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/entry_points.txt +0 -0
  76. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,486 @@
1
+ """Pure Responses-to-chat request translation and request-local tool names."""
2
+
3
+ import json
4
+ import typing
5
+ from copy import deepcopy
6
+
7
+ from .tools import WebSearchTool
8
+ from .tools.custom_adapter import CustomToolAdapterError
9
+ from .tools.custom_adapter import build_tool_call as build_custom_tool_call
10
+ from .tools.custom_adapter import build_tool_definition as build_custom_tool_definition
11
+ from .tools.web_search import build_tool_definition
12
+
13
+
14
+ class UnsupportedIncommingFeature(ValueError):
15
+ pass
16
+
17
+
18
+ class ToolNameMap:
19
+ """Request-local identities for flattened namespace tools and their calls."""
20
+
21
+ def __init__(self) -> "None":
22
+ self._identities: "typing.Dict[str, typing.Tuple[typing.Optional[str], str]]" = {}
23
+ self.custom_tool_names: "typing.Set[str]" = set()
24
+
25
+ def qualify(self, name: "object", namespace: "object" = None) -> "str":
26
+ if not isinstance(name, str) or not name.strip():
27
+ raise UnsupportedIncommingFeature("tool is missing a non-empty `name`")
28
+ name = name.strip()
29
+ if namespace is not None:
30
+ if not isinstance(namespace, str) or not namespace.strip():
31
+ raise UnsupportedIncommingFeature(
32
+ "tool namespace must be a non-empty string"
33
+ )
34
+ namespace = namespace.strip()
35
+ qualified = f"{namespace}__{name}" if namespace is not None else name
36
+ identity = (namespace, name)
37
+ if qualified in self._identities and self._identities[qualified] != identity:
38
+ raise UnsupportedIncommingFeature(
39
+ f"flattened tool name collision: {qualified!r}"
40
+ )
41
+ self._identities[qualified] = identity
42
+ return qualified
43
+
44
+ def restore_output_item(
45
+ self, item: "typing.Dict[str, object]"
46
+ ) -> "typing.Dict[str, object]":
47
+ if item.get("type") not in {"function_call", "custom_tool_call"}:
48
+ return item
49
+ name = item["name"]
50
+ namespace, original_name = self._identities.get(name, (None, name))
51
+ if namespace is None:
52
+ return item
53
+ return dict(item, namespace=namespace, name=original_name)
54
+
55
+
56
+ def build_outcomming_request(
57
+ incomming_request: "typing.Dict[str, object]",
58
+ tool_names: "typing.Union[ToolNameMap, None]" = None,
59
+ ) -> "typing.Dict[str, object]":
60
+ model = str(incomming_request.get("model", "")).strip()
61
+ if not model:
62
+ raise UnsupportedIncommingFeature("incomming request is missing `model`")
63
+
64
+ stream = incomming_request.get("stream", True)
65
+ if stream is not True:
66
+ raise UnsupportedIncommingFeature(
67
+ "only streaming incomming `/responses` requests are supported"
68
+ )
69
+
70
+ instructions = str(incomming_request.get("instructions", "") or "")
71
+ input_items = incomming_request.get("input") or []
72
+ if not isinstance(input_items, list):
73
+ raise UnsupportedIncommingFeature("incomming `input` must be a list")
74
+
75
+ if tool_names is None:
76
+ tool_names = ToolNameMap()
77
+ tools = incomming_request.get("tools") or []
78
+ if not isinstance(tools, list):
79
+ raise UnsupportedIncommingFeature("incomming `tools` must be a list")
80
+ translated_tools = _translate_tools(tools, tool_names)
81
+ payload: "typing.Dict[str, object]" = {
82
+ "model": model,
83
+ "messages": _responses_input_to_chat_messages(
84
+ instructions,
85
+ input_items,
86
+ tool_names,
87
+ ),
88
+ "stream": True,
89
+ }
90
+ reasoning = incomming_request.get("reasoning")
91
+ if isinstance(reasoning, dict):
92
+ reasoning_effort = reasoning.get("effort")
93
+ if isinstance(reasoning_effort, str) and reasoning_effort:
94
+ # vLLM's Responses renderer consumes effort as a template
95
+ # kwarg; keeping it out of the chat schema also preserves
96
+ # provider-specific values such as `max`.
97
+ payload["chat_template_kwargs"] = {
98
+ "reasoning_effort": reasoning_effort,
99
+ }
100
+
101
+ max_tokens = _coerce_positive_int(
102
+ incomming_request.get("max_output_tokens")
103
+ )
104
+ if max_tokens is None:
105
+ max_tokens = _coerce_positive_int(incomming_request.get("max_tokens"))
106
+ if max_tokens is not None:
107
+ payload["max_tokens"] = max_tokens
108
+ payload["stream_options"] = {"include_usage": True}
109
+
110
+ if translated_tools:
111
+ payload["tools"] = translated_tools
112
+
113
+ tool_choice = incomming_request.get("tool_choice")
114
+ if tool_choice is not None:
115
+ payload["tool_choice"] = _translate_tool_choice(
116
+ tool_choice, tool_names,
117
+ )
118
+
119
+ parallel_tool_calls = incomming_request.get("parallel_tool_calls")
120
+ if isinstance(parallel_tool_calls, bool):
121
+ payload["parallel_tool_calls"] = parallel_tool_calls
122
+
123
+ return payload
124
+
125
+
126
+ def _responses_input_to_chat_messages(
127
+ instructions: "str",
128
+ input_items: "typing.List[object]",
129
+ tool_names: "ToolNameMap",
130
+ ) -> "typing.List[typing.Dict[str, object]]":
131
+ messages: "typing.List[typing.Dict[str, object]]" = []
132
+ if instructions:
133
+ messages.append({"role": "developer", "content": instructions})
134
+
135
+ pending_assistant: "typing.Union[typing.Dict[str, object], None]" = None
136
+ pending_tool_images: "typing.List[typing.Dict[str, object]]" = []
137
+
138
+ def flush_pending_assistant() -> "None":
139
+ nonlocal pending_assistant
140
+ if pending_assistant is None:
141
+ return
142
+ if (
143
+ "content" not in pending_assistant
144
+ and "reasoning" not in pending_assistant
145
+ and "tool_calls" not in pending_assistant
146
+ and "provider_data" not in pending_assistant
147
+ ):
148
+ pending_assistant = None
149
+ return
150
+ messages.append(pending_assistant)
151
+ pending_assistant = None
152
+
153
+ def flush_pending_tool_images() -> "None":
154
+ if not pending_tool_images:
155
+ return
156
+ messages.append({"role": "user", "content": list(pending_tool_images)})
157
+ del pending_tool_images[:]
158
+
159
+ for raw_item in input_items:
160
+ if not isinstance(raw_item, dict):
161
+ raise UnsupportedIncommingFeature(
162
+ "all incomming `input` items must be objects"
163
+ )
164
+ item_type = raw_item.get("type")
165
+ if item_type not in {"function_call_output", "custom_tool_call_output"}:
166
+ flush_pending_tool_images()
167
+
168
+ if item_type == "agent_message":
169
+ if not all(
170
+ isinstance(raw_item.get(key), str) for key in ("author", "recipient")
171
+ ):
172
+ raise UnsupportedIncommingFeature(
173
+ "agent_message requires string `author` and `recipient`"
174
+ )
175
+ text, image_parts = _split_content_parts(raw_item.get("content"))
176
+ if image_parts:
177
+ raise UnsupportedIncommingFeature(
178
+ "agent_message content must contain only input_text parts"
179
+ )
180
+ flush_pending_assistant()
181
+ messages.append({
182
+ "role": "user",
183
+ "content": (
184
+ f"Agent message from {raw_item['author']} to "
185
+ f"{raw_item['recipient']}:\n{text}"
186
+ ),
187
+ })
188
+ continue
189
+
190
+ if item_type == "message":
191
+ role = str(raw_item.get("role", "")).strip()
192
+ if role not in {"developer", "user", "assistant", "system"}:
193
+ raise UnsupportedIncommingFeature(
194
+ f"unsupported incomming message role: {role or '<empty>'}"
195
+ )
196
+ text, image_parts = _split_content_parts(raw_item.get("content"))
197
+ if role == "assistant":
198
+ if image_parts:
199
+ raise UnsupportedIncommingFeature(
200
+ "assistant messages cannot carry `input_image` content parts"
201
+ )
202
+ if pending_assistant is None:
203
+ pending_assistant = {"role": "assistant"}
204
+ if text:
205
+ pending_assistant["content"] = (
206
+ str(pending_assistant.get("content", "")) + text
207
+ )
208
+ continue
209
+ flush_pending_assistant()
210
+ if image_parts:
211
+ content: "object" = (
212
+ [{"type": "text", "text": text}] if text else []
213
+ ) + image_parts
214
+ else:
215
+ content = text
216
+ messages.append({"role": role, "content": content})
217
+ continue
218
+
219
+ if item_type == "reasoning":
220
+ if pending_assistant is None:
221
+ pending_assistant = {"role": "assistant"}
222
+ if "provider_data" in raw_item:
223
+ pending_assistant.setdefault("provider_data", []).extend(
224
+ deepcopy(raw_item["provider_data"])
225
+ )
226
+ reasoning_text = coalesce_reasoning_text(raw_item)
227
+ if reasoning_text:
228
+ pending_assistant["reasoning"] = (
229
+ str(pending_assistant.get("reasoning", "")) + reasoning_text
230
+ )
231
+ continue
232
+
233
+ if item_type == "function_call":
234
+ if pending_assistant is None:
235
+ pending_assistant = {"role": "assistant"}
236
+ tool_calls = pending_assistant.setdefault("tool_calls", [])
237
+ if not isinstance(tool_calls, list):
238
+ raise UnsupportedIncommingFeature(
239
+ "assistant tool calls must be a list"
240
+ )
241
+ tool_calls.append(
242
+ {
243
+ "id": str(raw_item.get("call_id", "")).strip(),
244
+ "type": "function",
245
+ "function": {
246
+ "name": tool_names.qualify(
247
+ raw_item.get("name"), raw_item.get("namespace"),
248
+ ),
249
+ "arguments": str(raw_item.get("arguments", "") or "{}"),
250
+ },
251
+ }
252
+ )
253
+ continue
254
+
255
+ if item_type in {"function_call_output", "custom_tool_call_output"}:
256
+ flush_pending_assistant()
257
+ text, image_parts = _split_tool_output_parts(
258
+ raw_item.get("output")
259
+ )
260
+ messages.append(
261
+ {
262
+ "role": "tool",
263
+ "tool_call_id": str(raw_item.get("call_id", "")).strip(),
264
+ "content": text,
265
+ }
266
+ )
267
+ pending_tool_images.extend(image_parts)
268
+ continue
269
+
270
+ if item_type == "custom_tool_call":
271
+ if pending_assistant is None:
272
+ pending_assistant = {"role": "assistant"}
273
+ tool_calls = pending_assistant.setdefault("tool_calls", [])
274
+ if not isinstance(tool_calls, list):
275
+ raise UnsupportedIncommingFeature(
276
+ "assistant tool calls must be a list"
277
+ )
278
+ try:
279
+ tool_call = build_custom_tool_call(raw_item)
280
+ except CustomToolAdapterError as exc:
281
+ raise UnsupportedIncommingFeature(str(exc)) from exc
282
+ tool_call["function"]["name"] = tool_names.qualify(
283
+ raw_item.get("name"), raw_item.get("namespace"),
284
+ )
285
+ tool_calls.append(tool_call)
286
+ continue
287
+
288
+ raise UnsupportedIncommingFeature(
289
+ f"unsupported incomming input item type: {item_type!r}"
290
+ )
291
+
292
+ flush_pending_assistant()
293
+ flush_pending_tool_images()
294
+ return messages
295
+
296
+
297
+ def _coerce_positive_int(raw_value: "object") -> "typing.Union[int, None]":
298
+ if isinstance(raw_value, bool):
299
+ return None
300
+ if isinstance(raw_value, int) and raw_value > 0:
301
+ return raw_value
302
+ return None
303
+
304
+
305
+ def _split_content_parts(
306
+ raw_content: "object",
307
+ ) -> "typing.Tuple[str, typing.List[typing.Dict[str, object]]]":
308
+ if raw_content is None:
309
+ return "", []
310
+ if isinstance(raw_content, str):
311
+ return raw_content, []
312
+ if not isinstance(raw_content, list):
313
+ raise UnsupportedIncommingFeature(
314
+ "message `content` must be a list or string"
315
+ )
316
+
317
+ text_parts: "typing.List[str]" = []
318
+ image_parts: "typing.List[typing.Dict[str, object]]" = []
319
+ for part in raw_content:
320
+ if not isinstance(part, dict):
321
+ raise UnsupportedIncommingFeature(
322
+ "message content parts must be objects"
323
+ )
324
+ part_type = part.get("type")
325
+ if part_type in {"input_text", "output_text"}:
326
+ text_parts.append(str(part.get("text", "")))
327
+ continue
328
+ if part_type == "input_image":
329
+ image_parts.append(_build_chat_image_part(part))
330
+ continue
331
+ raise UnsupportedIncommingFeature(
332
+ f"content part type `{part_type}` is not yet supported by the chat backend"
333
+ )
334
+ return "".join(text_parts), image_parts
335
+
336
+
337
+ def _build_chat_image_part(
338
+ part: "typing.Dict[str, object]",
339
+ ) -> "typing.Dict[str, object]":
340
+ image_url = str(part.get("image_url", "") or "").strip()
341
+ if not image_url:
342
+ raise UnsupportedIncommingFeature(
343
+ "`input_image` content parts must carry a non-empty `image_url`"
344
+ )
345
+ image_payload: "typing.Dict[str, object]" = {"url": image_url}
346
+ detail = part.get("detail")
347
+ if isinstance(detail, str) and detail in {"auto", "low", "high"}:
348
+ image_payload["detail"] = detail
349
+ return {"type": "image_url", "image_url": image_payload}
350
+
351
+
352
+ def _split_tool_output_parts(
353
+ raw_output: "object",
354
+ ) -> "typing.Tuple[str, typing.List[typing.Dict[str, object]]]":
355
+ if isinstance(raw_output, str):
356
+ return raw_output, []
357
+ if isinstance(raw_output, list):
358
+ return _split_content_parts(raw_output)
359
+ return json.dumps(raw_output, ensure_ascii=False), []
360
+
361
+
362
+ def coalesce_reasoning_text(raw_item: "typing.Dict[str, object]") -> "str":
363
+ content = raw_item.get("content")
364
+ if isinstance(content, list):
365
+ text_parts: "typing.List[str]" = []
366
+ for part in content:
367
+ if not isinstance(part, dict):
368
+ continue
369
+ part_type = part.get("type")
370
+ if part_type in {"reasoning_text", "summary_text"}:
371
+ text_parts.append(str(part.get("text", "")))
372
+ if text_parts:
373
+ return "".join(text_parts)
374
+
375
+ summary = raw_item.get("summary")
376
+ if isinstance(summary, list):
377
+ text_parts = []
378
+ for part in summary:
379
+ if not isinstance(part, dict):
380
+ continue
381
+ if part.get("type") == "summary_text":
382
+ text_parts.append(str(part.get("text", "")))
383
+ if text_parts:
384
+ return "".join(text_parts)
385
+
386
+ for key in ("reasoning", "reasoning_content", "text"):
387
+ value = raw_item.get(key)
388
+ if isinstance(value, str) and value:
389
+ return value
390
+ return ""
391
+
392
+
393
+ def _translate_tools(
394
+ incomming_tools: "typing.List[object]",
395
+ tool_names: "ToolNameMap",
396
+ namespace: "typing.Union[str, None]" = None,
397
+ namespace_description: "str" = "",
398
+ ) -> "typing.List[typing.Dict[str, object]]":
399
+ translated: "typing.List[typing.Dict[str, object]]" = []
400
+ for raw_tool in incomming_tools:
401
+ if not isinstance(raw_tool, dict):
402
+ raise UnsupportedIncommingFeature("tool definitions must be objects")
403
+ tool_type = raw_tool.get("type")
404
+ if namespace is not None and tool_type not in {"function", "custom"}:
405
+ raise UnsupportedIncommingFeature(
406
+ "namespace tools must be function or custom tools"
407
+ )
408
+ if tool_type == "namespace":
409
+ namespace_name = raw_tool.get("name")
410
+ if not isinstance(namespace_name, str) or not namespace_name.strip():
411
+ raise UnsupportedIncommingFeature(
412
+ "namespace is missing a non-empty `name`"
413
+ )
414
+ nested_tools = raw_tool.get("tools")
415
+ if not isinstance(nested_tools, list):
416
+ raise UnsupportedIncommingFeature("namespace `tools` must be a list")
417
+ translated.extend(
418
+ _translate_tools(
419
+ nested_tools,
420
+ tool_names,
421
+ namespace_name,
422
+ str(raw_tool.get("description", "") or ""),
423
+ )
424
+ )
425
+ continue
426
+ if tool_type == "function":
427
+ name = tool_names.qualify(raw_tool.get("name"), namespace)
428
+ tool = {
429
+ "type": "function",
430
+ "name": name,
431
+ "function": {
432
+ "name": name,
433
+ "description": str(raw_tool.get("description", "") or ""),
434
+ "parameters": raw_tool.get("parameters") or {"type": "object"},
435
+ "strict": bool(raw_tool.get("strict", False)),
436
+ },
437
+ }
438
+ elif tool_type == "web_search":
439
+ tool_names.qualify(WebSearchTool.name)
440
+ translated.append(build_tool_definition(WebSearchTool()))
441
+ continue
442
+ elif tool_type == "custom":
443
+ try:
444
+ tool = build_custom_tool_definition(raw_tool)
445
+ except CustomToolAdapterError as exc:
446
+ raise UnsupportedIncommingFeature(str(exc)) from exc
447
+ name = tool_names.qualify(raw_tool.get("name"), namespace)
448
+ tool["name"] = name
449
+ tool["function"]["name"] = name
450
+ tool_names.custom_tool_names.add(name)
451
+ else:
452
+ raise UnsupportedIncommingFeature(
453
+ f"unsupported incomming tool type: {tool_type!r}"
454
+ )
455
+ if namespace_description:
456
+ tool["function"]["description"] = (
457
+ namespace_description + "\n\n" + tool["function"]["description"]
458
+ )
459
+ translated.append(tool)
460
+ return translated
461
+
462
+
463
+ def _translate_tool_choice(
464
+ raw_tool_choice: "object", tool_names: "ToolNameMap",
465
+ ) -> "object":
466
+ if isinstance(raw_tool_choice, str):
467
+ return raw_tool_choice
468
+ if not isinstance(raw_tool_choice, dict):
469
+ raise UnsupportedIncommingFeature("unsupported `tool_choice` shape")
470
+
471
+ choice_type = raw_tool_choice.get("type")
472
+ if choice_type in {"function", "custom"}:
473
+ name = raw_tool_choice.get("name")
474
+ if not isinstance(name, str) or not name.strip():
475
+ raise UnsupportedIncommingFeature(
476
+ f"{choice_type} tool_choice is missing `name`"
477
+ )
478
+ return {
479
+ "type": "function",
480
+ "function": {
481
+ "name": tool_names.qualify(name, raw_tool_choice.get("namespace")),
482
+ },
483
+ }
484
+ raise UnsupportedIncommingFeature(
485
+ f"unsupported incomming tool_choice type: {choice_type!r}"
486
+ )
@@ -1,10 +1,20 @@
1
1
  import typing
2
+ from dataclasses import dataclass
2
3
 
3
4
  from .config import CompatServerConfig
4
5
  from .payload_processors import post_process_outcomming_request
6
+ from .request_translation import ToolNameMap, build_outcomming_request
5
7
  from .session_store import SessionStore
6
8
  from .stream_router import StreamRouter
7
9
  from .trajectory_dump import TrajectoryDumpWriter
10
+ from .transport import OutcommingTransport
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class PreparedResponse:
15
+ request_body: "typing.Dict[str, object]"
16
+ outcomming_request: "typing.Dict[str, object]"
17
+ tool_names: "ToolNameMap"
8
18
 
9
19
 
10
20
  class ResponseServer:
@@ -14,52 +24,49 @@ class ResponseServer:
14
24
  session_store: "typing.Union[SessionStore, None]" = None,
15
25
  stream_router: "typing.Union[StreamRouter, None]" = None,
16
26
  ) -> "None":
17
- self._config = config
18
- self._session_store = session_store or SessionStore()
19
- self._stream_router = stream_router or StreamRouter(config)
27
+ self.config = config
28
+ self.session_store = session_store or SessionStore()
29
+ self.stream_router = stream_router or StreamRouter(OutcommingTransport(config))
20
30
  self._trajectory_dump = TrajectoryDumpWriter.from_env()
21
31
 
22
- @property
23
- def config(self) -> "CompatServerConfig":
24
- return self._config
25
-
26
- @property
27
- def session_store(self) -> "SessionStore":
28
- return self._session_store
29
-
30
- @property
31
- def stream_router(self) -> "StreamRouter":
32
- return self._stream_router
33
-
34
32
  def list_models(self) -> "typing.Dict[str, object]":
35
- return self._stream_router.list_models()
33
+ return self.stream_router.transport.list_models()
34
+
35
+ def prepare_response(
36
+ self, request_body: "typing.Dict[str, object]",
37
+ ) -> "PreparedResponse":
38
+ tool_names = ToolNameMap()
39
+ return PreparedResponse(
40
+ request_body,
41
+ build_outcomming_request(request_body, tool_names),
42
+ tool_names,
43
+ )
36
44
 
37
45
  def start_response_stream(
38
46
  self,
39
- request_body: "typing.Dict[str, object]",
47
+ prepared: "PreparedResponse",
40
48
  request_headers: "typing.Dict[str, str]",
41
49
  ):
42
- outcomming_request = self._stream_router.build_outcomming_request(request_body)
50
+ outcomming_request = prepared.outcomming_request
43
51
  if self._trajectory_dump is not None:
44
52
  # vLLM surfaces prompt/decode token IDs only when this flag is set.
45
53
  outcomming_request["return_token_ids"] = True
46
54
  outcomming_request = post_process_outcomming_request(
47
55
  outcomming_request,
48
- self._config.model_provider,
56
+ self.config.model_provider,
49
57
  )
50
- custom_tool_names = self._stream_router.collect_custom_tool_names(request_body)
51
58
  session_id = (
52
59
  request_headers.get("x-client-request-id")
53
- or str(request_body.get("prompt_cache_key", "")).strip()
60
+ or str(prepared.request_body.get("prompt_cache_key", "")).strip()
54
61
  or None
55
62
  )
56
- stored_response = self._session_store.create_response(
63
+ stored_response = self.session_store.create_response(
57
64
  session_id=session_id,
58
65
  model=str(outcomming_request["model"]),
59
66
  )
60
- return self._stream_router.route_stream(
67
+ return self.stream_router.route_stream(
61
68
  stored_response,
62
69
  outcomming_request,
63
- custom_tool_names,
70
+ prepared.tool_names,
64
71
  self._trajectory_dump,
65
72
  )