verifiers 0.3.2.dev20__py3-none-any.whl → 0.3.2.dev21__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/v1/harnesses/bash/harness.py +17 -38
- verifiers/v1/harnesses/browser_use/harness.py +17 -35
- verifiers/v1/harnesses/browser_use/program.py +4 -116
- verifiers/v1/harnesses/minimal/__init__.py +9 -0
- verifiers/v1/harnesses/{bash → minimal}/program.py +47 -127
- verifiers/v1/harnesses/null/harness.py +13 -41
- verifiers/v1/harnesses/standalone.py +74 -0
- verifiers/v1/mcp/__init__.py +12 -0
- verifiers/v1/mcp/client.py +127 -0
- verifiers/v1/tasksets/nemo_gym/toolset.py +17 -23
- {verifiers-0.3.2.dev20.dist-info → verifiers-0.3.2.dev21.dist-info}/METADATA +1 -1
- {verifiers-0.3.2.dev20.dist-info → verifiers-0.3.2.dev21.dist-info}/RECORD +15 -13
- verifiers/v1/harnesses/null/program.py +0 -258
- {verifiers-0.3.2.dev20.dist-info → verifiers-0.3.2.dev21.dist-info}/WHEEL +0 -0
- {verifiers-0.3.2.dev20.dist-info → verifiers-0.3.2.dev21.dist-info}/entry_points.txt +0 -0
- {verifiers-0.3.2.dev20.dist-info → verifiers-0.3.2.dev21.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,17 +1,14 @@
|
|
|
1
|
-
import json
|
|
2
1
|
import os
|
|
3
|
-
from pathlib import Path
|
|
4
2
|
|
|
5
3
|
from verifiers.v1.clients import ModelContext
|
|
6
4
|
from verifiers.v1.configs.harness import HarnessConfig
|
|
7
|
-
from verifiers.v1.dialects.chat import message_to_wire
|
|
8
5
|
from verifiers.v1.harness import Harness
|
|
6
|
+
from verifiers.v1.harnesses.minimal import PROGRAM_SOURCE
|
|
7
|
+
from verifiers.v1.harnesses.standalone import launch_chat_program
|
|
9
8
|
from verifiers.v1.runtimes import ProgramResult, Runtime
|
|
10
9
|
from verifiers.v1.task import TaskData
|
|
11
10
|
from verifiers.v1.trace import Trace
|
|
12
11
|
|
|
13
|
-
PROGRAM_SOURCE = (Path(__file__).resolve().parent / "program.py").read_text()
|
|
14
|
-
|
|
15
12
|
# Frames the model as a coding agent and names its local tools (a pure-text chat loop gets no
|
|
16
13
|
# harness-injected prompt). The edit clause is appended only when the `edit` tool is enabled.
|
|
17
14
|
BASH_SYSTEM_PROMPT = (
|
|
@@ -69,12 +66,7 @@ class BashHarness(Harness[BashHarnessConfig]):
|
|
|
69
66
|
p for p in (" ".join(fragments), system_prompt) if p
|
|
70
67
|
)
|
|
71
68
|
env = {**self.config.resolved_env}
|
|
72
|
-
args = [
|
|
73
|
-
f"--base-url={endpoint}",
|
|
74
|
-
f"--api-key={secret}",
|
|
75
|
-
f"--model={ctx.model}",
|
|
76
|
-
f"--system-prompt={system_prompt}",
|
|
77
|
-
]
|
|
69
|
+
args = ["--bash"]
|
|
78
70
|
if tool_interception_url:
|
|
79
71
|
args.append(f"--tool-interception-url={tool_interception_url}")
|
|
80
72
|
if self.config.edit:
|
|
@@ -97,31 +89,18 @@ class BashHarness(Harness[BashHarnessConfig]):
|
|
|
97
89
|
"(the host env or the harness config's env)"
|
|
98
90
|
)
|
|
99
91
|
args += ["--search", f"--serper-key={serper_key}"]
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
if isinstance(prompt, str):
|
|
115
|
-
args.append(f"--prompt={prompt}")
|
|
116
|
-
elif prompt is not None:
|
|
117
|
-
# Base64 images can exceed exec limits, so hand Messages off through a file.
|
|
118
|
-
path = f".vf-initial-messages-{trace.id}.json"
|
|
119
|
-
await runtime.write(
|
|
120
|
-
path,
|
|
121
|
-
json.dumps([message_to_wire(m) for m in prompt]).encode(),
|
|
122
|
-
)
|
|
123
|
-
args.append(f"--initial-messages-file={path}")
|
|
124
|
-
program = await runtime.prepare_uv_script(
|
|
125
|
-
PROGRAM_SOURCE, self.config.resolved_env, activate=False
|
|
92
|
+
return await launch_chat_program(
|
|
93
|
+
PROGRAM_SOURCE,
|
|
94
|
+
self.config,
|
|
95
|
+
ctx,
|
|
96
|
+
trace,
|
|
97
|
+
runtime,
|
|
98
|
+
endpoint,
|
|
99
|
+
secret,
|
|
100
|
+
mcp_urls,
|
|
101
|
+
system_prompt,
|
|
102
|
+
prompt,
|
|
103
|
+
extra_args=args,
|
|
104
|
+
env=env,
|
|
105
|
+
activate=False,
|
|
126
106
|
)
|
|
127
|
-
return await runtime.run_program([*program, *args], env)
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import json
|
|
2
1
|
from pathlib import Path
|
|
3
2
|
from typing import Literal
|
|
4
3
|
|
|
@@ -6,13 +5,15 @@ from pydantic import model_validator
|
|
|
6
5
|
|
|
7
6
|
from verifiers.v1.clients import ModelContext
|
|
8
7
|
from verifiers.v1.configs.harness import HarnessConfig
|
|
9
|
-
from verifiers.v1.dialects.chat import message_to_wire
|
|
10
8
|
from verifiers.v1.harness import Harness
|
|
9
|
+
from verifiers.v1.harnesses.standalone import inline_mcp_client, launch_chat_program
|
|
11
10
|
from verifiers.v1.runtimes import ProgramResult, Runtime
|
|
12
11
|
from verifiers.v1.task import TaskData
|
|
13
12
|
from verifiers.v1.trace import Trace
|
|
14
13
|
|
|
15
|
-
PROGRAM_SOURCE = (
|
|
14
|
+
PROGRAM_SOURCE = inline_mcp_client(
|
|
15
|
+
(Path(__file__).resolve().parent / "program.py").read_text()
|
|
16
|
+
)
|
|
16
17
|
|
|
17
18
|
# The helper names and persistence rules the model needs to use the local tool.
|
|
18
19
|
BROWSER_SYSTEM_PROMPT = """You are a browser automation agent. Your `browser` tool executes Python code that controls a real Chromium over CDP through browser-harness; its helpers are pre-imported.
|
|
@@ -85,42 +86,23 @@ class BrowserUseHarness(Harness[BrowserUseHarnessConfig]):
|
|
|
85
86
|
env = {**self.config.resolved_env}
|
|
86
87
|
state = f".vf-browser-{trace.id}"
|
|
87
88
|
args = [
|
|
88
|
-
f"--base-url={endpoint}",
|
|
89
|
-
f"--api-key={secret}",
|
|
90
|
-
f"--model={ctx.model}",
|
|
91
89
|
f"--browser={self.config.browser}",
|
|
92
90
|
# A resumed segment reuses this trace's browser and profile.
|
|
93
91
|
f"--state-dir={state}",
|
|
94
92
|
]
|
|
95
|
-
if not replaying_browser_prompt:
|
|
96
|
-
args.append(f"--system-prompt={system_prompt}")
|
|
97
93
|
if self.config.cdp_url:
|
|
98
94
|
args.append(f"--cdp-url={self.config.cdp_url}")
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
)
|
|
113
|
-
if isinstance(prompt, str):
|
|
114
|
-
args.append(f"--prompt={prompt}")
|
|
115
|
-
elif prompt is not None:
|
|
116
|
-
# Base64 images can exceed exec limits, so hand Messages off through a file.
|
|
117
|
-
path = f".vf-initial-messages-{trace.id}.json"
|
|
118
|
-
await runtime.write(
|
|
119
|
-
path,
|
|
120
|
-
json.dumps([message_to_wire(m) for m in prompt]).encode(),
|
|
121
|
-
)
|
|
122
|
-
args.append(f"--initial-messages-file={path}")
|
|
123
|
-
program = await runtime.prepare_uv_script(
|
|
124
|
-
PROGRAM_SOURCE, self.config.resolved_env
|
|
95
|
+
return await launch_chat_program(
|
|
96
|
+
PROGRAM_SOURCE,
|
|
97
|
+
self.config,
|
|
98
|
+
ctx,
|
|
99
|
+
trace,
|
|
100
|
+
runtime,
|
|
101
|
+
endpoint,
|
|
102
|
+
secret,
|
|
103
|
+
mcp_urls,
|
|
104
|
+
None if replaying_browser_prompt else system_prompt,
|
|
105
|
+
prompt,
|
|
106
|
+
extra_args=args,
|
|
107
|
+
env=env,
|
|
125
108
|
)
|
|
126
|
-
return await runtime.run_program([*program, *args], env)
|
|
@@ -27,16 +27,15 @@ import subprocess
|
|
|
27
27
|
import sys
|
|
28
28
|
import time
|
|
29
29
|
import urllib.request
|
|
30
|
-
from contextlib import AsyncExitStack, asynccontextmanager, suppress
|
|
31
30
|
from pathlib import Path
|
|
32
|
-
from typing import Any, cast
|
|
31
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
33
32
|
from urllib.parse import urlsplit
|
|
34
33
|
|
|
35
34
|
from openai import AsyncOpenAI
|
|
36
|
-
from tenacity import AsyncRetrying, stop_after_attempt, wait_exponential_jitter
|
|
37
35
|
|
|
38
|
-
|
|
39
|
-
|
|
36
|
+
if TYPE_CHECKING:
|
|
37
|
+
# The harness bundles this module into the generated script before execution.
|
|
38
|
+
from verifiers.v1.mcp.client import call_mcp, connect_mcp # noqa: TC004
|
|
40
39
|
|
|
41
40
|
BROWSER_TOOL_TIMEOUT = 3600
|
|
42
41
|
"""Matches the bash harness's command timeout."""
|
|
@@ -187,117 +186,6 @@ async def chat(
|
|
|
187
186
|
return completion.choices[0].message
|
|
188
187
|
|
|
189
188
|
|
|
190
|
-
@asynccontextmanager
|
|
191
|
-
async def mcp_client(spec: dict):
|
|
192
|
-
"""One fresh MCP client, negotiating the newest protocol and falling back for old servers.
|
|
193
|
-
|
|
194
|
-
It is opened and closed within the caller's task so AnyIO cancellation scopes stay correctly
|
|
195
|
-
nested. Closing noise after a completed body cannot fail or replay an answered call.
|
|
196
|
-
"""
|
|
197
|
-
import httpx2
|
|
198
|
-
from mcp import Client
|
|
199
|
-
from mcp.client.streamable_http import (
|
|
200
|
-
create_mcp_http_client,
|
|
201
|
-
streamable_http_client,
|
|
202
|
-
)
|
|
203
|
-
|
|
204
|
-
stack = AsyncExitStack()
|
|
205
|
-
try:
|
|
206
|
-
http_client = await stack.enter_async_context(
|
|
207
|
-
create_mcp_http_client(
|
|
208
|
-
headers=spec.get("headers") or None,
|
|
209
|
-
timeout=httpx2.Timeout(spec.get("timeout", MCP_TIMEOUT), connect=5.0),
|
|
210
|
-
)
|
|
211
|
-
)
|
|
212
|
-
transport = streamable_http_client(spec["url"], http_client=http_client)
|
|
213
|
-
yield await stack.enter_async_context(Client(transport))
|
|
214
|
-
finally:
|
|
215
|
-
with suppress(Exception):
|
|
216
|
-
await stack.aclose()
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
async def with_retry(call):
|
|
220
|
-
"""Run one client operation, retrying transient failures with backoff. A call whose
|
|
221
|
-
response was lost may be replayed — MCP has no idempotency key, so tools should tolerate
|
|
222
|
-
at-least-once delivery (a tool that fails reports through its result, not an exception)."""
|
|
223
|
-
async for attempt in AsyncRetrying(
|
|
224
|
-
stop=stop_after_attempt(MCP_CALL_ATTEMPTS),
|
|
225
|
-
wait=wait_exponential_jitter(initial=0.5, max=30),
|
|
226
|
-
reraise=True,
|
|
227
|
-
):
|
|
228
|
-
with attempt:
|
|
229
|
-
return await call()
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
async def connect_mcp(
|
|
233
|
-
config: dict, reserved: set[str]
|
|
234
|
-
) -> tuple[list[dict], dict, dict]:
|
|
235
|
-
"""Enumerate each configured MCP server's tools (a streamable-HTTP `url`); return (tool schemas,
|
|
236
|
-
dispatch mapping `<server>_<tool>` -> (server name, raw tool name), servers mapping name -> spec).
|
|
237
|
-
No protocol session is held; a fresh client handles each call."""
|
|
238
|
-
tool_schemas: list[dict] = []
|
|
239
|
-
dispatch: dict[str, tuple] = {}
|
|
240
|
-
servers: dict[str, dict] = {}
|
|
241
|
-
for name, spec in config.get("mcpServers", {}).items():
|
|
242
|
-
servers[name] = spec
|
|
243
|
-
|
|
244
|
-
async def list_tools(spec: dict = spec):
|
|
245
|
-
async with mcp_client(spec) as client:
|
|
246
|
-
return (await client.list_tools()).tools
|
|
247
|
-
|
|
248
|
-
for tool in await with_retry(list_tools):
|
|
249
|
-
# A server named "" (TOOL_PREFIX = None) advertises its tools bare.
|
|
250
|
-
full = f"{name}_{tool.name}" if name else tool.name
|
|
251
|
-
if full in reserved or full in dispatch:
|
|
252
|
-
raise ValueError(
|
|
253
|
-
f"duplicate tool name {full!r}; keep MCP tool names qualified"
|
|
254
|
-
)
|
|
255
|
-
tool_schemas.append(
|
|
256
|
-
{
|
|
257
|
-
"type": "function",
|
|
258
|
-
"function": {
|
|
259
|
-
"name": full,
|
|
260
|
-
"description": tool.description or "",
|
|
261
|
-
"parameters": tool.input_schema,
|
|
262
|
-
},
|
|
263
|
-
}
|
|
264
|
-
)
|
|
265
|
-
dispatch[full] = (name, tool.name)
|
|
266
|
-
return tool_schemas, dispatch, servers
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
def mcp_content_to_chat_content(blocks) -> str | list[dict]:
|
|
270
|
-
parts = []
|
|
271
|
-
for block in blocks:
|
|
272
|
-
if block.type == "text":
|
|
273
|
-
parts.append({"type": "text", "text": block.text})
|
|
274
|
-
elif block.type == "image":
|
|
275
|
-
url = f"data:{block.mime_type};base64,{block.data}"
|
|
276
|
-
parts.append({"type": "image_url", "image_url": {"url": url}})
|
|
277
|
-
else:
|
|
278
|
-
parts.append({"type": "text", "text": str(block)})
|
|
279
|
-
if not parts:
|
|
280
|
-
return str(blocks)
|
|
281
|
-
if all(part["type"] == "text" for part in parts):
|
|
282
|
-
return "\n".join(str(part["text"]) for part in parts)
|
|
283
|
-
return parts
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
async def call_mcp(
|
|
287
|
-
servers: dict, dispatch: dict, name: str, arguments: dict
|
|
288
|
-
) -> str | list[dict]:
|
|
289
|
-
"""Call a tool with a fresh client per attempt — see `with_retry` for replay semantics.
|
|
290
|
-
The result is converted outside the retry so a conversion failure fails once."""
|
|
291
|
-
server_name, raw = dispatch[name]
|
|
292
|
-
|
|
293
|
-
async def call():
|
|
294
|
-
async with mcp_client(servers[server_name]) as client:
|
|
295
|
-
return await client.call_tool(raw, arguments)
|
|
296
|
-
|
|
297
|
-
result = await with_retry(call)
|
|
298
|
-
return mcp_content_to_chat_content(result.content)
|
|
299
|
-
|
|
300
|
-
|
|
301
189
|
def parse_args() -> argparse.Namespace:
|
|
302
190
|
parser = argparse.ArgumentParser()
|
|
303
191
|
parser.add_argument("--base-url", required=True)
|
|
@@ -2,23 +2,42 @@
|
|
|
2
2
|
# requires-python = ">=3.10"
|
|
3
3
|
# dependencies = ["openai", "mcp==2.0.0", "httpx", "httpx2", "tenacity"]
|
|
4
4
|
# ///
|
|
5
|
-
"""
|
|
5
|
+
"""Shared Null/Bash chat program; secrets use argv so tools do not inherit them."""
|
|
6
6
|
|
|
7
7
|
import argparse
|
|
8
8
|
import asyncio
|
|
9
9
|
import json
|
|
10
10
|
import subprocess
|
|
11
|
-
from contextlib import AsyncExitStack, asynccontextmanager, suppress
|
|
12
11
|
from pathlib import Path
|
|
12
|
+
from typing import TYPE_CHECKING
|
|
13
13
|
|
|
14
14
|
import httpx
|
|
15
|
-
from openai import AsyncOpenAI
|
|
16
|
-
|
|
15
|
+
from openai import APIStatusError, AsyncOpenAI
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
# The harness bundles this module into the generated script before execution.
|
|
19
|
+
from verifiers.v1.mcp.client import call_mcp, connect_mcp # noqa: TC004
|
|
17
20
|
|
|
18
21
|
SERPER_URL = "https://google.serper.dev/search"
|
|
19
22
|
|
|
20
|
-
|
|
21
|
-
|
|
23
|
+
CONTEXT_OVERFLOW_MARKERS = (
|
|
24
|
+
"context_length_exceeded",
|
|
25
|
+
"exceeds the context window",
|
|
26
|
+
"reduce the length of the messages",
|
|
27
|
+
"maximum context length",
|
|
28
|
+
"prompt is too long",
|
|
29
|
+
"request_too_large",
|
|
30
|
+
"request entity too large",
|
|
31
|
+
"exceeds the maximum number of tokens",
|
|
32
|
+
"maximum prompt length is",
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def is_context_overflow(error: APIStatusError) -> bool:
|
|
37
|
+
details = f"{error} {error.body or ''}".casefold()
|
|
38
|
+
return error.status_code in (400, 413) and any(
|
|
39
|
+
marker in details for marker in CONTEXT_OVERFLOW_MARKERS
|
|
40
|
+
)
|
|
22
41
|
|
|
23
42
|
|
|
24
43
|
BASH_TOOL = {
|
|
@@ -186,117 +205,6 @@ async def chat(
|
|
|
186
205
|
return completion.choices[0].message
|
|
187
206
|
|
|
188
207
|
|
|
189
|
-
@asynccontextmanager
|
|
190
|
-
async def mcp_client(spec: dict):
|
|
191
|
-
"""One fresh MCP client, negotiating the newest protocol and falling back for old servers.
|
|
192
|
-
|
|
193
|
-
It is opened and closed within the caller's task so AnyIO cancellation scopes stay correctly
|
|
194
|
-
nested. Closing noise after a completed body cannot fail or replay an answered call.
|
|
195
|
-
"""
|
|
196
|
-
import httpx2
|
|
197
|
-
from mcp import Client
|
|
198
|
-
from mcp.client.streamable_http import (
|
|
199
|
-
create_mcp_http_client,
|
|
200
|
-
streamable_http_client,
|
|
201
|
-
)
|
|
202
|
-
|
|
203
|
-
stack = AsyncExitStack()
|
|
204
|
-
try:
|
|
205
|
-
http_client = await stack.enter_async_context(
|
|
206
|
-
create_mcp_http_client(
|
|
207
|
-
headers=spec.get("headers") or None,
|
|
208
|
-
timeout=httpx2.Timeout(spec.get("timeout", MCP_TIMEOUT), connect=5.0),
|
|
209
|
-
)
|
|
210
|
-
)
|
|
211
|
-
transport = streamable_http_client(spec["url"], http_client=http_client)
|
|
212
|
-
yield await stack.enter_async_context(Client(transport))
|
|
213
|
-
finally:
|
|
214
|
-
with suppress(Exception):
|
|
215
|
-
await stack.aclose()
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
async def with_retry(call):
|
|
219
|
-
"""Run one client operation, retrying transient failures with backoff. A call whose
|
|
220
|
-
response was lost may be replayed — MCP has no idempotency key, so tools should tolerate
|
|
221
|
-
at-least-once delivery (a tool that fails reports through its result, not an exception)."""
|
|
222
|
-
async for attempt in AsyncRetrying(
|
|
223
|
-
stop=stop_after_attempt(MCP_CALL_ATTEMPTS),
|
|
224
|
-
wait=wait_exponential_jitter(initial=0.5, max=30),
|
|
225
|
-
reraise=True,
|
|
226
|
-
):
|
|
227
|
-
with attempt:
|
|
228
|
-
return await call()
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
async def connect_mcp(
|
|
232
|
-
config: dict, reserved: set[str]
|
|
233
|
-
) -> tuple[list[dict], dict, dict]:
|
|
234
|
-
"""Enumerate each configured MCP server's tools (a streamable-HTTP `url`); return (tool schemas,
|
|
235
|
-
dispatch mapping `<server>_<tool>` -> (server name, raw tool name), servers mapping name -> spec).
|
|
236
|
-
No protocol session is held; a fresh client handles each call."""
|
|
237
|
-
tool_schemas: list[dict] = []
|
|
238
|
-
dispatch: dict[str, tuple] = {}
|
|
239
|
-
servers: dict[str, dict] = {}
|
|
240
|
-
for name, spec in config.get("mcpServers", {}).items():
|
|
241
|
-
servers[name] = spec
|
|
242
|
-
|
|
243
|
-
async def list_tools(spec: dict = spec):
|
|
244
|
-
async with mcp_client(spec) as client:
|
|
245
|
-
return (await client.list_tools()).tools
|
|
246
|
-
|
|
247
|
-
for tool in await with_retry(list_tools):
|
|
248
|
-
# A server named "" (TOOL_PREFIX = None) advertises its tools bare.
|
|
249
|
-
full = f"{name}_{tool.name}" if name else tool.name
|
|
250
|
-
if full in reserved or full in dispatch:
|
|
251
|
-
raise ValueError(
|
|
252
|
-
f"duplicate tool name {full!r}; keep MCP tool names qualified"
|
|
253
|
-
)
|
|
254
|
-
tool_schemas.append(
|
|
255
|
-
{
|
|
256
|
-
"type": "function",
|
|
257
|
-
"function": {
|
|
258
|
-
"name": full,
|
|
259
|
-
"description": tool.description or "",
|
|
260
|
-
"parameters": tool.input_schema,
|
|
261
|
-
},
|
|
262
|
-
}
|
|
263
|
-
)
|
|
264
|
-
dispatch[full] = (name, tool.name)
|
|
265
|
-
return tool_schemas, dispatch, servers
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
def mcp_content_to_chat_content(blocks) -> str | list[dict]:
|
|
269
|
-
parts = []
|
|
270
|
-
for block in blocks:
|
|
271
|
-
if block.type == "text":
|
|
272
|
-
parts.append({"type": "text", "text": block.text})
|
|
273
|
-
elif block.type == "image":
|
|
274
|
-
url = f"data:{block.mime_type};base64,{block.data}"
|
|
275
|
-
parts.append({"type": "image_url", "image_url": {"url": url}})
|
|
276
|
-
else:
|
|
277
|
-
parts.append({"type": "text", "text": str(block)})
|
|
278
|
-
if not parts:
|
|
279
|
-
return str(blocks)
|
|
280
|
-
if all(part["type"] == "text" for part in parts):
|
|
281
|
-
return "\n".join(part["text"] for part in parts)
|
|
282
|
-
return parts
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
async def call_mcp(
|
|
286
|
-
servers: dict, dispatch: dict, name: str, arguments: dict
|
|
287
|
-
) -> str | list[dict]:
|
|
288
|
-
"""Call a tool with a fresh client per attempt — see `with_retry` for replay semantics.
|
|
289
|
-
The result is converted outside the retry so a conversion failure fails once."""
|
|
290
|
-
server_name, raw = dispatch[name]
|
|
291
|
-
|
|
292
|
-
async def call():
|
|
293
|
-
async with mcp_client(servers[server_name]) as client:
|
|
294
|
-
return await client.call_tool(raw, arguments)
|
|
295
|
-
|
|
296
|
-
result = await with_retry(call)
|
|
297
|
-
return mcp_content_to_chat_content(result.content)
|
|
298
|
-
|
|
299
|
-
|
|
300
208
|
async def run_tool_hook(
|
|
301
209
|
client: httpx.AsyncClient,
|
|
302
210
|
url: str,
|
|
@@ -326,6 +234,7 @@ def parse_args() -> argparse.Namespace:
|
|
|
326
234
|
parser.add_argument("--initial-messages-file", default="")
|
|
327
235
|
parser.add_argument("--mcp-config", default="")
|
|
328
236
|
parser.add_argument("--tool-interception-url", default="")
|
|
237
|
+
parser.add_argument("--bash", action="store_true")
|
|
329
238
|
parser.add_argument("--edit", action="store_true")
|
|
330
239
|
parser.add_argument("--search", action="store_true")
|
|
331
240
|
parser.add_argument("--serper-key", default="")
|
|
@@ -340,26 +249,31 @@ async def main() -> None:
|
|
|
340
249
|
payload = path.read_bytes()
|
|
341
250
|
path.unlink()
|
|
342
251
|
initial = json.loads(payload)
|
|
343
|
-
client = AsyncOpenAI(
|
|
252
|
+
client = AsyncOpenAI(
|
|
253
|
+
base_url=args.base_url,
|
|
254
|
+
api_key=args.api_key,
|
|
255
|
+
timeout=httpx.Timeout(600.0 if args.bash else None, connect=5.0),
|
|
256
|
+
)
|
|
344
257
|
tool_client = (
|
|
345
258
|
httpx.AsyncClient(timeout=httpx.Timeout(None, connect=5.0))
|
|
346
259
|
if args.tool_interception_url
|
|
347
260
|
else None
|
|
348
261
|
)
|
|
349
262
|
config = json.loads(args.mcp_config or "{}")
|
|
350
|
-
tools = [BASH_TOOL]
|
|
351
|
-
reserved = {"bash"}
|
|
263
|
+
tools = [BASH_TOOL] if args.bash else []
|
|
264
|
+
reserved = {"bash"} if args.bash else set()
|
|
352
265
|
if args.edit:
|
|
353
266
|
tools.append(EDIT_TOOL)
|
|
354
267
|
reserved.add("edit")
|
|
355
268
|
if args.search:
|
|
356
269
|
tools.append(SEARCH_TOOL)
|
|
357
270
|
reserved.add("search")
|
|
358
|
-
|
|
359
|
-
await
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
271
|
+
if config.get("mcpServers"):
|
|
272
|
+
mcp_tools, dispatch, servers = await asyncio.wait_for(
|
|
273
|
+
connect_mcp(config, reserved), timeout=None if args.bash else 60
|
|
274
|
+
)
|
|
275
|
+
else:
|
|
276
|
+
mcp_tools, dispatch, servers = [], {}, {}
|
|
363
277
|
tools += mcp_tools
|
|
364
278
|
messages = (
|
|
365
279
|
[{"role": "system", "content": args.system_prompt}]
|
|
@@ -371,7 +285,13 @@ async def main() -> None:
|
|
|
371
285
|
elif args.prompt:
|
|
372
286
|
messages.append({"role": "user", "content": args.prompt})
|
|
373
287
|
while True:
|
|
374
|
-
|
|
288
|
+
try:
|
|
289
|
+
message = await chat(client, args.model, messages, tools)
|
|
290
|
+
except APIStatusError as error:
|
|
291
|
+
# Null cannot compact, so context exhaustion ends it with the transcript so far.
|
|
292
|
+
if args.bash or not is_context_overflow(error):
|
|
293
|
+
raise
|
|
294
|
+
return
|
|
375
295
|
messages.append(message.model_dump(exclude_none=True))
|
|
376
296
|
if not message.tool_calls:
|
|
377
297
|
break
|
|
@@ -405,7 +325,7 @@ async def main() -> None:
|
|
|
405
325
|
content = f"error: tool arguments must be a JSON object, got {type(tool_args).__name__}; resend as an object"
|
|
406
326
|
elif name in dispatch:
|
|
407
327
|
content = await call_mcp(servers, dispatch, name, tool_args)
|
|
408
|
-
elif name == "bash":
|
|
328
|
+
elif name == "bash" and args.bash:
|
|
409
329
|
content = await asyncio.to_thread(
|
|
410
330
|
run_bash, tool_args.get("command", "")
|
|
411
331
|
)
|
|
@@ -1,16 +1,12 @@
|
|
|
1
|
-
import json
|
|
2
|
-
from pathlib import Path
|
|
3
|
-
|
|
4
1
|
from verifiers.v1.clients import ModelContext
|
|
5
2
|
from verifiers.v1.configs.harness import HarnessConfig
|
|
6
|
-
from verifiers.v1.dialects.chat import message_to_wire
|
|
7
3
|
from verifiers.v1.harness import Harness
|
|
4
|
+
from verifiers.v1.harnesses.minimal import PROGRAM_SOURCE
|
|
5
|
+
from verifiers.v1.harnesses.standalone import launch_chat_program
|
|
8
6
|
from verifiers.v1.runtimes import ProgramResult, Runtime
|
|
9
7
|
from verifiers.v1.task import TaskData
|
|
10
8
|
from verifiers.v1.trace import Trace
|
|
11
9
|
|
|
12
|
-
PROGRAM_SOURCE = (Path(__file__).resolve().parent / "program.py").read_text()
|
|
13
|
-
|
|
14
10
|
|
|
15
11
|
class NullHarnessConfig(HarnessConfig):
|
|
16
12
|
pass
|
|
@@ -37,39 +33,15 @@ class NullHarness(Harness[NullHarnessConfig]):
|
|
|
37
33
|
data: TaskData,
|
|
38
34
|
) -> ProgramResult:
|
|
39
35
|
system_prompt, prompt = self.resolve_prompt(data)
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
args.append(
|
|
52
|
-
"--mcp-config="
|
|
53
|
-
+ json.dumps(
|
|
54
|
-
{
|
|
55
|
-
"mcpServers": {
|
|
56
|
-
name: {"url": url, "timeout": self.config.tool_timeout}
|
|
57
|
-
for name, url in mcp_urls.items()
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
)
|
|
61
|
-
)
|
|
62
|
-
if isinstance(prompt, str):
|
|
63
|
-
args.append(f"--prompt={prompt}")
|
|
64
|
-
elif prompt is not None:
|
|
65
|
-
# Base64 images can exceed exec limits, so hand Messages off through a file.
|
|
66
|
-
path = f".vf-initial-messages-{trace.id}.json"
|
|
67
|
-
await runtime.write(
|
|
68
|
-
path,
|
|
69
|
-
json.dumps([message_to_wire(m) for m in prompt]).encode(),
|
|
70
|
-
)
|
|
71
|
-
args.append(f"--initial-messages-file={path}")
|
|
72
|
-
program = await runtime.prepare_uv_script(
|
|
73
|
-
PROGRAM_SOURCE, self.config.resolved_env
|
|
36
|
+
return await launch_chat_program(
|
|
37
|
+
PROGRAM_SOURCE,
|
|
38
|
+
self.config,
|
|
39
|
+
ctx,
|
|
40
|
+
trace,
|
|
41
|
+
runtime,
|
|
42
|
+
endpoint,
|
|
43
|
+
secret,
|
|
44
|
+
mcp_urls,
|
|
45
|
+
system_prompt,
|
|
46
|
+
prompt,
|
|
74
47
|
)
|
|
75
|
-
return await runtime.run_program([*program, *args], env)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
import json
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
|
|
5
|
+
from verifiers.v1.clients import ModelContext
|
|
6
|
+
from verifiers.v1.configs.harness import HarnessConfig
|
|
7
|
+
from verifiers.v1.dialects.chat import message_to_wire
|
|
8
|
+
from verifiers.v1.mcp import client as mcp_client
|
|
9
|
+
from verifiers.v1.runtimes import ProgramResult, Runtime
|
|
10
|
+
from verifiers.v1.trace import Trace
|
|
11
|
+
from verifiers.v1.types import Messages
|
|
12
|
+
|
|
13
|
+
MCP_CLIENT_SOURCE = inspect.getsource(mcp_client)
|
|
14
|
+
PEP_723_END = "# ///\n"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def inline_mcp_client(program: str) -> str:
|
|
18
|
+
"""Embed the public client so PEP 723 programs need only their declared packages."""
|
|
19
|
+
metadata, body = program.split(PEP_723_END, 1)
|
|
20
|
+
return f"{metadata}{PEP_723_END}{MCP_CLIENT_SOURCE}\n{body}"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def launch_chat_program(
|
|
24
|
+
source: str,
|
|
25
|
+
config: HarnessConfig,
|
|
26
|
+
ctx: ModelContext,
|
|
27
|
+
trace: Trace,
|
|
28
|
+
runtime: Runtime,
|
|
29
|
+
endpoint: str,
|
|
30
|
+
secret: str,
|
|
31
|
+
mcp_urls: dict[str, str],
|
|
32
|
+
system_prompt: str | None,
|
|
33
|
+
prompt: str | Messages | None,
|
|
34
|
+
*,
|
|
35
|
+
extra_args: Sequence[str] = (),
|
|
36
|
+
env: dict[str, str] | None = None,
|
|
37
|
+
activate: bool = True,
|
|
38
|
+
) -> ProgramResult:
|
|
39
|
+
"""Prepare and run a standalone chat program with the shared wire arguments."""
|
|
40
|
+
args = [
|
|
41
|
+
f"--base-url={endpoint}",
|
|
42
|
+
f"--api-key={secret}",
|
|
43
|
+
f"--model={ctx.model}",
|
|
44
|
+
*extra_args,
|
|
45
|
+
]
|
|
46
|
+
if system_prompt:
|
|
47
|
+
args.append(f"--system-prompt={system_prompt}")
|
|
48
|
+
if mcp_urls:
|
|
49
|
+
args.append(
|
|
50
|
+
"--mcp-config="
|
|
51
|
+
+ json.dumps(
|
|
52
|
+
{
|
|
53
|
+
"mcpServers": {
|
|
54
|
+
name: {"url": url, "timeout": config.tool_timeout}
|
|
55
|
+
for name, url in mcp_urls.items()
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
)
|
|
59
|
+
)
|
|
60
|
+
if isinstance(prompt, str):
|
|
61
|
+
args.append(f"--prompt={prompt}")
|
|
62
|
+
elif prompt is not None:
|
|
63
|
+
path = f".vf-initial-messages-{trace.id}.json"
|
|
64
|
+
await runtime.write(
|
|
65
|
+
path,
|
|
66
|
+
json.dumps([message_to_wire(message) for message in prompt]).encode(),
|
|
67
|
+
)
|
|
68
|
+
args.append(f"--initial-messages-file={path}")
|
|
69
|
+
program = await runtime.prepare_uv_script(
|
|
70
|
+
source, config.resolved_env, activate=activate
|
|
71
|
+
)
|
|
72
|
+
return await runtime.run_program(
|
|
73
|
+
[*program, *args], env if env is not None else {**config.resolved_env}
|
|
74
|
+
)
|
verifiers/v1/mcp/__init__.py
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
from verifiers.v1.mcp.client import (
|
|
2
|
+
call_mcp,
|
|
3
|
+
connect_mcp,
|
|
4
|
+
mcp_client,
|
|
5
|
+
mcp_content_to_chat_content,
|
|
6
|
+
with_retry,
|
|
7
|
+
)
|
|
1
8
|
from verifiers.v1.mcp.launch import (
|
|
2
9
|
SharedToolServer,
|
|
3
10
|
serve,
|
|
@@ -13,7 +20,12 @@ __all__ = [
|
|
|
13
20
|
"SharedToolsetConfig",
|
|
14
21
|
"Toolset",
|
|
15
22
|
"ToolsetConfig",
|
|
23
|
+
"call_mcp",
|
|
24
|
+
"connect_mcp",
|
|
25
|
+
"mcp_client",
|
|
26
|
+
"mcp_content_to_chat_content",
|
|
16
27
|
"serve",
|
|
17
28
|
"serve_shared",
|
|
18
29
|
"serve_tools",
|
|
30
|
+
"with_retry",
|
|
19
31
|
]
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
|
|
2
|
+
from contextlib import AsyncExitStack, asynccontextmanager, suppress
|
|
3
|
+
from typing import Any, TypeVar, cast
|
|
4
|
+
|
|
5
|
+
import httpx2
|
|
6
|
+
from mcp import Client
|
|
7
|
+
from mcp.client.streamable_http import create_mcp_http_client, streamable_http_client
|
|
8
|
+
from tenacity import AsyncRetrying, stop_after_attempt, wait_exponential_jitter
|
|
9
|
+
|
|
10
|
+
MCP_CALL_ATTEMPTS = 6
|
|
11
|
+
MCP_TIMEOUT = 600.0
|
|
12
|
+
|
|
13
|
+
T = TypeVar("T")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@asynccontextmanager
|
|
17
|
+
async def mcp_client(spec: dict[str, Any]) -> AsyncIterator[Client]:
|
|
18
|
+
"""Open one fresh MCP client in the caller's task.
|
|
19
|
+
|
|
20
|
+
The client negotiates the newest protocol and falls back for older servers.
|
|
21
|
+
Teardown failures after the body completes are suppressed so closing noise cannot
|
|
22
|
+
fail or replay a call whose result is already available.
|
|
23
|
+
"""
|
|
24
|
+
stack = AsyncExitStack()
|
|
25
|
+
try:
|
|
26
|
+
http_client = await stack.enter_async_context(
|
|
27
|
+
create_mcp_http_client(
|
|
28
|
+
headers=spec.get("headers") or None,
|
|
29
|
+
timeout=httpx2.Timeout(
|
|
30
|
+
spec.get("timeout", MCP_TIMEOUT),
|
|
31
|
+
connect=spec.get("connect_timeout", 5.0),
|
|
32
|
+
),
|
|
33
|
+
)
|
|
34
|
+
)
|
|
35
|
+
transport = streamable_http_client(spec["url"], http_client=http_client)
|
|
36
|
+
yield await stack.enter_async_context(Client(transport))
|
|
37
|
+
finally:
|
|
38
|
+
with suppress(Exception):
|
|
39
|
+
await stack.aclose()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
async def with_retry(call: Callable[[], Awaitable[T]]) -> T:
|
|
43
|
+
"""Run one client operation with the existing at-least-once retries."""
|
|
44
|
+
async for attempt in AsyncRetrying(
|
|
45
|
+
stop=stop_after_attempt(MCP_CALL_ATTEMPTS),
|
|
46
|
+
wait=wait_exponential_jitter(initial=0.5, max=30),
|
|
47
|
+
reraise=True,
|
|
48
|
+
):
|
|
49
|
+
with attempt:
|
|
50
|
+
return await call()
|
|
51
|
+
raise RuntimeError("retrying stopped without returning or raising")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
async def connect_mcp(
|
|
55
|
+
config: dict[str, Any], reserved: set[str] | None = None
|
|
56
|
+
) -> tuple[
|
|
57
|
+
list[dict[str, Any]],
|
|
58
|
+
dict[str, tuple[str, str]],
|
|
59
|
+
dict[str, dict[str, Any]],
|
|
60
|
+
]:
|
|
61
|
+
"""Enumerate MCP tools and return their schemas, dispatch map, and servers."""
|
|
62
|
+
tool_schemas: list[dict[str, Any]] = []
|
|
63
|
+
dispatch: dict[str, tuple[str, str]] = {}
|
|
64
|
+
servers: dict[str, dict[str, Any]] = {}
|
|
65
|
+
reserved = reserved or set()
|
|
66
|
+
for name, spec in config.get("mcpServers", {}).items():
|
|
67
|
+
servers[name] = spec
|
|
68
|
+
|
|
69
|
+
async def list_tools(spec: dict[str, Any] = spec):
|
|
70
|
+
async with mcp_client(spec) as client:
|
|
71
|
+
return (await client.list_tools()).tools
|
|
72
|
+
|
|
73
|
+
for tool in await with_retry(list_tools):
|
|
74
|
+
full = f"{name}_{tool.name}" if name else tool.name
|
|
75
|
+
if full in reserved or full in dispatch:
|
|
76
|
+
raise ValueError(
|
|
77
|
+
f"duplicate tool name {full!r}; keep MCP tool names qualified"
|
|
78
|
+
)
|
|
79
|
+
tool_schemas.append(
|
|
80
|
+
{
|
|
81
|
+
"type": "function",
|
|
82
|
+
"function": {
|
|
83
|
+
"name": full,
|
|
84
|
+
"description": tool.description or "",
|
|
85
|
+
"parameters": tool.input_schema,
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
)
|
|
89
|
+
dispatch[full] = (name, tool.name)
|
|
90
|
+
return tool_schemas, dispatch, servers
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def mcp_content_to_chat_content(
|
|
94
|
+
blocks: Sequence[Any],
|
|
95
|
+
) -> str | list[dict[str, Any]]:
|
|
96
|
+
"""Convert MCP content blocks to OpenAI chat tool-result content."""
|
|
97
|
+
parts = []
|
|
98
|
+
for block in blocks:
|
|
99
|
+
if block.type == "text":
|
|
100
|
+
parts.append({"type": "text", "text": block.text})
|
|
101
|
+
elif block.type == "image":
|
|
102
|
+
url = f"data:{block.mime_type};base64,{block.data}"
|
|
103
|
+
parts.append({"type": "image_url", "image_url": {"url": url}})
|
|
104
|
+
else:
|
|
105
|
+
parts.append({"type": "text", "text": str(block)})
|
|
106
|
+
if not parts:
|
|
107
|
+
return str(blocks)
|
|
108
|
+
if all(part["type"] == "text" for part in parts):
|
|
109
|
+
return "\n".join(cast(str, part["text"]) for part in parts)
|
|
110
|
+
return parts
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
async def call_mcp(
|
|
114
|
+
servers: dict[str, dict[str, Any]],
|
|
115
|
+
dispatch: dict[str, tuple[str, str]],
|
|
116
|
+
name: str,
|
|
117
|
+
arguments: dict[str, Any],
|
|
118
|
+
) -> str | list[dict[str, Any]]:
|
|
119
|
+
"""Call one MCP tool with a fresh client per retry attempt."""
|
|
120
|
+
server_name, raw = dispatch[name]
|
|
121
|
+
|
|
122
|
+
async def call():
|
|
123
|
+
async with mcp_client(servers[server_name]) as client:
|
|
124
|
+
return await client.call_tool(raw, arguments)
|
|
125
|
+
|
|
126
|
+
result = await with_retry(call)
|
|
127
|
+
return mcp_content_to_chat_content(result.content)
|
|
@@ -1,17 +1,13 @@
|
|
|
1
1
|
"""Expose NeMo Gym resource tools through Verifiers MCP."""
|
|
2
2
|
|
|
3
|
-
from collections.abc import AsyncIterator
|
|
4
|
-
from contextlib import AsyncExitStack, asynccontextmanager, suppress
|
|
5
3
|
from typing import Any, cast
|
|
6
4
|
|
|
7
5
|
import httpx
|
|
8
|
-
from mcp import Client
|
|
9
|
-
from mcp.client.streamable_http import create_mcp_http_client, streamable_http_client
|
|
10
6
|
from mcp.server.mcpserver import Context, MCPServer
|
|
11
7
|
from mcp.types import CallToolResult, TextContent, Tool
|
|
12
8
|
from pydantic import Field
|
|
13
9
|
|
|
14
|
-
from verifiers.v1.mcp import SharedToolsetConfig, Toolset
|
|
10
|
+
from verifiers.v1.mcp import SharedToolsetConfig, Toolset, mcp_client
|
|
15
11
|
from verifiers.v1.state import State
|
|
16
12
|
|
|
17
13
|
|
|
@@ -36,22 +32,6 @@ class NeMoGymState(State):
|
|
|
36
32
|
) as client:
|
|
37
33
|
return await client.post(f"{self.resources_url}/{path}", json=body)
|
|
38
34
|
|
|
39
|
-
@asynccontextmanager
|
|
40
|
-
async def mcp_client(self) -> AsyncIterator[Client]:
|
|
41
|
-
"""Open an upstream MCP client using this rollout's credentials."""
|
|
42
|
-
assert self.mcp_url is not None
|
|
43
|
-
stack = AsyncExitStack()
|
|
44
|
-
try:
|
|
45
|
-
http_client = await stack.enter_async_context(
|
|
46
|
-
create_mcp_http_client(headers=self.mcp_headers)
|
|
47
|
-
)
|
|
48
|
-
http_client.timeout = self.request_timeout
|
|
49
|
-
transport = streamable_http_client(self.mcp_url, http_client=http_client)
|
|
50
|
-
yield await stack.enter_async_context(Client(transport))
|
|
51
|
-
finally:
|
|
52
|
-
with suppress(Exception):
|
|
53
|
-
await stack.aclose()
|
|
54
|
-
|
|
55
35
|
|
|
56
36
|
class NeMoGymToolset(Toolset[SharedToolsetConfig, NeMoGymState]):
|
|
57
37
|
"""Bridge rollout-specific Gym tools into the standard V1 MCP boundary."""
|
|
@@ -67,7 +47,14 @@ class NeMoGymToolset(Toolset[SharedToolsetConfig, NeMoGymState]):
|
|
|
67
47
|
|
|
68
48
|
async def list_tools(self) -> list[Tool]:
|
|
69
49
|
if self.state.mcp_url is not None:
|
|
70
|
-
async with
|
|
50
|
+
async with mcp_client(
|
|
51
|
+
{
|
|
52
|
+
"url": self.state.mcp_url,
|
|
53
|
+
"headers": self.state.mcp_headers,
|
|
54
|
+
"timeout": self.state.request_timeout,
|
|
55
|
+
"connect_timeout": self.state.request_timeout,
|
|
56
|
+
}
|
|
57
|
+
) as client:
|
|
71
58
|
tools = (await client.list_tools()).tools
|
|
72
59
|
else:
|
|
73
60
|
tools = [
|
|
@@ -88,7 +75,14 @@ class NeMoGymToolset(Toolset[SharedToolsetConfig, NeMoGymState]):
|
|
|
88
75
|
context: Context | None = None,
|
|
89
76
|
) -> CallToolResult:
|
|
90
77
|
if self.state.mcp_url is not None:
|
|
91
|
-
async with
|
|
78
|
+
async with mcp_client(
|
|
79
|
+
{
|
|
80
|
+
"url": self.state.mcp_url,
|
|
81
|
+
"headers": self.state.mcp_headers,
|
|
82
|
+
"timeout": self.state.request_timeout,
|
|
83
|
+
"connect_timeout": self.state.request_timeout,
|
|
84
|
+
}
|
|
85
|
+
) as client:
|
|
92
86
|
return await client.call_tool(name, arguments)
|
|
93
87
|
|
|
94
88
|
if name not in self.state.direct_tools:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: verifiers
|
|
3
|
-
Version: 0.3.2.
|
|
3
|
+
Version: 0.3.2.dev21
|
|
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
|
|
@@ -248,12 +248,12 @@ verifiers/v1/gepa/reflection.py,sha256=ptHhx0lcDLcWhWhXuslh9T8gPVNpnX5XLPtXoneW1
|
|
|
248
248
|
verifiers/v1/gepa/runner.py,sha256=fGEyFzejdQKBzBbvdiTDHV3JtRhXMXMGSBU5y8C8i3w,6054
|
|
249
249
|
verifiers/v1/harnesses/__init__.py,sha256=0FVi-mPF36fF0vpLY4H2vbK3U_om1Svz3KgJ3i-phs0,1918
|
|
250
250
|
verifiers/v1/harnesses/node.py,sha256=_-7NofTl-TNuwgEg8qxrD28shlQuyBWgiVHwCCwbdVo,2410
|
|
251
|
+
verifiers/v1/harnesses/standalone.py,sha256=4y5Mg0fFCdCBLIxbTIpfiNbJFqbM2kPrD4_K_W5SIYI,2358
|
|
251
252
|
verifiers/v1/harnesses/bash/__init__.py,sha256=IAV4eMMqDHSl-9ANb0Q3kxmBZ22SeHZFBM448X4gQio,140
|
|
252
|
-
verifiers/v1/harnesses/bash/harness.py,sha256=
|
|
253
|
-
verifiers/v1/harnesses/bash/program.py,sha256=HZOgtmTIRYBLY_9g17hMZ2Xh7RicYnAZNmhkcT2sAMs,16523
|
|
253
|
+
verifiers/v1/harnesses/bash/harness.py,sha256=MrcdKawd8i5WwnJwPIeRoiAJVxJNNNQT0L6eT1HIvsE,4479
|
|
254
254
|
verifiers/v1/harnesses/browser_use/__init__.py,sha256=yxm2IG5TDLadxZEkX8SL26XWbcPcODXcrJfPfm1GqwU,171
|
|
255
|
-
verifiers/v1/harnesses/browser_use/harness.py,sha256=
|
|
256
|
-
verifiers/v1/harnesses/browser_use/program.py,sha256=
|
|
255
|
+
verifiers/v1/harnesses/browser_use/harness.py,sha256=gISpaGOSHVdSjD41nTEhD0tO8IYim3Ro8MRV4LV_8PQ,4880
|
|
256
|
+
verifiers/v1/harnesses/browser_use/program.py,sha256=j9umhpD95poj3Emxp-uMEBHlIO_JWDbK5gGL6XMOTrA,9813
|
|
257
257
|
verifiers/v1/harnesses/claude_code/__init__.py,sha256=JkZQylMSA3o1fvBx_NM41y_umuahmOSqFjTrJ2hryTw,171
|
|
258
258
|
verifiers/v1/harnesses/claude_code/harness.py,sha256=bkYbQe0tih9tIGTUp-keSjUlx4DFGXYjX7Lisd212do,4620
|
|
259
259
|
verifiers/v1/harnesses/codex/__init__.py,sha256=ocyBvlpSO8c3pT6D1ebrQohoXYESQcCyPT5kN3j1-N4,132
|
|
@@ -266,9 +266,10 @@ verifiers/v1/harnesses/kimi_code/harness.py,sha256=3SSIty3JtQmvbItutjXJRGrh86KSA
|
|
|
266
266
|
verifiers/v1/harnesses/mini_swe_agent/__init__.py,sha256=1OBu2Y-XqL72-dGhFdgB6sr5uX_peEEXT9vEjPy1ovU,182
|
|
267
267
|
verifiers/v1/harnesses/mini_swe_agent/harness.py,sha256=7HHismhmfCtahlLtQdQyp_fTKidHfco-MdeWp7B9xCo,2522
|
|
268
268
|
verifiers/v1/harnesses/mini_swe_agent/program.py,sha256=Beej-JLIgSqnqIqB746oKU6kJYcynvppIbmwGa3nJJ0,167
|
|
269
|
+
verifiers/v1/harnesses/minimal/__init__.py,sha256=f_dKnFqgeypSh3t7EoPpx0lvosvn1UbsR6_zLpiSsBM,224
|
|
270
|
+
verifiers/v1/harnesses/minimal/program.py,sha256=yRzE93K0GbXm79F_2sBs9HfvYG6NGwiv9h7QQXdOpTY,13391
|
|
269
271
|
verifiers/v1/harnesses/null/__init__.py,sha256=XDeKOPeoXUQi9US9_Z3_yH9YaZ4EiOMKJmUtNNdtD7s,127
|
|
270
|
-
verifiers/v1/harnesses/null/harness.py,sha256=
|
|
271
|
-
verifiers/v1/harnesses/null/program.py,sha256=etJ-vSHafgeuMOcN2coCyRSUH58GsQV5TCpa-DliJFs,10134
|
|
272
|
+
verifiers/v1/harnesses/null/harness.py,sha256=2BhzTmA8suBW6p_8kWksX7GHWhvsblJZp1_yb57R09M,1342
|
|
272
273
|
verifiers/v1/harnesses/openclaw/__init__.py,sha256=kNyfPB1sGwEf4K3mTfKN0VEyxun3SGvNpvArVKvH-x8,160
|
|
273
274
|
verifiers/v1/harnesses/openclaw/harness.py,sha256=LcdfnP_wYvWUQWIt6d4sE0TnXaxt5Ne5r_f7R0lKkAc,9535
|
|
274
275
|
verifiers/v1/harnesses/pi/__init__.py,sha256=1mSnzOf-RdEchdeg6IHtcdobG5KIpAhuTdUIgsCIn74,117
|
|
@@ -296,7 +297,8 @@ verifiers/v1/judges/reference.py,sha256=iEVHw-iJ6dbwLOOqrvWrEMJOcUEYJ0YspT04rZz7
|
|
|
296
297
|
verifiers/v1/judges/reference.txt,sha256=Ej35kGXiT2uJ0LcHIeez49rCS_9uHmCQKoVdn93V6A8,353
|
|
297
298
|
verifiers/v1/judges/rubric.py,sha256=qwBjJCWfaUUcQA9A4EXFQK0NumGjoevSFT2HjgBZut4,12019
|
|
298
299
|
verifiers/v1/judges/rubric.txt,sha256=3KA2ZeYYdcDweJhUGopxu9EFgARhu2aWft5S5cj8Bc8,323
|
|
299
|
-
verifiers/v1/mcp/__init__.py,sha256=
|
|
300
|
+
verifiers/v1/mcp/__init__.py,sha256=GjaaLVZSIZY4VrcAg4wkuLQJTRqJqy1aRCplLJs1fBE,650
|
|
301
|
+
verifiers/v1/mcp/client.py,sha256=Sss-DVMtxdE1eGEfq1ycdi1v7SBsmUU5UcpcIY6dGTY,4572
|
|
300
302
|
verifiers/v1/mcp/launch.py,sha256=dqi5UCE-ShPn663glL4DwnTHk4_VBLG_0qUUwlr3p10,23776
|
|
301
303
|
verifiers/v1/mcp/server.py,sha256=q2uB4rMz_f3qpHPwduVN9V4B9HZUHfAjuBFHV8PjfdE,13380
|
|
302
304
|
verifiers/v1/mcp/toolset.py,sha256=G2wzNdEMGLXoQUcrwF0TartJkqokNPI3o7YUOAaaa6U,1007
|
|
@@ -325,7 +327,7 @@ verifiers/v1/tasksets/nemo_gym/__init__.py,sha256=654gAvG3Wd_Z_nh6mypeKn4s_IIQ0G
|
|
|
325
327
|
verifiers/v1/tasksets/nemo_gym/response.py,sha256=u_-qvmcyVHRC9fLJx5ED7BjCCUv5JttuTxM_GzZObkM,4382
|
|
326
328
|
verifiers/v1/tasksets/nemo_gym/server.py,sha256=33C-VDZxPtMV2TFxJVIKijmtBLNlVeRs92ctPE3qAsM,2036
|
|
327
329
|
verifiers/v1/tasksets/nemo_gym/taskset.py,sha256=71h5GGbkbMmUbt4O8eUB8y3z5wZRGQu9lH6ekQcw-Wk,6365
|
|
328
|
-
verifiers/v1/tasksets/nemo_gym/toolset.py,sha256=
|
|
330
|
+
verifiers/v1/tasksets/nemo_gym/toolset.py,sha256=rvRKkKNLc-tXuBoptDmze24kASgmn1C59FZ4piAvrsk,3671
|
|
329
331
|
verifiers/v1/tasksets/openenv/__init__.py,sha256=G726meYYDplC3QE3AyjdSShq7FUcb4NkVqowuwPPuJk,303
|
|
330
332
|
verifiers/v1/tasksets/openenv/taskset.py,sha256=1Wc9-5eN2HMKAwL34yTNex3zYOvXNXibF5wCROoMbFI,6075
|
|
331
333
|
verifiers/v1/tasksets/textarena/__init__.py,sha256=Os2OlBY_pSH0B1DP32RitumgSLpq2LtcI7VDUHYPzRE,329
|
|
@@ -349,8 +351,8 @@ verifiers/v1/utils/prime.py,sha256=UTYRjp9cbjNb6CVmBHda-1wWZAIIfxNOmTyNuT7_wL4,9
|
|
|
349
351
|
verifiers/v1/utils/retries.py,sha256=Y2ZgrAjn-qNkRKZP_RVNL_7EK0iaRcZeCa404lpGYi4,5417
|
|
350
352
|
verifiers/v1/utils/score.py,sha256=493yJVMw8teCu9JxapxMFPFzI0hNUqdo0Y2nGW4kckk,6200
|
|
351
353
|
verifiers/v1/utils/version.py,sha256=-obEo_-l9-D8FLef4hYxncOe-uJpxrM1g2Hig_37Sgs,1607
|
|
352
|
-
verifiers-0.3.2.
|
|
353
|
-
verifiers-0.3.2.
|
|
354
|
-
verifiers-0.3.2.
|
|
355
|
-
verifiers-0.3.2.
|
|
356
|
-
verifiers-0.3.2.
|
|
354
|
+
verifiers-0.3.2.dev21.dist-info/METADATA,sha256=b_Pyhiig672EDoQh1Ns7Od_X15F_bh8-E71IbqKwW04,4555
|
|
355
|
+
verifiers-0.3.2.dev21.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
356
|
+
verifiers-0.3.2.dev21.dist-info/entry_points.txt,sha256=hZ5wDc1T8y-EvOziw7kQqatBJ6PbdSu2ygP5rjANl7c,564
|
|
357
|
+
verifiers-0.3.2.dev21.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
|
|
358
|
+
verifiers-0.3.2.dev21.dist-info/RECORD,,
|
|
@@ -1,258 +0,0 @@
|
|
|
1
|
-
# /// script
|
|
2
|
-
# requires-python = ">=3.11"
|
|
3
|
-
# dependencies = ["openai", "mcp==2.0.0", "httpx", "httpx2", "tenacity"]
|
|
4
|
-
# ///
|
|
5
|
-
"""The interception endpoint and secret arrive through argv rather than the environment."""
|
|
6
|
-
|
|
7
|
-
import argparse
|
|
8
|
-
import asyncio
|
|
9
|
-
import json
|
|
10
|
-
from contextlib import AsyncExitStack, asynccontextmanager, suppress
|
|
11
|
-
from pathlib import Path
|
|
12
|
-
|
|
13
|
-
import httpx
|
|
14
|
-
from openai import APIStatusError, AsyncOpenAI
|
|
15
|
-
from tenacity import AsyncRetrying, stop_after_attempt, wait_exponential_jitter
|
|
16
|
-
|
|
17
|
-
MCP_CALL_ATTEMPTS = 6
|
|
18
|
-
MCP_TIMEOUT = 600.0
|
|
19
|
-
|
|
20
|
-
CONTEXT_OVERFLOW_MARKERS = (
|
|
21
|
-
# OpenAI error code "context_length_exceeded"; OpenRouter relays the raw body.
|
|
22
|
-
"context_length_exceeded",
|
|
23
|
-
# OpenAI Responses/Completions: "Your input exceeds the context window of this model".
|
|
24
|
-
"exceeds the context window",
|
|
25
|
-
# OpenAI chat: "Input tokens exceed the configured limit of N tokens. Please reduce
|
|
26
|
-
# the length of the messages."; Groq words it the same way.
|
|
27
|
-
"reduce the length of the messages",
|
|
28
|
-
# vLLM: "This model's maximum context length is N tokens"; the renderers pre-flight:
|
|
29
|
-
# "Prompt length (N) exceeds maximum context length (M)"; Mistral uses the same words.
|
|
30
|
-
"maximum context length",
|
|
31
|
-
# Anthropic: "prompt is too long: N tokens > M maximum".
|
|
32
|
-
"prompt is too long",
|
|
33
|
-
# Anthropic byte-size overflow: HTTP 413 {"type": "request_too_large"}.
|
|
34
|
-
"request_too_large",
|
|
35
|
-
# HTTP proxies reject an oversized body with 413 "Request Entity Too Large".
|
|
36
|
-
"request entity too large",
|
|
37
|
-
# Google: "The input token count (N) exceeds the maximum number of tokens allowed (M)".
|
|
38
|
-
"exceeds the maximum number of tokens",
|
|
39
|
-
# xAI: "This model's maximum prompt length is N but the request contains M tokens".
|
|
40
|
-
"maximum prompt length is",
|
|
41
|
-
)
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
def is_context_overflow(error: APIStatusError) -> bool:
|
|
45
|
-
details = f"{error} {error.body or ''}".casefold()
|
|
46
|
-
# An overflow is deterministic: a 400, or a 413 for a byte-size cap.
|
|
47
|
-
return error.status_code in (400, 413) and any(
|
|
48
|
-
marker in details for marker in CONTEXT_OVERFLOW_MARKERS
|
|
49
|
-
)
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
async def chat(
|
|
53
|
-
client: AsyncOpenAI, model: str, messages: list[dict], tools: list[dict]
|
|
54
|
-
):
|
|
55
|
-
completion = await client.chat.completions.create(
|
|
56
|
-
model=model, messages=messages, tools=tools or None
|
|
57
|
-
)
|
|
58
|
-
return completion.choices[0].message
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
@asynccontextmanager
|
|
62
|
-
async def mcp_client(spec: dict):
|
|
63
|
-
"""One fresh MCP client, negotiating the newest protocol and falling back for old servers.
|
|
64
|
-
|
|
65
|
-
It is opened and closed within the caller's task so AnyIO cancellation scopes stay correctly
|
|
66
|
-
nested. Closing noise after a completed body cannot fail or replay an answered call.
|
|
67
|
-
"""
|
|
68
|
-
import httpx2
|
|
69
|
-
from mcp import Client
|
|
70
|
-
from mcp.client.streamable_http import (
|
|
71
|
-
create_mcp_http_client,
|
|
72
|
-
streamable_http_client,
|
|
73
|
-
)
|
|
74
|
-
|
|
75
|
-
stack = AsyncExitStack()
|
|
76
|
-
try:
|
|
77
|
-
http_client = await stack.enter_async_context(
|
|
78
|
-
create_mcp_http_client(
|
|
79
|
-
headers=spec.get("headers") or None,
|
|
80
|
-
timeout=httpx2.Timeout(spec.get("timeout", MCP_TIMEOUT), connect=5.0),
|
|
81
|
-
)
|
|
82
|
-
)
|
|
83
|
-
transport = streamable_http_client(spec["url"], http_client=http_client)
|
|
84
|
-
yield await stack.enter_async_context(Client(transport))
|
|
85
|
-
finally:
|
|
86
|
-
with suppress(Exception):
|
|
87
|
-
await stack.aclose()
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
async def with_retry(call):
|
|
91
|
-
"""Run one client operation, retrying transient failures with backoff. A call whose
|
|
92
|
-
response was lost may be replayed — MCP has no idempotency key, so tools should tolerate
|
|
93
|
-
at-least-once delivery (a tool that fails reports through its result, not an exception)."""
|
|
94
|
-
async for attempt in AsyncRetrying(
|
|
95
|
-
stop=stop_after_attempt(MCP_CALL_ATTEMPTS),
|
|
96
|
-
wait=wait_exponential_jitter(initial=0.5, max=30),
|
|
97
|
-
reraise=True,
|
|
98
|
-
):
|
|
99
|
-
with attempt:
|
|
100
|
-
return await call()
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
async def connect_mcp(config: dict) -> tuple[list[dict], dict, dict]:
|
|
104
|
-
"""Enumerate each configured MCP server's tools (a streamable-HTTP `url`); return (tool schemas,
|
|
105
|
-
dispatch mapping advertised name -> (server name, raw tool name), servers mapping name -> spec).
|
|
106
|
-
No protocol session is held; a fresh client handles each call. Tools are advertised as
|
|
107
|
-
`<server>_<tool>`; a server named `""` (TOOL_PREFIX = None) advertises its tools bare, so names
|
|
108
|
-
must be unique across the rollout's servers."""
|
|
109
|
-
tool_schemas: list[dict] = []
|
|
110
|
-
dispatch: dict[str, tuple] = {}
|
|
111
|
-
servers: dict[str, dict] = {}
|
|
112
|
-
for name, spec in config.get("mcpServers", {}).items():
|
|
113
|
-
servers[name] = spec
|
|
114
|
-
|
|
115
|
-
async def list_tools(spec: dict = spec):
|
|
116
|
-
async with mcp_client(spec) as client:
|
|
117
|
-
return (await client.list_tools()).tools
|
|
118
|
-
|
|
119
|
-
for tool in await with_retry(list_tools):
|
|
120
|
-
full = f"{name}_{tool.name}" if name else tool.name
|
|
121
|
-
if full in dispatch:
|
|
122
|
-
raise ValueError(
|
|
123
|
-
f"duplicate tool name {full!r} across servers; keep qualified names"
|
|
124
|
-
)
|
|
125
|
-
tool_schemas.append(
|
|
126
|
-
{
|
|
127
|
-
"type": "function",
|
|
128
|
-
"function": {
|
|
129
|
-
"name": full,
|
|
130
|
-
"description": tool.description or "",
|
|
131
|
-
"parameters": tool.input_schema,
|
|
132
|
-
},
|
|
133
|
-
}
|
|
134
|
-
)
|
|
135
|
-
dispatch[full] = (name, tool.name)
|
|
136
|
-
return tool_schemas, dispatch, servers
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
def mcp_content_to_chat_content(blocks) -> str | list[dict]:
|
|
140
|
-
parts = []
|
|
141
|
-
for block in blocks:
|
|
142
|
-
if block.type == "text":
|
|
143
|
-
parts.append({"type": "text", "text": block.text})
|
|
144
|
-
elif block.type == "image":
|
|
145
|
-
url = f"data:{block.mime_type};base64,{block.data}"
|
|
146
|
-
parts.append({"type": "image_url", "image_url": {"url": url}})
|
|
147
|
-
else:
|
|
148
|
-
parts.append({"type": "text", "text": str(block)})
|
|
149
|
-
if not parts:
|
|
150
|
-
return str(blocks)
|
|
151
|
-
if all(part["type"] == "text" for part in parts):
|
|
152
|
-
return "\n".join(part["text"] for part in parts)
|
|
153
|
-
return parts
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
async def call_mcp(
|
|
157
|
-
servers: dict, dispatch: dict, name: str, arguments: dict
|
|
158
|
-
) -> str | list[dict]:
|
|
159
|
-
"""Call a tool with a fresh client per attempt — see `with_retry` for replay semantics.
|
|
160
|
-
The result is converted outside the retry so a conversion failure fails once."""
|
|
161
|
-
server_name, raw = dispatch[name]
|
|
162
|
-
|
|
163
|
-
async def call():
|
|
164
|
-
async with mcp_client(servers[server_name]) as client:
|
|
165
|
-
return await client.call_tool(raw, arguments)
|
|
166
|
-
|
|
167
|
-
result = await with_retry(call)
|
|
168
|
-
return mcp_content_to_chat_content(result.content)
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
def parse_args() -> argparse.Namespace:
|
|
172
|
-
parser = argparse.ArgumentParser()
|
|
173
|
-
parser.add_argument("--base-url", required=True)
|
|
174
|
-
parser.add_argument("--api-key", required=True)
|
|
175
|
-
parser.add_argument("--model", required=True)
|
|
176
|
-
parser.add_argument("--system-prompt", default="")
|
|
177
|
-
parser.add_argument("--prompt", default="")
|
|
178
|
-
parser.add_argument("--initial-messages-file", default="")
|
|
179
|
-
parser.add_argument("--mcp-config", default="")
|
|
180
|
-
return parser.parse_args()
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
async def main() -> None:
|
|
184
|
-
args = parse_args()
|
|
185
|
-
initial = []
|
|
186
|
-
if args.initial_messages_file:
|
|
187
|
-
path = Path(args.initial_messages_file)
|
|
188
|
-
payload = path.read_bytes()
|
|
189
|
-
path.unlink()
|
|
190
|
-
initial = json.loads(payload)
|
|
191
|
-
client = AsyncOpenAI(
|
|
192
|
-
base_url=args.base_url,
|
|
193
|
-
api_key=args.api_key,
|
|
194
|
-
timeout=httpx.Timeout(None, connect=5.0),
|
|
195
|
-
)
|
|
196
|
-
config = json.loads(args.mcp_config or "{}")
|
|
197
|
-
if config.get("mcpServers"):
|
|
198
|
-
# Bound only tool enumeration; each client is opened and closed within this task.
|
|
199
|
-
async with asyncio.timeout(60):
|
|
200
|
-
tools, dispatch, servers = await connect_mcp(config)
|
|
201
|
-
else:
|
|
202
|
-
tools, dispatch, servers = [], {}, {}
|
|
203
|
-
messages = (
|
|
204
|
-
[{"role": "system", "content": args.system_prompt}]
|
|
205
|
-
if args.system_prompt
|
|
206
|
-
else []
|
|
207
|
-
)
|
|
208
|
-
if initial:
|
|
209
|
-
messages.extend(initial)
|
|
210
|
-
elif args.prompt:
|
|
211
|
-
messages.append({"role": "user", "content": args.prompt})
|
|
212
|
-
while True:
|
|
213
|
-
try:
|
|
214
|
-
message = await chat(client, args.model, messages, tools)
|
|
215
|
-
except APIStatusError as error:
|
|
216
|
-
# Context exhaustion is a budget limit, not a crash: this harness has no
|
|
217
|
-
# compaction, so end the run cleanly with what the conversation holds.
|
|
218
|
-
if not is_context_overflow(error):
|
|
219
|
-
raise
|
|
220
|
-
return
|
|
221
|
-
messages.append(message.model_dump(exclude_none=True))
|
|
222
|
-
if not message.tool_calls:
|
|
223
|
-
break
|
|
224
|
-
for call in message.tool_calls:
|
|
225
|
-
name = call.function.name
|
|
226
|
-
try:
|
|
227
|
-
tool_args = json.loads(call.function.arguments or "{}")
|
|
228
|
-
except json.JSONDecodeError as e:
|
|
229
|
-
messages.append(
|
|
230
|
-
{
|
|
231
|
-
"role": "tool",
|
|
232
|
-
"tool_call_id": call.id,
|
|
233
|
-
"content": f"error: invalid JSON in tool arguments ({e}); resend the call with valid JSON",
|
|
234
|
-
}
|
|
235
|
-
)
|
|
236
|
-
continue
|
|
237
|
-
# Valid JSON can still be a non-object (`[]`, `42`, `null`); the MCP dispatch
|
|
238
|
-
# assumes a dict, so reject anything else as a tool error rather than crashing.
|
|
239
|
-
if not isinstance(tool_args, dict):
|
|
240
|
-
messages.append(
|
|
241
|
-
{
|
|
242
|
-
"role": "tool",
|
|
243
|
-
"tool_call_id": call.id,
|
|
244
|
-
"content": f"error: tool arguments must be a JSON object, got {type(tool_args).__name__}; resend as an object",
|
|
245
|
-
}
|
|
246
|
-
)
|
|
247
|
-
continue
|
|
248
|
-
if name in dispatch:
|
|
249
|
-
content = await call_mcp(servers, dispatch, name, tool_args)
|
|
250
|
-
else:
|
|
251
|
-
content = f"error: unknown tool {name!r}"
|
|
252
|
-
messages.append(
|
|
253
|
-
{"role": "tool", "tool_call_id": call.id, "content": content}
|
|
254
|
-
)
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
if __name__ == "__main__":
|
|
258
|
-
asyncio.run(main())
|
|
File without changes
|
|
File without changes
|
|
File without changes
|