python-codex 0.6.2__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.
- pycodex/agent.py +7 -0
- pycodex/bootstrap.py +8 -0
- pycodex/context.py +14 -8
- pycodex/model.py +32 -7
- pycodex/prompts/models.json +345 -0
- pycodex/utils/compactor.py +5 -2
- pycodex/utils/http_headers.py +25 -0
- {python_codex-0.6.2.dist-info → python_codex-0.6.3.dist-info}/METADATA +4 -1
- {python_codex-0.6.2.dist-info → python_codex-0.6.3.dist-info}/RECORD +20 -19
- responses_server/app.py +2 -0
- responses_server/config.py +4 -1
- responses_server/gemini_api.py +14 -6
- responses_server/messages_api.py +12 -6
- responses_server/payload_processors.py +1 -1
- responses_server/request_translation.py +55 -13
- responses_server/stream_router.py +9 -0
- responses_server/transport.py +12 -6
- {python_codex-0.6.2.dist-info → python_codex-0.6.3.dist-info}/WHEEL +0 -0
- {python_codex-0.6.2.dist-info → python_codex-0.6.3.dist-info}/entry_points.txt +0 -0
- {python_codex-0.6.2.dist-info → python_codex-0.6.3.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Resolve provider headers using Codex's static-then-environment precedence."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import typing
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def build_http_headers(
|
|
9
|
+
http_headers: "typing.Mapping[str, str]",
|
|
10
|
+
env_http_headers: "typing.Mapping[str, str]",
|
|
11
|
+
) -> "typing.Dict[str, str]":
|
|
12
|
+
headers = {}
|
|
13
|
+
values = list(http_headers.items())
|
|
14
|
+
for name, env_var in env_http_headers.items():
|
|
15
|
+
value = os.environ.get(env_var)
|
|
16
|
+
if value is not None and value.strip():
|
|
17
|
+
values.append((name, value))
|
|
18
|
+
for name, value in values:
|
|
19
|
+
if not re.fullmatch(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+", name):
|
|
20
|
+
continue
|
|
21
|
+
if re.search(r"[\x00-\x08\x0a-\x1f\x7f]", value):
|
|
22
|
+
continue
|
|
23
|
+
# Rust HeaderValue stores UTF-8 bytes; Python HTTP clients encode Latin-1.
|
|
24
|
+
headers[name.lower()] = value.encode("utf-8").decode("latin-1")
|
|
25
|
+
return headers
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: python-codex
|
|
3
|
-
Version: 0.6.
|
|
3
|
+
Version: 0.6.3
|
|
4
4
|
Summary: A minimal Python extraction of Codex's main agent loop
|
|
5
5
|
License-File: LICENSE
|
|
6
6
|
Requires-Python: >=3.6.2
|
|
@@ -87,6 +87,8 @@ See [configuration](docs/CONTEXT.md#配置读取与-profile) and the
|
|
|
87
87
|
[Gemini setup example](docs/responses_server/README.md#gemini-api).
|
|
88
88
|
Gemini 4 Argon includes a prompt adapted from Antigravity.
|
|
89
89
|
Gemini tool arguments stream as they are generated; tools run after the complete call is received.
|
|
90
|
+
Gemini tool results use `response.output`; returned images stay in the matching
|
|
91
|
+
`functionResponse.parts`.
|
|
90
92
|
Gemini continuation omits unsigned empty text parts while preserving thought signatures,
|
|
91
93
|
including when resuming recorded sessions.
|
|
92
94
|
|
|
@@ -146,6 +148,7 @@ pycodex-ws --listen 127.0.0.1:6007 --workspace-config workspaces.json
|
|
|
146
148
|
|
|
147
149
|
Open `http://127.0.0.1:6007`. The workspace uses the same model configuration as
|
|
148
150
|
the CLI and provides conversations, a live HTML Canvas, and file/diff viewers.
|
|
151
|
+
Chat updates arrive through two-second polling; completed replies render as Markdown.
|
|
149
152
|
Click file links to inspect code, then select text and use **Insert into chat**
|
|
150
153
|
to include it in your next message.
|
|
151
154
|
Each input displays its author and creation time, including separate messages
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
pycodex/__init__.py,sha256=2rP9Qd5ClJlSI3bPNB0Jmn9lJUpeeo7gcbRPUvH81eI,2904
|
|
2
2
|
pycodex/__main__.py,sha256=MHKZ_ae3fSLGTLUUMOx15fWdeOnJSHhq-zslRP5F5Lc,79
|
|
3
|
-
pycodex/agent.py,sha256=
|
|
4
|
-
pycodex/bootstrap.py,sha256=
|
|
3
|
+
pycodex/agent.py,sha256=EanBfEvRLnGSfvWv_P447mUw5CezVk680h2vP4pc_YI,23848
|
|
4
|
+
pycodex/bootstrap.py,sha256=4bn2MhNzAHk1fFVFO1V8p2hFKcOMbe4-y2PA5qhPY98,5429
|
|
5
5
|
pycodex/cli.py,sha256=HkX_fFNUyPnNo25FeSa9ZMaQG79rqk3b0oV4ZH0h68c,12576
|
|
6
6
|
pycodex/config.py,sha256=mGM7oLaciBwGXHMQjKVifWFTd7gZTfzqlQeJSFzcQic,1218
|
|
7
|
-
pycodex/context.py,sha256=
|
|
7
|
+
pycodex/context.py,sha256=OKIm-bs8ZosKn_tqy3CEU7XUu6rMFLbNZ_eyuIkzMaQ,42016
|
|
8
8
|
pycodex/events.py,sha256=8gPVe_wb5r5s2hVQhywFMnz1YVvBmDLhyq43e9Y71wk,23090
|
|
9
|
-
pycodex/model.py,sha256=
|
|
9
|
+
pycodex/model.py,sha256=SaAMysy0MaeFNbRgJS4zP_QcAerBYa5_Jilwvgtv34s,59992
|
|
10
10
|
pycodex/multi_agents.py,sha256=3KN_Ai3UremtsQppvxd0pE7pFam_v0zBastCNi-NNx8,16150
|
|
11
11
|
pycodex/protocol.py,sha256=qYUS9371F-DadlsYgctCpQbm3JCqyfpcWcxkANRAZWQ,15586
|
|
12
12
|
pycodex/runtime.py,sha256=92hVNdBzugUYQb01-bbkAOYpNpjIB1IWVEU6_U6SERA,37120
|
|
@@ -16,7 +16,7 @@ pycodex/portable/protocol.py,sha256=jtyPHI3aVY4UldlSIzeZRQX3MCFzPYfG-0iDC6JSWYo,
|
|
|
16
16
|
pycodex/portable/server.py,sha256=UCQAqcO0OTNkEv4MQgR-fIt1y5bzdqMndFJtMm16Lqk,7503
|
|
17
17
|
pycodex/prompts/default_base_instructions.md,sha256=D65mcj6bo4CDvVom-D9cbJRJVNquo0NghKt164_fRsg,20923
|
|
18
18
|
pycodex/prompts/developer_messages.json,sha256=E-CAWMOL2KoImJ1U_1aA-OYbuVtJF0-GtZkn983B-TI,4007
|
|
19
|
-
pycodex/prompts/models.json,sha256=
|
|
19
|
+
pycodex/prompts/models.json,sha256=m2edzANgpiRutpuw3nGJFiJQX4Y7751_omr4E4zN_uU,747802
|
|
20
20
|
pycodex/prompts/goals/budget_limit.md,sha256=RbvI03fMD3tTy-ytnzylqAsIr9b2O_Cb81CQejR1J-k,775
|
|
21
21
|
pycodex/prompts/goals/continuation.md,sha256=K7OtQKQNoCKcgne-e-SQBGJjEpnCVcVCtML7T-82bWI,6153
|
|
22
22
|
pycodex/prompts/permissions/approval_policy/never.md,sha256=QceTG6wjkaJARjYr0HYV1aPnPcpGcrkRUW-smWRr6MQ,120
|
|
@@ -62,7 +62,7 @@ pycodex/tools/write_stdin_tool.py,sha256=jvBDchLLmoDITd7g-ZVeEVXHRhWKkmnjM5laL-5
|
|
|
62
62
|
pycodex/utils/__init__.py,sha256=ih_KyZ2_bajR5YlZ1QMTWOHnuEBda-S3gQ7PwnBtLZQ,453
|
|
63
63
|
pycodex/utils/async_bridge.py,sha256=BXsKTUTUvUtPJnItQlulFRdV7opdKKDlsKLdtVTYshs,1732
|
|
64
64
|
pycodex/utils/codex_config.py,sha256=oCisEGUJcJxcZL1wIqXkon1xTShymOlz96E3VgDVTlY,3748
|
|
65
|
-
pycodex/utils/compactor.py,sha256=
|
|
65
|
+
pycodex/utils/compactor.py,sha256=qSHZpTP_hWuxuqeVt6JijbtgkXiW2act1CdTQ5wovBM,6399
|
|
66
66
|
pycodex/utils/compat.py,sha256=16FyHHlDES57mOHCasN4FWveEkGYd2aZex9-Eojlkg8,5277
|
|
67
67
|
pycodex/utils/crypto.py,sha256=HRCXF26Ft3S8CG2X0YpZwa8GMU9YJ0Loo8Q9PMPMcNw,1249
|
|
68
68
|
pycodex/utils/debug.py,sha256=5XMpWpwFSm6woyx6RGXvN2qL0afRtTQbwlOAv-LotTw,913
|
|
@@ -71,6 +71,7 @@ pycodex/utils/dotenv.py,sha256=rLHBfz5zPZMbrJqyRyYPy3j4oiDwuzfrH4mDH3XRrow,1647
|
|
|
71
71
|
pycodex/utils/event_helpers.py,sha256=ULvTSktxMd--VEL2UJA6CbuWHLsrctAcAuEk91wGLL8,12021
|
|
72
72
|
pycodex/utils/get_env.py,sha256=L4S8h84tkgxZKvrxY7ezTgePbXepG-yIigUTKeY6uuE,6094
|
|
73
73
|
pycodex/utils/history.py,sha256=qgt5IxxkfCYjjpr08VJFhasICSSlqxQM7d-DjRJVjHA,3845
|
|
74
|
+
pycodex/utils/http_headers.py,sha256=4Jlnmun6QFSQ6L7javlDQfom1p2AZZQFXvcHzD3_cQk,877
|
|
74
75
|
pycodex/utils/image_utils.py,sha256=OUzUs0Cow4L8Z2np0EBeEUotAqqsCmRmhrV8AxZUXRw,2460
|
|
75
76
|
pycodex/utils/model_metadata.py,sha256=uK3iI4yC7Ge7yN4I1_gQYalQ4MYKddz2qMwsmQb-P80,1337
|
|
76
77
|
pycodex/utils/random_ids.py,sha256=jLTxZZ0MBbRdQOFDFWGVRjWzIo6FKSQ5ADXbQSLPp1s,379
|
|
@@ -85,23 +86,23 @@ pycodex/utils/_aes_gcm/gcm.py,sha256=Z8fYHpnLpqJyTPmjDOZtryqe0xmT_93vscNuJe5ZY-w
|
|
|
85
86
|
pycodex/utils/_aes_gcm/source-sha256.json,sha256=g9uPWXuA0D9Wq9EGnduyiVanTgi8QWRFW-9T69FG-fc,215
|
|
86
87
|
responses_server/__init__.py,sha256=SOMO5Q-Z0dpaRih8yWuKUTclPl28tpy_XIPTOO_BPq0,447
|
|
87
88
|
responses_server/__main__.py,sha256=876xZTqhPeDBD2GKKr8pKX33Af8PhFTosAI8bYQsFgQ,61
|
|
88
|
-
responses_server/app.py,sha256=
|
|
89
|
-
responses_server/config.py,sha256=
|
|
90
|
-
responses_server/gemini_api.py,sha256=
|
|
91
|
-
responses_server/messages_api.py,sha256=
|
|
92
|
-
responses_server/payload_processors.py,sha256
|
|
93
|
-
responses_server/request_translation.py,sha256=
|
|
89
|
+
responses_server/app.py,sha256=6D23sAyftNUwGwmWT7WGM6aau78i7KCkhZfc16Sul3o,8600
|
|
90
|
+
responses_server/config.py,sha256=XxBRXrLEeCnaqKXGV-f_3iTtur0hPn4yqM7wLngcTFM,2931
|
|
91
|
+
responses_server/gemini_api.py,sha256=d5ChR4_fOnx2tPVSQQWWYIgXuIEcHdJUScaOptoGii4,16163
|
|
92
|
+
responses_server/messages_api.py,sha256=dDZ2z2AfE5Mfayuy0yt3tmgYp7fj11QtOBQ51gtdVCE,19613
|
|
93
|
+
responses_server/payload_processors.py,sha256=-lcw5DJ-uGiK4ZDsw373gjxpqVTapC-kWGVBXFGmr1A,3585
|
|
94
|
+
responses_server/request_translation.py,sha256=qG5rxW0bf6NS83L24YmMOuVNpPZGWnl2NVjNtQ-_GeQ,20508
|
|
94
95
|
responses_server/server.py,sha256=hFSRU3GjYa9cI1YSDxKvg2gLjp3OJ_Mh_JFyau3yzl4,2535
|
|
95
96
|
responses_server/session_store.py,sha256=nwGxQL6nUVKnDVeDHz8IzqNQ7dWk8Ybf0URekOHdxTo,1133
|
|
96
97
|
responses_server/stream_events.py,sha256=nWi5VcssytFD3SDHW5hQik5LR-US-Clk-5EEWAi3t-k,4984
|
|
97
|
-
responses_server/stream_router.py,sha256=
|
|
98
|
+
responses_server/stream_router.py,sha256=7-_KoXtaDtEISeSxGL-tJ-l6gmypbIgQ_Mxx9dtyklA,15474
|
|
98
99
|
responses_server/trajectory_dump.py,sha256=5_Wy6tslszrqx3j1JeP_boyTbzIicKy8No84PzMnmHk,5111
|
|
99
|
-
responses_server/transport.py,sha256=
|
|
100
|
+
responses_server/transport.py,sha256=PmflqUUZ-p7dO4vTFPNM4SzbQITXT0lntMqwiTrw2rw,16810
|
|
100
101
|
responses_server/tools/__init__.py,sha256=ivsBSEy0SBUhY-Uea5v1XMLXShkwHdCVl0id-1FwdZg,150
|
|
101
102
|
responses_server/tools/custom_adapter.py,sha256=leYNJKp4Ute0JWNfGpe-ntSyFqRgYCdWF4dMYQFINlk,8615
|
|
102
103
|
responses_server/tools/web_search.py,sha256=JyF6NHCS0SqoBrO18jX8cgBsiV4OYQBPz0Ky4u3juSQ,9059
|
|
103
|
-
python_codex-0.6.
|
|
104
|
-
python_codex-0.6.
|
|
105
|
-
python_codex-0.6.
|
|
106
|
-
python_codex-0.6.
|
|
107
|
-
python_codex-0.6.
|
|
104
|
+
python_codex-0.6.3.dist-info/METADATA,sha256=shh4KMFZrpoJD0vfiDk2WFzZ-5tbAni_J4nn8bevZ-g,8187
|
|
105
|
+
python_codex-0.6.3.dist-info/WHEEL,sha256=KGYbc1zXlYddvwxnNty23BeaKzh7YuoSIvIMO4jEhvw,87
|
|
106
|
+
python_codex-0.6.3.dist-info/entry_points.txt,sha256=sNUVakoVuTrzJH505ZgRTQxmtRRPUHV_EH0i6EbYTyM,45
|
|
107
|
+
python_codex-0.6.3.dist-info/licenses/LICENSE,sha256=0X8ifk312hYAORM4hlzg8wVSEXYKNmiPgWlB1YIy2Nw,10926
|
|
108
|
+
python_codex-0.6.3.dist-info/RECORD,,
|
responses_server/app.py
CHANGED
|
@@ -107,12 +107,14 @@ def launch_chat_completion_compat_server(
|
|
|
107
107
|
api_key_env: "typing.Union[str, None]" = None,
|
|
108
108
|
model_provider: "typing.Union[str, None]" = None,
|
|
109
109
|
outcomming_api: "str" = "chat_completions",
|
|
110
|
+
http_headers: "typing.Union[typing.Dict[str, str], None]" = None,
|
|
110
111
|
):
|
|
111
112
|
config = CompatServerConfig.from_base_url(
|
|
112
113
|
base_url,
|
|
113
114
|
api_key_env,
|
|
114
115
|
outcomming_api=outcomming_api,
|
|
115
116
|
model_provider=model_provider,
|
|
117
|
+
http_headers=http_headers,
|
|
116
118
|
)
|
|
117
119
|
server = ManagedResponseServer(config)
|
|
118
120
|
server.start()
|
responses_server/config.py
CHANGED
|
@@ -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
|
)
|
responses_server/gemini_api.py
CHANGED
|
@@ -5,6 +5,8 @@ import re
|
|
|
5
5
|
import uuid
|
|
6
6
|
from copy import deepcopy
|
|
7
7
|
|
|
8
|
+
from .request_translation import inline_history_instructions
|
|
9
|
+
|
|
8
10
|
|
|
9
11
|
class GeminiAPIAdapterError(ValueError):
|
|
10
12
|
pass
|
|
@@ -14,7 +16,7 @@ def build_gemini_request(request):
|
|
|
14
16
|
contents = []
|
|
15
17
|
system_parts = []
|
|
16
18
|
calls = {}
|
|
17
|
-
for message in request.get("messages", []):
|
|
19
|
+
for message in inline_history_instructions(request.get("messages", [])):
|
|
18
20
|
role = message["role"]
|
|
19
21
|
if role in {"system", "developer"}:
|
|
20
22
|
system_parts.extend(_content_parts(message.get("content")))
|
|
@@ -49,18 +51,24 @@ def build_gemini_request(request):
|
|
|
49
51
|
call_id = message["tool_call_id"]
|
|
50
52
|
if call_id not in calls:
|
|
51
53
|
raise GeminiAPIAdapterError("Gemini tool result has no matching function call")
|
|
52
|
-
|
|
54
|
+
output_parts = _content_parts(message.get("content"))
|
|
55
|
+
function_response = {
|
|
53
56
|
"name": calls[call_id], "id": call_id,
|
|
54
|
-
"response": {"
|
|
55
|
-
|
|
57
|
+
"response": {"output": "".join(
|
|
58
|
+
part["text"] for part in output_parts if "text" in part
|
|
59
|
+
)},
|
|
60
|
+
}
|
|
61
|
+
media_parts = [part for part in output_parts if "inlineData" in part]
|
|
62
|
+
if media_parts:
|
|
63
|
+
function_response["parts"] = media_parts
|
|
64
|
+
parts = [{"functionResponse": function_response}]
|
|
56
65
|
role = "user"
|
|
57
66
|
elif role == "user":
|
|
58
67
|
parts = _content_parts(message.get("content"))
|
|
59
68
|
else:
|
|
60
69
|
raise GeminiAPIAdapterError("unsupported Gemini message role: {!r}".format(role))
|
|
61
70
|
if parts:
|
|
62
|
-
# Batch
|
|
63
|
-
# in its own user content as provided by the canonical translator.
|
|
71
|
+
# Batch consecutive function responses into one user content.
|
|
64
72
|
if message["role"] == "tool" and contents and all(
|
|
65
73
|
"functionResponse" in part for part in contents[-1]["parts"]
|
|
66
74
|
):
|
responses_server/messages_api.py
CHANGED
|
@@ -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
|
|
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":
|
|
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":
|
|
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",
|
responses_server/transport.py
CHANGED
|
@@ -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(
|
|
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
|
-
|
|
355
|
-
|
|
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["
|
|
368
|
+
headers["authorization"] = f"Bearer {api_key}"
|
|
363
369
|
return headers
|
|
364
370
|
|
|
365
371
|
def _iter_sse_events(self, response):
|
|
File without changes
|
|
File without changes
|
|
File without changes
|