python-codex 0.6.0__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.
@@ -0,0 +1,333 @@
1
+ """Gemini generateContent request and streaming response adapter."""
2
+
3
+ import json
4
+ import re
5
+ import uuid
6
+ from copy import deepcopy
7
+
8
+
9
+ class GeminiAPIAdapterError(ValueError):
10
+ pass
11
+
12
+
13
+ def build_gemini_request(request):
14
+ contents = []
15
+ system_parts = []
16
+ calls = {}
17
+ for message in request.get("messages", []):
18
+ role = message["role"]
19
+ if role in {"system", "developer"}:
20
+ system_parts.extend(_content_parts(message.get("content")))
21
+ continue
22
+ if role == "assistant":
23
+ active_call_ids = set()
24
+ for call in message.get("tool_calls", []):
25
+ calls[call["id"]] = call["function"]["name"]
26
+ active_call_ids.add(call["id"])
27
+ native = message.get("provider_data", [])
28
+ native = [entry for entry in native if entry["provider"] == "gemini"]
29
+ if native:
30
+ # Compaction may prune a call/result pair while retaining the
31
+ # opaque reasoning item. Never replay a removed function call.
32
+ parts = [deepcopy(entry["part"]) for entry in native
33
+ if "call_id" not in entry or entry["call_id"] in active_call_ids]
34
+ else:
35
+ parts = _content_parts(message.get("content"))
36
+ for call in message.get("tool_calls", []):
37
+ function = call["function"]
38
+ arguments = json.loads(function["arguments"])
39
+ if not isinstance(arguments, dict):
40
+ raise GeminiAPIAdapterError("Gemini function arguments must be objects")
41
+ parts.append({"functionCall": {
42
+ "name": function["name"], "args": arguments, "id": call["id"],
43
+ }})
44
+ role = "model"
45
+ elif role == "tool":
46
+ call_id = message["tool_call_id"]
47
+ if call_id not in calls:
48
+ raise GeminiAPIAdapterError("Gemini tool result has no matching function call")
49
+ parts = [{"functionResponse": {
50
+ "name": calls[call_id], "id": call_id,
51
+ "response": {"result": message.get("content", "")},
52
+ }}]
53
+ role = "user"
54
+ elif role == "user":
55
+ parts = _content_parts(message.get("content"))
56
+ else:
57
+ raise GeminiAPIAdapterError("unsupported Gemini message role: {!r}".format(role))
58
+ if parts:
59
+ # Batch parallel function responses, keeping subsequent image input
60
+ # in its own user content as provided by the canonical translator.
61
+ if message["role"] == "tool" and contents and all(
62
+ "functionResponse" in part for part in contents[-1]["parts"]
63
+ ):
64
+ contents[-1]["parts"].extend(parts)
65
+ else:
66
+ contents.append({"role": role, "parts": parts})
67
+
68
+ payload = {"contents": contents}
69
+ if system_parts:
70
+ payload["systemInstruction"] = {"parts": system_parts}
71
+ generation = {"thinkingConfig": {"includeThoughts": True}}
72
+ if "max_tokens" in request:
73
+ generation["maxOutputTokens"] = request["max_tokens"]
74
+ effort = request.get("chat_template_kwargs", {}).get("reasoning_effort")
75
+ if effort is not None:
76
+ levels = {
77
+ "none": "minimal", "minimal": "minimal", "low": "low",
78
+ "medium": "medium", "high": "high", "xhigh": "high", "max": "high",
79
+ }
80
+ if effort not in levels:
81
+ raise GeminiAPIAdapterError("unsupported Gemini reasoning effort: {!r}".format(effort))
82
+ generation["thinkingConfig"]["thinkingLevel"] = levels[effort]
83
+ payload["generationConfig"] = generation
84
+
85
+ declarations = []
86
+ for tool in request.get("tools", []):
87
+ if tool["type"] != "function":
88
+ raise GeminiAPIAdapterError("Gemini backend requires function-style tools")
89
+ function = tool["function"]
90
+ declarations.append({
91
+ "name": function["name"], "description": function.get("description", ""),
92
+ "parametersJsonSchema": deepcopy(function.get("parameters", {"type": "object"})),
93
+ })
94
+ if declarations:
95
+ payload["tools"] = [{"functionDeclarations": declarations}]
96
+ choice = request.get("tool_choice", "auto")
97
+ if isinstance(choice, dict) and choice.get("type") == "function":
98
+ config = {"mode": "ANY", "allowedFunctionNames": [choice["function"]["name"]]}
99
+ elif choice in ("auto", "required", "none"):
100
+ config = {"mode": {"auto": "AUTO", "required": "ANY", "none": "NONE"}[choice]}
101
+ else:
102
+ raise GeminiAPIAdapterError("unsupported Gemini tool_choice")
103
+ config["streamFunctionCallArguments"] = True
104
+ payload["toolConfig"] = {"functionCallingConfig": config}
105
+ return payload
106
+
107
+
108
+ def _content_parts(content):
109
+ if not content:
110
+ return []
111
+ if isinstance(content, str):
112
+ return [{"text": content}]
113
+ parts = []
114
+ for part in content:
115
+ if part["type"] == "text":
116
+ parts.append({"text": part["text"]})
117
+ elif part["type"] == "image_url":
118
+ url = part["image_url"]["url"]
119
+ if url.startswith("data:"):
120
+ header, separator, data = url.partition(",")
121
+ mime_type = header[5:].split(";")[0]
122
+ if not separator or not header.endswith(";base64") or not mime_type or not data:
123
+ raise GeminiAPIAdapterError("Gemini images require a base64 data URL with a media type")
124
+ parts.append({"inlineData": {"mimeType": mime_type, "data": data}})
125
+ else:
126
+ raise GeminiAPIAdapterError("Gemini images require a base64 data URL with a media type")
127
+ else:
128
+ raise GeminiAPIAdapterError("unsupported Gemini content part: {!r}".format(part["type"]))
129
+ return parts
130
+
131
+
132
+ def iter_chat_chunks(payload, state):
133
+ if not isinstance(payload, dict):
134
+ raise GeminiAPIAdapterError("Gemini stream payload must be an object")
135
+ if "error" in payload:
136
+ error = payload["error"]
137
+ message = error.get("message", "Gemini API error") if isinstance(error, dict) else str(error)
138
+ raise GeminiAPIAdapterError(message)
139
+ blocked = payload.get("promptFeedback", {}).get("blockReason")
140
+ if blocked:
141
+ raise GeminiAPIAdapterError("Gemini prompt blocked: {}".format(blocked))
142
+ candidates = payload.get("candidates", [])
143
+ if len(candidates) > 1:
144
+ raise GeminiAPIAdapterError("Gemini adapter requires a single candidate")
145
+ for candidate in candidates:
146
+ if candidate.get("index", 0) != 0:
147
+ raise GeminiAPIAdapterError("unexpected Gemini candidate index")
148
+ finish = candidate.get("finishReason")
149
+ if finish and finish != "STOP":
150
+ raise GeminiAPIAdapterError("Gemini generation ended with {}".format(finish))
151
+ for part in candidate.get("content", {}).get("parts", []):
152
+ if "functionCall" in part:
153
+ chunk = _consume_function_call(part, state)
154
+ if chunk is not None:
155
+ yield chunk
156
+ elif "text" in part or "thoughtSignature" in part:
157
+ entry = {"provider": "gemini", "part": deepcopy(part)}
158
+ state.setdefault("provider_data", []).append(entry)
159
+ text = part.get("text", "")
160
+ if not text and state.get("last_call_id"):
161
+ entry["call_id"] = state["last_call_id"]
162
+ if text:
163
+ state.pop("last_call_id", None)
164
+ kind = "reasoning_content" if part.get("thought") else "content"
165
+ yield _delta({kind: text})
166
+ else:
167
+ raise GeminiAPIAdapterError("unsupported Gemini output part: {}".format(
168
+ ", ".join(sorted(part)),
169
+ ))
170
+ if finish:
171
+ if "function_call" in state:
172
+ raise GeminiAPIAdapterError("Gemini stream ended with an incomplete function call")
173
+ state["finished"] = True
174
+ yield {"choices": [{"index": 0, "delta": {}, "finish_reason": (
175
+ "tool_calls" if "tool_index" in state else "stop"
176
+ )}]}
177
+ usage = payload.get("usageMetadata", {})
178
+ token_counts = state.setdefault("token_counts", {})
179
+ for key in ("candidatesTokenCount", "thoughtsTokenCount"):
180
+ if key in usage:
181
+ token_counts[key] = usage[key]
182
+ translated = {}
183
+ for source, target in (("promptTokenCount", "prompt_tokens"), ("totalTokenCount", "total_tokens")):
184
+ if source in usage:
185
+ translated[target] = usage[source]
186
+ if "candidatesTokenCount" in usage or "thoughtsTokenCount" in usage:
187
+ translated["completion_tokens"] = (
188
+ token_counts.get("candidatesTokenCount", 0)
189
+ + token_counts.get("thoughtsTokenCount", 0)
190
+ )
191
+ if "thoughtsTokenCount" in usage:
192
+ translated["completion_tokens_details"] = {"reasoning_tokens": usage["thoughtsTokenCount"]}
193
+ if "cachedContentTokenCount" in usage:
194
+ translated["prompt_tokens_details"] = {"cached_tokens": usage["cachedContentTokenCount"]}
195
+ if translated:
196
+ yield {"choices": [], "usage": translated}
197
+
198
+
199
+ def _consume_function_call(part, state):
200
+ call = part["functionCall"]
201
+ active = state.get("function_call")
202
+ if active is None:
203
+ if not isinstance(call.get("name"), str) or not call["name"] or not isinstance(call.get("args", {}), dict):
204
+ raise GeminiAPIAdapterError("invalid Gemini function call")
205
+ native = {key: deepcopy(value) for key, value in call.items()
206
+ if key not in {"partialArgs", "willContinue"}}
207
+ entry = {"provider": "gemini", "part": dict(deepcopy(part), functionCall=native),
208
+ "call_id": call.get("id") or "call_" + uuid.uuid4().hex}
209
+ state.setdefault("provider_data", []).append(entry)
210
+ state["tool_index"] = state.get("tool_index", -1) + 1
211
+ active = {"entry": entry, "pending": {}}
212
+ state["function_call"] = active
213
+ state["last_call_id"] = entry["call_id"]
214
+ else:
215
+ native = active["entry"]["part"]["functionCall"]
216
+ if ("name" in call and call["name"] != native["name"]
217
+ or "id" in call and call["id"] != native.get("id")
218
+ or "args" in call):
219
+ raise GeminiAPIAdapterError("conflicting Gemini function call fragment")
220
+ if "thoughtSignature" in part:
221
+ state["provider_data"].append({
222
+ "provider": "gemini", "call_id": active["entry"]["call_id"],
223
+ "part": {"text": "", "thoughtSignature": part["thoughtSignature"]},
224
+ })
225
+ for partial in call.get("partialArgs", []):
226
+ _consume_partial_argument(partial, native.setdefault("args", {}), active["pending"])
227
+ if call.get("willContinue", False):
228
+ return None
229
+ if active["pending"]:
230
+ raise GeminiAPIAdapterError("Gemini function call ended with incomplete arguments")
231
+ del state["function_call"]
232
+ return _delta({"tool_calls": [{
233
+ "index": state["tool_index"], "id": active["entry"]["call_id"], "type": "function",
234
+ "function": {"name": native["name"], "arguments": json.dumps(
235
+ native.get("args", {}), ensure_ascii=False, separators=(",", ":"),
236
+ )},
237
+ }]})
238
+
239
+
240
+ def _consume_partial_argument(partial, arguments, pending):
241
+ raw_path = partial.get("jsonPath")
242
+ container = raw_path[-2:] if isinstance(raw_path, str) else None
243
+ is_container = container in ("{}", "[]")
244
+ path = _argument_path(raw_path[:-2] if is_container else raw_path)
245
+ fields = [key for key in ("stringValue", "numberValue", "boolValue", "nullValue")
246
+ if key in partial]
247
+ if len(fields) != (0 if is_container else 1):
248
+ raise GeminiAPIAdapterError("Gemini partial argument must contain one value")
249
+ field = fields[0] if fields else None
250
+ value = partial[field] if field is not None else ([] if container == "[]" else {})
251
+ if field == "stringValue":
252
+ if not isinstance(value, str):
253
+ raise GeminiAPIAdapterError("invalid Gemini string argument")
254
+ chunks = pending.setdefault(path, [])
255
+ chunks.append(value)
256
+ if partial.get("willContinue", False):
257
+ return
258
+ value = "".join(pending.pop(path))
259
+ else:
260
+ if path in pending or partial.get("willContinue", False):
261
+ raise GeminiAPIAdapterError("invalid Gemini scalar argument continuation")
262
+ if field == "numberValue" and (isinstance(value, bool) or not isinstance(value, (int, float))):
263
+ raise GeminiAPIAdapterError("invalid Gemini number argument")
264
+ if field == "boolValue" and not isinstance(value, bool):
265
+ raise GeminiAPIAdapterError("invalid Gemini boolean argument")
266
+ if field == "nullValue":
267
+ if isinstance(value, bool) or value not in (None, "NULL_VALUE", 0):
268
+ raise GeminiAPIAdapterError("invalid Gemini null argument")
269
+ value = None
270
+ node = arguments
271
+ for index, key in enumerate(path):
272
+ last = index == len(path) - 1
273
+ child = value if last else ([] if isinstance(path[index + 1], int) else {})
274
+ if isinstance(node, dict) and isinstance(key, str):
275
+ if key not in node:
276
+ node[key] = child
277
+ elif last:
278
+ raise GeminiAPIAdapterError("duplicate Gemini argument path")
279
+ elif isinstance(node, list) and isinstance(key, int) and key <= len(node):
280
+ if key == len(node):
281
+ node.append(child)
282
+ elif last:
283
+ raise GeminiAPIAdapterError("duplicate Gemini argument path")
284
+ else:
285
+ raise GeminiAPIAdapterError("invalid Gemini argument path structure")
286
+ node = node[key]
287
+
288
+
289
+ def _argument_path(path):
290
+ # Function arguments use concrete member/index paths, never JSONPath queries.
291
+ pattern = r'''\.([^\W\d]\w*)|\[(0|[1-9][0-9]*|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\]'''
292
+ if not isinstance(path, str) or not path.startswith("$"):
293
+ raise GeminiAPIAdapterError("invalid Gemini argument path")
294
+ keys = []
295
+ offset = 1
296
+ while offset < len(path):
297
+ match = re.match(pattern, path[offset:])
298
+ if match is None:
299
+ raise GeminiAPIAdapterError("invalid Gemini argument path")
300
+ member, bracket = match.groups()
301
+ if member is not None:
302
+ key = member
303
+ elif bracket[0] in ("'", '"'):
304
+ if bracket[0] == "'":
305
+ bracket = '"' + re.sub(
306
+ r'''\\(.)|"''',
307
+ lambda item: "'" if item.group(1) == "'" else
308
+ '\\"' if item.group(0) == '"' else item.group(0),
309
+ bracket[1:-1],
310
+ ) + '"'
311
+ try:
312
+ key = json.loads(bracket)
313
+ except ValueError as exc:
314
+ raise GeminiAPIAdapterError("invalid Gemini argument path") from exc
315
+ else:
316
+ key = int(bracket)
317
+ keys.append(key)
318
+ offset += match.end()
319
+ if not keys or not isinstance(keys[0], str):
320
+ raise GeminiAPIAdapterError("Gemini function arguments must be objects")
321
+ return tuple(keys)
322
+
323
+
324
+ def _delta(delta):
325
+ return {"choices": [{"index": 0, "delta": delta, "finish_reason": None}]}
326
+
327
+
328
+ def continuation_chunk(state):
329
+ """Use the existing opaque reasoning-item contract for durable native state."""
330
+ return {"reasoning_item": {
331
+ "type": "reasoning", "summary": [],
332
+ "provider_data": deepcopy(state.get("provider_data", [])),
333
+ }}
@@ -5,7 +5,9 @@ DEFAULT_MESSAGES_MAX_TOKENS = 32000
5
5
 
6
6
 
7
7
  class MessagesAPIAdapterError(ValueError):
8
- pass
8
+ def __init__(self, message, error_type=None):
9
+ super().__init__(message)
10
+ self.error_type = error_type
9
11
 
10
12
 
11
13
  def build_messages_request(
@@ -160,6 +162,12 @@ def iter_chat_chunks(
160
162
  delta = payload.get("delta") or {}
161
163
  if not isinstance(delta, dict):
162
164
  return chunks
165
+ if delta.get("stop_reason") == "refusal":
166
+ message = "messages generation refused (stop_reason=refusal)"
167
+ details = delta.get("stop_details")
168
+ if isinstance(details, dict) and details.get("explanation"):
169
+ message += ": " + str(details["explanation"])
170
+ raise MessagesAPIAdapterError(message, error_type="invalid_prompt")
163
171
  finish_reason = _translate_stop_reason(delta.get("stop_reason"))
164
172
  if finish_reason and not bool(state.get("finish_emitted")):
165
173
  state["finish_reason"] = finish_reason
@@ -2,6 +2,7 @@
2
2
 
3
3
  import json
4
4
  import typing
5
+ from copy import deepcopy
5
6
 
6
7
  from .tools import WebSearchTool
7
8
  from .tools.custom_adapter import CustomToolAdapterError
@@ -142,6 +143,7 @@ def _responses_input_to_chat_messages(
142
143
  "content" not in pending_assistant
143
144
  and "reasoning" not in pending_assistant
144
145
  and "tool_calls" not in pending_assistant
146
+ and "provider_data" not in pending_assistant
145
147
  ):
146
148
  pending_assistant = None
147
149
  return
@@ -217,6 +219,10 @@ def _responses_input_to_chat_messages(
217
219
  if item_type == "reasoning":
218
220
  if pending_assistant is None:
219
221
  pending_assistant = {"role": "assistant"}
222
+ if "provider_data" in raw_item:
223
+ pending_assistant.setdefault("provider_data", []).extend(
224
+ deepcopy(raw_item["provider_data"])
225
+ )
220
226
  reasoning_text = coalesce_reasoning_text(raw_item)
221
227
  if reasoning_text:
222
228
  pending_assistant["reasoning"] = (
@@ -61,7 +61,12 @@ class StreamRouter:
61
61
  current_usage: "typing.Dict[str, object]" = {}
62
62
  reasoning_start = len(reasoning_parts)
63
63
  text_start = len(text_parts)
64
+ continuation_item = None
64
65
  for chunk in current_stream:
66
+ if "reasoning_item" in chunk:
67
+ continuation_item = chunk["reasoning_item"]
68
+ continue
69
+ emitted_text = False
65
70
  for event_name, payload in self._consume_chat_chunk(
66
71
  chunk,
67
72
  reasoning_parts,
@@ -70,11 +75,15 @@ class StreamRouter:
70
75
  current_usage,
71
76
  finish_reasons,
72
77
  ):
78
+ emitted_text = True
73
79
  item_type = (
74
80
  "reasoning" if event_name == "response.reasoning_text.delta"
75
81
  else "message"
76
82
  )
77
83
  yield from output_stream.text_delta(item_type, payload["delta"])
84
+ if not emitted_text:
85
+ # Preserve downstream activity while tool arguments are buffered.
86
+ yield None, {}
78
87
  if current_usage:
79
88
  latest_usage = json.loads(json.dumps(current_usage))
80
89
 
@@ -86,6 +95,8 @@ class StreamRouter:
86
95
  )
87
96
  if mock_search_calls and not ordinary_tool_calls:
88
97
  yield from output_stream.finish_text()
98
+ if continuation_item is not None:
99
+ yield from output_stream.complete_tool(continuation_item)
89
100
  for item in build_output_items(mock_search_calls):
90
101
  yield from output_stream.complete_tool(item)
91
102
  try:
@@ -94,6 +105,8 @@ class StreamRouter:
94
105
  current_request,
95
106
  mock_search_calls,
96
107
  reasoning_text="".join(reasoning_parts),
108
+ provider_data=(continuation_item.get("provider_data")
109
+ if continuation_item is not None else None),
97
110
  )
98
111
  except ValueError as exc:
99
112
  raise OutcommingChatError(str(exc)) from exc
@@ -132,6 +145,8 @@ class StreamRouter:
132
145
  tool_names.custom_tool_names,
133
146
  )
134
147
  yield from output_stream.finish_text()
148
+ if continuation_item is not None:
149
+ yield from output_stream.complete_tool(continuation_item)
135
150
  for item in tool_items:
136
151
  yield from output_stream.complete_tool(tool_names.restore_output_item(item))
137
152
  for item in build_output_items(mock_search_calls):
@@ -131,6 +131,7 @@ def build_followup_request(
131
131
  outcomming_request: "typing.Dict[str, object]",
132
132
  mock_search_calls: "typing.List[typing.Dict[str, object]]",
133
133
  reasoning_text: "typing.Union[str, None]" = None,
134
+ provider_data=None,
134
135
  ) -> "typing.Dict[str, object]":
135
136
  followup_request = deepcopy(outcomming_request)
136
137
  messages = followup_request.get("messages") or []
@@ -159,6 +160,8 @@ def build_followup_request(
159
160
  }
160
161
  if reasoning_text:
161
162
  assistant_message["reasoning"] = reasoning_text
163
+ if provider_data:
164
+ assistant_message["provider_data"] = deepcopy(provider_data)
162
165
  messages.append(assistant_message)
163
166
 
164
167
  for tool_call in mock_search_calls:
@@ -6,10 +6,14 @@ import ssl
6
6
  import time
7
7
  import typing
8
8
  import urllib.error
9
+ import urllib.parse
9
10
  import urllib.request
10
11
  from contextlib import contextmanager
11
12
 
12
13
  from .config import CompatServerConfig
14
+ from .gemini_api import GeminiAPIAdapterError, build_gemini_request
15
+ from .gemini_api import continuation_chunk as gemini_continuation_chunk
16
+ from .gemini_api import iter_chat_chunks as iter_chat_chunks_from_gemini
13
17
  from .messages_api import MessagesAPIAdapterError, build_messages_request
14
18
  from .messages_api import iter_chat_chunks as iter_chat_chunks_from_messages
15
19
  from .messages_api import saw_message_stop as messages_saw_message_stop
@@ -30,6 +34,8 @@ class OutcommingTransport:
30
34
  self.config = config
31
35
 
32
36
  def list_models(self) -> "typing.Dict[str, object]":
37
+ if self.config.normalized_outcomming_api() == "gemini":
38
+ return self._list_gemini_models()
33
39
  request = urllib.request.Request(
34
40
  self.config.outcomming_models_url(),
35
41
  headers=self._build_headers(accept="application/json"),
@@ -37,10 +43,30 @@ class OutcommingTransport:
37
43
  )
38
44
  return self._request_json(request)
39
45
 
46
+ def _list_gemini_models(self):
47
+ url = self.config.outcomming_models_url()
48
+ models = []
49
+ while True:
50
+ request = urllib.request.Request(
51
+ url, headers=self._build_headers(accept="application/json"), method="GET",
52
+ )
53
+ payload = self._request_json(request)
54
+ for model in payload.get("models", []):
55
+ name = model["name"]
56
+ if not name.startswith("models/"):
57
+ raise OutcommingChatError("invalid Gemini model resource name")
58
+ models.append({"id": name[len("models/"):], "object": "model"})
59
+ page_token = payload.get("nextPageToken")
60
+ if not page_token:
61
+ return {"object": "list", "data": models}
62
+ url = self.config.outcomming_models_url() + "?" + urllib.parse.urlencode({"pageToken": page_token})
63
+
40
64
  def open_stream(self, outcomming_request: "typing.Dict[str, object]"):
41
65
  outcomming_api = self.config.normalized_outcomming_api()
42
66
  if outcomming_api == "messages":
43
67
  return self._open_outcomming_messages_stream(outcomming_request)
68
+ if outcomming_api == "gemini":
69
+ return self._open_outcomming_gemini_stream(outcomming_request)
44
70
  if outcomming_api != "chat_completions":
45
71
  raise OutcommingChatError(
46
72
  f"unsupported outcomming API: {self.config.outcomming_api!r}"
@@ -74,6 +100,7 @@ class OutcommingTransport:
74
100
  saw_done = False
75
101
  for _event_name, data in self._iter_sse_events(response):
76
102
  if not data:
103
+ yield {}
77
104
  continue
78
105
  if data == "[DONE]":
79
106
  saw_done = True
@@ -140,9 +167,22 @@ class OutcommingTransport:
140
167
  method="POST",
141
168
  )
142
169
  with self._request_diagnostics(request) as progress:
143
- yield from self._read_outcomming_messages_stream(request, progress)
170
+ yield from self._read_outcomming_native_stream(request, progress, "messages")
144
171
 
145
- def _read_outcomming_messages_stream(self, request, progress):
172
+ def _open_outcomming_gemini_stream(self, outcomming_request):
173
+ try:
174
+ payload = build_gemini_request(outcomming_request)
175
+ url = self.config.outcomming_gemini_url(outcomming_request["model"])
176
+ except ValueError as exc:
177
+ raise OutcommingChatError(str(exc)) from exc
178
+ request = urllib.request.Request(
179
+ url, data=json.dumps(payload).encode("utf-8"),
180
+ headers=self._build_headers(accept="text/event-stream"), method="POST",
181
+ )
182
+ with self._request_diagnostics(request) as progress:
183
+ yield from self._read_outcomming_native_stream(request, progress, "gemini")
184
+
185
+ def _read_outcomming_native_stream(self, request, progress, api):
146
186
  try:
147
187
  with urllib.request.urlopen(
148
188
  request,
@@ -156,31 +196,43 @@ class OutcommingTransport:
156
196
  stream_state: "typing.Dict[str, object]" = {}
157
197
  for event_name, data in self._iter_sse_events(response):
158
198
  if not data:
199
+ yield {}
159
200
  continue
160
201
  payload = json.loads(data)
161
- if not isinstance(payload, dict):
162
- continue
163
202
  self._received_chunk(progress)
164
- for chunk in iter_chat_chunks_from_messages(
165
- event_name,
166
- payload,
167
- stream_state,
168
- ):
169
- yield chunk
170
- if not messages_saw_message_stop(stream_state):
203
+ if api == "gemini":
204
+ chunks = list(iter_chat_chunks_from_gemini(payload, stream_state))
205
+ elif isinstance(payload, dict):
206
+ chunks = iter_chat_chunks_from_messages(event_name, payload, stream_state)
207
+ else:
208
+ chunks = []
209
+ yield from chunks or [{}]
210
+ finished = (
211
+ stream_state.get("finished") if api == "gemini"
212
+ else messages_saw_message_stop(stream_state)
213
+ )
214
+ if not finished:
215
+ terminal = "finishReason" if api == "gemini" else "message_stop"
171
216
  raise OutcommingChatError(
172
- "outcomming messages stream ended before `message_stop`"
217
+ f"outcomming {api} stream ended before `{terminal}`"
173
218
  )
219
+ if api == "gemini":
220
+ yield gemini_continuation_chunk(stream_state)
221
+ except MessagesAPIAdapterError as exc:
222
+ raise OutcommingChatError(
223
+ "outcomming messages stream failed while reading response body: "
224
+ + str(exc), error_type=exc.error_type,
225
+ ) from exc
174
226
  except (
175
227
  ConnectionError,
176
228
  EOFError,
177
229
  OSError,
178
230
  http.client.HTTPException,
179
231
  json.JSONDecodeError,
180
- MessagesAPIAdapterError,
232
+ GeminiAPIAdapterError,
181
233
  ) as exc:
182
234
  raise OutcommingChatError(
183
- "outcomming messages stream failed while reading response body: "
235
+ f"outcomming {api} stream failed while reading response body: "
184
236
  f"{exc}"
185
237
  ) from exc
186
238
  except urllib.error.HTTPError as exc:
@@ -189,20 +241,20 @@ class OutcommingTransport:
189
241
  progress["phase"] = "reading_error_body"
190
242
  body = exc.read().decode("utf-8", errors="replace")
191
243
  raise OutcommingChatError(
192
- f"outcomming messages request failed with status {exc.code}: {body[:500]}"
244
+ f"outcomming {api} request failed with status {exc.code}: {body[:500]}"
193
245
  ) from exc
194
246
  except TimeoutError as exc:
195
247
  raise OutcommingChatError(
196
- "outcomming messages request timed out after "
248
+ f"outcomming {api} request timed out after "
197
249
  f"{self.config.timeout_seconds:g}s"
198
250
  ) from exc
199
251
  except urllib.error.URLError as exc:
200
252
  raise OutcommingChatError(
201
- f"outcomming messages request failed: {exc.reason}"
253
+ f"outcomming {api} request failed: {exc.reason}"
202
254
  ) from exc
203
255
  except (OSError, EOFError, http.client.HTTPException) as exc:
204
256
  raise OutcommingChatError(
205
- "outcomming messages request failed while opening response: "
257
+ f"outcomming {api} request failed while opening response: "
206
258
  f"{type(exc).__name__}: {exc}"
207
259
  ) from exc
208
260
 
@@ -304,7 +356,10 @@ class OutcommingTransport:
304
356
  }
305
357
  api_key = self.config.outcomming_api_key()
306
358
  if api_key is not None:
307
- headers["Authorization"] = f"Bearer {api_key}"
359
+ if self.config.normalized_outcomming_api() == "gemini":
360
+ headers["x-goog-api-key"] = api_key
361
+ else:
362
+ headers["Authorization"] = f"Bearer {api_key}"
308
363
  return headers
309
364
 
310
365
  def _iter_sse_events(self, response):
@@ -321,6 +376,7 @@ class OutcommingTransport:
321
376
  continue
322
377
 
323
378
  if line.startswith(":"):
379
+ yield None, ""
324
380
  continue
325
381
  if line.startswith("event:"):
326
382
  event_name = line.split(":", 1)[1].lstrip()