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.
- pycodex/__init__.py +18 -8
- pycodex/agent.py +89 -74
- pycodex/bootstrap.py +27 -239
- pycodex/cli.py +19 -14
- pycodex/config.py +36 -0
- pycodex/context.py +369 -51
- pycodex/events.py +13 -186
- pycodex/model.py +181 -88
- pycodex/multi_agents.py +401 -0
- pycodex/portable/__init__.py +8 -6
- pycodex/portable/client.py +24 -39
- pycodex/portable/protocol.py +28 -0
- pycodex/portable/server.py +3 -3
- pycodex/prompts/developer_messages.json +13 -0
- pycodex/prompts/goals/budget_limit.md +19 -0
- pycodex/prompts/goals/continuation.md +56 -0
- pycodex/prompts/models.json +1069 -140
- pycodex/protocol.py +78 -15
- pycodex/runtime.py +370 -226
- pycodex/tools/__init__.py +100 -7
- pycodex/tools/agent_tool_schemas.py +0 -38
- pycodex/tools/apply_patch_tool.py +17 -34
- pycodex/tools/base_tool.py +63 -35
- pycodex/tools/clock_manager.py +182 -0
- pycodex/tools/clock_tool.py +2 -181
- pycodex/tools/code_mode_manager.py +165 -246
- pycodex/tools/exec_command_tool.py +0 -18
- pycodex/tools/exec_runtime.py +381 -0
- pycodex/tools/exec_tool.py +78 -31
- pycodex/tools/followup_task_tool.py +44 -0
- pycodex/tools/goal_manager.py +205 -0
- pycodex/tools/goal_tool.py +126 -0
- pycodex/tools/interrupt_agent_tool.py +48 -0
- pycodex/tools/list_agents_tool.py +66 -0
- pycodex/tools/python_tool_schema.py +141 -0
- pycodex/tools/request_permissions_tool.py +1 -0
- pycodex/tools/request_user_input_tool.py +3 -23
- pycodex/tools/runtime_services.py +122 -450
- pycodex/tools/send_message_tool.py +42 -0
- pycodex/tools/spawn_agent_tool.py +55 -94
- pycodex/tools/unified_exec_manager.py +26 -35
- pycodex/tools/wait_agent_tool.py +46 -66
- pycodex/tools/wait_tool.py +24 -13
- pycodex/tools/web_search_tool.py +1 -0
- pycodex/utils/codex_config.py +105 -0
- pycodex/utils/compactor.py +4 -0
- pycodex/utils/compat.py +2 -2
- pycodex/utils/doctor.py +5 -4
- pycodex/utils/event_helpers.py +143 -13
- pycodex/utils/history.py +33 -0
- pycodex/utils/session_persist.py +78 -36
- {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/METADATA +117 -27
- python_codex-0.6.0.dist-info/RECORD +106 -0
- responses_server/__init__.py +2 -0
- responses_server/app.py +7 -6
- responses_server/config.py +0 -11
- responses_server/payload_processors.py +4 -4
- responses_server/request_translation.py +480 -0
- responses_server/server.py +31 -24
- responses_server/stream_events.py +124 -0
- responses_server/stream_router.py +33 -830
- responses_server/tools/custom_adapter.py +29 -29
- responses_server/transport.py +332 -0
- pycodex/tools/close_agent_tool.py +0 -60
- pycodex/tools/exec_runtime.js +0 -161
- pycodex/tools/resume_agent_tool.py +0 -54
- pycodex/tools/send_input_tool.py +0 -110
- python_codex-0.5.2.dist-info/RECORD +0 -90
- {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/WHEEL +0 -0
- {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/entry_points.txt +0 -0
- {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,355 +1,34 @@
|
|
|
1
|
-
|
|
1
|
+
"""Coordinate downstream streams, retries, mock tool follow-ups and output."""
|
|
2
|
+
|
|
2
3
|
import json
|
|
3
|
-
import ssl
|
|
4
|
-
import time
|
|
5
4
|
import typing
|
|
6
|
-
import urllib.error
|
|
7
|
-
import urllib.request
|
|
8
|
-
from contextlib import contextmanager
|
|
9
5
|
|
|
10
|
-
from .
|
|
11
|
-
from .messages_api import MessagesAPIAdapterError, build_messages_request
|
|
12
|
-
from .messages_api import iter_chat_chunks as iter_chat_chunks_from_messages
|
|
13
|
-
from .messages_api import saw_message_stop as messages_saw_message_stop
|
|
6
|
+
from .request_translation import ToolNameMap, coalesce_reasoning_text
|
|
14
7
|
from .session_store import StoredResponse
|
|
15
|
-
from .
|
|
8
|
+
from .stream_events import ResponseOutputStream
|
|
9
|
+
from .tools import WebSearchTool
|
|
16
10
|
from .tools.custom_adapter import CustomToolAdapterError
|
|
17
11
|
from .tools.custom_adapter import build_output_item as build_custom_output_item
|
|
18
|
-
from .tools.custom_adapter import build_tool_call as build_custom_tool_call
|
|
19
|
-
from .tools.custom_adapter import build_tool_definition as build_custom_tool_definition
|
|
20
12
|
from .tools.web_search import (
|
|
21
13
|
build_followup_request,
|
|
22
14
|
build_output_items,
|
|
23
|
-
build_tool_definition,
|
|
24
15
|
hydrate_tool_call_names,
|
|
25
16
|
partition_tool_calls,
|
|
26
17
|
)
|
|
27
18
|
from .trajectory_dump import TrajectoryDumpWriter
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
class UnsupportedIncommingFeature(ValueError):
|
|
31
|
-
pass
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
class OutcommingChatError(RuntimeError):
|
|
35
|
-
def __init__(
|
|
36
|
-
self,
|
|
37
|
-
message: "str",
|
|
38
|
-
error_type: "typing.Union[str, None]" = None,
|
|
39
|
-
) -> "None":
|
|
40
|
-
super().__init__(message)
|
|
41
|
-
self.error_type = error_type
|
|
19
|
+
from .transport import OutcommingChatError, OutcommingTransport
|
|
42
20
|
|
|
43
21
|
|
|
44
22
|
class StreamRouter:
|
|
45
|
-
def __init__(self,
|
|
46
|
-
self.
|
|
23
|
+
def __init__(self, transport: "OutcommingTransport") -> "None":
|
|
24
|
+
self.transport = transport
|
|
47
25
|
self._mock_web_search = WebSearchTool()
|
|
48
26
|
|
|
49
|
-
def _provider_capability(
|
|
50
|
-
self,
|
|
51
|
-
explicit_support: "typing.Dict[str, bool]",
|
|
52
|
-
default: "typing.Union[bool, None]" = None,
|
|
53
|
-
) -> "bool":
|
|
54
|
-
provider_name = str(self._config.model_provider or "").strip().lower()
|
|
55
|
-
if provider_name in explicit_support:
|
|
56
|
-
return explicit_support[provider_name]
|
|
57
|
-
if "vllm" in explicit_support:
|
|
58
|
-
return explicit_support["vllm"]
|
|
59
|
-
if default is not None:
|
|
60
|
-
return default
|
|
61
|
-
raise KeyError("provider capability map is missing `vllm` fallback")
|
|
62
|
-
|
|
63
|
-
def _supports_chat_reasoning(self) -> "bool":
|
|
64
|
-
# Unknown providers inherit the vLLM compatibility behavior unless a
|
|
65
|
-
# provider is explicitly declared otherwise.
|
|
66
|
-
return self._provider_capability(
|
|
67
|
-
{
|
|
68
|
-
"vllm": True,
|
|
69
|
-
"stepfun": True,
|
|
70
|
-
}
|
|
71
|
-
)
|
|
72
|
-
|
|
73
|
-
def _supports_stream_usage(self) -> "bool":
|
|
74
|
-
return self._provider_capability(
|
|
75
|
-
{
|
|
76
|
-
"vllm": True,
|
|
77
|
-
"stepfun": True,
|
|
78
|
-
}
|
|
79
|
-
)
|
|
80
|
-
|
|
81
|
-
def validate_incomming_request(
|
|
82
|
-
self,
|
|
83
|
-
incomming_request: "typing.Dict[str, object]",
|
|
84
|
-
) -> "None":
|
|
85
|
-
model = str(incomming_request.get("model", "")).strip()
|
|
86
|
-
if not model:
|
|
87
|
-
raise UnsupportedIncommingFeature("incomming request is missing `model`")
|
|
88
|
-
|
|
89
|
-
stream = incomming_request.get("stream", True)
|
|
90
|
-
if stream is not True:
|
|
91
|
-
raise UnsupportedIncommingFeature(
|
|
92
|
-
"only streaming incomming `/responses` requests are supported"
|
|
93
|
-
)
|
|
94
|
-
|
|
95
|
-
input_items = incomming_request.get("input") or []
|
|
96
|
-
if not isinstance(input_items, list):
|
|
97
|
-
raise UnsupportedIncommingFeature("incomming `input` must be a list")
|
|
98
|
-
|
|
99
|
-
self.build_outcomming_request(incomming_request)
|
|
100
|
-
|
|
101
|
-
def collect_custom_tool_names(
|
|
102
|
-
self,
|
|
103
|
-
incomming_request: "typing.Dict[str, object]",
|
|
104
|
-
) -> "typing.Set[str]":
|
|
105
|
-
return collect_custom_tool_names(incomming_request.get("tools") or [])
|
|
106
|
-
|
|
107
|
-
def list_models(self) -> "typing.Dict[str, object]":
|
|
108
|
-
request = urllib.request.Request(
|
|
109
|
-
self._config.outcomming_models_url(),
|
|
110
|
-
headers=self._build_headers(accept="application/json"),
|
|
111
|
-
method="GET",
|
|
112
|
-
)
|
|
113
|
-
return self._request_json(request)
|
|
114
|
-
|
|
115
|
-
def build_outcomming_request(
|
|
116
|
-
self,
|
|
117
|
-
incomming_request: "typing.Dict[str, object]",
|
|
118
|
-
) -> "typing.Dict[str, object]":
|
|
119
|
-
model = str(incomming_request.get("model", "")).strip()
|
|
120
|
-
if not model:
|
|
121
|
-
raise UnsupportedIncommingFeature("incomming request is missing `model`")
|
|
122
|
-
|
|
123
|
-
stream = incomming_request.get("stream", True)
|
|
124
|
-
if stream is not True:
|
|
125
|
-
raise UnsupportedIncommingFeature(
|
|
126
|
-
"only streaming incomming `/responses` requests are supported"
|
|
127
|
-
)
|
|
128
|
-
|
|
129
|
-
instructions = str(incomming_request.get("instructions", "") or "")
|
|
130
|
-
input_items = incomming_request.get("input") or []
|
|
131
|
-
if not isinstance(input_items, list):
|
|
132
|
-
raise UnsupportedIncommingFeature("incomming `input` must be a list")
|
|
133
|
-
|
|
134
|
-
payload: "typing.Dict[str, object]" = {
|
|
135
|
-
"model": model,
|
|
136
|
-
"messages": self._responses_input_to_chat_messages(
|
|
137
|
-
instructions,
|
|
138
|
-
input_items,
|
|
139
|
-
),
|
|
140
|
-
"stream": True,
|
|
141
|
-
}
|
|
142
|
-
reasoning = incomming_request.get("reasoning")
|
|
143
|
-
if isinstance(reasoning, dict):
|
|
144
|
-
reasoning_effort = reasoning.get("effort")
|
|
145
|
-
if isinstance(reasoning_effort, str) and reasoning_effort:
|
|
146
|
-
# vLLM's Responses renderer consumes effort as a template
|
|
147
|
-
# kwarg; keeping it out of the chat schema also preserves
|
|
148
|
-
# provider-specific values such as `max`.
|
|
149
|
-
payload["chat_template_kwargs"] = {
|
|
150
|
-
"reasoning_effort": reasoning_effort,
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
max_tokens = self._coerce_positive_int(
|
|
154
|
-
incomming_request.get("max_output_tokens")
|
|
155
|
-
)
|
|
156
|
-
if max_tokens is None:
|
|
157
|
-
max_tokens = self._coerce_positive_int(incomming_request.get("max_tokens"))
|
|
158
|
-
if max_tokens is not None:
|
|
159
|
-
payload["max_tokens"] = max_tokens
|
|
160
|
-
if self._supports_stream_usage():
|
|
161
|
-
payload["stream_options"] = {"include_usage": True}
|
|
162
|
-
|
|
163
|
-
tools = incomming_request.get("tools") or []
|
|
164
|
-
if tools:
|
|
165
|
-
if not isinstance(tools, list):
|
|
166
|
-
raise UnsupportedIncommingFeature("incomming `tools` must be a list")
|
|
167
|
-
payload["tools"] = self._translate_tools(tools)
|
|
168
|
-
|
|
169
|
-
tool_choice = incomming_request.get("tool_choice")
|
|
170
|
-
if tool_choice is not None:
|
|
171
|
-
payload["tool_choice"] = self._translate_tool_choice(tool_choice)
|
|
172
|
-
|
|
173
|
-
parallel_tool_calls = incomming_request.get("parallel_tool_calls")
|
|
174
|
-
if isinstance(parallel_tool_calls, bool):
|
|
175
|
-
payload["parallel_tool_calls"] = parallel_tool_calls
|
|
176
|
-
|
|
177
|
-
return payload
|
|
178
|
-
|
|
179
|
-
def open_outcomming_stream(self, outcomming_request: "typing.Dict[str, object]"):
|
|
180
|
-
outcomming_api = self._config.normalized_outcomming_api()
|
|
181
|
-
if outcomming_api == "messages":
|
|
182
|
-
return self._open_outcomming_messages_stream(outcomming_request)
|
|
183
|
-
if outcomming_api != "chat_completions":
|
|
184
|
-
raise OutcommingChatError(
|
|
185
|
-
f"unsupported outcomming API: {self._config.outcomming_api!r}"
|
|
186
|
-
)
|
|
187
|
-
return self._open_outcomming_chat_stream(outcomming_request)
|
|
188
|
-
|
|
189
|
-
def _open_outcomming_chat_stream(
|
|
190
|
-
self,
|
|
191
|
-
outcomming_request: "typing.Dict[str, object]",
|
|
192
|
-
):
|
|
193
|
-
request = urllib.request.Request(
|
|
194
|
-
self._config.outcomming_chat_completions_url(),
|
|
195
|
-
data=json.dumps(outcomming_request).encode("utf-8"),
|
|
196
|
-
headers=self._build_headers(accept="text/event-stream"),
|
|
197
|
-
method="POST",
|
|
198
|
-
)
|
|
199
|
-
with self._request_diagnostics(request) as progress:
|
|
200
|
-
yield from self._read_outcomming_chat_stream(request, progress)
|
|
201
|
-
|
|
202
|
-
def _read_outcomming_chat_stream(self, request, progress):
|
|
203
|
-
try:
|
|
204
|
-
with urllib.request.urlopen(
|
|
205
|
-
request,
|
|
206
|
-
context=ssl.create_default_context(),
|
|
207
|
-
timeout=self._config.timeout_seconds,
|
|
208
|
-
) as response:
|
|
209
|
-
progress["headers_at"] = time.monotonic()
|
|
210
|
-
progress["status"] = response.status
|
|
211
|
-
progress["phase"] = "waiting_first_chunk"
|
|
212
|
-
try:
|
|
213
|
-
saw_done = False
|
|
214
|
-
for _event_name, data in self._iter_sse_events(response):
|
|
215
|
-
if not data:
|
|
216
|
-
continue
|
|
217
|
-
if data == "[DONE]":
|
|
218
|
-
saw_done = True
|
|
219
|
-
break
|
|
220
|
-
payload = json.loads(data)
|
|
221
|
-
self._received_chunk(progress)
|
|
222
|
-
if isinstance(payload, dict) and payload.get("error") is not None:
|
|
223
|
-
raise OutcommingChatError(
|
|
224
|
-
"outcomming chat stream returned an error: "
|
|
225
|
-
+ json.dumps(payload["error"], ensure_ascii=False)[:500]
|
|
226
|
-
)
|
|
227
|
-
yield payload
|
|
228
|
-
if not saw_done:
|
|
229
|
-
raise OutcommingChatError(
|
|
230
|
-
"outcomming chat stream ended before [DONE]"
|
|
231
|
-
)
|
|
232
|
-
except (
|
|
233
|
-
ConnectionError,
|
|
234
|
-
EOFError,
|
|
235
|
-
OSError,
|
|
236
|
-
http.client.HTTPException,
|
|
237
|
-
json.JSONDecodeError,
|
|
238
|
-
) as exc:
|
|
239
|
-
raise OutcommingChatError(
|
|
240
|
-
"outcomming chat stream failed while reading response body: "
|
|
241
|
-
f"{exc}"
|
|
242
|
-
) from exc
|
|
243
|
-
except urllib.error.HTTPError as exc:
|
|
244
|
-
progress["headers_at"] = time.monotonic()
|
|
245
|
-
progress["status"] = exc.code
|
|
246
|
-
progress["phase"] = "reading_error_body"
|
|
247
|
-
body = exc.read().decode("utf-8", errors="replace")
|
|
248
|
-
raise OutcommingChatError(
|
|
249
|
-
f"outcomming chat request failed with status {exc.code}: {body[:500]}"
|
|
250
|
-
) from exc
|
|
251
|
-
except TimeoutError as exc:
|
|
252
|
-
raise OutcommingChatError(
|
|
253
|
-
"outcomming chat request timed out after "
|
|
254
|
-
f"{self._config.timeout_seconds:g}s"
|
|
255
|
-
) from exc
|
|
256
|
-
except urllib.error.URLError as exc:
|
|
257
|
-
raise OutcommingChatError(
|
|
258
|
-
f"outcomming chat request failed: {exc.reason}"
|
|
259
|
-
) from exc
|
|
260
|
-
except (OSError, EOFError, http.client.HTTPException) as exc:
|
|
261
|
-
raise OutcommingChatError(
|
|
262
|
-
"outcomming chat request failed while opening response: "
|
|
263
|
-
f"{type(exc).__name__}: {exc}"
|
|
264
|
-
) from exc
|
|
265
|
-
|
|
266
|
-
def _open_outcomming_messages_stream(
|
|
267
|
-
self,
|
|
268
|
-
outcomming_request: "typing.Dict[str, object]",
|
|
269
|
-
):
|
|
270
|
-
try:
|
|
271
|
-
messages_request = build_messages_request(outcomming_request)
|
|
272
|
-
except MessagesAPIAdapterError as exc:
|
|
273
|
-
raise OutcommingChatError(str(exc)) from exc
|
|
274
|
-
|
|
275
|
-
request = urllib.request.Request(
|
|
276
|
-
self._config.outcomming_messages_url(),
|
|
277
|
-
data=json.dumps(messages_request).encode("utf-8"),
|
|
278
|
-
headers=self._build_headers(accept="text/event-stream"),
|
|
279
|
-
method="POST",
|
|
280
|
-
)
|
|
281
|
-
with self._request_diagnostics(request) as progress:
|
|
282
|
-
yield from self._read_outcomming_messages_stream(request, progress)
|
|
283
|
-
|
|
284
|
-
def _read_outcomming_messages_stream(self, request, progress):
|
|
285
|
-
try:
|
|
286
|
-
with urllib.request.urlopen(
|
|
287
|
-
request,
|
|
288
|
-
context=ssl.create_default_context(),
|
|
289
|
-
timeout=self._config.timeout_seconds,
|
|
290
|
-
) as response:
|
|
291
|
-
progress["headers_at"] = time.monotonic()
|
|
292
|
-
progress["status"] = response.status
|
|
293
|
-
progress["phase"] = "waiting_first_chunk"
|
|
294
|
-
try:
|
|
295
|
-
stream_state: "typing.Dict[str, object]" = {}
|
|
296
|
-
for event_name, data in self._iter_sse_events(response):
|
|
297
|
-
if not data:
|
|
298
|
-
continue
|
|
299
|
-
payload = json.loads(data)
|
|
300
|
-
if not isinstance(payload, dict):
|
|
301
|
-
continue
|
|
302
|
-
self._received_chunk(progress)
|
|
303
|
-
for chunk in iter_chat_chunks_from_messages(
|
|
304
|
-
event_name,
|
|
305
|
-
payload,
|
|
306
|
-
stream_state,
|
|
307
|
-
):
|
|
308
|
-
yield chunk
|
|
309
|
-
if not messages_saw_message_stop(stream_state):
|
|
310
|
-
raise OutcommingChatError(
|
|
311
|
-
"outcomming messages stream ended before `message_stop`"
|
|
312
|
-
)
|
|
313
|
-
except (
|
|
314
|
-
ConnectionError,
|
|
315
|
-
EOFError,
|
|
316
|
-
OSError,
|
|
317
|
-
http.client.HTTPException,
|
|
318
|
-
json.JSONDecodeError,
|
|
319
|
-
MessagesAPIAdapterError,
|
|
320
|
-
) as exc:
|
|
321
|
-
raise OutcommingChatError(
|
|
322
|
-
"outcomming messages stream failed while reading response body: "
|
|
323
|
-
f"{exc}"
|
|
324
|
-
) from exc
|
|
325
|
-
except urllib.error.HTTPError as exc:
|
|
326
|
-
progress["headers_at"] = time.monotonic()
|
|
327
|
-
progress["status"] = exc.code
|
|
328
|
-
progress["phase"] = "reading_error_body"
|
|
329
|
-
body = exc.read().decode("utf-8", errors="replace")
|
|
330
|
-
raise OutcommingChatError(
|
|
331
|
-
f"outcomming messages request failed with status {exc.code}: {body[:500]}"
|
|
332
|
-
) from exc
|
|
333
|
-
except TimeoutError as exc:
|
|
334
|
-
raise OutcommingChatError(
|
|
335
|
-
"outcomming messages request timed out after "
|
|
336
|
-
f"{self._config.timeout_seconds:g}s"
|
|
337
|
-
) from exc
|
|
338
|
-
except urllib.error.URLError as exc:
|
|
339
|
-
raise OutcommingChatError(
|
|
340
|
-
f"outcomming messages request failed: {exc.reason}"
|
|
341
|
-
) from exc
|
|
342
|
-
except (OSError, EOFError, http.client.HTTPException) as exc:
|
|
343
|
-
raise OutcommingChatError(
|
|
344
|
-
"outcomming messages request failed while opening response: "
|
|
345
|
-
f"{type(exc).__name__}: {exc}"
|
|
346
|
-
) from exc
|
|
347
|
-
|
|
348
27
|
def route_stream(
|
|
349
28
|
self,
|
|
350
29
|
stored_response: "StoredResponse",
|
|
351
30
|
outcomming_request: "typing.Dict[str, object]",
|
|
352
|
-
|
|
31
|
+
tool_names: "ToolNameMap",
|
|
353
32
|
trajectory_dump: "typing.Union[TrajectoryDumpWriter, None]" = None,
|
|
354
33
|
):
|
|
355
34
|
yield (
|
|
@@ -367,6 +46,7 @@ class StreamRouter:
|
|
|
367
46
|
|
|
368
47
|
text_parts: "typing.List[str]" = []
|
|
369
48
|
reasoning_parts: "typing.List[str]" = []
|
|
49
|
+
output_stream = ResponseOutputStream()
|
|
370
50
|
latest_usage: "typing.Dict[str, object]" = {}
|
|
371
51
|
current_request = json.loads(json.dumps(outcomming_request))
|
|
372
52
|
current_stream = self._open_tracked_outcomming_stream(
|
|
@@ -390,7 +70,11 @@ class StreamRouter:
|
|
|
390
70
|
current_usage,
|
|
391
71
|
finish_reasons,
|
|
392
72
|
):
|
|
393
|
-
|
|
73
|
+
item_type = (
|
|
74
|
+
"reasoning" if event_name == "response.reasoning_text.delta"
|
|
75
|
+
else "message"
|
|
76
|
+
)
|
|
77
|
+
yield from output_stream.text_delta(item_type, payload["delta"])
|
|
394
78
|
if current_usage:
|
|
395
79
|
latest_usage = json.loads(json.dumps(current_usage))
|
|
396
80
|
|
|
@@ -401,24 +85,15 @@ class StreamRouter:
|
|
|
401
85
|
current_request,
|
|
402
86
|
)
|
|
403
87
|
if mock_search_calls and not ordinary_tool_calls:
|
|
88
|
+
yield from output_stream.finish_text()
|
|
404
89
|
for item in build_output_items(mock_search_calls):
|
|
405
|
-
yield (
|
|
406
|
-
"response.output_item.done",
|
|
407
|
-
{
|
|
408
|
-
"type": "response.output_item.done",
|
|
409
|
-
"item": item,
|
|
410
|
-
},
|
|
411
|
-
)
|
|
90
|
+
yield from output_stream.complete_tool(item)
|
|
412
91
|
try:
|
|
413
92
|
current_request = build_followup_request(
|
|
414
93
|
self._mock_web_search,
|
|
415
94
|
current_request,
|
|
416
95
|
mock_search_calls,
|
|
417
|
-
reasoning_text=(
|
|
418
|
-
"".join(reasoning_parts)
|
|
419
|
-
if self._supports_chat_reasoning()
|
|
420
|
-
else None
|
|
421
|
-
),
|
|
96
|
+
reasoning_text="".join(reasoning_parts),
|
|
422
97
|
)
|
|
423
98
|
except ValueError as exc:
|
|
424
99
|
raise OutcommingChatError(str(exc)) from exc
|
|
@@ -437,6 +112,7 @@ class StreamRouter:
|
|
|
437
112
|
retried_reasoning_only_output = True
|
|
438
113
|
del reasoning_parts[reasoning_start:]
|
|
439
114
|
del text_parts[text_start:]
|
|
115
|
+
output_stream.discard_text()
|
|
440
116
|
current_request = json.loads(json.dumps(current_request))
|
|
441
117
|
current_stream = self._open_tracked_outcomming_stream(
|
|
442
118
|
current_request,
|
|
@@ -451,27 +127,15 @@ class StreamRouter:
|
|
|
451
127
|
error_type="model_output_invalid",
|
|
452
128
|
)
|
|
453
129
|
|
|
454
|
-
|
|
455
|
-
reasoning_parts,
|
|
456
|
-
text_parts,
|
|
130
|
+
tool_items = self._build_tool_output_items(
|
|
457
131
|
ordinary_tool_calls,
|
|
458
|
-
custom_tool_names
|
|
459
|
-
)
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
"type": "response.output_item.done",
|
|
464
|
-
"item": item,
|
|
465
|
-
},
|
|
466
|
-
)
|
|
132
|
+
tool_names.custom_tool_names,
|
|
133
|
+
)
|
|
134
|
+
yield from output_stream.finish_text()
|
|
135
|
+
for item in tool_items:
|
|
136
|
+
yield from output_stream.complete_tool(tool_names.restore_output_item(item))
|
|
467
137
|
for item in build_output_items(mock_search_calls):
|
|
468
|
-
yield (
|
|
469
|
-
"response.output_item.done",
|
|
470
|
-
{
|
|
471
|
-
"type": "response.output_item.done",
|
|
472
|
-
"item": item,
|
|
473
|
-
},
|
|
474
|
-
)
|
|
138
|
+
yield from output_stream.complete_tool(item)
|
|
475
139
|
break
|
|
476
140
|
|
|
477
141
|
yield (
|
|
@@ -480,7 +144,10 @@ class StreamRouter:
|
|
|
480
144
|
"type": "response.completed",
|
|
481
145
|
"response": {
|
|
482
146
|
"id": stored_response.response_id,
|
|
483
|
-
"
|
|
147
|
+
"object": "response",
|
|
148
|
+
"status": "completed",
|
|
149
|
+
"model": stored_response.model,
|
|
150
|
+
"output": output_stream.items,
|
|
484
151
|
**(
|
|
485
152
|
{"usage": json.loads(json.dumps(latest_usage))}
|
|
486
153
|
if latest_usage
|
|
@@ -495,7 +162,7 @@ class StreamRouter:
|
|
|
495
162
|
outcomming_request: "typing.Dict[str, object]",
|
|
496
163
|
trajectory_dump: "typing.Union[TrajectoryDumpWriter, None]" = None,
|
|
497
164
|
):
|
|
498
|
-
outcomming_stream = self.
|
|
165
|
+
outcomming_stream = self.transport.open_stream(outcomming_request)
|
|
499
166
|
if trajectory_dump is None:
|
|
500
167
|
return outcomming_stream
|
|
501
168
|
return trajectory_dump.wrap_stream(
|
|
@@ -503,367 +170,6 @@ class StreamRouter:
|
|
|
503
170
|
outcomming_request,
|
|
504
171
|
)
|
|
505
172
|
|
|
506
|
-
@contextmanager
|
|
507
|
-
def _request_diagnostics(self, request):
|
|
508
|
-
started = time.monotonic()
|
|
509
|
-
progress = {
|
|
510
|
-
"phase": "waiting_response_headers",
|
|
511
|
-
"headers_at": None,
|
|
512
|
-
"first_chunk_at": None,
|
|
513
|
-
"last_chunk_at": None,
|
|
514
|
-
"chunks": 0,
|
|
515
|
-
"status": None,
|
|
516
|
-
}
|
|
517
|
-
try:
|
|
518
|
-
yield progress
|
|
519
|
-
except OutcommingChatError as exc:
|
|
520
|
-
now = time.monotonic()
|
|
521
|
-
cause = exc.__cause__ or exc
|
|
522
|
-
if isinstance(cause, urllib.error.URLError) and isinstance(
|
|
523
|
-
cause.reason, BaseException
|
|
524
|
-
):
|
|
525
|
-
cause = cause.reason
|
|
526
|
-
|
|
527
|
-
def timing(received_at):
|
|
528
|
-
if received_at is None:
|
|
529
|
-
return "not_received"
|
|
530
|
-
return f"{received_at - started:.2f}s"
|
|
531
|
-
|
|
532
|
-
idle = (
|
|
533
|
-
f"{now - progress['last_chunk_at']:.2f}s"
|
|
534
|
-
if progress["last_chunk_at"] is not None
|
|
535
|
-
else "not_started"
|
|
536
|
-
)
|
|
537
|
-
details = (
|
|
538
|
-
f"phase={progress['phase']}, elapsed={now - started:.2f}s, "
|
|
539
|
-
f"timeout={self._config.timeout_seconds:g}s\n"
|
|
540
|
-
f"headers={timing(progress['headers_at'])}, "
|
|
541
|
-
f"first_chunk={timing(progress['first_chunk_at'])}, "
|
|
542
|
-
f"chunks={progress['chunks']}, idle={idle}\n"
|
|
543
|
-
f"status={progress['status']}, "
|
|
544
|
-
f"request_bytes={len(request.data or b'')}, "
|
|
545
|
-
f"exception={type(cause).__name__}"
|
|
546
|
-
)
|
|
547
|
-
exc.args = (f"{exc}\n{details}",)
|
|
548
|
-
raise
|
|
549
|
-
|
|
550
|
-
def _received_chunk(self, progress):
|
|
551
|
-
now = time.monotonic()
|
|
552
|
-
if progress["chunks"] == 0:
|
|
553
|
-
progress["first_chunk_at"] = now
|
|
554
|
-
progress["last_chunk_at"] = now
|
|
555
|
-
progress["chunks"] += 1
|
|
556
|
-
progress["phase"] = "reading_stream"
|
|
557
|
-
|
|
558
|
-
def _responses_input_to_chat_messages(
|
|
559
|
-
self,
|
|
560
|
-
instructions: "str",
|
|
561
|
-
input_items: "typing.List[object]",
|
|
562
|
-
) -> "typing.List[typing.Dict[str, object]]":
|
|
563
|
-
messages: "typing.List[typing.Dict[str, object]]" = []
|
|
564
|
-
if instructions:
|
|
565
|
-
messages.append({"role": "developer", "content": instructions})
|
|
566
|
-
|
|
567
|
-
pending_assistant: "typing.Union[typing.Dict[str, object], None]" = None
|
|
568
|
-
pending_tool_images: "typing.List[typing.Dict[str, object]]" = []
|
|
569
|
-
|
|
570
|
-
def flush_pending_assistant() -> "None":
|
|
571
|
-
nonlocal pending_assistant
|
|
572
|
-
if pending_assistant is None:
|
|
573
|
-
return
|
|
574
|
-
if (
|
|
575
|
-
"content" not in pending_assistant
|
|
576
|
-
and "reasoning" not in pending_assistant
|
|
577
|
-
and "tool_calls" not in pending_assistant
|
|
578
|
-
):
|
|
579
|
-
pending_assistant = None
|
|
580
|
-
return
|
|
581
|
-
messages.append(pending_assistant)
|
|
582
|
-
pending_assistant = None
|
|
583
|
-
|
|
584
|
-
def flush_pending_tool_images() -> "None":
|
|
585
|
-
if not pending_tool_images:
|
|
586
|
-
return
|
|
587
|
-
messages.append({"role": "user", "content": list(pending_tool_images)})
|
|
588
|
-
del pending_tool_images[:]
|
|
589
|
-
|
|
590
|
-
for raw_item in input_items:
|
|
591
|
-
if not isinstance(raw_item, dict):
|
|
592
|
-
raise UnsupportedIncommingFeature(
|
|
593
|
-
"all incomming `input` items must be objects"
|
|
594
|
-
)
|
|
595
|
-
item_type = raw_item.get("type")
|
|
596
|
-
if item_type not in {"function_call_output", "custom_tool_call_output"}:
|
|
597
|
-
flush_pending_tool_images()
|
|
598
|
-
|
|
599
|
-
if item_type == "message":
|
|
600
|
-
role = str(raw_item.get("role", "")).strip()
|
|
601
|
-
if role not in {"developer", "user", "assistant", "system"}:
|
|
602
|
-
raise UnsupportedIncommingFeature(
|
|
603
|
-
f"unsupported incomming message role: {role or '<empty>'}"
|
|
604
|
-
)
|
|
605
|
-
text, image_parts = self._split_content_parts(raw_item.get("content"))
|
|
606
|
-
if role == "assistant":
|
|
607
|
-
if image_parts:
|
|
608
|
-
raise UnsupportedIncommingFeature(
|
|
609
|
-
"assistant messages cannot carry `input_image` content parts"
|
|
610
|
-
)
|
|
611
|
-
if pending_assistant is None:
|
|
612
|
-
pending_assistant = {"role": "assistant"}
|
|
613
|
-
if text:
|
|
614
|
-
pending_assistant["content"] = (
|
|
615
|
-
str(pending_assistant.get("content", "")) + text
|
|
616
|
-
)
|
|
617
|
-
continue
|
|
618
|
-
flush_pending_assistant()
|
|
619
|
-
if image_parts:
|
|
620
|
-
content: "object" = (
|
|
621
|
-
[{"type": "text", "text": text}] if text else []
|
|
622
|
-
) + image_parts
|
|
623
|
-
else:
|
|
624
|
-
content = text
|
|
625
|
-
messages.append({"role": role, "content": content})
|
|
626
|
-
continue
|
|
627
|
-
|
|
628
|
-
if item_type == "reasoning":
|
|
629
|
-
if not self._supports_chat_reasoning():
|
|
630
|
-
raise UnsupportedIncommingFeature(
|
|
631
|
-
"incomming `reasoning` items are not supported by this chat backend"
|
|
632
|
-
)
|
|
633
|
-
if pending_assistant is None:
|
|
634
|
-
pending_assistant = {"role": "assistant"}
|
|
635
|
-
reasoning_text = self._coalesce_reasoning_text(raw_item)
|
|
636
|
-
if reasoning_text:
|
|
637
|
-
pending_assistant["reasoning"] = (
|
|
638
|
-
str(pending_assistant.get("reasoning", "")) + reasoning_text
|
|
639
|
-
)
|
|
640
|
-
continue
|
|
641
|
-
|
|
642
|
-
if item_type == "function_call":
|
|
643
|
-
if pending_assistant is None:
|
|
644
|
-
pending_assistant = {"role": "assistant"}
|
|
645
|
-
tool_calls = pending_assistant.setdefault("tool_calls", [])
|
|
646
|
-
if not isinstance(tool_calls, list):
|
|
647
|
-
raise UnsupportedIncommingFeature(
|
|
648
|
-
"assistant tool calls must be a list"
|
|
649
|
-
)
|
|
650
|
-
tool_calls.append(
|
|
651
|
-
{
|
|
652
|
-
"id": str(raw_item.get("call_id", "")).strip(),
|
|
653
|
-
"type": "function",
|
|
654
|
-
"function": {
|
|
655
|
-
"name": str(raw_item.get("name", "")).strip(),
|
|
656
|
-
"arguments": str(raw_item.get("arguments", "") or "{}"),
|
|
657
|
-
},
|
|
658
|
-
}
|
|
659
|
-
)
|
|
660
|
-
continue
|
|
661
|
-
|
|
662
|
-
if item_type == "function_call_output":
|
|
663
|
-
flush_pending_assistant()
|
|
664
|
-
text, image_parts = self._split_tool_output_parts(
|
|
665
|
-
raw_item.get("output")
|
|
666
|
-
)
|
|
667
|
-
messages.append(
|
|
668
|
-
{
|
|
669
|
-
"role": "tool",
|
|
670
|
-
"tool_call_id": str(raw_item.get("call_id", "")).strip(),
|
|
671
|
-
"content": text,
|
|
672
|
-
}
|
|
673
|
-
)
|
|
674
|
-
pending_tool_images.extend(image_parts)
|
|
675
|
-
continue
|
|
676
|
-
|
|
677
|
-
if item_type == "custom_tool_call":
|
|
678
|
-
if pending_assistant is None:
|
|
679
|
-
pending_assistant = {"role": "assistant"}
|
|
680
|
-
tool_calls = pending_assistant.setdefault("tool_calls", [])
|
|
681
|
-
if not isinstance(tool_calls, list):
|
|
682
|
-
raise UnsupportedIncommingFeature(
|
|
683
|
-
"assistant tool calls must be a list"
|
|
684
|
-
)
|
|
685
|
-
try:
|
|
686
|
-
tool_calls.append(build_custom_tool_call(raw_item))
|
|
687
|
-
except CustomToolAdapterError as exc:
|
|
688
|
-
raise UnsupportedIncommingFeature(str(exc)) from exc
|
|
689
|
-
continue
|
|
690
|
-
|
|
691
|
-
if item_type == "custom_tool_call_output":
|
|
692
|
-
flush_pending_assistant()
|
|
693
|
-
text, image_parts = self._split_tool_output_parts(
|
|
694
|
-
raw_item.get("output")
|
|
695
|
-
)
|
|
696
|
-
messages.append(
|
|
697
|
-
{
|
|
698
|
-
"role": "tool",
|
|
699
|
-
"tool_call_id": str(raw_item.get("call_id", "")).strip(),
|
|
700
|
-
"content": text,
|
|
701
|
-
}
|
|
702
|
-
)
|
|
703
|
-
pending_tool_images.extend(image_parts)
|
|
704
|
-
continue
|
|
705
|
-
|
|
706
|
-
raise UnsupportedIncommingFeature(
|
|
707
|
-
f"unsupported incomming input item type: {item_type!r}"
|
|
708
|
-
)
|
|
709
|
-
|
|
710
|
-
flush_pending_assistant()
|
|
711
|
-
flush_pending_tool_images()
|
|
712
|
-
return messages
|
|
713
|
-
|
|
714
|
-
def _coerce_positive_int(self, raw_value: "object") -> "typing.Union[int, None]":
|
|
715
|
-
if isinstance(raw_value, bool):
|
|
716
|
-
return None
|
|
717
|
-
if isinstance(raw_value, int) and raw_value > 0:
|
|
718
|
-
return raw_value
|
|
719
|
-
return None
|
|
720
|
-
|
|
721
|
-
def _split_content_parts(
|
|
722
|
-
self,
|
|
723
|
-
raw_content: "object",
|
|
724
|
-
) -> "typing.Tuple[str, typing.List[typing.Dict[str, object]]]":
|
|
725
|
-
if raw_content is None:
|
|
726
|
-
return "", []
|
|
727
|
-
if isinstance(raw_content, str):
|
|
728
|
-
return raw_content, []
|
|
729
|
-
if not isinstance(raw_content, list):
|
|
730
|
-
raise UnsupportedIncommingFeature(
|
|
731
|
-
"message `content` must be a list or string"
|
|
732
|
-
)
|
|
733
|
-
|
|
734
|
-
text_parts: "typing.List[str]" = []
|
|
735
|
-
image_parts: "typing.List[typing.Dict[str, object]]" = []
|
|
736
|
-
for part in raw_content:
|
|
737
|
-
if not isinstance(part, dict):
|
|
738
|
-
raise UnsupportedIncommingFeature(
|
|
739
|
-
"message content parts must be objects"
|
|
740
|
-
)
|
|
741
|
-
part_type = part.get("type")
|
|
742
|
-
if part_type in {"input_text", "output_text"}:
|
|
743
|
-
text_parts.append(str(part.get("text", "")))
|
|
744
|
-
continue
|
|
745
|
-
if part_type == "input_image":
|
|
746
|
-
image_parts.append(self._build_chat_image_part(part))
|
|
747
|
-
continue
|
|
748
|
-
raise UnsupportedIncommingFeature(
|
|
749
|
-
f"content part type `{part_type}` is not yet supported by the chat backend"
|
|
750
|
-
)
|
|
751
|
-
return "".join(text_parts), image_parts
|
|
752
|
-
|
|
753
|
-
def _build_chat_image_part(
|
|
754
|
-
self,
|
|
755
|
-
part: "typing.Dict[str, object]",
|
|
756
|
-
) -> "typing.Dict[str, object]":
|
|
757
|
-
image_url = str(part.get("image_url", "") or "").strip()
|
|
758
|
-
if not image_url:
|
|
759
|
-
raise UnsupportedIncommingFeature(
|
|
760
|
-
"`input_image` content parts must carry a non-empty `image_url`"
|
|
761
|
-
)
|
|
762
|
-
image_payload: "typing.Dict[str, object]" = {"url": image_url}
|
|
763
|
-
detail = part.get("detail")
|
|
764
|
-
if isinstance(detail, str) and detail in {"auto", "low", "high"}:
|
|
765
|
-
image_payload["detail"] = detail
|
|
766
|
-
return {"type": "image_url", "image_url": image_payload}
|
|
767
|
-
|
|
768
|
-
def _split_tool_output_parts(
|
|
769
|
-
self,
|
|
770
|
-
raw_output: "object",
|
|
771
|
-
) -> "typing.Tuple[str, typing.List[typing.Dict[str, object]]]":
|
|
772
|
-
if isinstance(raw_output, str):
|
|
773
|
-
return raw_output, []
|
|
774
|
-
if isinstance(raw_output, list):
|
|
775
|
-
return self._split_content_parts(raw_output)
|
|
776
|
-
return json.dumps(raw_output, ensure_ascii=False), []
|
|
777
|
-
|
|
778
|
-
def _coalesce_reasoning_text(self, raw_item: "typing.Dict[str, object]") -> "str":
|
|
779
|
-
content = raw_item.get("content")
|
|
780
|
-
if isinstance(content, list):
|
|
781
|
-
text_parts: "typing.List[str]" = []
|
|
782
|
-
for part in content:
|
|
783
|
-
if not isinstance(part, dict):
|
|
784
|
-
continue
|
|
785
|
-
part_type = part.get("type")
|
|
786
|
-
if part_type in {"reasoning_text", "summary_text"}:
|
|
787
|
-
text_parts.append(str(part.get("text", "")))
|
|
788
|
-
if text_parts:
|
|
789
|
-
return "".join(text_parts)
|
|
790
|
-
|
|
791
|
-
summary = raw_item.get("summary")
|
|
792
|
-
if isinstance(summary, list):
|
|
793
|
-
text_parts = []
|
|
794
|
-
for part in summary:
|
|
795
|
-
if not isinstance(part, dict):
|
|
796
|
-
continue
|
|
797
|
-
if part.get("type") == "summary_text":
|
|
798
|
-
text_parts.append(str(part.get("text", "")))
|
|
799
|
-
if text_parts:
|
|
800
|
-
return "".join(text_parts)
|
|
801
|
-
|
|
802
|
-
for key in ("reasoning", "reasoning_content", "text"):
|
|
803
|
-
value = raw_item.get(key)
|
|
804
|
-
if isinstance(value, str) and value:
|
|
805
|
-
return value
|
|
806
|
-
return ""
|
|
807
|
-
|
|
808
|
-
def _translate_tools(
|
|
809
|
-
self, incomming_tools: "typing.List[object]"
|
|
810
|
-
) -> "typing.List[typing.Dict[str, object]]":
|
|
811
|
-
translated: "typing.List[typing.Dict[str, object]]" = []
|
|
812
|
-
for raw_tool in incomming_tools:
|
|
813
|
-
if not isinstance(raw_tool, dict):
|
|
814
|
-
raise UnsupportedIncommingFeature("tool definitions must be objects")
|
|
815
|
-
tool_type = raw_tool.get("type")
|
|
816
|
-
if tool_type == "function":
|
|
817
|
-
name = str(raw_tool.get("name", "")).strip()
|
|
818
|
-
translated.append(
|
|
819
|
-
{
|
|
820
|
-
"type": "function",
|
|
821
|
-
"name": name,
|
|
822
|
-
"function": {
|
|
823
|
-
"name": name,
|
|
824
|
-
"description": str(raw_tool.get("description", "") or ""),
|
|
825
|
-
"parameters": raw_tool.get("parameters")
|
|
826
|
-
or {"type": "object"},
|
|
827
|
-
"strict": bool(raw_tool.get("strict", False)),
|
|
828
|
-
},
|
|
829
|
-
}
|
|
830
|
-
)
|
|
831
|
-
continue
|
|
832
|
-
if tool_type == "web_search":
|
|
833
|
-
translated.append(build_tool_definition(self._mock_web_search))
|
|
834
|
-
continue
|
|
835
|
-
if tool_type == "custom":
|
|
836
|
-
try:
|
|
837
|
-
translated.append(build_custom_tool_definition(raw_tool))
|
|
838
|
-
except CustomToolAdapterError as exc:
|
|
839
|
-
raise UnsupportedIncommingFeature(str(exc)) from exc
|
|
840
|
-
continue
|
|
841
|
-
raise UnsupportedIncommingFeature(
|
|
842
|
-
f"unsupported incomming tool type: {tool_type!r}"
|
|
843
|
-
)
|
|
844
|
-
return translated
|
|
845
|
-
|
|
846
|
-
def _translate_tool_choice(self, raw_tool_choice: "object") -> "object":
|
|
847
|
-
if isinstance(raw_tool_choice, str):
|
|
848
|
-
return raw_tool_choice
|
|
849
|
-
if not isinstance(raw_tool_choice, dict):
|
|
850
|
-
raise UnsupportedIncommingFeature("unsupported `tool_choice` shape")
|
|
851
|
-
|
|
852
|
-
choice_type = raw_tool_choice.get("type")
|
|
853
|
-
if choice_type in {"function", "custom"}:
|
|
854
|
-
name = raw_tool_choice.get("name")
|
|
855
|
-
if not isinstance(name, str) or not name.strip():
|
|
856
|
-
raise UnsupportedIncommingFeature(
|
|
857
|
-
f"{choice_type} tool_choice is missing `name`"
|
|
858
|
-
)
|
|
859
|
-
return {
|
|
860
|
-
"type": "function",
|
|
861
|
-
"function": {"name": name},
|
|
862
|
-
}
|
|
863
|
-
raise UnsupportedIncommingFeature(
|
|
864
|
-
f"unsupported incomming tool_choice type: {choice_type!r}"
|
|
865
|
-
)
|
|
866
|
-
|
|
867
173
|
def _consume_chat_chunk(
|
|
868
174
|
self,
|
|
869
175
|
payload: "typing.Dict[str, object]",
|
|
@@ -1000,43 +306,12 @@ class StreamRouter:
|
|
|
1000
306
|
if isinstance(value, dict):
|
|
1001
307
|
current_usage[key] = json.loads(json.dumps(value))
|
|
1002
308
|
|
|
1003
|
-
def
|
|
309
|
+
def _build_tool_output_items(
|
|
1004
310
|
self,
|
|
1005
|
-
reasoning_parts: "typing.List[str]",
|
|
1006
|
-
text_parts: "typing.List[str]",
|
|
1007
311
|
tool_calls: "typing.Dict[int, typing.Dict[str, object]]",
|
|
1008
312
|
custom_tool_names: "typing.Set[str]",
|
|
1009
313
|
) -> "typing.List[typing.Dict[str, object]]":
|
|
1010
314
|
items: "typing.List[typing.Dict[str, object]]" = []
|
|
1011
|
-
reasoning_text = "".join(reasoning_parts)
|
|
1012
|
-
if reasoning_text:
|
|
1013
|
-
items.append(
|
|
1014
|
-
{
|
|
1015
|
-
"type": "reasoning",
|
|
1016
|
-
"summary": [],
|
|
1017
|
-
"content": [
|
|
1018
|
-
{
|
|
1019
|
-
"type": "reasoning_text",
|
|
1020
|
-
"text": reasoning_text,
|
|
1021
|
-
}
|
|
1022
|
-
],
|
|
1023
|
-
}
|
|
1024
|
-
)
|
|
1025
|
-
text = "".join(text_parts)
|
|
1026
|
-
if text:
|
|
1027
|
-
items.append(
|
|
1028
|
-
{
|
|
1029
|
-
"type": "message",
|
|
1030
|
-
"role": "assistant",
|
|
1031
|
-
"content": [
|
|
1032
|
-
{
|
|
1033
|
-
"type": "output_text",
|
|
1034
|
-
"text": text,
|
|
1035
|
-
}
|
|
1036
|
-
],
|
|
1037
|
-
}
|
|
1038
|
-
)
|
|
1039
|
-
|
|
1040
315
|
for index in sorted(tool_calls):
|
|
1041
316
|
tool_call = tool_calls[index]
|
|
1042
317
|
if tool_call.get("type") != "function":
|
|
@@ -1074,80 +349,8 @@ class StreamRouter:
|
|
|
1074
349
|
"call_id": str(tool_call.get("id", "")).strip() or f"call_{index}",
|
|
1075
350
|
"name": name,
|
|
1076
351
|
"arguments": arguments,
|
|
352
|
+
"encrypted_function_args": [],
|
|
1077
353
|
}
|
|
1078
354
|
)
|
|
1079
355
|
|
|
1080
356
|
return items
|
|
1081
|
-
|
|
1082
|
-
def _request_json(
|
|
1083
|
-
self, request: "urllib.request.Request"
|
|
1084
|
-
) -> "typing.Dict[str, object]":
|
|
1085
|
-
with self._request_diagnostics(request) as progress:
|
|
1086
|
-
return self._read_json_response(request, progress)
|
|
1087
|
-
|
|
1088
|
-
def _read_json_response(self, request, progress):
|
|
1089
|
-
try:
|
|
1090
|
-
with urllib.request.urlopen(
|
|
1091
|
-
request,
|
|
1092
|
-
context=ssl.create_default_context(),
|
|
1093
|
-
timeout=self._config.timeout_seconds,
|
|
1094
|
-
) as response:
|
|
1095
|
-
progress["headers_at"] = time.monotonic()
|
|
1096
|
-
progress["status"] = response.status
|
|
1097
|
-
progress["phase"] = "reading_response_body"
|
|
1098
|
-
return json.loads(response.read().decode("utf-8"))
|
|
1099
|
-
except urllib.error.HTTPError as exc:
|
|
1100
|
-
progress["headers_at"] = time.monotonic()
|
|
1101
|
-
progress["status"] = exc.code
|
|
1102
|
-
progress["phase"] = "reading_error_body"
|
|
1103
|
-
body = exc.read().decode("utf-8", errors="replace")
|
|
1104
|
-
raise OutcommingChatError(
|
|
1105
|
-
f"outcomming request failed with status {exc.code}: {body[:500]}"
|
|
1106
|
-
) from exc
|
|
1107
|
-
except TimeoutError as exc:
|
|
1108
|
-
raise OutcommingChatError(
|
|
1109
|
-
"outcomming request timed out after "
|
|
1110
|
-
f"{self._config.timeout_seconds:g}s"
|
|
1111
|
-
) from exc
|
|
1112
|
-
except urllib.error.URLError as exc:
|
|
1113
|
-
raise OutcommingChatError(
|
|
1114
|
-
f"outcomming request failed: {exc.reason}"
|
|
1115
|
-
) from exc
|
|
1116
|
-
except (OSError, EOFError, http.client.HTTPException) as exc:
|
|
1117
|
-
raise OutcommingChatError(
|
|
1118
|
-
f"outcomming request failed: {type(exc).__name__}: {exc}"
|
|
1119
|
-
) from exc
|
|
1120
|
-
|
|
1121
|
-
def _build_headers(self, accept: "str") -> "typing.Dict[str, str]":
|
|
1122
|
-
headers = {
|
|
1123
|
-
"Accept": accept,
|
|
1124
|
-
"Content-Type": "application/json",
|
|
1125
|
-
}
|
|
1126
|
-
api_key = self._config.outcomming_api_key()
|
|
1127
|
-
if api_key is not None:
|
|
1128
|
-
headers["Authorization"] = f"Bearer {api_key}"
|
|
1129
|
-
return headers
|
|
1130
|
-
|
|
1131
|
-
def _iter_sse_events(self, response):
|
|
1132
|
-
event_name: "typing.Union[str, None]" = None
|
|
1133
|
-
data_lines: "typing.List[str]" = []
|
|
1134
|
-
|
|
1135
|
-
for raw_line in response:
|
|
1136
|
-
line = raw_line.decode("utf-8", errors="replace").rstrip("\r\n")
|
|
1137
|
-
if line == "":
|
|
1138
|
-
if data_lines:
|
|
1139
|
-
yield event_name or "message", "\n".join(data_lines)
|
|
1140
|
-
event_name = None
|
|
1141
|
-
data_lines = []
|
|
1142
|
-
continue
|
|
1143
|
-
|
|
1144
|
-
if line.startswith(":"):
|
|
1145
|
-
continue
|
|
1146
|
-
if line.startswith("event:"):
|
|
1147
|
-
event_name = line.split(":", 1)[1].lstrip()
|
|
1148
|
-
continue
|
|
1149
|
-
if line.startswith("data:"):
|
|
1150
|
-
data_lines.append(line.split(":", 1)[1].lstrip())
|
|
1151
|
-
|
|
1152
|
-
if data_lines:
|
|
1153
|
-
yield event_name or "message", "\n".join(data_lines)
|