verifiers 0.3.2.dev18__py3-none-any.whl → 0.3.2.dev20__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.
- verifiers/legacy/__init__.py +0 -5
- verifiers/legacy/clients/__init__.py +6 -12
- {verifiers-0.3.2.dev18.dist-info → verifiers-0.3.2.dev20.dist-info}/METADATA +2 -3
- {verifiers-0.3.2.dev18.dist-info → verifiers-0.3.2.dev20.dist-info}/RECORD +7 -8
- verifiers/legacy/clients/renderer_client.py +0 -677
- {verifiers-0.3.2.dev18.dist-info → verifiers-0.3.2.dev20.dist-info}/WHEEL +0 -0
- {verifiers-0.3.2.dev18.dist-info → verifiers-0.3.2.dev20.dist-info}/entry_points.txt +0 -0
- {verifiers-0.3.2.dev18.dist-info → verifiers-0.3.2.dev20.dist-info}/licenses/LICENSE +0 -0
verifiers/legacy/__init__.py
CHANGED
|
@@ -87,7 +87,6 @@ __all__ = [
|
|
|
87
87
|
"OpenAIChatCompletionsClient",
|
|
88
88
|
"OpenAICompletionsClient",
|
|
89
89
|
"OpenAIResponsesClient",
|
|
90
|
-
"RendererClient",
|
|
91
90
|
"extract_boxed_answer",
|
|
92
91
|
"extract_hash_answer",
|
|
93
92
|
"load_example_dataset",
|
|
@@ -116,7 +115,6 @@ _LAZY_IMPORTS = {
|
|
|
116
115
|
"OpenAIChatCompletionsClient": (
|
|
117
116
|
"verifiers.legacy.clients.openai_chat_completions_client:OpenAIChatCompletionsClient"
|
|
118
117
|
),
|
|
119
|
-
"RendererClient": ("verifiers.legacy.clients.renderer_client:RendererClient"),
|
|
120
118
|
"OpenAICompletionsClient": (
|
|
121
119
|
"verifiers.legacy.clients.openai_completions_client:OpenAICompletionsClient"
|
|
122
120
|
),
|
|
@@ -152,8 +150,6 @@ def __getattr__(name: str):
|
|
|
152
150
|
except KeyError:
|
|
153
151
|
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
154
152
|
except ModuleNotFoundError as e:
|
|
155
|
-
if name == "RendererClient":
|
|
156
|
-
raise
|
|
157
153
|
raise AttributeError(
|
|
158
154
|
f"To use verifiers.{name}, install as `verifiers[all]`. "
|
|
159
155
|
) from e
|
|
@@ -167,7 +163,6 @@ if TYPE_CHECKING:
|
|
|
167
163
|
)
|
|
168
164
|
from .clients.openai_completions_client import OpenAICompletionsClient # noqa: F401
|
|
169
165
|
from .clients.openai_responses_client import OpenAIResponsesClient # noqa: F401
|
|
170
|
-
from .clients.renderer_client import RendererClient # noqa: F401
|
|
171
166
|
from .envs.env_group import EnvGroup # noqa: F401
|
|
172
167
|
from .envs.environment import Environment # noqa: F401
|
|
173
168
|
from .envs.experimental.cli_agent_env import CliAgentEnv # noqa: F401
|
|
@@ -33,9 +33,12 @@ def resolve_client(client_or_config: Client | ClientConfig) -> Client:
|
|
|
33
33
|
case "openai_responses":
|
|
34
34
|
return OpenAIResponsesClient(client_or_config)
|
|
35
35
|
case "renderer":
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
36
|
+
raise ValueError(
|
|
37
|
+
"client_type 'renderer' was removed: the legacy "
|
|
38
|
+
"RendererClient depended on renderer pool APIs dropped in "
|
|
39
|
+
"renderers 0.1.11. Use the verifiers.v1 train client for "
|
|
40
|
+
"renderer-backed token generation."
|
|
41
|
+
)
|
|
39
42
|
case "anthropic_messages":
|
|
40
43
|
return AnthropicMessagesClient(client_or_config)
|
|
41
44
|
case "nemorl_chat_completions":
|
|
@@ -44,14 +47,6 @@ def resolve_client(client_or_config: Client | ClientConfig) -> Client:
|
|
|
44
47
|
raise ValueError(f"Unsupported client type: {type(client_or_config)}")
|
|
45
48
|
|
|
46
49
|
|
|
47
|
-
def __getattr__(name: str):
|
|
48
|
-
if name == "RendererClient":
|
|
49
|
-
from verifiers.legacy.clients.renderer_client import RendererClient
|
|
50
|
-
|
|
51
|
-
return RendererClient
|
|
52
|
-
raise AttributeError(f"module 'verifiers.legacy.clients' has no attribute '{name}'")
|
|
53
|
-
|
|
54
|
-
|
|
55
50
|
__all__ = [
|
|
56
51
|
"AnthropicMessagesClient",
|
|
57
52
|
"NeMoRLChatCompletionsClient",
|
|
@@ -59,6 +54,5 @@ __all__ = [
|
|
|
59
54
|
"OpenAIChatCompletionsClient",
|
|
60
55
|
"OpenAIChatCompletionsTokenClient",
|
|
61
56
|
"OpenAIResponsesClient",
|
|
62
|
-
"RendererClient",
|
|
63
57
|
"Client",
|
|
64
58
|
]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: verifiers
|
|
3
|
-
Version: 0.3.2.
|
|
3
|
+
Version: 0.3.2.dev20
|
|
4
4
|
Summary: Verifiers: Environments for LLM Reinforcement Learning
|
|
5
5
|
Project-URL: Homepage, https://github.com/primeintellect-ai/verifiers
|
|
6
6
|
Project-URL: Documentation, https://github.com/primeintellect-ai/verifiers
|
|
@@ -39,7 +39,7 @@ Requires-Dist: prime-sandboxes>=0.2.39
|
|
|
39
39
|
Requires-Dist: prime-tunnel>=0.1.8
|
|
40
40
|
Requires-Dist: pydantic>=2.12.3
|
|
41
41
|
Requires-Dist: pyzmq>=27.1.0
|
|
42
|
-
Requires-Dist: renderers>=0.1.
|
|
42
|
+
Requires-Dist: renderers[multimodal]>=0.1.11
|
|
43
43
|
Requires-Dist: requests
|
|
44
44
|
Requires-Dist: rich>=11.0.0
|
|
45
45
|
Requires-Dist: setproctitle>=1.3.0
|
|
@@ -54,7 +54,6 @@ Provides-Extra: harbor
|
|
|
54
54
|
Requires-Dist: harbor==0.21.0; (python_full_version >= '3.12') and extra == 'harbor'
|
|
55
55
|
Provides-Extra: modal
|
|
56
56
|
Requires-Dist: modal>=1.4.0; extra == 'modal'
|
|
57
|
-
Provides-Extra: nemo-gym
|
|
58
57
|
Provides-Extra: notebook
|
|
59
58
|
Requires-Dist: nest-asyncio>=1.6.0; extra == 'notebook'
|
|
60
59
|
Provides-Extra: openenv
|
|
@@ -10,11 +10,11 @@ verifiers/cli/commands/install.py,sha256=tBPvIIqP4MKayceMSsCg6xXZGe67HJbtDYVgxZs
|
|
|
10
10
|
verifiers/cli/commands/setup.py,sha256=yGNi2h0UHze59DzpsxCE-lfGte7kaFPvQTKN1UAYpaQ,190
|
|
11
11
|
verifiers/cli/plugins/__init__.py,sha256=lvQmVT0qSmmv3BGbTGtbnOLqS8TUCK5p4aAlQ4Ullfg,190
|
|
12
12
|
verifiers/cli/plugins/prime.py,sha256=xO_lKBbeMxYO2vo6U8UTTriyttunx2U_3cCvM5OhltA,5998
|
|
13
|
-
verifiers/legacy/__init__.py,sha256=
|
|
13
|
+
verifiers/legacy/__init__.py,sha256=yH9rngGVwuvZytXG7gWfaecZqngs-fWzPbF90dpCtmk,6600
|
|
14
14
|
verifiers/legacy/decorators.py,sha256=QaZxUV821935zTqVLrdG1lKNasQ6VGKTpR5hTr_9B74,7883
|
|
15
15
|
verifiers/legacy/errors.py,sha256=xaFqOSaYlce2dXt4UPV1ZT-1-hwLzV1ycmXqiNymzeM,1306
|
|
16
16
|
verifiers/legacy/types.py,sha256=cAZo2RL8Ii0qVHJml5E4T8WPPHfvkLGCpZsZX1i0X_g,33433
|
|
17
|
-
verifiers/legacy/clients/__init__.py,sha256=
|
|
17
|
+
verifiers/legacy/clients/__init__.py,sha256=rpXFBynQD9u6gNZMM9pwh6FGuR8bw531WtD8VcrmyBo,2403
|
|
18
18
|
verifiers/legacy/clients/anthropic_messages_client.py,sha256=DCWPS45_Khtu5zQzxLoLw8ewTPdiPWJFlINJrt-phUQ,19836
|
|
19
19
|
verifiers/legacy/clients/client.py,sha256=nQ4hQNeBjEg3lBaWNKW-h3aVaOxWDhirnImN2GPZ53I,4766
|
|
20
20
|
verifiers/legacy/clients/nemorl_chat_completions_client.py,sha256=s-yzNoPURjwHrMIPT64Kp0TXOIHf1c2qmZqrbOtfa9g,4478
|
|
@@ -22,7 +22,6 @@ verifiers/legacy/clients/openai_chat_completions_client.py,sha256=2SlVcCn4DmDcy6
|
|
|
22
22
|
verifiers/legacy/clients/openai_chat_completions_token_client.py,sha256=kr-b56pi2uAhgEp43EapX59IfFDNCcFik5ROq8nNQe0,16747
|
|
23
23
|
verifiers/legacy/clients/openai_completions_client.py,sha256=B6sh5njHuN5TyVAzjT2k4Zba4QorQ-PbHZ8zFVN9BYQ,7249
|
|
24
24
|
verifiers/legacy/clients/openai_responses_client.py,sha256=By3oZ1QYFfaw5cFE6_LSl1c_qVDQi6hnm0DVS30WEcE,18139
|
|
25
|
-
verifiers/legacy/clients/renderer_client.py,sha256=vbEgvSi3mnx1V3SayTT5LCmmnVWKtevmOIMQ5IAoYAg,26849
|
|
26
25
|
verifiers/legacy/envs/__init__.py,sha256=OXkw2QcypssNW5BJmIzw7IpBs9uRMyYQSjlXDHpjIIE,86
|
|
27
26
|
verifiers/legacy/envs/env_group.py,sha256=xSi__NnqXJadNHvr4sN6_PpJT_k0btfIPaHVtZvzpxw,16713
|
|
28
27
|
verifiers/legacy/envs/environment.py,sha256=HSWOpOSTAqYGi9C2o3C41ZatiLSl07u2RJeZbKodTX4,54179
|
|
@@ -350,8 +349,8 @@ verifiers/v1/utils/prime.py,sha256=UTYRjp9cbjNb6CVmBHda-1wWZAIIfxNOmTyNuT7_wL4,9
|
|
|
350
349
|
verifiers/v1/utils/retries.py,sha256=Y2ZgrAjn-qNkRKZP_RVNL_7EK0iaRcZeCa404lpGYi4,5417
|
|
351
350
|
verifiers/v1/utils/score.py,sha256=493yJVMw8teCu9JxapxMFPFzI0hNUqdo0Y2nGW4kckk,6200
|
|
352
351
|
verifiers/v1/utils/version.py,sha256=-obEo_-l9-D8FLef4hYxncOe-uJpxrM1g2Hig_37Sgs,1607
|
|
353
|
-
verifiers-0.3.2.
|
|
354
|
-
verifiers-0.3.2.
|
|
355
|
-
verifiers-0.3.2.
|
|
356
|
-
verifiers-0.3.2.
|
|
357
|
-
verifiers-0.3.2.
|
|
352
|
+
verifiers-0.3.2.dev20.dist-info/METADATA,sha256=49HaOyD_mcEXTCCsukiR3hBWxEMC1-k7WOluQfDX92M,4555
|
|
353
|
+
verifiers-0.3.2.dev20.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
354
|
+
verifiers-0.3.2.dev20.dist-info/entry_points.txt,sha256=hZ5wDc1T8y-EvOziw7kQqatBJ6PbdSu2ygP5rjANl7c,564
|
|
355
|
+
verifiers-0.3.2.dev20.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
|
|
356
|
+
verifiers-0.3.2.dev20.dist-info/RECORD,,
|
|
@@ -1,677 +0,0 @@
|
|
|
1
|
-
# ruff: noqa
|
|
2
|
-
|
|
3
|
-
"""Renderer-based client.
|
|
4
|
-
|
|
5
|
-
All tokenization happens client-side via a Renderer from the renderers package.
|
|
6
|
-
For multi-turn rollouts, the client preserves exact sampled completion tokens
|
|
7
|
-
and only renders the newly appended environment messages.
|
|
8
|
-
|
|
9
|
-
A shared RendererPool (one per model) offloads sync tokenization to threads so
|
|
10
|
-
concurrent rollouts tokenize in parallel instead of blocking the event loop.
|
|
11
|
-
"""
|
|
12
|
-
|
|
13
|
-
import json
|
|
14
|
-
import threading
|
|
15
|
-
from collections.abc import Mapping
|
|
16
|
-
from typing import Any, ClassVar, cast
|
|
17
|
-
|
|
18
|
-
from openai import AsyncOpenAI
|
|
19
|
-
|
|
20
|
-
from renderers import Message as RendererMessage
|
|
21
|
-
from renderers import OverlongPromptError as RendererOverlongPromptError
|
|
22
|
-
from renderers import (
|
|
23
|
-
MultimodalRenderer,
|
|
24
|
-
ParsedToolCall,
|
|
25
|
-
RenderedTokens,
|
|
26
|
-
Renderer,
|
|
27
|
-
RendererConfig,
|
|
28
|
-
RendererPool,
|
|
29
|
-
ToolSpec,
|
|
30
|
-
create_renderer_pool,
|
|
31
|
-
is_multimodal,
|
|
32
|
-
)
|
|
33
|
-
from renderers import ToolCall as RendererToolCall
|
|
34
|
-
from renderers import ToolCallFunction
|
|
35
|
-
from renderers.client import _maybe_offload, generate
|
|
36
|
-
|
|
37
|
-
from verifiers.legacy.clients.client import Client
|
|
38
|
-
from verifiers.legacy.clients.openai_chat_completions_client import (
|
|
39
|
-
handle_openai_overlong_prompt,
|
|
40
|
-
)
|
|
41
|
-
from verifiers.legacy.errors import EmptyModelResponseError, OverlongPromptError
|
|
42
|
-
from verifiers.legacy.types import (
|
|
43
|
-
AssistantMessage,
|
|
44
|
-
ClientConfig,
|
|
45
|
-
FinishReason,
|
|
46
|
-
Message,
|
|
47
|
-
Messages,
|
|
48
|
-
Response,
|
|
49
|
-
ResponseMessage,
|
|
50
|
-
ResponseTokens,
|
|
51
|
-
SamplingArgs,
|
|
52
|
-
SystemMessage,
|
|
53
|
-
TextMessage,
|
|
54
|
-
Tool,
|
|
55
|
-
ToolCall,
|
|
56
|
-
ToolMessage,
|
|
57
|
-
Usage,
|
|
58
|
-
UserMessage,
|
|
59
|
-
)
|
|
60
|
-
from verifiers.legacy.utils.client_utils import setup_openai_client
|
|
61
|
-
|
|
62
|
-
# Module-level bridge counters. Incremented by every RendererClient instance
|
|
63
|
-
# that tries to stitch a multi-turn prompt; callers (e.g. prime-rl's
|
|
64
|
-
# orchestrator) can read and reset these per training step to surface a
|
|
65
|
-
# bridge_break_rate metric.
|
|
66
|
-
_bridge_metrics_lock = threading.Lock()
|
|
67
|
-
_bridge_metrics: dict[str, int] = {"attempts": 0, "successes": 0, "failures": 0}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
def get_bridge_metrics() -> dict[str, int]:
|
|
71
|
-
"""Snapshot the in-memory bridge counters (attempts/successes/failures)."""
|
|
72
|
-
with _bridge_metrics_lock:
|
|
73
|
-
return dict(_bridge_metrics)
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
def reset_bridge_metrics() -> None:
|
|
77
|
-
"""Zero the in-memory bridge counters."""
|
|
78
|
-
with _bridge_metrics_lock:
|
|
79
|
-
for k in _bridge_metrics:
|
|
80
|
-
_bridge_metrics[k] = 0
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
# Size 1 by default. HF fast tokenizers encode a short chat prompt in a few
|
|
84
|
-
# tens of microseconds, so even 2k rollouts tokenize serially in ~100ms — far
|
|
85
|
-
# cheaper than dispatching each one through asyncio.to_thread and queueing on
|
|
86
|
-
# a multi-slot pool. Larger pools mostly just inflate startup time: each slot
|
|
87
|
-
# instantiates its own AutoTokenizer (300-600ms each, and GIL-bound, so extra
|
|
88
|
-
# workers don't parallelize well). Callers with genuinely long prompts or
|
|
89
|
-
# big tokenizers can bump this per-client.
|
|
90
|
-
_DEFAULT_POOL_SIZE = 1
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
# ── Helpers ─────────────────────────────────────────────────────────
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
def _get_value(obj: Any, key: str, default: Any = None) -> Any:
|
|
97
|
-
if isinstance(obj, Mapping):
|
|
98
|
-
return obj.get(key, default)
|
|
99
|
-
return getattr(obj, key, default)
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
def _chat_template_kwargs_key(
|
|
103
|
-
chat_template_kwargs: Mapping[str, Any] | None,
|
|
104
|
-
) -> str | None:
|
|
105
|
-
if not chat_template_kwargs:
|
|
106
|
-
return None
|
|
107
|
-
return json.dumps(chat_template_kwargs, sort_keys=True, separators=(",", ":"))
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
def _normalize_for_comparison(value: Any, _key: str | None = None) -> Any:
|
|
111
|
-
# tool_call.arguments is serialized as a string on one side (our trajectory
|
|
112
|
-
# uses json.dumps with default separators) and often comes back from
|
|
113
|
-
# upstream scaffolds re-stringified with JS JSON.stringify (compact, no
|
|
114
|
-
# spaces). Both encode the same dict; parse and normalize structurally so
|
|
115
|
-
# pure-format drift doesn't block incremental prompt matching.
|
|
116
|
-
if _key == "arguments" and isinstance(value, str):
|
|
117
|
-
try:
|
|
118
|
-
value = json.loads(value)
|
|
119
|
-
except (json.JSONDecodeError, ValueError):
|
|
120
|
-
pass
|
|
121
|
-
if hasattr(value, "model_dump"):
|
|
122
|
-
return _normalize_for_comparison(value.model_dump(exclude_none=True))
|
|
123
|
-
if isinstance(value, Mapping):
|
|
124
|
-
# Treat content="" as equivalent to content=None (absent): tool-call-only
|
|
125
|
-
# assistant messages get serialized either way depending on the upstream
|
|
126
|
-
# pipeline (e.g., reasoning parsers strip text content to "" while other
|
|
127
|
-
# paths leave it as None), and the prefix-match must be unaffected.
|
|
128
|
-
return {
|
|
129
|
-
str(k): _normalize_for_comparison(v, _key=str(k))
|
|
130
|
-
for k, v in value.items()
|
|
131
|
-
if v is not None and not (str(k) == "content" and v == "")
|
|
132
|
-
}
|
|
133
|
-
if isinstance(value, list):
|
|
134
|
-
return [_normalize_for_comparison(v) for v in value]
|
|
135
|
-
return value
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
def _normalize_content(content: Any) -> Any:
|
|
139
|
-
"""Convert Pydantic content parts to plain dicts."""
|
|
140
|
-
if isinstance(content, list):
|
|
141
|
-
return [
|
|
142
|
-
dict(p)
|
|
143
|
-
if isinstance(p, Mapping)
|
|
144
|
-
else cast(dict, p.model_dump())
|
|
145
|
-
if hasattr(p, "model_dump")
|
|
146
|
-
else p
|
|
147
|
-
for p in content
|
|
148
|
-
]
|
|
149
|
-
return content
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
def _to_renderer_message(message: Message) -> RendererMessage:
|
|
153
|
-
"""Convert a verifiers Message (Pydantic model) to a renderer Message (TypedDict)."""
|
|
154
|
-
if isinstance(message, SystemMessage):
|
|
155
|
-
return RendererMessage(
|
|
156
|
-
role="system", content=_normalize_content(message.content)
|
|
157
|
-
)
|
|
158
|
-
elif isinstance(message, UserMessage):
|
|
159
|
-
return RendererMessage(role="user", content=_normalize_content(message.content))
|
|
160
|
-
elif isinstance(message, AssistantMessage):
|
|
161
|
-
msg = RendererMessage(
|
|
162
|
-
role="assistant",
|
|
163
|
-
content=_normalize_content(message.content),
|
|
164
|
-
)
|
|
165
|
-
if message.reasoning_content is not None:
|
|
166
|
-
msg["reasoning_content"] = message.reasoning_content
|
|
167
|
-
if message.tool_calls is not None:
|
|
168
|
-
msg["tool_calls"] = [
|
|
169
|
-
RendererToolCall(
|
|
170
|
-
type="function",
|
|
171
|
-
id=tc.id,
|
|
172
|
-
function=ToolCallFunction(name=tc.name, arguments=tc.arguments),
|
|
173
|
-
)
|
|
174
|
-
for tc in message.tool_calls
|
|
175
|
-
]
|
|
176
|
-
return msg
|
|
177
|
-
elif isinstance(message, ToolMessage):
|
|
178
|
-
return RendererMessage(
|
|
179
|
-
role="tool",
|
|
180
|
-
content=_normalize_content(message.content),
|
|
181
|
-
tool_call_id=message.tool_call_id,
|
|
182
|
-
)
|
|
183
|
-
elif isinstance(message, TextMessage):
|
|
184
|
-
return RendererMessage(role="user", content=message.content)
|
|
185
|
-
else:
|
|
186
|
-
raise ValueError(f"Unknown message type: {type(message)}")
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
def _attach_tool_call_names(
|
|
190
|
-
messages: list[RendererMessage],
|
|
191
|
-
) -> list[RendererMessage]:
|
|
192
|
-
"""Fill ``name`` on tool-role messages from prior assistant ``tool_calls``.
|
|
193
|
-
|
|
194
|
-
The verifiers ``ToolMessage`` schema has ``role``/``content``/``tool_call_id``
|
|
195
|
-
but no ``name`` field. Some renderers use the function name when emitting
|
|
196
|
-
tool results — notably GPT-OSS Harmony, which prefixes results with
|
|
197
|
-
``<|start|>functions.{name} to=assistant``. Without recovery, every result
|
|
198
|
-
falls back to ``functions.unknown``.
|
|
199
|
-
|
|
200
|
-
We walk the converted-renderer-dict list once, build a ``tool_call_id →
|
|
201
|
-
name`` map from assistant ``tool_calls`` entries, and set ``name`` on
|
|
202
|
-
every subsequent tool message that doesn't already carry one. Validated
|
|
203
|
-
end-to-end on GPT-OSS-20b.
|
|
204
|
-
"""
|
|
205
|
-
lookup: dict[str, str] = {}
|
|
206
|
-
for m in messages:
|
|
207
|
-
role = m.get("role") if isinstance(m, Mapping) else None
|
|
208
|
-
if role == "assistant":
|
|
209
|
-
for tc in m.get("tool_calls") or []:
|
|
210
|
-
if not isinstance(tc, Mapping):
|
|
211
|
-
continue
|
|
212
|
-
tc_id = tc.get("id")
|
|
213
|
-
fn = tc.get("function")
|
|
214
|
-
tc_name = fn.get("name") if isinstance(fn, Mapping) else None
|
|
215
|
-
if isinstance(tc_id, str) and isinstance(tc_name, str):
|
|
216
|
-
lookup[tc_id] = tc_name
|
|
217
|
-
elif role == "tool" and "name" not in m:
|
|
218
|
-
tcid = m.get("tool_call_id")
|
|
219
|
-
if isinstance(tcid, str):
|
|
220
|
-
name = lookup.get(tcid)
|
|
221
|
-
if name is not None:
|
|
222
|
-
m["name"] = name
|
|
223
|
-
return messages
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
def _coerce_renderer_message(message: Any) -> RendererMessage:
|
|
227
|
-
if isinstance(message, Mapping):
|
|
228
|
-
return cast(
|
|
229
|
-
RendererMessage,
|
|
230
|
-
{
|
|
231
|
-
str(k): _normalize_content(v)
|
|
232
|
-
for k, v in message.items()
|
|
233
|
-
if v is not None
|
|
234
|
-
},
|
|
235
|
-
)
|
|
236
|
-
return _to_renderer_message(cast(Message, message))
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
def _is_valid_incremental_tail(messages: list[RendererMessage]) -> bool:
|
|
240
|
-
if not messages:
|
|
241
|
-
return False
|
|
242
|
-
|
|
243
|
-
roles = []
|
|
244
|
-
for message in messages:
|
|
245
|
-
role = _get_value(message, "role")
|
|
246
|
-
roles.append(role if isinstance(role, str) else None)
|
|
247
|
-
if roles[-1] == "user":
|
|
248
|
-
return all(role == "tool" for role in roles[:-1])
|
|
249
|
-
return all(role == "tool" for role in roles)
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
def _step_token_ids(step: Any) -> tuple[list[int], list[int]] | None:
|
|
253
|
-
# Prefer step.tokens (post-parse_response_tokens) when populated. In
|
|
254
|
-
# multi-turn rollouts, parse_response_tokens zeroes out completion_ids
|
|
255
|
-
# whenever prompt_len > max_seq_len (training-budget enforcement) —
|
|
256
|
-
# that destroys the anchor tokens this lookup needs for bridging. Fall
|
|
257
|
-
# back to the raw response tokens in that case so the bridge can
|
|
258
|
-
# continue to chain across turns; interleave_rollout still enforces
|
|
259
|
-
# training budget at sample-assembly time.
|
|
260
|
-
tokens = _get_value(step, "tokens")
|
|
261
|
-
if tokens is not None:
|
|
262
|
-
prompt_ids = _get_value(tokens, "prompt_ids")
|
|
263
|
-
completion_ids = _get_value(tokens, "completion_ids")
|
|
264
|
-
if prompt_ids and completion_ids:
|
|
265
|
-
return list(prompt_ids), list(completion_ids)
|
|
266
|
-
|
|
267
|
-
response = _get_value(step, "response")
|
|
268
|
-
message = _get_value(response, "message")
|
|
269
|
-
raw_tokens = _get_value(message, "tokens")
|
|
270
|
-
if raw_tokens is None:
|
|
271
|
-
return None
|
|
272
|
-
prompt_ids = _get_value(raw_tokens, "prompt_ids")
|
|
273
|
-
completion_ids = _get_value(raw_tokens, "completion_ids")
|
|
274
|
-
if not prompt_ids or not completion_ids:
|
|
275
|
-
return None
|
|
276
|
-
return list(prompt_ids), list(completion_ids)
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
def _step_multi_modal_data(step: Any):
|
|
280
|
-
"""Recover the previous turn's ``MultiModalData`` for bridging.
|
|
281
|
-
|
|
282
|
-
Mirrors :func:`_step_token_ids`: prefer ``step.tokens.multi_modal_data``
|
|
283
|
-
(post-parse_response_tokens), fall back to ``step.response.message.tokens``.
|
|
284
|
-
Returns ``None`` when no multimodal sidecar was emitted (text-only
|
|
285
|
-
rollouts) — the bridge handles that branch transparently.
|
|
286
|
-
"""
|
|
287
|
-
tokens = _get_value(step, "tokens")
|
|
288
|
-
if tokens is not None:
|
|
289
|
-
mm = _get_value(tokens, "multi_modal_data")
|
|
290
|
-
if mm is not None:
|
|
291
|
-
return mm
|
|
292
|
-
|
|
293
|
-
response = _get_value(step, "response")
|
|
294
|
-
message = _get_value(response, "message")
|
|
295
|
-
raw_tokens = _get_value(message, "tokens")
|
|
296
|
-
if raw_tokens is None:
|
|
297
|
-
return None
|
|
298
|
-
return _get_value(raw_tokens, "multi_modal_data")
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
async def _get_incremental_prompt_ids(
|
|
302
|
-
*,
|
|
303
|
-
renderer: Renderer | RendererPool,
|
|
304
|
-
prompt: list[RendererMessage],
|
|
305
|
-
state: Any,
|
|
306
|
-
tools: list[ToolSpec] | None,
|
|
307
|
-
) -> "tuple[RenderedTokens, int] | None":
|
|
308
|
-
"""Return the bridged prompt and routed-experts replay start.
|
|
309
|
-
|
|
310
|
-
Returns ``None`` when no prior trajectory step lines up with the new
|
|
311
|
-
prompt's prefix or the renderer's ``bridge_to_next_turn`` can't extend
|
|
312
|
-
— both cases fall back to a full re-render in :func:`generate`.
|
|
313
|
-
"""
|
|
314
|
-
if not state:
|
|
315
|
-
return None
|
|
316
|
-
|
|
317
|
-
trajectory = _get_value(state, "trajectory")
|
|
318
|
-
if not trajectory:
|
|
319
|
-
return None
|
|
320
|
-
|
|
321
|
-
# Each renderer's bridge_to_next_turn (or the generic fallback) decides
|
|
322
|
-
# how to handle a truncated anchor, so we don't special-case truncation
|
|
323
|
-
# here. When the bridge can't extend (e.g. DefaultRenderer, which
|
|
324
|
-
# doesn't know its template's close), it returns None and the caller
|
|
325
|
-
# falls back to a full re-render — matching main's TITO-on-truncation
|
|
326
|
-
# behavior.
|
|
327
|
-
normalized_prompt = _normalize_for_comparison(prompt)
|
|
328
|
-
for step in reversed(list(trajectory)):
|
|
329
|
-
token_ids = _step_token_ids(step)
|
|
330
|
-
if token_ids is None:
|
|
331
|
-
continue
|
|
332
|
-
|
|
333
|
-
step_prompt = list(_get_value(step, "prompt", []) or [])
|
|
334
|
-
step_completion = list(_get_value(step, "completion", []) or [])
|
|
335
|
-
previous_messages = _attach_tool_call_names(
|
|
336
|
-
[
|
|
337
|
-
_coerce_renderer_message(message)
|
|
338
|
-
for message in step_prompt + step_completion
|
|
339
|
-
]
|
|
340
|
-
)
|
|
341
|
-
if not previous_messages or len(previous_messages) >= len(prompt):
|
|
342
|
-
continue
|
|
343
|
-
prefix_len = len(previous_messages)
|
|
344
|
-
norm_prev = _normalize_for_comparison(previous_messages)
|
|
345
|
-
if normalized_prompt[:prefix_len] != norm_prev:
|
|
346
|
-
continue
|
|
347
|
-
|
|
348
|
-
tail = prompt[prefix_len:]
|
|
349
|
-
if not _is_valid_incremental_tail(tail):
|
|
350
|
-
continue
|
|
351
|
-
|
|
352
|
-
previous_prompt_ids, previous_completion_ids = token_ids
|
|
353
|
-
previous_mm_data = _step_multi_modal_data(step)
|
|
354
|
-
# Multimodal renderers' bridge accepts ``previous_multi_modal_data``
|
|
355
|
-
# so earlier-turn images carry forward into the new prompt's
|
|
356
|
-
# ``mm_placeholders``. Without that carry-forward, vLLM sees
|
|
357
|
-
# placeholder counts that don't match the combined token sequence
|
|
358
|
-
# and silently falls back to hash-cache lookup (or errors).
|
|
359
|
-
# Text-only renderers' bridge signature doesn't include that
|
|
360
|
-
# kwarg. ``is_multimodal`` is type-cached so this dispatch is a
|
|
361
|
-
# dict lookup, not a runtime_checkable Protocol walk.
|
|
362
|
-
if is_multimodal(renderer):
|
|
363
|
-
mm_renderer = cast(MultimodalRenderer, renderer)
|
|
364
|
-
bridge = lambda: mm_renderer.bridge_to_next_turn( # noqa: E731
|
|
365
|
-
previous_prompt_ids,
|
|
366
|
-
previous_completion_ids,
|
|
367
|
-
tail,
|
|
368
|
-
tools=tools,
|
|
369
|
-
previous_multi_modal_data=previous_mm_data,
|
|
370
|
-
)
|
|
371
|
-
else:
|
|
372
|
-
bridge = lambda: renderer.bridge_to_next_turn( # noqa: E731
|
|
373
|
-
previous_prompt_ids,
|
|
374
|
-
previous_completion_ids,
|
|
375
|
-
tail,
|
|
376
|
-
tools=tools,
|
|
377
|
-
)
|
|
378
|
-
bridged = await _maybe_offload(renderer, bridge)
|
|
379
|
-
with _bridge_metrics_lock:
|
|
380
|
-
_bridge_metrics["attempts"] += 1
|
|
381
|
-
_bridge_metrics["successes" if bridged is not None else "failures"] += 1
|
|
382
|
-
if bridged is not None:
|
|
383
|
-
start = max(len(previous_prompt_ids) + len(previous_completion_ids) - 1, 0)
|
|
384
|
-
return bridged, start
|
|
385
|
-
return None
|
|
386
|
-
|
|
387
|
-
return None
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
class RendererClient(
|
|
391
|
-
Client[AsyncOpenAI, list[RendererMessage], dict[str, Any], ToolSpec]
|
|
392
|
-
):
|
|
393
|
-
"""Client that tokenizes prompts client-side via a Renderer.
|
|
394
|
-
|
|
395
|
-
First turn: Renderer renders messages → sends token IDs to vLLM /v1/generate.
|
|
396
|
-
Later turns reuse exact sampled tokens and render only new environment messages.
|
|
397
|
-
|
|
398
|
-
A class-level RendererPool (keyed by model) is shared across all instances
|
|
399
|
-
so that concurrent rollouts tokenize in parallel threads.
|
|
400
|
-
"""
|
|
401
|
-
|
|
402
|
-
# Cache key is ``(renderer_model_name, pool_size, renderer_config_json,
|
|
403
|
-
# chat_template_kwargs_json)``. Renderers owns the concrete config
|
|
404
|
-
# resolution; verifiers only separates pools whose construction inputs differ.
|
|
405
|
-
_shared_pools: ClassVar[
|
|
406
|
-
dict[
|
|
407
|
-
tuple[str, int, str | None, str | None],
|
|
408
|
-
RendererPool,
|
|
409
|
-
]
|
|
410
|
-
] = {}
|
|
411
|
-
_shared_pools_lock: ClassVar[threading.Lock] = threading.Lock()
|
|
412
|
-
|
|
413
|
-
def __init__(
|
|
414
|
-
self,
|
|
415
|
-
config: ClientConfig,
|
|
416
|
-
renderer: Renderer | None = None,
|
|
417
|
-
pool_size: int = _DEFAULT_POOL_SIZE,
|
|
418
|
-
):
|
|
419
|
-
super().__init__(config)
|
|
420
|
-
self._renderer = renderer
|
|
421
|
-
# ClientConfig.renderer_pool_size wins over the constructor default so
|
|
422
|
-
# callers can tune pool size via config without subclassing.
|
|
423
|
-
cfg_size = getattr(config, "renderer_pool_size", None)
|
|
424
|
-
self._pool_size = cfg_size if cfg_size is not None else pool_size
|
|
425
|
-
|
|
426
|
-
def setup_client(self, config: ClientConfig) -> AsyncOpenAI:
|
|
427
|
-
return setup_openai_client(config)
|
|
428
|
-
|
|
429
|
-
async def close(self) -> None:
|
|
430
|
-
await self.client.close()
|
|
431
|
-
|
|
432
|
-
# ── Renderer management ─────────────────────────────────────────
|
|
433
|
-
|
|
434
|
-
def _get_renderer_or_pool(
|
|
435
|
-
self,
|
|
436
|
-
model: str,
|
|
437
|
-
*,
|
|
438
|
-
renderer_config: RendererConfig | None = None,
|
|
439
|
-
chat_template_kwargs: Mapping[str, Any] | None = None,
|
|
440
|
-
) -> Renderer | RendererPool:
|
|
441
|
-
if self._renderer is not None:
|
|
442
|
-
return self._renderer
|
|
443
|
-
|
|
444
|
-
if renderer_config is None:
|
|
445
|
-
renderer_config = (
|
|
446
|
-
self._config.renderer_config if self._config is not None else None
|
|
447
|
-
)
|
|
448
|
-
renderer_model = (
|
|
449
|
-
self._config.renderer_model_name
|
|
450
|
-
if self._config is not None and self._config.renderer_model_name is not None
|
|
451
|
-
else model
|
|
452
|
-
)
|
|
453
|
-
cfg_key = (
|
|
454
|
-
renderer_config.model_dump_json() if renderer_config is not None else None
|
|
455
|
-
)
|
|
456
|
-
kwargs_key = _chat_template_kwargs_key(chat_template_kwargs)
|
|
457
|
-
cache_key = (renderer_model, self._pool_size, cfg_key, kwargs_key)
|
|
458
|
-
|
|
459
|
-
with self._shared_pools_lock:
|
|
460
|
-
if cache_key not in self._shared_pools:
|
|
461
|
-
pool_kwargs: dict[str, Any] = {"size": self._pool_size}
|
|
462
|
-
if chat_template_kwargs:
|
|
463
|
-
pool_kwargs["chat_template_kwargs"] = chat_template_kwargs
|
|
464
|
-
self._shared_pools[cache_key] = create_renderer_pool(
|
|
465
|
-
renderer_model,
|
|
466
|
-
renderer_config,
|
|
467
|
-
**pool_kwargs,
|
|
468
|
-
)
|
|
469
|
-
|
|
470
|
-
return self._shared_pools[cache_key]
|
|
471
|
-
|
|
472
|
-
# ── Type conversions ────────────────────────────────────────────
|
|
473
|
-
|
|
474
|
-
async def to_native_prompt(
|
|
475
|
-
self, messages: Messages
|
|
476
|
-
) -> tuple[list[RendererMessage], dict]:
|
|
477
|
-
return (
|
|
478
|
-
_attach_tool_call_names([_to_renderer_message(m) for m in messages]),
|
|
479
|
-
{},
|
|
480
|
-
)
|
|
481
|
-
|
|
482
|
-
async def to_native_tool(self, tool: Tool) -> ToolSpec:
|
|
483
|
-
function: dict[str, Any] = {
|
|
484
|
-
"name": tool.name,
|
|
485
|
-
"description": tool.description,
|
|
486
|
-
"parameters": tool.parameters,
|
|
487
|
-
}
|
|
488
|
-
if tool.strict is not None:
|
|
489
|
-
function["strict"] = tool.strict
|
|
490
|
-
return cast(ToolSpec, {"type": "function", "function": function})
|
|
491
|
-
|
|
492
|
-
# ── Core request cycle ──────────────────────────────────────────
|
|
493
|
-
|
|
494
|
-
@handle_openai_overlong_prompt
|
|
495
|
-
async def get_native_response(
|
|
496
|
-
self,
|
|
497
|
-
prompt: list[RendererMessage],
|
|
498
|
-
model: str,
|
|
499
|
-
sampling_args: SamplingArgs,
|
|
500
|
-
tools: list[ToolSpec] | None = None,
|
|
501
|
-
**kwargs: Any,
|
|
502
|
-
) -> dict[str, Any]:
|
|
503
|
-
args = dict(sampling_args)
|
|
504
|
-
extra_headers = {
|
|
505
|
-
**dict(args.pop("extra_headers", None) or {}),
|
|
506
|
-
**dict(kwargs.pop("extra_headers", None) or {}),
|
|
507
|
-
}
|
|
508
|
-
sampling_params: dict[str, Any] = dict(args.pop("extra_body", None) or {})
|
|
509
|
-
|
|
510
|
-
# ``chat_template_kwargs`` belong to the renderer, not the engine.
|
|
511
|
-
# Renderers owns resolving them against the concrete chat template;
|
|
512
|
-
# verifiers only routes them into pool construction.
|
|
513
|
-
chat_template_kwargs = sampling_params.pop("chat_template_kwargs", None)
|
|
514
|
-
renderer = self._get_renderer_or_pool(
|
|
515
|
-
model,
|
|
516
|
-
chat_template_kwargs=chat_template_kwargs,
|
|
517
|
-
)
|
|
518
|
-
|
|
519
|
-
for key in (
|
|
520
|
-
"temperature",
|
|
521
|
-
"top_p",
|
|
522
|
-
"top_k",
|
|
523
|
-
"min_p",
|
|
524
|
-
"seed",
|
|
525
|
-
"n",
|
|
526
|
-
"repetition_penalty",
|
|
527
|
-
"min_tokens",
|
|
528
|
-
):
|
|
529
|
-
if args.get(key) is not None:
|
|
530
|
-
sampling_params[key] = args[key]
|
|
531
|
-
max_tokens = args.get("max_tokens") or args.get("max_completion_tokens")
|
|
532
|
-
if max_tokens is not None:
|
|
533
|
-
sampling_params["max_tokens"] = max_tokens
|
|
534
|
-
if args.get("prompt_logprobs"):
|
|
535
|
-
sampling_params["prompt_logprobs"] = 1
|
|
536
|
-
|
|
537
|
-
bridged_with_start = await _get_incremental_prompt_ids(
|
|
538
|
-
renderer=renderer,
|
|
539
|
-
prompt=prompt,
|
|
540
|
-
state=kwargs.get("state"),
|
|
541
|
-
tools=tools,
|
|
542
|
-
)
|
|
543
|
-
# ``bridged_with_start`` is (RenderedTokens, replay_start) | None.
|
|
544
|
-
# Unpack token_ids + mm_data (multimodal feature pass-through) and
|
|
545
|
-
# prompt_attribution (per-token mask sidecar). On the first turn
|
|
546
|
-
# (``bridged_with_start is None``), ``generate`` renders and emits the
|
|
547
|
-
# attribution itself.
|
|
548
|
-
if bridged_with_start is not None:
|
|
549
|
-
bridged, routed_experts_prompt_start = bridged_with_start
|
|
550
|
-
prompt_ids = bridged.token_ids
|
|
551
|
-
multi_modal_data = bridged.multi_modal_data
|
|
552
|
-
prompt_attribution = bridged
|
|
553
|
-
sampling_params["routed_experts_prompt_start"] = routed_experts_prompt_start
|
|
554
|
-
else:
|
|
555
|
-
prompt_ids = None
|
|
556
|
-
multi_modal_data = None
|
|
557
|
-
prompt_attribution = None
|
|
558
|
-
|
|
559
|
-
# ``renderers.client.generate`` discovers the engine's context-length
|
|
560
|
-
# cap on its own (via ``GET /v1/models``, cached) and raises
|
|
561
|
-
# ``renderers.OverlongPromptError`` on pre-flight overflow. Rebadge
|
|
562
|
-
# that into the verifiers-native ``OverlongPromptError`` so the
|
|
563
|
-
# ``MultiTurnEnv.prompt_too_long`` stop condition picks it up via
|
|
564
|
-
# the ``vf.Error`` hierarchy. The ``@handle_openai_overlong_prompt``
|
|
565
|
-
# decorator still handles the fallback case (cap unknown → engine
|
|
566
|
-
# 4xx → vf.OverlongPromptError) for engines whose ``/v1/models``
|
|
567
|
-
# doesn't expose ``max_model_len``.
|
|
568
|
-
try:
|
|
569
|
-
return await generate(
|
|
570
|
-
client=self.client,
|
|
571
|
-
renderer=renderer,
|
|
572
|
-
messages=prompt,
|
|
573
|
-
model=model,
|
|
574
|
-
prompt_ids=prompt_ids,
|
|
575
|
-
multi_modal_data=multi_modal_data,
|
|
576
|
-
prompt_attribution=prompt_attribution,
|
|
577
|
-
tools=tools,
|
|
578
|
-
sampling_params=sampling_params,
|
|
579
|
-
cache_salt=args.get("cache_salt")
|
|
580
|
-
or sampling_params.pop("cache_salt", None),
|
|
581
|
-
priority=args.get("priority") or sampling_params.pop("priority", None),
|
|
582
|
-
extra_headers=extra_headers or None,
|
|
583
|
-
)
|
|
584
|
-
except RendererOverlongPromptError as exc:
|
|
585
|
-
raise OverlongPromptError(str(exc)) from exc
|
|
586
|
-
|
|
587
|
-
async def raise_from_native_response(self, response: dict[str, Any]) -> None:
|
|
588
|
-
if response is None:
|
|
589
|
-
raise EmptyModelResponseError("Model returned no response")
|
|
590
|
-
|
|
591
|
-
has_content = bool(response.get("content"))
|
|
592
|
-
# ``tool_calls`` is now ``list[ParsedToolCall]`` (renderers >=0.1.8.dev1)
|
|
593
|
-
# — a non-empty list with only malformed attempts still counts as the
|
|
594
|
-
# model having tried to call a tool, so we don't filter by status here.
|
|
595
|
-
has_tool_calls = bool(response.get("tool_calls"))
|
|
596
|
-
has_reasoning = bool(response.get("reasoning_content"))
|
|
597
|
-
if not (has_content or has_tool_calls or has_reasoning):
|
|
598
|
-
raise EmptyModelResponseError(
|
|
599
|
-
"Model returned no content and did not call any tools"
|
|
600
|
-
)
|
|
601
|
-
|
|
602
|
-
async def from_native_response(self, response: dict[str, Any]) -> Response:
|
|
603
|
-
"""Parse the generate() result dict into a verifiers Response."""
|
|
604
|
-
content = response.get("content", "")
|
|
605
|
-
reasoning_content = response.get("reasoning_content")
|
|
606
|
-
match response.get("finish_reason"):
|
|
607
|
-
case "stop":
|
|
608
|
-
finish_reason: FinishReason = "stop"
|
|
609
|
-
case "length":
|
|
610
|
-
finish_reason = "length"
|
|
611
|
-
case "tool_calls":
|
|
612
|
-
finish_reason = "tool_calls"
|
|
613
|
-
case _:
|
|
614
|
-
finish_reason = None
|
|
615
|
-
|
|
616
|
-
# Forward any ``ParsedToolCall`` with a ``name`` regardless of
|
|
617
|
-
# ``.status``: argument errors surface to the model as tool-role
|
|
618
|
-
# validation messages via the env's ``call_tool`` for self-
|
|
619
|
-
# correction, instead of an empty ``tool_calls`` that terminates
|
|
620
|
-
# the rollout via ``no_tools_called``. ``status`` stays on each
|
|
621
|
-
# call for downstream filtering.
|
|
622
|
-
tool_calls = None
|
|
623
|
-
raw_tcs = response.get("tool_calls") or []
|
|
624
|
-
usable_tcs = [
|
|
625
|
-
tc for tc in raw_tcs if isinstance(tc, ParsedToolCall) and tc.name
|
|
626
|
-
]
|
|
627
|
-
if usable_tcs:
|
|
628
|
-
tool_calls = [
|
|
629
|
-
ToolCall(
|
|
630
|
-
id=tc.id or f"call_{i}",
|
|
631
|
-
name=tc.name or "",
|
|
632
|
-
arguments=(
|
|
633
|
-
tc.arguments
|
|
634
|
-
if isinstance(tc.arguments, str)
|
|
635
|
-
else json.dumps(tc.arguments or {})
|
|
636
|
-
),
|
|
637
|
-
)
|
|
638
|
-
for i, tc in enumerate(usable_tcs)
|
|
639
|
-
]
|
|
640
|
-
|
|
641
|
-
prompt_ids = response.get("prompt_ids", [])
|
|
642
|
-
completion_ids = response.get("completion_ids", [])
|
|
643
|
-
completion_logprobs = response.get("completion_logprobs", [])
|
|
644
|
-
|
|
645
|
-
tokens = ResponseTokens(
|
|
646
|
-
prompt_ids=prompt_ids,
|
|
647
|
-
prompt_mask=[0] * len(prompt_ids),
|
|
648
|
-
completion_ids=completion_ids,
|
|
649
|
-
completion_mask=[1] * len(completion_ids),
|
|
650
|
-
completion_logprobs=completion_logprobs,
|
|
651
|
-
routed_experts=response.get("routed_experts"),
|
|
652
|
-
multi_modal_data=response.get("multi_modal_data"),
|
|
653
|
-
prompt_attribution=response.get("prompt_attribution"),
|
|
654
|
-
)
|
|
655
|
-
|
|
656
|
-
# /inference/v1/generate doesn't return usage; reconstruct from tokens.
|
|
657
|
-
usage = Usage(
|
|
658
|
-
prompt_tokens=len(prompt_ids),
|
|
659
|
-
reasoning_tokens=0,
|
|
660
|
-
completion_tokens=len(completion_ids),
|
|
661
|
-
total_tokens=len(prompt_ids) + len(completion_ids),
|
|
662
|
-
)
|
|
663
|
-
|
|
664
|
-
return Response(
|
|
665
|
-
id=response.get("request_id", ""),
|
|
666
|
-
created=0,
|
|
667
|
-
model="",
|
|
668
|
-
usage=usage,
|
|
669
|
-
message=ResponseMessage(
|
|
670
|
-
content=content,
|
|
671
|
-
reasoning_content=reasoning_content,
|
|
672
|
-
finish_reason=finish_reason,
|
|
673
|
-
is_truncated=finish_reason == "length",
|
|
674
|
-
tokens=tokens,
|
|
675
|
-
tool_calls=tool_calls,
|
|
676
|
-
),
|
|
677
|
-
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|