python-codex 0.6.1__py3-none-any.whl → 0.6.3__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.
@@ -123,6 +123,56 @@ def build_outcomming_request(
123
123
  return payload
124
124
 
125
125
 
126
+ def inline_history_instructions(
127
+ messages: "typing.List[typing.Dict[str, object]]",
128
+ ) -> "typing.List[typing.Dict[str, object]]":
129
+ """Keep non-prefix instructions in order for APIs with only a top-level system."""
130
+ result = []
131
+ in_system_prefix = True
132
+ for message in messages:
133
+ if message["role"] in {"system", "developer"}:
134
+ if not in_system_prefix:
135
+ content = message["content"]
136
+ if isinstance(content, list):
137
+ content = [{"type": "text", "text": "<system-reminder>\n"}] + content + [
138
+ {"type": "text", "text": "\n</system-reminder>"},
139
+ ]
140
+ else:
141
+ content = "<system-reminder>\n" + content + "\n</system-reminder>"
142
+ message = dict(message, role="user", content=content)
143
+ else:
144
+ in_system_prefix = False
145
+ result.append(message)
146
+ return result
147
+
148
+
149
+ def split_tool_images(
150
+ messages: "typing.List[typing.Dict[str, object]]",
151
+ ) -> "typing.List[typing.Dict[str, object]]":
152
+ """Move tool images after their result group for Chat/Messages backends."""
153
+ result = []
154
+ pending_images = []
155
+ for message in messages:
156
+ if message.get("role") != "tool" and pending_images:
157
+ result.append({"role": "user", "content": pending_images})
158
+ pending_images = []
159
+ content = message.get("content")
160
+ if message.get("role") == "tool" and isinstance(content, list):
161
+ text_parts = []
162
+ for part in content:
163
+ if part["type"] == "text":
164
+ text_parts.append(part["text"])
165
+ elif part["type"] == "image_url":
166
+ pending_images.append(part)
167
+ else:
168
+ raise ValueError("unsupported tool content part: {!r}".format(part["type"]))
169
+ message = dict(message, content="".join(text_parts))
170
+ result.append(message)
171
+ if pending_images:
172
+ result.append({"role": "user", "content": pending_images})
173
+ return result
174
+
175
+
126
176
  def _responses_input_to_chat_messages(
127
177
  instructions: "str",
128
178
  input_items: "typing.List[object]",
@@ -133,7 +183,6 @@ def _responses_input_to_chat_messages(
133
183
  messages.append({"role": "developer", "content": instructions})
134
184
 
135
185
  pending_assistant: "typing.Union[typing.Dict[str, object], None]" = None
136
- pending_tool_images: "typing.List[typing.Dict[str, object]]" = []
137
186
 
138
187
  def flush_pending_assistant() -> "None":
139
188
  nonlocal pending_assistant
@@ -150,21 +199,12 @@ def _responses_input_to_chat_messages(
150
199
  messages.append(pending_assistant)
151
200
  pending_assistant = None
152
201
 
153
- def flush_pending_tool_images() -> "None":
154
- if not pending_tool_images:
155
- return
156
- messages.append({"role": "user", "content": list(pending_tool_images)})
157
- del pending_tool_images[:]
158
-
159
202
  for raw_item in input_items:
160
203
  if not isinstance(raw_item, dict):
161
204
  raise UnsupportedIncommingFeature(
162
205
  "all incomming `input` items must be objects"
163
206
  )
164
207
  item_type = raw_item.get("type")
165
- if item_type not in {"function_call_output", "custom_tool_call_output"}:
166
- flush_pending_tool_images()
167
-
168
208
  if item_type == "agent_message":
169
209
  if not all(
170
210
  isinstance(raw_item.get(key), str) for key in ("author", "recipient")
@@ -257,14 +297,17 @@ def _responses_input_to_chat_messages(
257
297
  text, image_parts = _split_tool_output_parts(
258
298
  raw_item.get("output")
259
299
  )
300
+ if image_parts:
301
+ content = ([{"type": "text", "text": text}] if text else []) + image_parts
302
+ else:
303
+ content = text
260
304
  messages.append(
261
305
  {
262
306
  "role": "tool",
263
307
  "tool_call_id": str(raw_item.get("call_id", "")).strip(),
264
- "content": text,
308
+ "content": content,
265
309
  }
266
310
  )
267
- pending_tool_images.extend(image_parts)
268
311
  continue
269
312
 
270
313
  if item_type == "custom_tool_call":
@@ -290,7 +333,6 @@ def _responses_input_to_chat_messages(
290
333
  )
291
334
 
292
335
  flush_pending_assistant()
293
- flush_pending_tool_images()
294
336
  return messages
295
337
 
296
338
 
@@ -304,6 +304,15 @@ class StreamRouter:
304
304
  if isinstance(value, int):
305
305
  current_usage[key] = value
306
306
 
307
+ if (
308
+ not isinstance(usage.get("total_tokens"), int)
309
+ and any(isinstance(value, int) for _, value in scalar_mappings[:2])
310
+ and isinstance(current_usage.get("input_tokens"), int)
311
+ and isinstance(current_usage.get("output_tokens"), int)
312
+ ):
313
+ current_usage["total_tokens"] = (
314
+ current_usage["input_tokens"] + current_usage["output_tokens"]
315
+ )
307
316
  detail_mappings = (
308
317
  (
309
318
  "input_tokens_details",
@@ -17,6 +17,7 @@ from .gemini_api import iter_chat_chunks as iter_chat_chunks_from_gemini
17
17
  from .messages_api import MessagesAPIAdapterError, build_messages_request
18
18
  from .messages_api import iter_chat_chunks as iter_chat_chunks_from_messages
19
19
  from .messages_api import saw_message_stop as messages_saw_message_stop
20
+ from .request_translation import split_tool_images
20
21
 
21
22
 
22
23
  class OutcommingChatError(RuntimeError):
@@ -77,9 +78,13 @@ class OutcommingTransport:
77
78
  self,
78
79
  outcomming_request: "typing.Dict[str, object]",
79
80
  ):
81
+ payload = dict(
82
+ outcomming_request,
83
+ messages=split_tool_images(outcomming_request["messages"]),
84
+ )
80
85
  request = urllib.request.Request(
81
86
  self.config.outcomming_chat_completions_url(),
82
- data=json.dumps(outcomming_request).encode("utf-8"),
87
+ data=json.dumps(payload).encode("utf-8"),
83
88
  headers=self._build_headers(accept="text/event-stream"),
84
89
  method="POST",
85
90
  )
@@ -350,16 +355,17 @@ class OutcommingTransport:
350
355
  ) from exc
351
356
 
352
357
  def _build_headers(self, accept: "str") -> "typing.Dict[str, str]":
353
- headers = {
354
- "Accept": accept,
355
- "Content-Type": "application/json",
356
- }
358
+ headers = {"content-type": "application/json"}
359
+ headers.update({
360
+ name.lower(): value for name, value in self.config.outcomming_http_headers.items()
361
+ })
362
+ headers["accept"] = accept
357
363
  api_key = self.config.outcomming_api_key()
358
364
  if api_key is not None:
359
365
  if self.config.normalized_outcomming_api() == "gemini":
360
366
  headers["x-goog-api-key"] = api_key
361
367
  else:
362
- headers["Authorization"] = f"Bearer {api_key}"
368
+ headers["authorization"] = f"Bearer {api_key}"
363
369
  return headers
364
370
 
365
371
  def _iter_sse_events(self, response):