python-codex 0.6.2__py3-none-any.whl → 0.7.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.
@@ -1,7 +1,7 @@
1
1
  import os
2
2
  import typing
3
3
  import urllib.parse
4
- from dataclasses import dataclass
4
+ from dataclasses import dataclass, field
5
5
 
6
6
  DEFAULT_OUTCOMMING_TIMEOUT_SECONDS = 300.0
7
7
 
@@ -17,6 +17,7 @@ class CompatServerConfig:
17
17
  outcomming_api_key_env: "typing.Union[str, None]" = None
18
18
  model_provider: "typing.Union[str, None]" = None
19
19
  timeout_seconds: "float" = DEFAULT_OUTCOMMING_TIMEOUT_SECONDS
20
+ outcomming_http_headers: "typing.Dict[str, str]" = field(default_factory=dict, repr=False)
20
21
 
21
22
  def outcomming_api_key(self) -> "typing.Union[str, None]":
22
23
  if self.outcomming_api_key_env is None:
@@ -52,6 +53,7 @@ class CompatServerConfig:
52
53
  api_key_env: "typing.Union[str, None]" = None,
53
54
  model_provider: "typing.Union[str, None]" = None,
54
55
  outcomming_api: "str" = "chat_completions",
56
+ http_headers: "typing.Union[typing.Dict[str, str], None]" = None,
55
57
  ) -> "CompatServerConfig":
56
58
  parsed = urllib.parse.urlparse(outcomming_base_url)
57
59
  if not parsed.scheme or not parsed.netloc:
@@ -69,4 +71,5 @@ class CompatServerConfig:
69
71
  outcomming_api=outcomming_api,
70
72
  outcomming_api_key_env=api_key_env,
71
73
  model_provider=model_provider,
74
+ outcomming_http_headers=dict(http_headers) if http_headers is not None else {},
72
75
  )
@@ -1,10 +1,17 @@
1
1
  """Gemini generateContent request and streaming response adapter."""
2
2
 
3
+ import base64
3
4
  import json
4
5
  import re
5
6
  import uuid
6
7
  from copy import deepcopy
7
8
 
9
+ from .request_translation import inline_history_instructions
10
+
11
+ SKIP_THOUGHT_SIGNATURE_VALIDATOR = base64.b64encode(
12
+ b"skip_thought_signature_validator"
13
+ ).decode("ascii")
14
+
8
15
 
9
16
  class GeminiAPIAdapterError(ValueError):
10
17
  pass
@@ -14,7 +21,7 @@ def build_gemini_request(request):
14
21
  contents = []
15
22
  system_parts = []
16
23
  calls = {}
17
- for message in request.get("messages", []):
24
+ for message in inline_history_instructions(request.get("messages", [])):
18
25
  role = message["role"]
19
26
  if role in {"system", "developer"}:
20
27
  system_parts.extend(_content_parts(message.get("content")))
@@ -34,33 +41,40 @@ def build_gemini_request(request):
34
41
  # Unsigned empty text can end a stream, but is not input data.
35
42
  parts = [part for part in parts
36
43
  if part.get("text") != "" or "thoughtSignature" in part]
44
+ native_call_ids = {
45
+ entry["call_id"] for entry in native
46
+ if "call_id" in entry and "functionCall" in entry["part"]
47
+ }
48
+ for call in message.get("tool_calls", []):
49
+ if call["id"] not in native_call_ids:
50
+ parts.append(_unsigned_function_call_part(call))
37
51
  else:
38
52
  parts = _content_parts(message.get("content"))
39
53
  for call in message.get("tool_calls", []):
40
- function = call["function"]
41
- arguments = json.loads(function["arguments"])
42
- if not isinstance(arguments, dict):
43
- raise GeminiAPIAdapterError("Gemini function arguments must be objects")
44
- parts.append({"functionCall": {
45
- "name": function["name"], "args": arguments, "id": call["id"],
46
- }})
54
+ parts.append(_unsigned_function_call_part(call))
47
55
  role = "model"
48
56
  elif role == "tool":
49
57
  call_id = message["tool_call_id"]
50
58
  if call_id not in calls:
51
59
  raise GeminiAPIAdapterError("Gemini tool result has no matching function call")
52
- parts = [{"functionResponse": {
60
+ output_parts = _content_parts(message.get("content"))
61
+ function_response = {
53
62
  "name": calls[call_id], "id": call_id,
54
- "response": {"result": message.get("content", "")},
55
- }}]
63
+ "response": {"output": "".join(
64
+ part["text"] for part in output_parts if "text" in part
65
+ )},
66
+ }
67
+ media_parts = [part for part in output_parts if "inlineData" in part]
68
+ if media_parts:
69
+ function_response["parts"] = media_parts
70
+ parts = [{"functionResponse": function_response}]
56
71
  role = "user"
57
72
  elif role == "user":
58
73
  parts = _content_parts(message.get("content"))
59
74
  else:
60
75
  raise GeminiAPIAdapterError("unsupported Gemini message role: {!r}".format(role))
61
76
  if parts:
62
- # Batch parallel function responses, keeping subsequent image input
63
- # in its own user content as provided by the canonical translator.
77
+ # Batch consecutive function responses into one user content.
64
78
  if message["role"] == "tool" and contents and all(
65
79
  "functionResponse" in part for part in contents[-1]["parts"]
66
80
  ):
@@ -108,6 +122,19 @@ def build_gemini_request(request):
108
122
  return payload
109
123
 
110
124
 
125
+ def _unsigned_function_call_part(call):
126
+ function = call["function"]
127
+ arguments = json.loads(function["arguments"])
128
+ if not isinstance(arguments, dict):
129
+ raise GeminiAPIAdapterError("Gemini function arguments must be objects")
130
+ return {
131
+ "functionCall": {
132
+ "name": function["name"], "args": arguments, "id": call["id"],
133
+ },
134
+ "thoughtSignature": SKIP_THOUGHT_SIGNATURE_VALIDATOR,
135
+ }
136
+
137
+
111
138
  def _content_parts(content):
112
139
  if not content:
113
140
  return []
@@ -1,6 +1,8 @@
1
1
  import json
2
2
  import typing
3
3
 
4
+ from .request_translation import inline_history_instructions, split_tool_images
5
+
4
6
  DEFAULT_MESSAGES_MAX_TOKENS = 32000
5
7
 
6
8
 
@@ -20,12 +22,12 @@ def build_messages_request(
20
22
  raw_messages = outcomming_request.get("messages") or []
21
23
  if not isinstance(raw_messages, list):
22
24
  raise MessagesAPIAdapterError("outcomming request `messages` must be a list")
25
+ if any(not isinstance(message, dict) for message in raw_messages):
26
+ raise MessagesAPIAdapterError("outcomming request messages must be objects")
23
27
 
24
28
  system_blocks: "typing.List[typing.Dict[str, object]]" = []
25
29
  messages: "typing.List[typing.Dict[str, object]]" = []
26
- for raw_message in raw_messages:
27
- if not isinstance(raw_message, dict):
28
- raise MessagesAPIAdapterError("outcomming request messages must be objects")
30
+ for raw_message in split_tool_images(inline_history_instructions(raw_messages)):
29
31
  role = str(raw_message.get("role", "")).strip()
30
32
  if role in {"developer", "system"}:
31
33
  text = str(raw_message.get("content", "") or "")
@@ -348,7 +350,7 @@ def _translate_tool_choice(
348
350
  elif choice == "required":
349
351
  translated = {"type": "any"}
350
352
  elif choice == "none":
351
- return None
353
+ return {"type": "none"}
352
354
  else:
353
355
  raise MessagesAPIAdapterError(
354
356
  f"unsupported tool_choice for messages API: {raw_tool_choice!r}"
@@ -430,7 +432,12 @@ def _translate_usage(raw_usage: "object") -> "typing.Dict[str, object]":
430
432
  usage: "typing.Dict[str, object]" = {}
431
433
  input_tokens = raw_usage.get("input_tokens")
432
434
  output_tokens = raw_usage.get("output_tokens")
435
+ cache_creation = raw_usage.get("cache_creation_input_tokens")
436
+ cache_read = raw_usage.get("cache_read_input_tokens")
433
437
  if isinstance(input_tokens, int):
438
+ input_tokens += sum(
439
+ value for value in (cache_creation, cache_read) if isinstance(value, int)
440
+ )
434
441
  usage["input_tokens"] = input_tokens
435
442
  if isinstance(output_tokens, int):
436
443
  usage["output_tokens"] = output_tokens
@@ -441,12 +448,11 @@ def _translate_usage(raw_usage: "object") -> "typing.Dict[str, object]":
441
448
  usage["total_tokens"] = input_tokens + output_tokens
442
449
 
443
450
  input_details: "typing.Dict[str, int]" = {}
444
- cache_creation = raw_usage.get("cache_creation_input_tokens")
445
451
  if isinstance(cache_creation, int):
446
452
  input_details["cache_creation_input_tokens"] = cache_creation
447
- cache_read = raw_usage.get("cache_read_input_tokens")
448
453
  if isinstance(cache_read, int):
449
454
  input_details["cache_read_input_tokens"] = cache_read
455
+ input_details["cached_tokens"] = cache_read
450
456
  if input_details:
451
457
  usage["input_tokens_details"] = input_details
452
458
  return usage
@@ -72,7 +72,7 @@ def _replace_developer_messages(
72
72
 
73
73
  PAYLOAD_POST_PROCESSORS: "typing.Dict[str, PayloadPostProcessor]" = {
74
74
  "stepfun": _replace_developer_messages,
75
- "vllm": _identity,
75
+ "vllm": _replace_developer_messages,
76
76
  }
77
77
  """Mapping from normalized `model_provider` name to payload rewrite hook."""
78
78
 
@@ -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):
@@ -24,9 +25,13 @@ class OutcommingChatError(RuntimeError):
24
25
  self,
25
26
  message: "str",
26
27
  error_type: "typing.Union[str, None]" = None,
28
+ http_status: "typing.Union[int, None]" = None,
29
+ error_code: "typing.Union[str, None]" = None,
27
30
  ) -> "None":
28
31
  super().__init__(message)
29
32
  self.error_type = error_type
33
+ self.http_status = http_status
34
+ self.error_code = error_code
30
35
 
31
36
 
32
37
  class OutcommingTransport:
@@ -77,9 +82,13 @@ class OutcommingTransport:
77
82
  self,
78
83
  outcomming_request: "typing.Dict[str, object]",
79
84
  ):
85
+ payload = dict(
86
+ outcomming_request,
87
+ messages=split_tool_images(outcomming_request["messages"]),
88
+ )
80
89
  request = urllib.request.Request(
81
90
  self.config.outcomming_chat_completions_url(),
82
- data=json.dumps(outcomming_request).encode("utf-8"),
91
+ data=json.dumps(payload).encode("utf-8"),
83
92
  headers=self._build_headers(accept="text/event-stream"),
84
93
  method="POST",
85
94
  )
@@ -115,7 +124,7 @@ class OutcommingTransport:
115
124
  yield payload
116
125
  if not saw_done:
117
126
  raise OutcommingChatError(
118
- "outcomming chat stream ended before [DONE]"
127
+ "outcomming chat stream ended before [DONE]", error_code="502",
119
128
  )
120
129
  except (
121
130
  ConnectionError,
@@ -134,7 +143,8 @@ class OutcommingTransport:
134
143
  progress["phase"] = "reading_error_body"
135
144
  body = exc.read().decode("utf-8", errors="replace")
136
145
  raise OutcommingChatError(
137
- f"outcomming chat request failed with status {exc.code}: {body[:500]}"
146
+ f"outcomming chat request failed with status {exc.code}: {body[:500]}",
147
+ http_status=exc.code,
138
148
  ) from exc
139
149
  except TimeoutError as exc:
140
150
  raise OutcommingChatError(
@@ -214,7 +224,7 @@ class OutcommingTransport:
214
224
  if not finished:
215
225
  terminal = "finishReason" if api == "gemini" else "message_stop"
216
226
  raise OutcommingChatError(
217
- f"outcomming {api} stream ended before `{terminal}`"
227
+ f"outcomming {api} stream ended before `{terminal}`", error_code="502",
218
228
  )
219
229
  if api == "gemini":
220
230
  yield gemini_continuation_chunk(stream_state)
@@ -241,7 +251,8 @@ class OutcommingTransport:
241
251
  progress["phase"] = "reading_error_body"
242
252
  body = exc.read().decode("utf-8", errors="replace")
243
253
  raise OutcommingChatError(
244
- f"outcomming {api} request failed with status {exc.code}: {body[:500]}"
254
+ f"outcomming {api} request failed with status {exc.code}: {body[:500]}",
255
+ http_status=exc.code,
245
256
  ) from exc
246
257
  except TimeoutError as exc:
247
258
  raise OutcommingChatError(
@@ -333,7 +344,8 @@ class OutcommingTransport:
333
344
  progress["phase"] = "reading_error_body"
334
345
  body = exc.read().decode("utf-8", errors="replace")
335
346
  raise OutcommingChatError(
336
- f"outcomming request failed with status {exc.code}: {body[:500]}"
347
+ f"outcomming request failed with status {exc.code}: {body[:500]}",
348
+ http_status=exc.code,
337
349
  ) from exc
338
350
  except TimeoutError as exc:
339
351
  raise OutcommingChatError(
@@ -350,16 +362,17 @@ class OutcommingTransport:
350
362
  ) from exc
351
363
 
352
364
  def _build_headers(self, accept: "str") -> "typing.Dict[str, str]":
353
- headers = {
354
- "Accept": accept,
355
- "Content-Type": "application/json",
356
- }
365
+ headers = {"content-type": "application/json"}
366
+ headers.update({
367
+ name.lower(): value for name, value in self.config.outcomming_http_headers.items()
368
+ })
369
+ headers["accept"] = accept
357
370
  api_key = self.config.outcomming_api_key()
358
371
  if api_key is not None:
359
372
  if self.config.normalized_outcomming_api() == "gemini":
360
373
  headers["x-goog-api-key"] = api_key
361
374
  else:
362
- headers["Authorization"] = f"Bearer {api_key}"
375
+ headers["authorization"] = f"Bearer {api_key}"
363
376
  return headers
364
377
 
365
378
  def _iter_sse_events(self, response):