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.
- pycodex/__init__.py +22 -12
- pycodex/agent.py +89 -74
- pycodex/bootstrap.py +37 -251
- pycodex/cli.py +19 -28
- pycodex/config.py +36 -0
- pycodex/context.py +368 -51
- pycodex/events.py +14 -187
- pycodex/model.py +197 -95
- 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 +1143 -200
- pycodex/protocol.py +81 -15
- pycodex/runtime.py +370 -226
- pycodex/tools/__init__.py +102 -10
- 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 +58 -187
- pycodex/tools/code_mode_manager.py +165 -246
- pycodex/tools/exec_command_tool.py +0 -18
- pycodex/tools/exec_runtime.py +332 -0
- pycodex/tools/exec_tool.py +74 -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/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 +43 -2
- pycodex/utils/doctor.py +5 -4
- pycodex/utils/dotenv.py +0 -7
- pycodex/utils/event_helpers.py +143 -13
- pycodex/utils/history.py +59 -0
- pycodex/utils/session_persist.py +104 -48
- python_codex-0.6.1.dist-info/METADATA +201 -0
- python_codex-0.6.1.dist-info/RECORD +106 -0
- responses_server/__init__.py +2 -0
- responses_server/app.py +10 -7
- responses_server/config.py +6 -12
- responses_server/gemini_api.py +333 -0
- responses_server/messages_api.py +9 -1
- responses_server/payload_processors.py +4 -4
- responses_server/request_translation.py +486 -0
- responses_server/server.py +31 -24
- responses_server/stream_events.py +124 -0
- responses_server/stream_router.py +48 -830
- responses_server/tools/custom_adapter.py +29 -29
- responses_server/tools/web_search.py +3 -0
- responses_server/transport.py +388 -0
- pycodex/tools/close_agent_tool.py +0 -60
- pycodex/tools/exec_runtime.js +0 -161
- pycodex/tools/request_user_input_tool.py +0 -102
- pycodex/tools/resume_agent_tool.py +0 -54
- pycodex/tools/send_input_tool.py +0 -110
- python_codex-0.5.2.dist-info/METADATA +0 -262
- python_codex-0.5.2.dist-info/RECORD +0 -90
- {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/WHEEL +0 -0
- {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/entry_points.txt +0 -0
- {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/licenses/LICENSE +0 -0
pycodex/model.py
CHANGED
|
@@ -6,6 +6,7 @@ import threading
|
|
|
6
6
|
import typing
|
|
7
7
|
import urllib.parse
|
|
8
8
|
import uuid
|
|
9
|
+
from copy import deepcopy
|
|
9
10
|
from dataclasses import dataclass, field, replace
|
|
10
11
|
from pathlib import Path
|
|
11
12
|
from time import monotonic
|
|
@@ -15,11 +16,7 @@ import requests
|
|
|
15
16
|
from urllib3.exceptions import ReadTimeoutError
|
|
16
17
|
|
|
17
18
|
from .utils.compat import Protocol
|
|
18
|
-
|
|
19
|
-
try:
|
|
20
|
-
import tomllib
|
|
21
|
-
except ModuleNotFoundError: # pragma: no cover - Python 3.10 path
|
|
22
|
-
import tomli as tomllib
|
|
19
|
+
from .utils.codex_config import DEFAULT_CODEX_CONFIG_PATH, read_codex_config
|
|
23
20
|
|
|
24
21
|
from .events import (
|
|
25
22
|
AssistantDeltaEvent,
|
|
@@ -38,10 +35,11 @@ from .protocol import (
|
|
|
38
35
|
Prompt,
|
|
39
36
|
ReasoningItem,
|
|
40
37
|
ToolCall,
|
|
38
|
+
ToolSpec,
|
|
39
|
+
qualified_tool_name,
|
|
41
40
|
)
|
|
42
41
|
from .utils import build_user_agent, uuid7_string
|
|
43
42
|
|
|
44
|
-
DEFAULT_CODEX_CONFIG_PATH = Path.home() / ".codex" / "config.toml"
|
|
45
43
|
DEFAULT_ORIGINATOR = "pycodex"
|
|
46
44
|
RESPONSES_LITE_HEADER = "x-openai-internal-codex-responses-lite"
|
|
47
45
|
ModelStreamEventHandler = Callable[[ModelEvent], None]
|
|
@@ -55,10 +53,25 @@ RATE_LIMIT_RETRY_AFTER_RE = re.compile(
|
|
|
55
53
|
)
|
|
56
54
|
|
|
57
55
|
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class ModelRecordingMetadata:
|
|
58
|
+
originator: "str"
|
|
59
|
+
provider_name: "typing.Union[str, None]"
|
|
60
|
+
|
|
61
|
+
|
|
58
62
|
class ModelClient(Protocol):
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
63
|
+
model: "str"
|
|
64
|
+
reasoning_effort: "typing.Union[str, None]"
|
|
65
|
+
recording_metadata: "ModelRecordingMetadata"
|
|
66
|
+
|
|
67
|
+
def with_overrides(
|
|
68
|
+
self,
|
|
69
|
+
model: "typing.Union[str, None]",
|
|
70
|
+
reasoning_effort: "typing.Union[str, None]",
|
|
71
|
+
session_id: "typing.Union[str, None]" = None,
|
|
72
|
+
openai_subagent: "typing.Union[str, None]" = None,
|
|
73
|
+
) -> "ModelClient":
|
|
74
|
+
"""Construct an independent client for a child Agent."""
|
|
62
75
|
|
|
63
76
|
async def complete(
|
|
64
77
|
self,
|
|
@@ -68,10 +81,7 @@ class ModelClient(Protocol):
|
|
|
68
81
|
"""Return the next batch of model output items for the current prompt."""
|
|
69
82
|
|
|
70
83
|
|
|
71
|
-
class ModelControl(Protocol):
|
|
72
|
-
model: "str"
|
|
73
|
-
reasoning_effort: "typing.Union[str, None]"
|
|
74
|
-
|
|
84
|
+
class ModelControl(ModelClient, Protocol):
|
|
75
85
|
@property
|
|
76
86
|
def endpoint(self) -> "str":
|
|
77
87
|
"""Return the active API base URL, safe for display."""
|
|
@@ -88,7 +98,6 @@ class ResponsesProviderConfig:
|
|
|
88
98
|
provider_name: "str"
|
|
89
99
|
base_url: "str"
|
|
90
100
|
api_key_env: "typing.Union[str, None]"
|
|
91
|
-
use_chat_completion: "bool" = False
|
|
92
101
|
wire_api: "str" = "responses"
|
|
93
102
|
query_params: "typing.Dict[str, str]" = field(default_factory=dict)
|
|
94
103
|
reasoning_effort: "typing.Union[str, None]" = None
|
|
@@ -103,8 +112,11 @@ class ResponsesProviderConfig:
|
|
|
103
112
|
fallback_models: "typing.Tuple[str, ...]" = ()
|
|
104
113
|
fallback_cooldown_seconds: "int" = 900
|
|
105
114
|
stream_first_data_timeout_ms: "typing.Union[int, None]" = None
|
|
115
|
+
compat_api: "str" = "none"
|
|
106
116
|
|
|
107
117
|
def __post_init__(self):
|
|
118
|
+
if self.compat_api not in ("none", "chat_completions", "messages", "gemini"):
|
|
119
|
+
raise ValueError("compat_api must be none, chat_completions, messages or gemini")
|
|
108
120
|
cooldown = self.fallback_cooldown_seconds
|
|
109
121
|
if isinstance(cooldown, bool) or not isinstance(cooldown, int) or cooldown < 0:
|
|
110
122
|
raise ValueError("fallback_cooldown_seconds must be a non-negative integer")
|
|
@@ -119,17 +131,18 @@ class ResponsesProviderConfig:
|
|
|
119
131
|
cls,
|
|
120
132
|
config_path: "typing.Union[str, Path]" = DEFAULT_CODEX_CONFIG_PATH,
|
|
121
133
|
profile: "typing.Union[str, None]" = None,
|
|
134
|
+
use_default_profile: "bool" = True,
|
|
122
135
|
) -> "ResponsesProviderConfig":
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
overrides = data.get("profiles", {}).get(profile)
|
|
127
|
-
if overrides is None:
|
|
128
|
-
raise ValueError(f"unknown Codex profile: {profile}")
|
|
129
|
-
selected.update(overrides)
|
|
136
|
+
return cls.from_mapping(
|
|
137
|
+
read_codex_config(config_path, profile, use_default_profile)
|
|
138
|
+
)
|
|
130
139
|
|
|
140
|
+
@classmethod
|
|
141
|
+
def from_mapping(
|
|
142
|
+
cls, selected: "typing.Mapping[str, typing.Any]",
|
|
143
|
+
) -> "ResponsesProviderConfig":
|
|
131
144
|
provider_name = selected.get("model_provider", "openai")
|
|
132
|
-
provider =
|
|
145
|
+
provider = selected.get("model_providers", {}).get(provider_name)
|
|
133
146
|
if provider is None:
|
|
134
147
|
if provider_name != "openai":
|
|
135
148
|
raise ValueError(f"unknown Codex model provider: {provider_name}")
|
|
@@ -153,11 +166,18 @@ class ResponsesProviderConfig:
|
|
|
153
166
|
beta_features: "typing.List[str]" = []
|
|
154
167
|
if isinstance(features, dict) and features.get("guardian_approval") is True:
|
|
155
168
|
beta_features.append("guardian_approval")
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
169
|
+
for key in ("use_messages", "use_gemini"):
|
|
170
|
+
if key in selected or key in provider:
|
|
171
|
+
raise ValueError(f"{key} has been removed; use compat_api instead")
|
|
172
|
+
compat_api = "none"
|
|
173
|
+
for source in (selected, provider):
|
|
174
|
+
if "compat_api" in source:
|
|
175
|
+
compat_api = source["compat_api"]
|
|
176
|
+
break
|
|
177
|
+
use_chat_completion = _optional_bool(source.get("use_chat_completion"))
|
|
178
|
+
if use_chat_completion is not None:
|
|
179
|
+
compat_api = "chat_completions" if use_chat_completion else "none"
|
|
180
|
+
break
|
|
161
181
|
fallback_models = provider.get("fallback_models", [])
|
|
162
182
|
if not isinstance(fallback_models, list) or any(
|
|
163
183
|
not isinstance(model, str) or not model or any(c.isspace() for c in model)
|
|
@@ -169,7 +189,7 @@ class ResponsesProviderConfig:
|
|
|
169
189
|
provider_name=provider_name,
|
|
170
190
|
base_url=provider["base_url"],
|
|
171
191
|
api_key_env=api_key_env,
|
|
172
|
-
|
|
192
|
+
compat_api=compat_api,
|
|
173
193
|
wire_api=wire_api,
|
|
174
194
|
query_params=query_params,
|
|
175
195
|
reasoning_effort=selected.get("model_reasoning_effort"),
|
|
@@ -197,19 +217,6 @@ class ResponsesProviderConfig:
|
|
|
197
217
|
)
|
|
198
218
|
return value
|
|
199
219
|
|
|
200
|
-
def with_overrides(
|
|
201
|
-
self,
|
|
202
|
-
model: "typing.Union[str, None]" = None,
|
|
203
|
-
reasoning_effort: "typing.Union[str, None]" = None,
|
|
204
|
-
) -> "ResponsesProviderConfig":
|
|
205
|
-
return replace(
|
|
206
|
-
self,
|
|
207
|
-
model=self.model if model is None else model,
|
|
208
|
-
reasoning_effort=(
|
|
209
|
-
self.reasoning_effort if reasoning_effort is None else reasoning_effort
|
|
210
|
-
),
|
|
211
|
-
)
|
|
212
|
-
|
|
213
220
|
def effective_stream_max_retries(self) -> "int":
|
|
214
221
|
if self.stream_max_retries is None:
|
|
215
222
|
return DEFAULT_STREAM_MAX_RETRIES
|
|
@@ -334,6 +341,22 @@ def _strip_image_detail_from_content_items(items: "typing.Iterable[object]") ->
|
|
|
334
341
|
item.pop("detail", None)
|
|
335
342
|
|
|
336
343
|
|
|
344
|
+
def _filter_audio_inputs(items, metadata):
|
|
345
|
+
if metadata is None or "audio" in metadata.get("input_modalities", ()):
|
|
346
|
+
return
|
|
347
|
+
for item in items:
|
|
348
|
+
for key in ("content", "output"):
|
|
349
|
+
content = item.get(key)
|
|
350
|
+
if not isinstance(content, list):
|
|
351
|
+
continue
|
|
352
|
+
for index, part in enumerate(content):
|
|
353
|
+
if part.get("type") == "input_audio":
|
|
354
|
+
content[index] = {
|
|
355
|
+
"type": "input_text",
|
|
356
|
+
"text": "audio content omitted because you do not support audio input",
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
|
|
337
360
|
class ResponsesApiError(RuntimeError):
|
|
338
361
|
pass
|
|
339
362
|
|
|
@@ -426,7 +449,7 @@ class ResponsesModelClient:
|
|
|
426
449
|
self._config = config
|
|
427
450
|
self._timeout_seconds = timeout_seconds
|
|
428
451
|
self._session_id = session_id or uuid7_string()
|
|
429
|
-
self.
|
|
452
|
+
self.recording_metadata = ModelRecordingMetadata(originator, config.provider_name)
|
|
430
453
|
self._user_agent = user_agent or build_user_agent(originator)
|
|
431
454
|
self._openai_subagent = openai_subagent
|
|
432
455
|
self._model_cooldowns: "typing.Dict[str, float]" = {}
|
|
@@ -483,13 +506,17 @@ class ResponsesModelClient:
|
|
|
483
506
|
openai_subagent: "typing.Union[str, None]" = None,
|
|
484
507
|
) -> "ResponsesModelClient":
|
|
485
508
|
return ResponsesModelClient(
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
509
|
+
replace(
|
|
510
|
+
self._config,
|
|
511
|
+
model=model or self.model,
|
|
512
|
+
reasoning_effort=(
|
|
513
|
+
self._config.reasoning_effort
|
|
514
|
+
if reasoning_effort is None else reasoning_effort
|
|
515
|
+
),
|
|
489
516
|
),
|
|
490
517
|
self._timeout_seconds,
|
|
491
518
|
session_id=self._session_id if session_id is None else session_id,
|
|
492
|
-
originator=self.
|
|
519
|
+
originator=self.recording_metadata.originator,
|
|
493
520
|
user_agent=self._user_agent,
|
|
494
521
|
openai_subagent=(
|
|
495
522
|
self._openai_subagent if openai_subagent is None else openai_subagent
|
|
@@ -613,6 +640,7 @@ class ResponsesModelClient:
|
|
|
613
640
|
event_handler: "ModelStreamEventHandler",
|
|
614
641
|
) -> "ModelResponse":
|
|
615
642
|
payload = self._build_payload(prompt)
|
|
643
|
+
session_id = payload["prompt_cache_key"]
|
|
616
644
|
body = json.dumps(payload).encode("utf-8")
|
|
617
645
|
url = self.responses_url()
|
|
618
646
|
prepared = requests.PreparedRequest()
|
|
@@ -688,6 +716,7 @@ class ResponsesModelClient:
|
|
|
688
716
|
tracked_lines,
|
|
689
717
|
event_handler,
|
|
690
718
|
diagnostics=diagnostics,
|
|
719
|
+
session_id=session_id,
|
|
691
720
|
)
|
|
692
721
|
completed = True
|
|
693
722
|
return result
|
|
@@ -702,7 +731,7 @@ class ResponsesModelClient:
|
|
|
702
731
|
)
|
|
703
732
|
):
|
|
704
733
|
error_type = ResponsesFirstDataTimeout
|
|
705
|
-
error = error_type(self._format_transport_error(url, exc, diagnostics))
|
|
734
|
+
error = error_type(self._format_transport_error(url, exc, diagnostics, session_id))
|
|
706
735
|
error.elapsed_seconds = monotonic() - diagnostics.started_at
|
|
707
736
|
error.first_data_seconds = diagnostics.first_data_seconds
|
|
708
737
|
raise error from exc
|
|
@@ -716,13 +745,70 @@ class ResponsesModelClient:
|
|
|
716
745
|
diagnostics.first_data_seconds, "completed" if completed else "failed",
|
|
717
746
|
))
|
|
718
747
|
|
|
748
|
+
@staticmethod
|
|
749
|
+
def _serialize_tools(
|
|
750
|
+
tools: "typing.Iterable[ToolSpec]", use_responses_lite: "bool",
|
|
751
|
+
) -> "typing.List[JSONDict]":
|
|
752
|
+
declarations = []
|
|
753
|
+
namespaces = {}
|
|
754
|
+
for tool in tools:
|
|
755
|
+
declaration = tool.serialize()
|
|
756
|
+
if not tool.namespace:
|
|
757
|
+
declarations.append(declaration)
|
|
758
|
+
continue
|
|
759
|
+
if tool.tool_type not in ("function", "custom"):
|
|
760
|
+
raise ValueError("tool namespaces only contain function/custom tools")
|
|
761
|
+
if tool.namespace not in namespaces:
|
|
762
|
+
namespace = {
|
|
763
|
+
"type": "namespace",
|
|
764
|
+
"name": tool.namespace,
|
|
765
|
+
"description": tool.namespace_description,
|
|
766
|
+
"tools": [],
|
|
767
|
+
}
|
|
768
|
+
namespaces[tool.namespace] = namespace
|
|
769
|
+
declarations.append(namespace)
|
|
770
|
+
namespace = namespaces[tool.namespace]
|
|
771
|
+
if not namespace["description"].strip():
|
|
772
|
+
namespace["description"] = tool.namespace_description
|
|
773
|
+
namespace["tools"].append(declaration)
|
|
774
|
+
for namespace in namespaces.values():
|
|
775
|
+
namespace["tools"].sort(key=lambda tool: tool["name"])
|
|
776
|
+
if not use_responses_lite:
|
|
777
|
+
return declarations
|
|
778
|
+
|
|
779
|
+
functions = {
|
|
780
|
+
"type": "namespace", "name": "functions", "description": "", "tools": [],
|
|
781
|
+
}
|
|
782
|
+
functions_index = None
|
|
783
|
+
payload = []
|
|
784
|
+
for declaration in declarations:
|
|
785
|
+
if declaration["type"] in ("function", "custom"):
|
|
786
|
+
functions["tools"].append(declaration)
|
|
787
|
+
elif (
|
|
788
|
+
declaration["type"] == "namespace"
|
|
789
|
+
and declaration["name"] == "functions"
|
|
790
|
+
):
|
|
791
|
+
functions["tools"].extend(declaration["tools"])
|
|
792
|
+
if declaration["description"].strip():
|
|
793
|
+
functions["description"] = declaration["description"]
|
|
794
|
+
else:
|
|
795
|
+
payload.append(declaration)
|
|
796
|
+
continue
|
|
797
|
+
if functions_index is None:
|
|
798
|
+
functions_index = len(payload)
|
|
799
|
+
if functions["tools"]:
|
|
800
|
+
payload.insert(functions_index, functions)
|
|
801
|
+
return payload
|
|
802
|
+
|
|
719
803
|
def _build_payload(self, prompt: "Prompt") -> "typing.Dict[str, object]":
|
|
804
|
+
session_id = self._session_id if prompt.session_id is None else prompt.session_id
|
|
720
805
|
use_responses_lite = self._config.use_responses_lite()
|
|
721
806
|
input_items = [item.serialize() for item in prompt.input]
|
|
807
|
+
_filter_audio_inputs(input_items, model_metadata(self.model))
|
|
722
808
|
if use_responses_lite:
|
|
723
809
|
_strip_image_details(input_items)
|
|
724
810
|
|
|
725
|
-
tools =
|
|
811
|
+
tools = self._serialize_tools(prompt.tools, use_responses_lite)
|
|
726
812
|
payload: "typing.Dict[str, object]" = {
|
|
727
813
|
"model": self.model,
|
|
728
814
|
"input": input_items,
|
|
@@ -731,11 +817,12 @@ class ResponsesModelClient:
|
|
|
731
817
|
"store": False,
|
|
732
818
|
"stream": True,
|
|
733
819
|
"include": ["reasoning.encrypted_content"],
|
|
734
|
-
"prompt_cache_key":
|
|
820
|
+
"prompt_cache_key": session_id,
|
|
735
821
|
}
|
|
822
|
+
prefix_namespace = uuid.uuid5(uuid.NAMESPACE_OID, session_id)
|
|
823
|
+
prefix: "typing.List[typing.Dict[str, object]]" = []
|
|
736
824
|
if use_responses_lite:
|
|
737
|
-
|
|
738
|
-
prefix: "typing.List[typing.Dict[str, object]]" = [
|
|
825
|
+
prefix.append(
|
|
739
826
|
{
|
|
740
827
|
"type": "additional_tools",
|
|
741
828
|
"id": "at_"
|
|
@@ -750,25 +837,24 @@ class ResponsesModelClient:
|
|
|
750
837
|
"role": "developer",
|
|
751
838
|
"tools": tools,
|
|
752
839
|
}
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
payload["instructions"] = prompt.base_instructions or ""
|
|
840
|
+
)
|
|
841
|
+
if prompt.base_instructions:
|
|
842
|
+
prefix.append(
|
|
843
|
+
{
|
|
844
|
+
"type": "message",
|
|
845
|
+
"id": "msg_"
|
|
846
|
+
+ str(uuid.uuid5(prefix_namespace, prompt.base_instructions)),
|
|
847
|
+
"role": "developer",
|
|
848
|
+
"content": [
|
|
849
|
+
{
|
|
850
|
+
"type": "input_text",
|
|
851
|
+
"text": prompt.base_instructions,
|
|
852
|
+
}
|
|
853
|
+
],
|
|
854
|
+
}
|
|
855
|
+
)
|
|
856
|
+
payload["input"] = prefix + input_items
|
|
857
|
+
if not use_responses_lite:
|
|
772
858
|
payload["tools"] = tools
|
|
773
859
|
|
|
774
860
|
if prompt.tools or use_responses_lite:
|
|
@@ -847,12 +933,13 @@ class ResponsesModelClient:
|
|
|
847
933
|
return models
|
|
848
934
|
|
|
849
935
|
def _build_headers(self, prompt: "Prompt") -> "typing.Dict[str, str]":
|
|
936
|
+
session_id = self._session_id if prompt.session_id is None else prompt.session_id
|
|
850
937
|
headers = {
|
|
851
938
|
"content-type": "application/json",
|
|
852
939
|
"accept": "text/event-stream",
|
|
853
|
-
"x-client-request-id":
|
|
854
|
-
"session_id":
|
|
855
|
-
"originator": self.
|
|
940
|
+
"x-client-request-id": session_id,
|
|
941
|
+
"session_id": session_id,
|
|
942
|
+
"originator": self.recording_metadata.originator,
|
|
856
943
|
"user-agent": self._user_agent,
|
|
857
944
|
}
|
|
858
945
|
api_key = self._config.api_key()
|
|
@@ -874,7 +961,7 @@ class ResponsesModelClient:
|
|
|
874
961
|
def _build_model_list_headers(self) -> "typing.Dict[str, str]":
|
|
875
962
|
headers = {
|
|
876
963
|
"accept": "application/json",
|
|
877
|
-
"originator": self.
|
|
964
|
+
"originator": self.recording_metadata.originator,
|
|
878
965
|
"user-agent": self._user_agent,
|
|
879
966
|
}
|
|
880
967
|
api_key = self._config.api_key()
|
|
@@ -891,6 +978,7 @@ class ResponsesModelClient:
|
|
|
891
978
|
response,
|
|
892
979
|
event_handler: "ModelStreamEventHandler",
|
|
893
980
|
diagnostics: "typing.Union[_StreamDiagnostics, None]" = None,
|
|
981
|
+
session_id: "typing.Union[str, None]" = None,
|
|
894
982
|
) -> "ModelResponse":
|
|
895
983
|
items: "typing.List[typing.Union[typing.Union[AssistantMessage, ToolCall], ReasoningItem]]" = ([])
|
|
896
984
|
saw_completed = False
|
|
@@ -903,7 +991,7 @@ class ResponsesModelClient:
|
|
|
903
991
|
payload = json.loads(data)
|
|
904
992
|
except json.JSONDecodeError as exc:
|
|
905
993
|
raise ResponsesRetryableError(
|
|
906
|
-
self._format_invalid_event_error(event_name, data, exc)
|
|
994
|
+
self._format_invalid_event_error(event_name, data, exc, session_id)
|
|
907
995
|
) from exc
|
|
908
996
|
event_type = payload.get("type", event_name)
|
|
909
997
|
last_event_type = str(event_type)
|
|
@@ -990,23 +1078,24 @@ class ResponsesModelClient:
|
|
|
990
1078
|
payload,
|
|
991
1079
|
len(partial_items),
|
|
992
1080
|
reason,
|
|
1081
|
+
session_id,
|
|
993
1082
|
),
|
|
994
1083
|
partial_items,
|
|
995
1084
|
reason=reason,
|
|
996
1085
|
)
|
|
997
1086
|
|
|
998
1087
|
if event_type == "response.failed":
|
|
999
|
-
self._raise_response_failed_error(payload)
|
|
1088
|
+
self._raise_response_failed_error(payload, session_id)
|
|
1000
1089
|
|
|
1001
1090
|
if not saw_completed:
|
|
1002
1091
|
raise ResponsesRetryableError(
|
|
1003
|
-
self._format_incomplete_stream_error(last_event_type, len(items))
|
|
1092
|
+
self._format_incomplete_stream_error(last_event_type, len(items), session_id)
|
|
1004
1093
|
)
|
|
1005
1094
|
|
|
1006
1095
|
return ModelResponse(items=items)
|
|
1007
1096
|
|
|
1097
|
+
@staticmethod
|
|
1008
1098
|
def _parse_output_item(
|
|
1009
|
-
self,
|
|
1010
1099
|
item: "typing.Dict[str, object]",
|
|
1011
1100
|
) -> "typing.Union[typing.Union[typing.Union[AssistantMessage, ToolCall], ReasoningItem], None]":
|
|
1012
1101
|
item_type = item.get("type")
|
|
@@ -1016,6 +1105,13 @@ class ResponsesModelClient:
|
|
|
1016
1105
|
if item_type == "message" and item.get("role") == "assistant":
|
|
1017
1106
|
return AssistantMessage.from_response_item(item)
|
|
1018
1107
|
|
|
1108
|
+
if item_type in ("function_call", "custom_tool_call"):
|
|
1109
|
+
name = str(item["name"])
|
|
1110
|
+
if "." in name:
|
|
1111
|
+
raise ResponsesApiError("tool call names must not contain '.'")
|
|
1112
|
+
namespace = item.get("namespace")
|
|
1113
|
+
name = qualified_tool_name(name, namespace)
|
|
1114
|
+
|
|
1019
1115
|
if item_type == "function_call":
|
|
1020
1116
|
raw_arguments = item["arguments"]
|
|
1021
1117
|
arguments = json.loads(raw_arguments)
|
|
@@ -1025,17 +1121,18 @@ class ResponsesModelClient:
|
|
|
1025
1121
|
)
|
|
1026
1122
|
return ToolCall(
|
|
1027
1123
|
call_id=str(item["call_id"]),
|
|
1028
|
-
name=
|
|
1124
|
+
name=name,
|
|
1029
1125
|
arguments=arguments,
|
|
1030
1126
|
id=item.get("id"),
|
|
1031
1127
|
raw_arguments=raw_arguments,
|
|
1032
1128
|
namespace=item.get("namespace"),
|
|
1129
|
+
encrypted_function_args=deepcopy(item.get("encrypted_function_args")),
|
|
1033
1130
|
)
|
|
1034
1131
|
|
|
1035
1132
|
if item_type == "custom_tool_call":
|
|
1036
1133
|
return ToolCall(
|
|
1037
1134
|
call_id=str(item["call_id"]),
|
|
1038
|
-
name=
|
|
1135
|
+
name=name,
|
|
1039
1136
|
arguments=str(item.get("input", "")),
|
|
1040
1137
|
tool_type="custom",
|
|
1041
1138
|
id=item.get("id"),
|
|
@@ -1114,16 +1211,17 @@ class ResponsesModelClient:
|
|
|
1114
1211
|
def _base_error_details(
|
|
1115
1212
|
self,
|
|
1116
1213
|
url: "str",
|
|
1214
|
+
session_id: "typing.Union[str, None]" = None,
|
|
1117
1215
|
) -> "typing.List[typing.Tuple[str, str]]":
|
|
1118
1216
|
return [
|
|
1119
1217
|
("provider", self._config.provider_name),
|
|
1120
1218
|
("model", self.model),
|
|
1121
1219
|
("request", f"POST {url}"),
|
|
1122
|
-
("session_id", self._session_id),
|
|
1220
|
+
("session_id", self._session_id if session_id is None else session_id),
|
|
1123
1221
|
]
|
|
1124
1222
|
|
|
1223
|
+
@staticmethod
|
|
1125
1224
|
def _format_error_message(
|
|
1126
|
-
self,
|
|
1127
1225
|
summary: "str",
|
|
1128
1226
|
details: "typing.Iterable[typing.Tuple[str, str]]",
|
|
1129
1227
|
) -> "str":
|
|
@@ -1140,8 +1238,9 @@ class ResponsesModelClient:
|
|
|
1140
1238
|
url: "str",
|
|
1141
1239
|
exc: "BaseException",
|
|
1142
1240
|
diagnostics: "typing.Union[_StreamDiagnostics, None]" = None,
|
|
1241
|
+
session_id: "typing.Union[str, None]" = None,
|
|
1143
1242
|
) -> "str":
|
|
1144
|
-
details = self._base_error_details(url)
|
|
1243
|
+
details = self._base_error_details(url, session_id)
|
|
1145
1244
|
if diagnostics is not None:
|
|
1146
1245
|
details.extend(self._transport_diagnostics_details(diagnostics))
|
|
1147
1246
|
details.append(("elapsed_seconds", round(monotonic() - diagnostics.started_at, 3)))
|
|
@@ -1179,8 +1278,9 @@ class ResponsesModelClient:
|
|
|
1179
1278
|
self,
|
|
1180
1279
|
message: "str",
|
|
1181
1280
|
code: "str" = "",
|
|
1281
|
+
session_id: "typing.Union[str, None]" = None,
|
|
1182
1282
|
) -> "str":
|
|
1183
|
-
details = self._base_error_details(self.responses_url())
|
|
1283
|
+
details = self._base_error_details(self.responses_url(), session_id)
|
|
1184
1284
|
details.append(("detail", message))
|
|
1185
1285
|
if code:
|
|
1186
1286
|
details.append(("code", code))
|
|
@@ -1201,8 +1301,9 @@ class ResponsesModelClient:
|
|
|
1201
1301
|
payload: "typing.Dict[str, object]",
|
|
1202
1302
|
output_item_count: "int",
|
|
1203
1303
|
reason: "typing.Union[str, None]" = None,
|
|
1304
|
+
session_id: "typing.Union[str, None]" = None,
|
|
1204
1305
|
) -> "str":
|
|
1205
|
-
details = self._base_error_details(self.responses_url())
|
|
1306
|
+
details = self._base_error_details(self.responses_url(), session_id)
|
|
1206
1307
|
if reason:
|
|
1207
1308
|
details.append(("reason", reason))
|
|
1208
1309
|
details.append(("output_items_received", str(output_item_count)))
|
|
@@ -1228,35 +1329,34 @@ class ResponsesModelClient:
|
|
|
1228
1329
|
return str(incomplete_details.get("reason") or "").strip()
|
|
1229
1330
|
|
|
1230
1331
|
def _raise_response_failed_error(
|
|
1231
|
-
self, payload: "typing.Dict[str, object]"
|
|
1332
|
+
self, payload: "typing.Dict[str, object]", session_id=None,
|
|
1232
1333
|
) -> "None":
|
|
1233
1334
|
response = payload.get("response")
|
|
1234
1335
|
error = response.get("error") if isinstance(response, dict) else None
|
|
1235
1336
|
if not isinstance(error, dict):
|
|
1236
1337
|
raise ResponsesRetryableError(
|
|
1237
|
-
self._format_response_failed_error("responses stream failed")
|
|
1338
|
+
self._format_response_failed_error("responses stream failed", session_id=session_id)
|
|
1238
1339
|
)
|
|
1239
1340
|
|
|
1240
1341
|
message = str(error.get("message") or "responses stream failed")
|
|
1241
1342
|
code = str(error.get("code") or error.get("type") or "").strip()
|
|
1343
|
+
formatted = self._format_response_failed_error(message, code, session_id)
|
|
1242
1344
|
if code == "context_length_exceeded" or _is_context_length_error_message(
|
|
1243
1345
|
message
|
|
1244
1346
|
):
|
|
1245
|
-
raise ContextLengthExceeded(
|
|
1246
|
-
self._format_response_failed_error(message, code)
|
|
1247
|
-
)
|
|
1347
|
+
raise ContextLengthExceeded(formatted)
|
|
1248
1348
|
if code in {"model_not_found", "model_not_available", "permission_denied"}:
|
|
1249
|
-
raise ResponsesModelUnavailableError(
|
|
1349
|
+
raise ResponsesModelUnavailableError(formatted)
|
|
1250
1350
|
if code in {
|
|
1251
1351
|
"insufficient_quota",
|
|
1252
1352
|
"invalid_prompt",
|
|
1253
1353
|
"model_output_invalid",
|
|
1254
1354
|
"usage_not_included",
|
|
1255
1355
|
}:
|
|
1256
|
-
raise ResponsesApiError(
|
|
1356
|
+
raise ResponsesApiError(formatted)
|
|
1257
1357
|
|
|
1258
1358
|
raise ResponsesRetryableError(
|
|
1259
|
-
|
|
1359
|
+
formatted,
|
|
1260
1360
|
retry_delay_seconds=self._try_parse_retry_after_seconds(code, message),
|
|
1261
1361
|
)
|
|
1262
1362
|
|
|
@@ -1264,8 +1364,9 @@ class ResponsesModelClient:
|
|
|
1264
1364
|
self,
|
|
1265
1365
|
last_event_type: "str",
|
|
1266
1366
|
output_item_count: "int",
|
|
1367
|
+
session_id: "typing.Union[str, None]" = None,
|
|
1267
1368
|
) -> "str":
|
|
1268
|
-
details = self._base_error_details(self.responses_url())
|
|
1369
|
+
details = self._base_error_details(self.responses_url(), session_id)
|
|
1269
1370
|
if last_event_type:
|
|
1270
1371
|
details.append(("last_event", last_event_type))
|
|
1271
1372
|
details.append(("output_items_received", str(output_item_count)))
|
|
@@ -1292,8 +1393,9 @@ class ResponsesModelClient:
|
|
|
1292
1393
|
event_name: "str",
|
|
1293
1394
|
raw_data: "str",
|
|
1294
1395
|
exc: "json.JSONDecodeError",
|
|
1396
|
+
session_id: "typing.Union[str, None]" = None,
|
|
1295
1397
|
) -> "str":
|
|
1296
|
-
details = self._base_error_details(self.responses_url())
|
|
1398
|
+
details = self._base_error_details(self.responses_url(), session_id)
|
|
1297
1399
|
details.append(("event", event_name or "message"))
|
|
1298
1400
|
details.append(("exception", type(exc).__name__))
|
|
1299
1401
|
details.append(("detail", str(exc)))
|