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
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
- @property
60
- def model(self) -> "str":
61
- """Return the current model identifier."""
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."""
@@ -119,17 +129,18 @@ class ResponsesProviderConfig:
119
129
  cls,
120
130
  config_path: "typing.Union[str, Path]" = DEFAULT_CODEX_CONFIG_PATH,
121
131
  profile: "typing.Union[str, None]" = None,
132
+ use_default_profile: "bool" = True,
122
133
  ) -> "ResponsesProviderConfig":
123
- data = tomllib.loads(Path(config_path).read_text(encoding="utf-8"))
124
- selected = dict(data)
125
- if profile is not None:
126
- overrides = data.get("profiles", {}).get(profile)
127
- if overrides is None:
128
- raise ValueError(f"unknown Codex profile: {profile}")
129
- selected.update(overrides)
134
+ return cls.from_mapping(
135
+ read_codex_config(config_path, profile, use_default_profile)
136
+ )
130
137
 
138
+ @classmethod
139
+ def from_mapping(
140
+ cls, selected: "typing.Mapping[str, typing.Any]",
141
+ ) -> "ResponsesProviderConfig":
131
142
  provider_name = selected.get("model_provider", "openai")
132
- provider = data.get("model_providers", {}).get(provider_name)
143
+ provider = selected.get("model_providers", {}).get(provider_name)
133
144
  if provider is None:
134
145
  if provider_name != "openai":
135
146
  raise ValueError(f"unknown Codex model provider: {provider_name}")
@@ -197,19 +208,6 @@ class ResponsesProviderConfig:
197
208
  )
198
209
  return value
199
210
 
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
211
  def effective_stream_max_retries(self) -> "int":
214
212
  if self.stream_max_retries is None:
215
213
  return DEFAULT_STREAM_MAX_RETRIES
@@ -334,6 +332,22 @@ def _strip_image_detail_from_content_items(items: "typing.Iterable[object]") ->
334
332
  item.pop("detail", None)
335
333
 
336
334
 
335
+ def _filter_audio_inputs(items, metadata):
336
+ if metadata is None or "audio" in metadata.get("input_modalities", ()):
337
+ return
338
+ for item in items:
339
+ for key in ("content", "output"):
340
+ content = item.get(key)
341
+ if not isinstance(content, list):
342
+ continue
343
+ for index, part in enumerate(content):
344
+ if part.get("type") == "input_audio":
345
+ content[index] = {
346
+ "type": "input_text",
347
+ "text": "audio content omitted because you do not support audio input",
348
+ }
349
+
350
+
337
351
  class ResponsesApiError(RuntimeError):
338
352
  pass
339
353
 
@@ -426,7 +440,7 @@ class ResponsesModelClient:
426
440
  self._config = config
427
441
  self._timeout_seconds = timeout_seconds
428
442
  self._session_id = session_id or uuid7_string()
429
- self._originator = originator
443
+ self.recording_metadata = ModelRecordingMetadata(originator, config.provider_name)
430
444
  self._user_agent = user_agent or build_user_agent(originator)
431
445
  self._openai_subagent = openai_subagent
432
446
  self._model_cooldowns: "typing.Dict[str, float]" = {}
@@ -483,13 +497,17 @@ class ResponsesModelClient:
483
497
  openai_subagent: "typing.Union[str, None]" = None,
484
498
  ) -> "ResponsesModelClient":
485
499
  return ResponsesModelClient(
486
- self._config.with_overrides(
487
- model or self.model,
488
- reasoning_effort,
500
+ replace(
501
+ self._config,
502
+ model=model or self.model,
503
+ reasoning_effort=(
504
+ self._config.reasoning_effort
505
+ if reasoning_effort is None else reasoning_effort
506
+ ),
489
507
  ),
490
508
  self._timeout_seconds,
491
509
  session_id=self._session_id if session_id is None else session_id,
492
- originator=self._originator,
510
+ originator=self.recording_metadata.originator,
493
511
  user_agent=self._user_agent,
494
512
  openai_subagent=(
495
513
  self._openai_subagent if openai_subagent is None else openai_subagent
@@ -613,6 +631,7 @@ class ResponsesModelClient:
613
631
  event_handler: "ModelStreamEventHandler",
614
632
  ) -> "ModelResponse":
615
633
  payload = self._build_payload(prompt)
634
+ session_id = payload["prompt_cache_key"]
616
635
  body = json.dumps(payload).encode("utf-8")
617
636
  url = self.responses_url()
618
637
  prepared = requests.PreparedRequest()
@@ -688,6 +707,7 @@ class ResponsesModelClient:
688
707
  tracked_lines,
689
708
  event_handler,
690
709
  diagnostics=diagnostics,
710
+ session_id=session_id,
691
711
  )
692
712
  completed = True
693
713
  return result
@@ -702,7 +722,7 @@ class ResponsesModelClient:
702
722
  )
703
723
  ):
704
724
  error_type = ResponsesFirstDataTimeout
705
- error = error_type(self._format_transport_error(url, exc, diagnostics))
725
+ error = error_type(self._format_transport_error(url, exc, diagnostics, session_id))
706
726
  error.elapsed_seconds = monotonic() - diagnostics.started_at
707
727
  error.first_data_seconds = diagnostics.first_data_seconds
708
728
  raise error from exc
@@ -716,13 +736,70 @@ class ResponsesModelClient:
716
736
  diagnostics.first_data_seconds, "completed" if completed else "failed",
717
737
  ))
718
738
 
739
+ @staticmethod
740
+ def _serialize_tools(
741
+ tools: "typing.Iterable[ToolSpec]", use_responses_lite: "bool",
742
+ ) -> "typing.List[JSONDict]":
743
+ declarations = []
744
+ namespaces = {}
745
+ for tool in tools:
746
+ declaration = tool.serialize()
747
+ if not tool.namespace:
748
+ declarations.append(declaration)
749
+ continue
750
+ if tool.tool_type not in ("function", "custom"):
751
+ raise ValueError("tool namespaces only contain function/custom tools")
752
+ if tool.namespace not in namespaces:
753
+ namespace = {
754
+ "type": "namespace",
755
+ "name": tool.namespace,
756
+ "description": tool.namespace_description,
757
+ "tools": [],
758
+ }
759
+ namespaces[tool.namespace] = namespace
760
+ declarations.append(namespace)
761
+ namespace = namespaces[tool.namespace]
762
+ if not namespace["description"].strip():
763
+ namespace["description"] = tool.namespace_description
764
+ namespace["tools"].append(declaration)
765
+ for namespace in namespaces.values():
766
+ namespace["tools"].sort(key=lambda tool: tool["name"])
767
+ if not use_responses_lite:
768
+ return declarations
769
+
770
+ functions = {
771
+ "type": "namespace", "name": "functions", "description": "", "tools": [],
772
+ }
773
+ functions_index = None
774
+ payload = []
775
+ for declaration in declarations:
776
+ if declaration["type"] in ("function", "custom"):
777
+ functions["tools"].append(declaration)
778
+ elif (
779
+ declaration["type"] == "namespace"
780
+ and declaration["name"] == "functions"
781
+ ):
782
+ functions["tools"].extend(declaration["tools"])
783
+ if declaration["description"].strip():
784
+ functions["description"] = declaration["description"]
785
+ else:
786
+ payload.append(declaration)
787
+ continue
788
+ if functions_index is None:
789
+ functions_index = len(payload)
790
+ if functions["tools"]:
791
+ payload.insert(functions_index, functions)
792
+ return payload
793
+
719
794
  def _build_payload(self, prompt: "Prompt") -> "typing.Dict[str, object]":
795
+ session_id = self._session_id if prompt.session_id is None else prompt.session_id
720
796
  use_responses_lite = self._config.use_responses_lite()
721
797
  input_items = [item.serialize() for item in prompt.input]
798
+ _filter_audio_inputs(input_items, model_metadata(self.model))
722
799
  if use_responses_lite:
723
800
  _strip_image_details(input_items)
724
801
 
725
- tools = [tool.serialize() for tool in prompt.tools]
802
+ tools = self._serialize_tools(prompt.tools, use_responses_lite)
726
803
  payload: "typing.Dict[str, object]" = {
727
804
  "model": self.model,
728
805
  "input": input_items,
@@ -731,11 +808,12 @@ class ResponsesModelClient:
731
808
  "store": False,
732
809
  "stream": True,
733
810
  "include": ["reasoning.encrypted_content"],
734
- "prompt_cache_key": self._session_id,
811
+ "prompt_cache_key": session_id,
735
812
  }
813
+ prefix_namespace = uuid.uuid5(uuid.NAMESPACE_OID, session_id)
814
+ prefix: "typing.List[typing.Dict[str, object]]" = []
736
815
  if use_responses_lite:
737
- prefix_namespace = uuid.uuid5(uuid.NAMESPACE_OID, self._session_id)
738
- prefix: "typing.List[typing.Dict[str, object]]" = [
816
+ prefix.append(
739
817
  {
740
818
  "type": "additional_tools",
741
819
  "id": "at_"
@@ -750,25 +828,24 @@ class ResponsesModelClient:
750
828
  "role": "developer",
751
829
  "tools": tools,
752
830
  }
753
- ]
754
- if prompt.base_instructions:
755
- prefix.append(
756
- {
757
- "type": "message",
758
- "id": "msg_"
759
- + str(uuid.uuid5(prefix_namespace, prompt.base_instructions)),
760
- "role": "developer",
761
- "content": [
762
- {
763
- "type": "input_text",
764
- "text": prompt.base_instructions,
765
- }
766
- ],
767
- }
768
- )
769
- payload["input"] = prefix + input_items
770
- else:
771
- payload["instructions"] = prompt.base_instructions or ""
831
+ )
832
+ if prompt.base_instructions:
833
+ prefix.append(
834
+ {
835
+ "type": "message",
836
+ "id": "msg_"
837
+ + str(uuid.uuid5(prefix_namespace, prompt.base_instructions)),
838
+ "role": "developer",
839
+ "content": [
840
+ {
841
+ "type": "input_text",
842
+ "text": prompt.base_instructions,
843
+ }
844
+ ],
845
+ }
846
+ )
847
+ payload["input"] = prefix + input_items
848
+ if not use_responses_lite:
772
849
  payload["tools"] = tools
773
850
 
774
851
  if prompt.tools or use_responses_lite:
@@ -847,12 +924,13 @@ class ResponsesModelClient:
847
924
  return models
848
925
 
849
926
  def _build_headers(self, prompt: "Prompt") -> "typing.Dict[str, str]":
927
+ session_id = self._session_id if prompt.session_id is None else prompt.session_id
850
928
  headers = {
851
929
  "content-type": "application/json",
852
930
  "accept": "text/event-stream",
853
- "x-client-request-id": self._session_id,
854
- "session_id": self._session_id,
855
- "originator": self._originator,
931
+ "x-client-request-id": session_id,
932
+ "session_id": session_id,
933
+ "originator": self.recording_metadata.originator,
856
934
  "user-agent": self._user_agent,
857
935
  }
858
936
  api_key = self._config.api_key()
@@ -874,7 +952,7 @@ class ResponsesModelClient:
874
952
  def _build_model_list_headers(self) -> "typing.Dict[str, str]":
875
953
  headers = {
876
954
  "accept": "application/json",
877
- "originator": self._originator,
955
+ "originator": self.recording_metadata.originator,
878
956
  "user-agent": self._user_agent,
879
957
  }
880
958
  api_key = self._config.api_key()
@@ -891,6 +969,7 @@ class ResponsesModelClient:
891
969
  response,
892
970
  event_handler: "ModelStreamEventHandler",
893
971
  diagnostics: "typing.Union[_StreamDiagnostics, None]" = None,
972
+ session_id: "typing.Union[str, None]" = None,
894
973
  ) -> "ModelResponse":
895
974
  items: "typing.List[typing.Union[typing.Union[AssistantMessage, ToolCall], ReasoningItem]]" = ([])
896
975
  saw_completed = False
@@ -903,7 +982,7 @@ class ResponsesModelClient:
903
982
  payload = json.loads(data)
904
983
  except json.JSONDecodeError as exc:
905
984
  raise ResponsesRetryableError(
906
- self._format_invalid_event_error(event_name, data, exc)
985
+ self._format_invalid_event_error(event_name, data, exc, session_id)
907
986
  ) from exc
908
987
  event_type = payload.get("type", event_name)
909
988
  last_event_type = str(event_type)
@@ -990,23 +1069,24 @@ class ResponsesModelClient:
990
1069
  payload,
991
1070
  len(partial_items),
992
1071
  reason,
1072
+ session_id,
993
1073
  ),
994
1074
  partial_items,
995
1075
  reason=reason,
996
1076
  )
997
1077
 
998
1078
  if event_type == "response.failed":
999
- self._raise_response_failed_error(payload)
1079
+ self._raise_response_failed_error(payload, session_id)
1000
1080
 
1001
1081
  if not saw_completed:
1002
1082
  raise ResponsesRetryableError(
1003
- self._format_incomplete_stream_error(last_event_type, len(items))
1083
+ self._format_incomplete_stream_error(last_event_type, len(items), session_id)
1004
1084
  )
1005
1085
 
1006
1086
  return ModelResponse(items=items)
1007
1087
 
1088
+ @staticmethod
1008
1089
  def _parse_output_item(
1009
- self,
1010
1090
  item: "typing.Dict[str, object]",
1011
1091
  ) -> "typing.Union[typing.Union[typing.Union[AssistantMessage, ToolCall], ReasoningItem], None]":
1012
1092
  item_type = item.get("type")
@@ -1016,6 +1096,13 @@ class ResponsesModelClient:
1016
1096
  if item_type == "message" and item.get("role") == "assistant":
1017
1097
  return AssistantMessage.from_response_item(item)
1018
1098
 
1099
+ if item_type in ("function_call", "custom_tool_call"):
1100
+ name = str(item["name"])
1101
+ if "." in name:
1102
+ raise ResponsesApiError("tool call names must not contain '.'")
1103
+ namespace = item.get("namespace")
1104
+ name = qualified_tool_name(name, namespace)
1105
+
1019
1106
  if item_type == "function_call":
1020
1107
  raw_arguments = item["arguments"]
1021
1108
  arguments = json.loads(raw_arguments)
@@ -1025,17 +1112,18 @@ class ResponsesModelClient:
1025
1112
  )
1026
1113
  return ToolCall(
1027
1114
  call_id=str(item["call_id"]),
1028
- name=str(item["name"]),
1115
+ name=name,
1029
1116
  arguments=arguments,
1030
1117
  id=item.get("id"),
1031
1118
  raw_arguments=raw_arguments,
1032
1119
  namespace=item.get("namespace"),
1120
+ encrypted_function_args=deepcopy(item.get("encrypted_function_args")),
1033
1121
  )
1034
1122
 
1035
1123
  if item_type == "custom_tool_call":
1036
1124
  return ToolCall(
1037
1125
  call_id=str(item["call_id"]),
1038
- name=str(item["name"]),
1126
+ name=name,
1039
1127
  arguments=str(item.get("input", "")),
1040
1128
  tool_type="custom",
1041
1129
  id=item.get("id"),
@@ -1114,16 +1202,17 @@ class ResponsesModelClient:
1114
1202
  def _base_error_details(
1115
1203
  self,
1116
1204
  url: "str",
1205
+ session_id: "typing.Union[str, None]" = None,
1117
1206
  ) -> "typing.List[typing.Tuple[str, str]]":
1118
1207
  return [
1119
1208
  ("provider", self._config.provider_name),
1120
1209
  ("model", self.model),
1121
1210
  ("request", f"POST {url}"),
1122
- ("session_id", self._session_id),
1211
+ ("session_id", self._session_id if session_id is None else session_id),
1123
1212
  ]
1124
1213
 
1214
+ @staticmethod
1125
1215
  def _format_error_message(
1126
- self,
1127
1216
  summary: "str",
1128
1217
  details: "typing.Iterable[typing.Tuple[str, str]]",
1129
1218
  ) -> "str":
@@ -1140,8 +1229,9 @@ class ResponsesModelClient:
1140
1229
  url: "str",
1141
1230
  exc: "BaseException",
1142
1231
  diagnostics: "typing.Union[_StreamDiagnostics, None]" = None,
1232
+ session_id: "typing.Union[str, None]" = None,
1143
1233
  ) -> "str":
1144
- details = self._base_error_details(url)
1234
+ details = self._base_error_details(url, session_id)
1145
1235
  if diagnostics is not None:
1146
1236
  details.extend(self._transport_diagnostics_details(diagnostics))
1147
1237
  details.append(("elapsed_seconds", round(monotonic() - diagnostics.started_at, 3)))
@@ -1179,8 +1269,9 @@ class ResponsesModelClient:
1179
1269
  self,
1180
1270
  message: "str",
1181
1271
  code: "str" = "",
1272
+ session_id: "typing.Union[str, None]" = None,
1182
1273
  ) -> "str":
1183
- details = self._base_error_details(self.responses_url())
1274
+ details = self._base_error_details(self.responses_url(), session_id)
1184
1275
  details.append(("detail", message))
1185
1276
  if code:
1186
1277
  details.append(("code", code))
@@ -1201,8 +1292,9 @@ class ResponsesModelClient:
1201
1292
  payload: "typing.Dict[str, object]",
1202
1293
  output_item_count: "int",
1203
1294
  reason: "typing.Union[str, None]" = None,
1295
+ session_id: "typing.Union[str, None]" = None,
1204
1296
  ) -> "str":
1205
- details = self._base_error_details(self.responses_url())
1297
+ details = self._base_error_details(self.responses_url(), session_id)
1206
1298
  if reason:
1207
1299
  details.append(("reason", reason))
1208
1300
  details.append(("output_items_received", str(output_item_count)))
@@ -1228,35 +1320,34 @@ class ResponsesModelClient:
1228
1320
  return str(incomplete_details.get("reason") or "").strip()
1229
1321
 
1230
1322
  def _raise_response_failed_error(
1231
- self, payload: "typing.Dict[str, object]"
1323
+ self, payload: "typing.Dict[str, object]", session_id=None,
1232
1324
  ) -> "None":
1233
1325
  response = payload.get("response")
1234
1326
  error = response.get("error") if isinstance(response, dict) else None
1235
1327
  if not isinstance(error, dict):
1236
1328
  raise ResponsesRetryableError(
1237
- self._format_response_failed_error("responses stream failed")
1329
+ self._format_response_failed_error("responses stream failed", session_id=session_id)
1238
1330
  )
1239
1331
 
1240
1332
  message = str(error.get("message") or "responses stream failed")
1241
1333
  code = str(error.get("code") or error.get("type") or "").strip()
1334
+ formatted = self._format_response_failed_error(message, code, session_id)
1242
1335
  if code == "context_length_exceeded" or _is_context_length_error_message(
1243
1336
  message
1244
1337
  ):
1245
- raise ContextLengthExceeded(
1246
- self._format_response_failed_error(message, code)
1247
- )
1338
+ raise ContextLengthExceeded(formatted)
1248
1339
  if code in {"model_not_found", "model_not_available", "permission_denied"}:
1249
- raise ResponsesModelUnavailableError(self._format_response_failed_error(message, code))
1340
+ raise ResponsesModelUnavailableError(formatted)
1250
1341
  if code in {
1251
1342
  "insufficient_quota",
1252
1343
  "invalid_prompt",
1253
1344
  "model_output_invalid",
1254
1345
  "usage_not_included",
1255
1346
  }:
1256
- raise ResponsesApiError(self._format_response_failed_error(message, code))
1347
+ raise ResponsesApiError(formatted)
1257
1348
 
1258
1349
  raise ResponsesRetryableError(
1259
- self._format_response_failed_error(message, code),
1350
+ formatted,
1260
1351
  retry_delay_seconds=self._try_parse_retry_after_seconds(code, message),
1261
1352
  )
1262
1353
 
@@ -1264,8 +1355,9 @@ class ResponsesModelClient:
1264
1355
  self,
1265
1356
  last_event_type: "str",
1266
1357
  output_item_count: "int",
1358
+ session_id: "typing.Union[str, None]" = None,
1267
1359
  ) -> "str":
1268
- details = self._base_error_details(self.responses_url())
1360
+ details = self._base_error_details(self.responses_url(), session_id)
1269
1361
  if last_event_type:
1270
1362
  details.append(("last_event", last_event_type))
1271
1363
  details.append(("output_items_received", str(output_item_count)))
@@ -1292,8 +1384,9 @@ class ResponsesModelClient:
1292
1384
  event_name: "str",
1293
1385
  raw_data: "str",
1294
1386
  exc: "json.JSONDecodeError",
1387
+ session_id: "typing.Union[str, None]" = None,
1295
1388
  ) -> "str":
1296
- details = self._base_error_details(self.responses_url())
1389
+ details = self._base_error_details(self.responses_url(), session_id)
1297
1390
  details.append(("event", event_name or "message"))
1298
1391
  details.append(("exception", type(exc).__name__))
1299
1392
  details.append(("detail", str(exc)))