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