python-codex 0.6.0__py3-none-any.whl → 0.6.2__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 +4 -4
- pycodex/agent.py +28 -9
- pycodex/bootstrap.py +10 -12
- pycodex/cli.py +0 -14
- pycodex/context.py +43 -32
- pycodex/events.py +20 -11
- pycodex/model.py +16 -7
- pycodex/prompts/models.json +14 -0
- pycodex/protocol.py +18 -0
- pycodex/runtime.py +49 -54
- pycodex/tools/__init__.py +9 -10
- pycodex/tools/clock_tool.py +57 -7
- pycodex/tools/exec_runtime.py +29 -78
- pycodex/tools/exec_tool.py +2 -6
- pycodex/utils/compat.py +41 -0
- pycodex/utils/dotenv.py +0 -7
- pycodex/utils/event_helpers.py +5 -9
- pycodex/utils/history.py +79 -20
- pycodex/utils/session_persist.py +133 -36
- pycodex/utils/skill_catalog.py +18 -0
- python_codex-0.6.2.dist-info/METADATA +216 -0
- {python_codex-0.6.0.dist-info → python_codex-0.6.2.dist-info}/RECORD +33 -32
- responses_server/app.py +3 -1
- responses_server/config.py +6 -1
- responses_server/gemini_api.py +336 -0
- responses_server/messages_api.py +9 -1
- responses_server/request_translation.py +6 -0
- responses_server/stream_router.py +15 -0
- responses_server/tools/web_search.py +3 -0
- responses_server/transport.py +75 -19
- pycodex/tools/request_user_input_tool.py +0 -82
- python_codex-0.6.0.dist-info/METADATA +0 -352
- {python_codex-0.6.0.dist-info → python_codex-0.6.2.dist-info}/WHEEL +0 -0
- {python_codex-0.6.0.dist-info → python_codex-0.6.2.dist-info}/entry_points.txt +0 -0
- {python_codex-0.6.0.dist-info → python_codex-0.6.2.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,336 @@
|
|
|
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
|
+
# Unsigned empty text can end a stream, but is not input data.
|
|
35
|
+
parts = [part for part in parts
|
|
36
|
+
if part.get("text") != "" or "thoughtSignature" in part]
|
|
37
|
+
else:
|
|
38
|
+
parts = _content_parts(message.get("content"))
|
|
39
|
+
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
|
+
}})
|
|
47
|
+
role = "model"
|
|
48
|
+
elif role == "tool":
|
|
49
|
+
call_id = message["tool_call_id"]
|
|
50
|
+
if call_id not in calls:
|
|
51
|
+
raise GeminiAPIAdapterError("Gemini tool result has no matching function call")
|
|
52
|
+
parts = [{"functionResponse": {
|
|
53
|
+
"name": calls[call_id], "id": call_id,
|
|
54
|
+
"response": {"result": message.get("content", "")},
|
|
55
|
+
}}]
|
|
56
|
+
role = "user"
|
|
57
|
+
elif role == "user":
|
|
58
|
+
parts = _content_parts(message.get("content"))
|
|
59
|
+
else:
|
|
60
|
+
raise GeminiAPIAdapterError("unsupported Gemini message role: {!r}".format(role))
|
|
61
|
+
if parts:
|
|
62
|
+
# Batch parallel function responses, keeping subsequent image input
|
|
63
|
+
# in its own user content as provided by the canonical translator.
|
|
64
|
+
if message["role"] == "tool" and contents and all(
|
|
65
|
+
"functionResponse" in part for part in contents[-1]["parts"]
|
|
66
|
+
):
|
|
67
|
+
contents[-1]["parts"].extend(parts)
|
|
68
|
+
else:
|
|
69
|
+
contents.append({"role": role, "parts": parts})
|
|
70
|
+
|
|
71
|
+
payload = {"contents": contents}
|
|
72
|
+
if system_parts:
|
|
73
|
+
payload["systemInstruction"] = {"parts": system_parts}
|
|
74
|
+
generation = {"thinkingConfig": {"includeThoughts": True}}
|
|
75
|
+
if "max_tokens" in request:
|
|
76
|
+
generation["maxOutputTokens"] = request["max_tokens"]
|
|
77
|
+
effort = request.get("chat_template_kwargs", {}).get("reasoning_effort")
|
|
78
|
+
if effort is not None:
|
|
79
|
+
levels = {
|
|
80
|
+
"none": "minimal", "minimal": "minimal", "low": "low",
|
|
81
|
+
"medium": "medium", "high": "high", "xhigh": "high", "max": "high",
|
|
82
|
+
}
|
|
83
|
+
if effort not in levels:
|
|
84
|
+
raise GeminiAPIAdapterError("unsupported Gemini reasoning effort: {!r}".format(effort))
|
|
85
|
+
generation["thinkingConfig"]["thinkingLevel"] = levels[effort]
|
|
86
|
+
payload["generationConfig"] = generation
|
|
87
|
+
|
|
88
|
+
declarations = []
|
|
89
|
+
for tool in request.get("tools", []):
|
|
90
|
+
if tool["type"] != "function":
|
|
91
|
+
raise GeminiAPIAdapterError("Gemini backend requires function-style tools")
|
|
92
|
+
function = tool["function"]
|
|
93
|
+
declarations.append({
|
|
94
|
+
"name": function["name"], "description": function.get("description", ""),
|
|
95
|
+
"parametersJsonSchema": deepcopy(function.get("parameters", {"type": "object"})),
|
|
96
|
+
})
|
|
97
|
+
if declarations:
|
|
98
|
+
payload["tools"] = [{"functionDeclarations": declarations}]
|
|
99
|
+
choice = request.get("tool_choice", "auto")
|
|
100
|
+
if isinstance(choice, dict) and choice.get("type") == "function":
|
|
101
|
+
config = {"mode": "ANY", "allowedFunctionNames": [choice["function"]["name"]]}
|
|
102
|
+
elif choice in ("auto", "required", "none"):
|
|
103
|
+
config = {"mode": {"auto": "AUTO", "required": "ANY", "none": "NONE"}[choice]}
|
|
104
|
+
else:
|
|
105
|
+
raise GeminiAPIAdapterError("unsupported Gemini tool_choice")
|
|
106
|
+
config["streamFunctionCallArguments"] = True
|
|
107
|
+
payload["toolConfig"] = {"functionCallingConfig": config}
|
|
108
|
+
return payload
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _content_parts(content):
|
|
112
|
+
if not content:
|
|
113
|
+
return []
|
|
114
|
+
if isinstance(content, str):
|
|
115
|
+
return [{"text": content}]
|
|
116
|
+
parts = []
|
|
117
|
+
for part in content:
|
|
118
|
+
if part["type"] == "text":
|
|
119
|
+
parts.append({"text": part["text"]})
|
|
120
|
+
elif part["type"] == "image_url":
|
|
121
|
+
url = part["image_url"]["url"]
|
|
122
|
+
if url.startswith("data:"):
|
|
123
|
+
header, separator, data = url.partition(",")
|
|
124
|
+
mime_type = header[5:].split(";")[0]
|
|
125
|
+
if not separator or not header.endswith(";base64") or not mime_type or not data:
|
|
126
|
+
raise GeminiAPIAdapterError("Gemini images require a base64 data URL with a media type")
|
|
127
|
+
parts.append({"inlineData": {"mimeType": mime_type, "data": data}})
|
|
128
|
+
else:
|
|
129
|
+
raise GeminiAPIAdapterError("Gemini images require a base64 data URL with a media type")
|
|
130
|
+
else:
|
|
131
|
+
raise GeminiAPIAdapterError("unsupported Gemini content part: {!r}".format(part["type"]))
|
|
132
|
+
return parts
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def iter_chat_chunks(payload, state):
|
|
136
|
+
if not isinstance(payload, dict):
|
|
137
|
+
raise GeminiAPIAdapterError("Gemini stream payload must be an object")
|
|
138
|
+
if "error" in payload:
|
|
139
|
+
error = payload["error"]
|
|
140
|
+
message = error.get("message", "Gemini API error") if isinstance(error, dict) else str(error)
|
|
141
|
+
raise GeminiAPIAdapterError(message)
|
|
142
|
+
blocked = payload.get("promptFeedback", {}).get("blockReason")
|
|
143
|
+
if blocked:
|
|
144
|
+
raise GeminiAPIAdapterError("Gemini prompt blocked: {}".format(blocked))
|
|
145
|
+
candidates = payload.get("candidates", [])
|
|
146
|
+
if len(candidates) > 1:
|
|
147
|
+
raise GeminiAPIAdapterError("Gemini adapter requires a single candidate")
|
|
148
|
+
for candidate in candidates:
|
|
149
|
+
if candidate.get("index", 0) != 0:
|
|
150
|
+
raise GeminiAPIAdapterError("unexpected Gemini candidate index")
|
|
151
|
+
finish = candidate.get("finishReason")
|
|
152
|
+
if finish and finish != "STOP":
|
|
153
|
+
raise GeminiAPIAdapterError("Gemini generation ended with {}".format(finish))
|
|
154
|
+
for part in candidate.get("content", {}).get("parts", []):
|
|
155
|
+
if "functionCall" in part:
|
|
156
|
+
chunk = _consume_function_call(part, state)
|
|
157
|
+
if chunk is not None:
|
|
158
|
+
yield chunk
|
|
159
|
+
elif "text" in part or "thoughtSignature" in part:
|
|
160
|
+
entry = {"provider": "gemini", "part": deepcopy(part)}
|
|
161
|
+
state.setdefault("provider_data", []).append(entry)
|
|
162
|
+
text = part.get("text", "")
|
|
163
|
+
if not text and state.get("last_call_id"):
|
|
164
|
+
entry["call_id"] = state["last_call_id"]
|
|
165
|
+
if text:
|
|
166
|
+
state.pop("last_call_id", None)
|
|
167
|
+
kind = "reasoning_content" if part.get("thought") else "content"
|
|
168
|
+
yield _delta({kind: text})
|
|
169
|
+
else:
|
|
170
|
+
raise GeminiAPIAdapterError("unsupported Gemini output part: {}".format(
|
|
171
|
+
", ".join(sorted(part)),
|
|
172
|
+
))
|
|
173
|
+
if finish:
|
|
174
|
+
if "function_call" in state:
|
|
175
|
+
raise GeminiAPIAdapterError("Gemini stream ended with an incomplete function call")
|
|
176
|
+
state["finished"] = True
|
|
177
|
+
yield {"choices": [{"index": 0, "delta": {}, "finish_reason": (
|
|
178
|
+
"tool_calls" if "tool_index" in state else "stop"
|
|
179
|
+
)}]}
|
|
180
|
+
usage = payload.get("usageMetadata", {})
|
|
181
|
+
token_counts = state.setdefault("token_counts", {})
|
|
182
|
+
for key in ("candidatesTokenCount", "thoughtsTokenCount"):
|
|
183
|
+
if key in usage:
|
|
184
|
+
token_counts[key] = usage[key]
|
|
185
|
+
translated = {}
|
|
186
|
+
for source, target in (("promptTokenCount", "prompt_tokens"), ("totalTokenCount", "total_tokens")):
|
|
187
|
+
if source in usage:
|
|
188
|
+
translated[target] = usage[source]
|
|
189
|
+
if "candidatesTokenCount" in usage or "thoughtsTokenCount" in usage:
|
|
190
|
+
translated["completion_tokens"] = (
|
|
191
|
+
token_counts.get("candidatesTokenCount", 0)
|
|
192
|
+
+ token_counts.get("thoughtsTokenCount", 0)
|
|
193
|
+
)
|
|
194
|
+
if "thoughtsTokenCount" in usage:
|
|
195
|
+
translated["completion_tokens_details"] = {"reasoning_tokens": usage["thoughtsTokenCount"]}
|
|
196
|
+
if "cachedContentTokenCount" in usage:
|
|
197
|
+
translated["prompt_tokens_details"] = {"cached_tokens": usage["cachedContentTokenCount"]}
|
|
198
|
+
if translated:
|
|
199
|
+
yield {"choices": [], "usage": translated}
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _consume_function_call(part, state):
|
|
203
|
+
call = part["functionCall"]
|
|
204
|
+
active = state.get("function_call")
|
|
205
|
+
if active is None:
|
|
206
|
+
if not isinstance(call.get("name"), str) or not call["name"] or not isinstance(call.get("args", {}), dict):
|
|
207
|
+
raise GeminiAPIAdapterError("invalid Gemini function call")
|
|
208
|
+
native = {key: deepcopy(value) for key, value in call.items()
|
|
209
|
+
if key not in {"partialArgs", "willContinue"}}
|
|
210
|
+
entry = {"provider": "gemini", "part": dict(deepcopy(part), functionCall=native),
|
|
211
|
+
"call_id": call.get("id") or "call_" + uuid.uuid4().hex}
|
|
212
|
+
state.setdefault("provider_data", []).append(entry)
|
|
213
|
+
state["tool_index"] = state.get("tool_index", -1) + 1
|
|
214
|
+
active = {"entry": entry, "pending": {}}
|
|
215
|
+
state["function_call"] = active
|
|
216
|
+
state["last_call_id"] = entry["call_id"]
|
|
217
|
+
else:
|
|
218
|
+
native = active["entry"]["part"]["functionCall"]
|
|
219
|
+
if ("name" in call and call["name"] != native["name"]
|
|
220
|
+
or "id" in call and call["id"] != native.get("id")
|
|
221
|
+
or "args" in call):
|
|
222
|
+
raise GeminiAPIAdapterError("conflicting Gemini function call fragment")
|
|
223
|
+
if "thoughtSignature" in part:
|
|
224
|
+
state["provider_data"].append({
|
|
225
|
+
"provider": "gemini", "call_id": active["entry"]["call_id"],
|
|
226
|
+
"part": {"text": "", "thoughtSignature": part["thoughtSignature"]},
|
|
227
|
+
})
|
|
228
|
+
for partial in call.get("partialArgs", []):
|
|
229
|
+
_consume_partial_argument(partial, native.setdefault("args", {}), active["pending"])
|
|
230
|
+
if call.get("willContinue", False):
|
|
231
|
+
return None
|
|
232
|
+
if active["pending"]:
|
|
233
|
+
raise GeminiAPIAdapterError("Gemini function call ended with incomplete arguments")
|
|
234
|
+
del state["function_call"]
|
|
235
|
+
return _delta({"tool_calls": [{
|
|
236
|
+
"index": state["tool_index"], "id": active["entry"]["call_id"], "type": "function",
|
|
237
|
+
"function": {"name": native["name"], "arguments": json.dumps(
|
|
238
|
+
native.get("args", {}), ensure_ascii=False, separators=(",", ":"),
|
|
239
|
+
)},
|
|
240
|
+
}]})
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _consume_partial_argument(partial, arguments, pending):
|
|
244
|
+
raw_path = partial.get("jsonPath")
|
|
245
|
+
container = raw_path[-2:] if isinstance(raw_path, str) else None
|
|
246
|
+
is_container = container in ("{}", "[]")
|
|
247
|
+
path = _argument_path(raw_path[:-2] if is_container else raw_path)
|
|
248
|
+
fields = [key for key in ("stringValue", "numberValue", "boolValue", "nullValue")
|
|
249
|
+
if key in partial]
|
|
250
|
+
if len(fields) != (0 if is_container else 1):
|
|
251
|
+
raise GeminiAPIAdapterError("Gemini partial argument must contain one value")
|
|
252
|
+
field = fields[0] if fields else None
|
|
253
|
+
value = partial[field] if field is not None else ([] if container == "[]" else {})
|
|
254
|
+
if field == "stringValue":
|
|
255
|
+
if not isinstance(value, str):
|
|
256
|
+
raise GeminiAPIAdapterError("invalid Gemini string argument")
|
|
257
|
+
chunks = pending.setdefault(path, [])
|
|
258
|
+
chunks.append(value)
|
|
259
|
+
if partial.get("willContinue", False):
|
|
260
|
+
return
|
|
261
|
+
value = "".join(pending.pop(path))
|
|
262
|
+
else:
|
|
263
|
+
if path in pending or partial.get("willContinue", False):
|
|
264
|
+
raise GeminiAPIAdapterError("invalid Gemini scalar argument continuation")
|
|
265
|
+
if field == "numberValue" and (isinstance(value, bool) or not isinstance(value, (int, float))):
|
|
266
|
+
raise GeminiAPIAdapterError("invalid Gemini number argument")
|
|
267
|
+
if field == "boolValue" and not isinstance(value, bool):
|
|
268
|
+
raise GeminiAPIAdapterError("invalid Gemini boolean argument")
|
|
269
|
+
if field == "nullValue":
|
|
270
|
+
if isinstance(value, bool) or value not in (None, "NULL_VALUE", 0):
|
|
271
|
+
raise GeminiAPIAdapterError("invalid Gemini null argument")
|
|
272
|
+
value = None
|
|
273
|
+
node = arguments
|
|
274
|
+
for index, key in enumerate(path):
|
|
275
|
+
last = index == len(path) - 1
|
|
276
|
+
child = value if last else ([] if isinstance(path[index + 1], int) else {})
|
|
277
|
+
if isinstance(node, dict) and isinstance(key, str):
|
|
278
|
+
if key not in node:
|
|
279
|
+
node[key] = child
|
|
280
|
+
elif last:
|
|
281
|
+
raise GeminiAPIAdapterError("duplicate Gemini argument path")
|
|
282
|
+
elif isinstance(node, list) and isinstance(key, int) and key <= len(node):
|
|
283
|
+
if key == len(node):
|
|
284
|
+
node.append(child)
|
|
285
|
+
elif last:
|
|
286
|
+
raise GeminiAPIAdapterError("duplicate Gemini argument path")
|
|
287
|
+
else:
|
|
288
|
+
raise GeminiAPIAdapterError("invalid Gemini argument path structure")
|
|
289
|
+
node = node[key]
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _argument_path(path):
|
|
293
|
+
# Function arguments use concrete member/index paths, never JSONPath queries.
|
|
294
|
+
pattern = r'''\.([^\W\d]\w*)|\[(0|[1-9][0-9]*|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\]'''
|
|
295
|
+
if not isinstance(path, str) or not path.startswith("$"):
|
|
296
|
+
raise GeminiAPIAdapterError("invalid Gemini argument path")
|
|
297
|
+
keys = []
|
|
298
|
+
offset = 1
|
|
299
|
+
while offset < len(path):
|
|
300
|
+
match = re.match(pattern, path[offset:])
|
|
301
|
+
if match is None:
|
|
302
|
+
raise GeminiAPIAdapterError("invalid Gemini argument path")
|
|
303
|
+
member, bracket = match.groups()
|
|
304
|
+
if member is not None:
|
|
305
|
+
key = member
|
|
306
|
+
elif bracket[0] in ("'", '"'):
|
|
307
|
+
if bracket[0] == "'":
|
|
308
|
+
bracket = '"' + re.sub(
|
|
309
|
+
r'''\\(.)|"''',
|
|
310
|
+
lambda item: "'" if item.group(1) == "'" else
|
|
311
|
+
'\\"' if item.group(0) == '"' else item.group(0),
|
|
312
|
+
bracket[1:-1],
|
|
313
|
+
) + '"'
|
|
314
|
+
try:
|
|
315
|
+
key = json.loads(bracket)
|
|
316
|
+
except ValueError as exc:
|
|
317
|
+
raise GeminiAPIAdapterError("invalid Gemini argument path") from exc
|
|
318
|
+
else:
|
|
319
|
+
key = int(bracket)
|
|
320
|
+
keys.append(key)
|
|
321
|
+
offset += match.end()
|
|
322
|
+
if not keys or not isinstance(keys[0], str):
|
|
323
|
+
raise GeminiAPIAdapterError("Gemini function arguments must be objects")
|
|
324
|
+
return tuple(keys)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _delta(delta):
|
|
328
|
+
return {"choices": [{"index": 0, "delta": delta, "finish_reason": None}]}
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def continuation_chunk(state):
|
|
332
|
+
"""Use the existing opaque reasoning-item contract for durable native state."""
|
|
333
|
+
return {"reasoning_item": {
|
|
334
|
+
"type": "reasoning", "summary": [],
|
|
335
|
+
"provider_data": deepcopy(state.get("provider_data", [])),
|
|
336
|
+
}}
|
responses_server/messages_api.py
CHANGED
|
@@ -5,7 +5,9 @@ DEFAULT_MESSAGES_MAX_TOKENS = 32000
|
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
class MessagesAPIAdapterError(ValueError):
|
|
8
|
-
|
|
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:
|
responses_server/transport.py
CHANGED
|
@@ -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.
|
|
170
|
+
yield from self._read_outcomming_native_stream(request, progress, "messages")
|
|
144
171
|
|
|
145
|
-
def
|
|
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
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
stream_state
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
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
|
|
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
|
-
|
|
232
|
+
GeminiAPIAdapterError,
|
|
181
233
|
) as exc:
|
|
182
234
|
raise OutcommingChatError(
|
|
183
|
-
"outcomming
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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()
|