verifiers 0.3.2.dev26__py3-none-any.whl → 0.3.2.dev27__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 +6 -4
- verifiers/v1/harnesses/browser_use/harness.py +4 -3
- verifiers/v1/harnesses/browser_use/program.py +1 -1
- verifiers/v1/harnesses/null/harness.py +6 -4
- verifiers/v1/harnesses/utils/__init__.py +7 -0
- verifiers/v1/harnesses/utils/compaction.py +256 -0
- verifiers/v1/harnesses/{minimal/program.py → utils/core.py} +102 -345
- verifiers/v1/harnesses/{standalone.py → utils/launch.py} +19 -5
- verifiers/v1/mcp/__init__.py +0 -12
- verifiers/v1/tasksets/nemo_gym/toolset.py +2 -1
- {verifiers-0.3.2.dev26.dist-info → verifiers-0.3.2.dev27.dist-info}/METADATA +1 -1
- {verifiers-0.3.2.dev26.dist-info → verifiers-0.3.2.dev27.dist-info}/RECORD +16 -15
- verifiers/v1/harnesses/minimal/__init__.py +0 -9
- /verifiers/v1/{mcp/client.py → harnesses/utils/mcp.py} +0 -0
- {verifiers-0.3.2.dev26.dist-info → verifiers-0.3.2.dev27.dist-info}/WHEEL +0 -0
- {verifiers-0.3.2.dev26.dist-info → verifiers-0.3.2.dev27.dist-info}/entry_points.txt +0 -0
- {verifiers-0.3.2.dev26.dist-info → verifiers-0.3.2.dev27.dist-info}/licenses/LICENSE +0 -0
|
@@ -6,8 +6,10 @@ from pydantic_config import BaseConfig
|
|
|
6
6
|
from verifiers.v1.clients import ModelContext
|
|
7
7
|
from verifiers.v1.configs.harness import HarnessConfig
|
|
8
8
|
from verifiers.v1.harness import Harness
|
|
9
|
-
from verifiers.v1.harnesses.
|
|
10
|
-
|
|
9
|
+
from verifiers.v1.harnesses.utils.launch import (
|
|
10
|
+
CHAT_PROGRAM_SOURCE,
|
|
11
|
+
launch_chat_program,
|
|
12
|
+
)
|
|
11
13
|
from verifiers.v1.runtimes import ProgramResult, Runtime
|
|
12
14
|
from verifiers.v1.task import TaskData
|
|
13
15
|
from verifiers.v1.trace import Trace
|
|
@@ -57,7 +59,7 @@ class BashHarness(Harness[BashHarnessConfig]):
|
|
|
57
59
|
NEEDS_CONTAINER = False
|
|
58
60
|
|
|
59
61
|
async def setup(self, runtime: Runtime) -> None:
|
|
60
|
-
await runtime.prepare_uv_script(
|
|
62
|
+
await runtime.prepare_uv_script(CHAT_PROGRAM_SOURCE, self.config.resolved_env)
|
|
61
63
|
|
|
62
64
|
async def launch(
|
|
63
65
|
self,
|
|
@@ -109,7 +111,7 @@ class BashHarness(Harness[BashHarnessConfig]):
|
|
|
109
111
|
)
|
|
110
112
|
args += ["--search", f"--serper-key={serper_key}"]
|
|
111
113
|
return await launch_chat_program(
|
|
112
|
-
|
|
114
|
+
CHAT_PROGRAM_SOURCE,
|
|
113
115
|
self.config,
|
|
114
116
|
ctx,
|
|
115
117
|
trace,
|
|
@@ -6,13 +6,14 @@ from pydantic import model_validator
|
|
|
6
6
|
from verifiers.v1.clients import ModelContext
|
|
7
7
|
from verifiers.v1.configs.harness import HarnessConfig
|
|
8
8
|
from verifiers.v1.harness import Harness
|
|
9
|
-
from verifiers.v1.harnesses.
|
|
9
|
+
from verifiers.v1.harnesses.utils import mcp
|
|
10
|
+
from verifiers.v1.harnesses.utils.launch import bundle_program, launch_chat_program
|
|
10
11
|
from verifiers.v1.runtimes import ProgramResult, Runtime
|
|
11
12
|
from verifiers.v1.task import TaskData
|
|
12
13
|
from verifiers.v1.trace import Trace
|
|
13
14
|
|
|
14
|
-
PROGRAM_SOURCE =
|
|
15
|
-
(Path(__file__).resolve().parent / "program.py").read_text()
|
|
15
|
+
PROGRAM_SOURCE = bundle_program(
|
|
16
|
+
(Path(__file__).resolve().parent / "program.py").read_text(), mcp
|
|
16
17
|
)
|
|
17
18
|
|
|
18
19
|
# The helper names and persistence rules the model needs to use the local tool.
|
|
@@ -35,7 +35,7 @@ from openai import AsyncOpenAI
|
|
|
35
35
|
|
|
36
36
|
if TYPE_CHECKING:
|
|
37
37
|
# The harness bundles this module into the generated script before execution.
|
|
38
|
-
from verifiers.v1.mcp
|
|
38
|
+
from verifiers.v1.harnesses.utils.mcp import call_mcp, connect_mcp # noqa: TC004
|
|
39
39
|
|
|
40
40
|
BROWSER_TOOL_TIMEOUT = 3600
|
|
41
41
|
"""Matches the bash harness's command timeout."""
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
from verifiers.v1.clients import ModelContext
|
|
2
2
|
from verifiers.v1.configs.harness import HarnessConfig
|
|
3
3
|
from verifiers.v1.harness import Harness
|
|
4
|
-
from verifiers.v1.harnesses.
|
|
5
|
-
|
|
4
|
+
from verifiers.v1.harnesses.utils.launch import (
|
|
5
|
+
CHAT_PROGRAM_SOURCE,
|
|
6
|
+
launch_chat_program,
|
|
7
|
+
)
|
|
6
8
|
from verifiers.v1.runtimes import ProgramResult, Runtime
|
|
7
9
|
from verifiers.v1.task import TaskData
|
|
8
10
|
from verifiers.v1.trace import Trace
|
|
@@ -20,7 +22,7 @@ class NullHarness(Harness[NullHarnessConfig]):
|
|
|
20
22
|
NEEDS_CONTAINER = False
|
|
21
23
|
|
|
22
24
|
async def setup(self, runtime: Runtime) -> None:
|
|
23
|
-
await runtime.prepare_uv_script(
|
|
25
|
+
await runtime.prepare_uv_script(CHAT_PROGRAM_SOURCE, self.config.resolved_env)
|
|
24
26
|
|
|
25
27
|
async def launch(
|
|
26
28
|
self,
|
|
@@ -34,7 +36,7 @@ class NullHarness(Harness[NullHarnessConfig]):
|
|
|
34
36
|
) -> ProgramResult:
|
|
35
37
|
system_prompt, prompt = self.resolve_prompt(data)
|
|
36
38
|
return await launch_chat_program(
|
|
37
|
-
|
|
39
|
+
CHAT_PROGRAM_SOURCE,
|
|
38
40
|
self.config,
|
|
39
41
|
ctx,
|
|
40
42
|
trace,
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Shared building blocks for harness implementations.
|
|
2
|
+
|
|
3
|
+
`mcp`, `compaction`, and `core` are written to run inside bundled PEP 723
|
|
4
|
+
programs: `launch.bundle_program` splices their sources into a program script,
|
|
5
|
+
so they import only the packages a program declares and reference each other
|
|
6
|
+
through `TYPE_CHECKING` imports that the flat bundle resolves at runtime.
|
|
7
|
+
"""
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Tool-output bounding and context compaction for bundled chat programs."""
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
from openai import APIError, APIStatusError, AsyncOpenAI
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
# The harness bundles this module into the generated script before execution.
|
|
9
|
+
from verifiers.v1.harnesses.utils.core import chat # noqa: TC004
|
|
10
|
+
|
|
11
|
+
RESERVE_TOKENS = 16_384
|
|
12
|
+
"""Compact when this many tokens remain below the model context window."""
|
|
13
|
+
|
|
14
|
+
COMPACTION_ATTEMPTS = 3
|
|
15
|
+
"""Checkpoint attempts before compaction fails: a rejected request falls back to the
|
|
16
|
+
last good snapshot; an empty or tool-calling reply is resampled."""
|
|
17
|
+
|
|
18
|
+
TOOL_OUTPUT_MAX_BYTES = 20_000
|
|
19
|
+
"""Middle-out truncation budget for one tool result before it enters the conversation."""
|
|
20
|
+
|
|
21
|
+
CHECKPOINT_COMPACTION_PROMPT = """You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.
|
|
22
|
+
|
|
23
|
+
Include:
|
|
24
|
+
- Current progress and key decisions made
|
|
25
|
+
- Important context, constraints, or user preferences
|
|
26
|
+
- What remains to be done (clear next steps)
|
|
27
|
+
- Any critical data, examples, or references needed to continue
|
|
28
|
+
|
|
29
|
+
Be concise, structured, and focused on helping the next LLM seamlessly continue the work.
|
|
30
|
+
|
|
31
|
+
Reply with the summary as plain text. Do not call any tools - summarize from the conversation as it stands."""
|
|
32
|
+
|
|
33
|
+
POST_COMPACTION_FRAMING = """Another language model started to solve this problem and produced \
|
|
34
|
+
a summary of its thinking process. You also have access to the state of the tools that \
|
|
35
|
+
were used by that language model. Use this to build on the work \
|
|
36
|
+
that has already been done and avoid duplicating work. Here is \
|
|
37
|
+
the summary produced by the other language model, use the \
|
|
38
|
+
information in this summary to assist with your own analysis:"""
|
|
39
|
+
|
|
40
|
+
CONTEXT_OVERFLOW_MARKERS = (
|
|
41
|
+
# OpenAI error code "context_length_exceeded"; OpenRouter relays the raw body.
|
|
42
|
+
"context_length_exceeded",
|
|
43
|
+
# OpenAI Responses/Completions: "Your input exceeds the context window of this model".
|
|
44
|
+
"exceeds the context window",
|
|
45
|
+
# OpenAI chat: "Input tokens exceed the configured limit of N tokens. Please reduce
|
|
46
|
+
# the length of the messages."; Groq words it the same way.
|
|
47
|
+
"reduce the length of the messages",
|
|
48
|
+
# vLLM: "This model's maximum context length is N tokens"; the renderers pre-flight:
|
|
49
|
+
# "Prompt length (N) exceeds maximum context length (M)"; Mistral uses the same words.
|
|
50
|
+
"maximum context length",
|
|
51
|
+
# Anthropic: "prompt is too long: N tokens > M maximum".
|
|
52
|
+
"prompt is too long",
|
|
53
|
+
# Anthropic byte-size overflow: HTTP 413 {"type": "request_too_large"}.
|
|
54
|
+
"request_too_large",
|
|
55
|
+
# HTTP proxies reject an oversized body with 413 "Request Entity Too Large".
|
|
56
|
+
"request entity too large",
|
|
57
|
+
# Google: "The input token count (N) exceeds the maximum number of tokens allowed (M)".
|
|
58
|
+
"exceeds the maximum number of tokens",
|
|
59
|
+
# xAI: "This model's maximum prompt length is N but the request contains M tokens".
|
|
60
|
+
"maximum prompt length is",
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
CONTEXT_WINDOW_FIELDS = (
|
|
64
|
+
"max_model_len",
|
|
65
|
+
"context_length",
|
|
66
|
+
"context_window",
|
|
67
|
+
"max_context_length",
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class CompactionFailed(Exception):
|
|
72
|
+
"""Every checkpoint attempt failed - the caller ends the run cleanly instead."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def is_context_overflow(error: APIStatusError) -> bool:
|
|
76
|
+
details = f"{error} {error.body or ''}"
|
|
77
|
+
# An overflow is deterministic: a 400, or a 413 for a byte-size cap.
|
|
78
|
+
return error.status_code in (400, 413) and any(
|
|
79
|
+
marker in details.casefold() for marker in CONTEXT_OVERFLOW_MARKERS
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def default_threshold(context_window: int) -> int:
|
|
84
|
+
"""Leave a fixed reserve below the window; small windows keep at least half."""
|
|
85
|
+
return max(context_window - RESERVE_TOKENS, context_window // 2)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
async def discover_threshold(client: AsyncOpenAI, model: str) -> int | None:
|
|
89
|
+
"""The compaction threshold, when the provider's model card advertises a context window.
|
|
90
|
+
|
|
91
|
+
`models.list()` keeps provider extensions in each card's `model_extra`; a raw
|
|
92
|
+
`cast_to` parse breaks on one Python version or another."""
|
|
93
|
+
try:
|
|
94
|
+
page = await client.models.list()
|
|
95
|
+
except APIError:
|
|
96
|
+
return None
|
|
97
|
+
for card in page.data:
|
|
98
|
+
if card.id != model:
|
|
99
|
+
continue
|
|
100
|
+
extra = card.model_extra or {}
|
|
101
|
+
for field in CONTEXT_WINDOW_FIELDS:
|
|
102
|
+
value = extra.get(field)
|
|
103
|
+
if isinstance(value, int) and not isinstance(value, bool) and value > 0:
|
|
104
|
+
return default_threshold(value)
|
|
105
|
+
break
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def compactable(messages: list[dict]) -> bool:
|
|
110
|
+
"""Whether compaction can reclaim anything - some history beyond the task exists."""
|
|
111
|
+
first_user = next(
|
|
112
|
+
(i for i, m in enumerate(messages) if m.get("role") == "user"), None
|
|
113
|
+
)
|
|
114
|
+
return any(
|
|
115
|
+
m.get("role") != "system" and i != first_user for i, m in enumerate(messages)
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def bound_tool_message(message: dict) -> dict:
|
|
120
|
+
"""Bound a tool message before it enters the conversation - rewrites included."""
|
|
121
|
+
content = message.get("content")
|
|
122
|
+
if isinstance(content, str):
|
|
123
|
+
return {**message, "content": truncate_tool_output(content)}
|
|
124
|
+
# Multimodal results come back as content-part lists; only plain text is truncated.
|
|
125
|
+
return message
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def truncate_tool_output(text: str) -> str:
|
|
129
|
+
"""Keep the head and tail of an oversized tool result and say what was cut."""
|
|
130
|
+
data = text.encode("utf-8")
|
|
131
|
+
if len(data) <= TOOL_OUTPUT_MAX_BYTES:
|
|
132
|
+
return text
|
|
133
|
+
keep = TOOL_OUTPUT_MAX_BYTES // 2
|
|
134
|
+
head = data[:keep].decode("utf-8", errors="ignore")
|
|
135
|
+
tail = data[-keep:].decode("utf-8", errors="ignore")
|
|
136
|
+
return (
|
|
137
|
+
f"Warning: truncated output (original token count: {estimated_tokens(text)})\n"
|
|
138
|
+
f"Total output lines: {text.count(chr(10)) + 1}\n\n"
|
|
139
|
+
f"{head}\n[... {len(data) - 2 * keep} bytes truncated ...]\n{tail}"
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def estimated_tokens(chars: str) -> int:
|
|
144
|
+
"""Rough token count at four characters per token."""
|
|
145
|
+
return (len(chars) + 3) // 4
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def context_tokens(completion) -> int:
|
|
149
|
+
usage = completion.usage
|
|
150
|
+
if usage is None:
|
|
151
|
+
return 0
|
|
152
|
+
return (usage.prompt_tokens or 0) + (usage.completion_tokens or 0)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class Compactor:
|
|
156
|
+
"""Compact once and retry once when a model turn exhausts its context."""
|
|
157
|
+
|
|
158
|
+
def __init__(self, client, model, tools, enabled, threshold):
|
|
159
|
+
self.client = client
|
|
160
|
+
self.model = model
|
|
161
|
+
self.tools = tools
|
|
162
|
+
self.enabled = enabled
|
|
163
|
+
self.threshold = threshold
|
|
164
|
+
self.compacted = False
|
|
165
|
+
self.last_good = 0
|
|
166
|
+
"""Message count of the newest state that passed a threshold check - by
|
|
167
|
+
definition a state with a full reserve of room, so a checkpoint over it fits."""
|
|
168
|
+
|
|
169
|
+
def reached(self, completion, extra_tokens: int = 0) -> bool:
|
|
170
|
+
return (
|
|
171
|
+
self.enabled
|
|
172
|
+
and self.threshold is not None
|
|
173
|
+
and context_tokens(completion) + extra_tokens >= self.threshold
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
def note_good(self, messages: list[dict]) -> None:
|
|
177
|
+
self.last_good = len(messages)
|
|
178
|
+
|
|
179
|
+
async def complete(self, messages: list[dict]):
|
|
180
|
+
try:
|
|
181
|
+
completion = await chat(self.client, self.model, messages, self.tools)
|
|
182
|
+
except APIStatusError as error:
|
|
183
|
+
if (
|
|
184
|
+
not self.enabled
|
|
185
|
+
or self.threshold is None
|
|
186
|
+
or not is_context_overflow(error)
|
|
187
|
+
):
|
|
188
|
+
raise
|
|
189
|
+
if not compactable(messages):
|
|
190
|
+
if self.compacted:
|
|
191
|
+
# The conversation is already a compaction floor and still
|
|
192
|
+
# overflows - out of moves, end cleanly.
|
|
193
|
+
raise CompactionFailed(
|
|
194
|
+
"the compacted conversation still overflows"
|
|
195
|
+
) from error
|
|
196
|
+
raise
|
|
197
|
+
else:
|
|
198
|
+
choice = completion.choices[0]
|
|
199
|
+
if not self.reached(completion):
|
|
200
|
+
# Usage-verified: this exact prompt was accepted with a full
|
|
201
|
+
# reserve of room, so it is a safe checkpoint fallback.
|
|
202
|
+
self.note_good(messages)
|
|
203
|
+
return completion, messages
|
|
204
|
+
if choice.finish_reason != "length" or not compactable(messages):
|
|
205
|
+
return completion, messages
|
|
206
|
+
|
|
207
|
+
messages = await self.compact(messages)
|
|
208
|
+
try:
|
|
209
|
+
completion = await chat(self.client, self.model, messages, self.tools)
|
|
210
|
+
except APIStatusError as error:
|
|
211
|
+
# The rebuilt conversation is sized to fit, so this is out of moves.
|
|
212
|
+
if is_context_overflow(error):
|
|
213
|
+
raise CompactionFailed(
|
|
214
|
+
"the rebuilt conversation still overflows"
|
|
215
|
+
) from error
|
|
216
|
+
raise
|
|
217
|
+
return completion, messages
|
|
218
|
+
|
|
219
|
+
async def compact(self, messages: list[dict]) -> list[dict]:
|
|
220
|
+
# A rejected checkpoint falls back to the last good snapshot (which has a
|
|
221
|
+
# full reserve of room, so it fits); an empty or tool-calling reply is
|
|
222
|
+
# resampled. Reasoning is never part of the summary.
|
|
223
|
+
system = [message for message in messages if message.get("role") == "system"]
|
|
224
|
+
base = messages
|
|
225
|
+
for _ in range(COMPACTION_ATTEMPTS):
|
|
226
|
+
checkpoint = [
|
|
227
|
+
*base,
|
|
228
|
+
{"role": "user", "content": CHECKPOINT_COMPACTION_PROMPT},
|
|
229
|
+
]
|
|
230
|
+
try:
|
|
231
|
+
completion = await chat(
|
|
232
|
+
self.client,
|
|
233
|
+
self.model,
|
|
234
|
+
checkpoint,
|
|
235
|
+
self.tools,
|
|
236
|
+
tool_choice="none",
|
|
237
|
+
)
|
|
238
|
+
except APIStatusError as error:
|
|
239
|
+
if not is_context_overflow(error):
|
|
240
|
+
raise
|
|
241
|
+
base = messages[: self.last_good]
|
|
242
|
+
continue
|
|
243
|
+
message = completion.choices[0].message
|
|
244
|
+
# Reasoning never enters the summary: only the reply's final text
|
|
245
|
+
# counts, so a reply that lives entirely in the reasoning channel
|
|
246
|
+
# is resampled like an empty one.
|
|
247
|
+
text = (message.content or "").strip()
|
|
248
|
+
if not message.tool_calls and text:
|
|
249
|
+
framed = POST_COMPACTION_FRAMING + "\n\n" + text
|
|
250
|
+
rebuilt = [*system, {"role": "user", "content": framed}]
|
|
251
|
+
self.note_good(rebuilt)
|
|
252
|
+
self.compacted = True
|
|
253
|
+
return rebuilt
|
|
254
|
+
raise CompactionFailed(
|
|
255
|
+
f"no usable summary after {COMPACTION_ATTEMPTS} attempts"
|
|
256
|
+
)
|
|
@@ -1,8 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
# requires-python = ">=3.10"
|
|
3
|
-
# dependencies = ["openai", "mcp==2.0.0", "httpx", "httpx2", "tenacity"]
|
|
4
|
-
# ///
|
|
5
|
-
"""Shared Null/Bash chat program; secrets use argv so tools do not inherit them."""
|
|
1
|
+
"""Chat loop, local tools, and interception hook for bundled chat programs."""
|
|
6
2
|
|
|
7
3
|
import argparse
|
|
8
4
|
import asyncio
|
|
@@ -12,119 +8,22 @@ from pathlib import Path
|
|
|
12
8
|
from typing import TYPE_CHECKING
|
|
13
9
|
|
|
14
10
|
import httpx
|
|
15
|
-
from openai import
|
|
11
|
+
from openai import APIStatusError, AsyncOpenAI
|
|
16
12
|
|
|
17
13
|
if TYPE_CHECKING:
|
|
18
14
|
# The harness bundles this module into the generated script before execution.
|
|
19
|
-
from verifiers.v1.
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
|
15
|
+
from verifiers.v1.harnesses.utils.compaction import ( # noqa: TC004
|
|
16
|
+
CompactionFailed,
|
|
17
|
+
Compactor,
|
|
18
|
+
bound_tool_message,
|
|
19
|
+
compactable,
|
|
20
|
+
discover_threshold,
|
|
21
|
+
estimated_tokens,
|
|
22
|
+
is_context_overflow,
|
|
40
23
|
)
|
|
24
|
+
from verifiers.v1.harnesses.utils.mcp import call_mcp, connect_mcp # noqa: TC004
|
|
41
25
|
|
|
42
|
-
|
|
43
|
-
RESERVE_TOKENS = 16_384
|
|
44
|
-
"""Compact when this many tokens remain below the model context window."""
|
|
45
|
-
|
|
46
|
-
COMPACTION_ATTEMPTS = 3
|
|
47
|
-
"""Checkpoint attempts before compaction fails: a rejected request falls back to the
|
|
48
|
-
last good snapshot; an empty or tool-calling reply is resampled."""
|
|
49
|
-
|
|
50
|
-
TOOL_OUTPUT_MAX_BYTES = 20_000
|
|
51
|
-
"""Middle-out truncation budget for one tool result before it enters the conversation."""
|
|
52
|
-
|
|
53
|
-
CHECKPOINT_COMPACTION_PROMPT = """You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.
|
|
54
|
-
|
|
55
|
-
Include:
|
|
56
|
-
- Current progress and key decisions made
|
|
57
|
-
- Important context, constraints, or user preferences
|
|
58
|
-
- What remains to be done (clear next steps)
|
|
59
|
-
- Any critical data, examples, or references needed to continue
|
|
60
|
-
|
|
61
|
-
Be concise, structured, and focused on helping the next LLM seamlessly continue the work.
|
|
62
|
-
|
|
63
|
-
Reply with the summary as plain text. Do not call any tools - summarize from the conversation as it stands."""
|
|
64
|
-
|
|
65
|
-
POST_COMPACTION_FRAMING = """Another language model started to solve this problem and produced \
|
|
66
|
-
a summary of its thinking process. You also have access to the state of the tools that \
|
|
67
|
-
were used by that language model. Use this to build on the work \
|
|
68
|
-
that has already been done and avoid duplicating work. Here is \
|
|
69
|
-
the summary produced by the other language model, use the \
|
|
70
|
-
information in this summary to assist with your own analysis:"""
|
|
71
|
-
|
|
72
|
-
CONTEXT_OVERFLOW_MARKERS = (
|
|
73
|
-
# OpenAI error code "context_length_exceeded"; OpenRouter relays the raw body.
|
|
74
|
-
"context_length_exceeded",
|
|
75
|
-
# OpenAI Responses/Completions: "Your input exceeds the context window of this model".
|
|
76
|
-
"exceeds the context window",
|
|
77
|
-
# OpenAI chat: "Input tokens exceed the configured limit of N tokens. Please reduce
|
|
78
|
-
# the length of the messages."; Groq words it the same way.
|
|
79
|
-
"reduce the length of the messages",
|
|
80
|
-
# vLLM: "This model's maximum context length is N tokens"; the renderers pre-flight:
|
|
81
|
-
# "Prompt length (N) exceeds maximum context length (M)"; Mistral uses the same words.
|
|
82
|
-
"maximum context length",
|
|
83
|
-
# Anthropic: "prompt is too long: N tokens > M maximum".
|
|
84
|
-
"prompt is too long",
|
|
85
|
-
# Anthropic byte-size overflow: HTTP 413 {"type": "request_too_large"}.
|
|
86
|
-
"request_too_large",
|
|
87
|
-
# HTTP proxies reject an oversized body with 413 "Request Entity Too Large".
|
|
88
|
-
"request entity too large",
|
|
89
|
-
# Google: "The input token count (N) exceeds the maximum number of tokens allowed (M)".
|
|
90
|
-
"exceeds the maximum number of tokens",
|
|
91
|
-
# xAI: "This model's maximum prompt length is N but the request contains M tokens".
|
|
92
|
-
"maximum prompt length is",
|
|
93
|
-
)
|
|
94
|
-
|
|
95
|
-
CONTEXT_WINDOW_FIELDS = (
|
|
96
|
-
"max_model_len",
|
|
97
|
-
"context_length",
|
|
98
|
-
"context_window",
|
|
99
|
-
"max_context_length",
|
|
100
|
-
)
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
def default_threshold(context_window: int) -> int:
|
|
104
|
-
"""Leave a fixed reserve below the window; small windows keep at least half."""
|
|
105
|
-
return max(context_window - RESERVE_TOKENS, context_window // 2)
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
async def discover_threshold(client: AsyncOpenAI, model: str) -> int | None:
|
|
109
|
-
"""The compaction threshold, when the provider's model card advertises a context window.
|
|
110
|
-
|
|
111
|
-
`models.list()` keeps provider extensions in each card's `model_extra`; a raw
|
|
112
|
-
`cast_to` parse breaks on one Python version or another."""
|
|
113
|
-
try:
|
|
114
|
-
page = await client.models.list()
|
|
115
|
-
except APIError:
|
|
116
|
-
return None
|
|
117
|
-
for card in page.data:
|
|
118
|
-
if card.id != model:
|
|
119
|
-
continue
|
|
120
|
-
extra = card.model_extra or {}
|
|
121
|
-
for field in CONTEXT_WINDOW_FIELDS:
|
|
122
|
-
value = extra.get(field)
|
|
123
|
-
if isinstance(value, int) and not isinstance(value, bool) and value > 0:
|
|
124
|
-
return default_threshold(value)
|
|
125
|
-
break
|
|
126
|
-
return None
|
|
127
|
-
|
|
26
|
+
SERPER_URL = "https://google.serper.dev/search"
|
|
128
27
|
|
|
129
28
|
BASH_TOOL = {
|
|
130
29
|
"type": "function",
|
|
@@ -166,7 +65,6 @@ EDIT_TOOL = {
|
|
|
166
65
|
},
|
|
167
66
|
}
|
|
168
67
|
|
|
169
|
-
|
|
170
68
|
SEARCH_TOOL = {
|
|
171
69
|
"type": "function",
|
|
172
70
|
"function": {
|
|
@@ -296,160 +194,6 @@ async def chat(
|
|
|
296
194
|
return await client.chat.completions.create(**kwargs)
|
|
297
195
|
|
|
298
196
|
|
|
299
|
-
class CompactionFailed(Exception):
|
|
300
|
-
"""Every checkpoint attempt failed - the caller ends the run cleanly instead."""
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
def compactable(messages: list[dict]) -> bool:
|
|
304
|
-
"""Whether compaction can reclaim anything - some history beyond the task exists."""
|
|
305
|
-
first_user = next(
|
|
306
|
-
(i for i, m in enumerate(messages) if m.get("role") == "user"), None
|
|
307
|
-
)
|
|
308
|
-
return any(
|
|
309
|
-
m.get("role") != "system" and i != first_user for i, m in enumerate(messages)
|
|
310
|
-
)
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
def bound_tool_message(message: dict) -> dict:
|
|
314
|
-
"""Bound a tool message before it enters the conversation - rewrites included."""
|
|
315
|
-
content = message.get("content")
|
|
316
|
-
if isinstance(content, str):
|
|
317
|
-
return {**message, "content": truncate_tool_output(content)}
|
|
318
|
-
# Multimodal results come back as content-part lists; only plain text is truncated.
|
|
319
|
-
return message
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
def truncate_tool_output(text: str) -> str:
|
|
323
|
-
"""Keep the head and tail of an oversized tool result and say what was cut."""
|
|
324
|
-
data = text.encode("utf-8")
|
|
325
|
-
if len(data) <= TOOL_OUTPUT_MAX_BYTES:
|
|
326
|
-
return text
|
|
327
|
-
keep = TOOL_OUTPUT_MAX_BYTES // 2
|
|
328
|
-
head = data[:keep].decode("utf-8", errors="ignore")
|
|
329
|
-
tail = data[-keep:].decode("utf-8", errors="ignore")
|
|
330
|
-
return (
|
|
331
|
-
f"Warning: truncated output (original token count: {estimated_tokens(text)})\n"
|
|
332
|
-
f"Total output lines: {text.count(chr(10)) + 1}\n\n"
|
|
333
|
-
f"{head}\n[... {len(data) - 2 * keep} bytes truncated ...]\n{tail}"
|
|
334
|
-
)
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
def estimated_tokens(chars: str) -> int:
|
|
338
|
-
"""Rough token count at four characters per token."""
|
|
339
|
-
return (len(chars) + 3) // 4
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
def context_tokens(completion) -> int:
|
|
343
|
-
usage = completion.usage
|
|
344
|
-
if usage is None:
|
|
345
|
-
return 0
|
|
346
|
-
return (usage.prompt_tokens or 0) + (usage.completion_tokens or 0)
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
class Compactor:
|
|
350
|
-
"""Compact once and retry once when a model turn exhausts its context."""
|
|
351
|
-
|
|
352
|
-
def __init__(self, client, model, tools, enabled, threshold):
|
|
353
|
-
self.client = client
|
|
354
|
-
self.model = model
|
|
355
|
-
self.tools = tools
|
|
356
|
-
self.enabled = enabled
|
|
357
|
-
self.threshold = threshold
|
|
358
|
-
self.compacted = False
|
|
359
|
-
self.last_good = 0
|
|
360
|
-
"""Message count of the newest state that passed a threshold check - by
|
|
361
|
-
definition a state with a full reserve of room, so a checkpoint over it fits."""
|
|
362
|
-
|
|
363
|
-
def reached(self, completion, extra_tokens: int = 0) -> bool:
|
|
364
|
-
return (
|
|
365
|
-
self.enabled
|
|
366
|
-
and self.threshold is not None
|
|
367
|
-
and context_tokens(completion) + extra_tokens >= self.threshold
|
|
368
|
-
)
|
|
369
|
-
|
|
370
|
-
def note_good(self, messages: list[dict]) -> None:
|
|
371
|
-
self.last_good = len(messages)
|
|
372
|
-
|
|
373
|
-
async def complete(self, messages: list[dict]):
|
|
374
|
-
try:
|
|
375
|
-
completion = await chat(self.client, self.model, messages, self.tools)
|
|
376
|
-
except APIStatusError as error:
|
|
377
|
-
if (
|
|
378
|
-
not self.enabled
|
|
379
|
-
or self.threshold is None
|
|
380
|
-
or not is_context_overflow(error)
|
|
381
|
-
):
|
|
382
|
-
raise
|
|
383
|
-
if not compactable(messages):
|
|
384
|
-
if self.compacted:
|
|
385
|
-
# The conversation is already a compaction floor and still
|
|
386
|
-
# overflows - out of moves, end cleanly.
|
|
387
|
-
raise CompactionFailed(
|
|
388
|
-
"the compacted conversation still overflows"
|
|
389
|
-
) from error
|
|
390
|
-
raise
|
|
391
|
-
else:
|
|
392
|
-
choice = completion.choices[0]
|
|
393
|
-
if not self.reached(completion):
|
|
394
|
-
# Usage-verified: this exact prompt was accepted with a full
|
|
395
|
-
# reserve of room, so it is a safe checkpoint fallback.
|
|
396
|
-
self.note_good(messages)
|
|
397
|
-
return completion, messages
|
|
398
|
-
if choice.finish_reason != "length" or not compactable(messages):
|
|
399
|
-
return completion, messages
|
|
400
|
-
|
|
401
|
-
messages = await self.compact(messages)
|
|
402
|
-
try:
|
|
403
|
-
completion = await chat(self.client, self.model, messages, self.tools)
|
|
404
|
-
except APIStatusError as error:
|
|
405
|
-
# The rebuilt conversation is sized to fit, so this is out of moves.
|
|
406
|
-
if is_context_overflow(error):
|
|
407
|
-
raise CompactionFailed(
|
|
408
|
-
"the rebuilt conversation still overflows"
|
|
409
|
-
) from error
|
|
410
|
-
raise
|
|
411
|
-
return completion, messages
|
|
412
|
-
|
|
413
|
-
async def compact(self, messages: list[dict]) -> list[dict]:
|
|
414
|
-
# A rejected checkpoint falls back to the last good snapshot (which has a
|
|
415
|
-
# full reserve of room, so it fits); an empty or tool-calling reply is
|
|
416
|
-
# resampled. Reasoning is never part of the summary.
|
|
417
|
-
system = [message for message in messages if message.get("role") == "system"]
|
|
418
|
-
base = messages
|
|
419
|
-
for _ in range(COMPACTION_ATTEMPTS):
|
|
420
|
-
checkpoint = [
|
|
421
|
-
*base,
|
|
422
|
-
{"role": "user", "content": CHECKPOINT_COMPACTION_PROMPT},
|
|
423
|
-
]
|
|
424
|
-
try:
|
|
425
|
-
completion = await chat(
|
|
426
|
-
self.client,
|
|
427
|
-
self.model,
|
|
428
|
-
checkpoint,
|
|
429
|
-
self.tools,
|
|
430
|
-
tool_choice="none",
|
|
431
|
-
)
|
|
432
|
-
except APIStatusError as error:
|
|
433
|
-
if not is_context_overflow(error):
|
|
434
|
-
raise
|
|
435
|
-
base = messages[: self.last_good]
|
|
436
|
-
continue
|
|
437
|
-
message = completion.choices[0].message
|
|
438
|
-
# Reasoning never enters the summary: only the reply's final text
|
|
439
|
-
# counts, so a reply that lives entirely in the reasoning channel
|
|
440
|
-
# is resampled like an empty one.
|
|
441
|
-
text = (message.content or "").strip()
|
|
442
|
-
if not message.tool_calls and text:
|
|
443
|
-
framed = POST_COMPACTION_FRAMING + "\n\n" + text
|
|
444
|
-
rebuilt = [*system, {"role": "user", "content": framed}]
|
|
445
|
-
self.note_good(rebuilt)
|
|
446
|
-
self.compacted = True
|
|
447
|
-
return rebuilt
|
|
448
|
-
raise CompactionFailed(
|
|
449
|
-
f"no usable summary after {COMPACTION_ATTEMPTS} attempts"
|
|
450
|
-
)
|
|
451
|
-
|
|
452
|
-
|
|
453
197
|
async def run_tool_hook(
|
|
454
198
|
client: httpx.AsyncClient,
|
|
455
199
|
url: str,
|
|
@@ -469,87 +213,22 @@ async def run_tool_hook(
|
|
|
469
213
|
return decision
|
|
470
214
|
|
|
471
215
|
|
|
472
|
-
def
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
parser.add_argument("--tool-interception-url", default="")
|
|
482
|
-
parser.add_argument("--bash", action="store_true")
|
|
483
|
-
parser.add_argument("--compaction", action="store_true")
|
|
484
|
-
parser.add_argument("--summarize-at-tokens", type=int)
|
|
485
|
-
parser.add_argument("--edit", action="store_true")
|
|
486
|
-
parser.add_argument("--search", action="store_true")
|
|
487
|
-
parser.add_argument("--serper-key", default="")
|
|
488
|
-
return parser.parse_args()
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
async def main() -> None:
|
|
492
|
-
args = parse_args()
|
|
493
|
-
initial = []
|
|
494
|
-
if args.initial_messages_file:
|
|
495
|
-
path = Path(args.initial_messages_file)
|
|
496
|
-
payload = path.read_bytes()
|
|
497
|
-
path.unlink()
|
|
498
|
-
initial = json.loads(payload)
|
|
499
|
-
client = AsyncOpenAI(
|
|
500
|
-
base_url=args.base_url,
|
|
501
|
-
api_key=args.api_key,
|
|
502
|
-
timeout=httpx.Timeout(600.0 if args.bash else None, connect=5.0),
|
|
503
|
-
)
|
|
504
|
-
tool_client = (
|
|
505
|
-
httpx.AsyncClient(timeout=httpx.Timeout(None, connect=5.0))
|
|
506
|
-
if args.tool_interception_url
|
|
507
|
-
else None
|
|
508
|
-
)
|
|
509
|
-
config = json.loads(args.mcp_config or "{}")
|
|
510
|
-
tools = [BASH_TOOL] if args.bash else []
|
|
511
|
-
reserved = {"bash"} if args.bash else set()
|
|
512
|
-
if args.edit:
|
|
513
|
-
tools.append(EDIT_TOOL)
|
|
514
|
-
reserved.add("edit")
|
|
515
|
-
if args.search:
|
|
516
|
-
tools.append(SEARCH_TOOL)
|
|
517
|
-
reserved.add("search")
|
|
518
|
-
if config.get("mcpServers"):
|
|
519
|
-
mcp_tools, dispatch, servers = await asyncio.wait_for(
|
|
520
|
-
connect_mcp(config, reserved), timeout=None if args.bash else 60
|
|
521
|
-
)
|
|
522
|
-
else:
|
|
523
|
-
mcp_tools, dispatch, servers = [], {}, {}
|
|
524
|
-
tools += mcp_tools
|
|
525
|
-
messages = (
|
|
526
|
-
[{"role": "system", "content": args.system_prompt}]
|
|
527
|
-
if args.system_prompt
|
|
528
|
-
else []
|
|
529
|
-
)
|
|
530
|
-
if initial:
|
|
531
|
-
messages.extend(initial)
|
|
532
|
-
elif args.prompt:
|
|
533
|
-
messages.append({"role": "user", "content": args.prompt})
|
|
534
|
-
compactor = Compactor(
|
|
535
|
-
client,
|
|
536
|
-
args.model,
|
|
537
|
-
tools,
|
|
538
|
-
args.compaction,
|
|
539
|
-
args.summarize_at_tokens,
|
|
540
|
-
)
|
|
541
|
-
if compactor.enabled and compactor.threshold is None:
|
|
542
|
-
compactor.threshold = await discover_threshold(client, args.model)
|
|
543
|
-
# The initial conversation is the floor for checkpoint fallbacks: a first-turn
|
|
544
|
-
# checkpoint must never retry from an empty base.
|
|
545
|
-
compactor.note_good(messages)
|
|
216
|
+
async def run_chat_loop(
|
|
217
|
+
args: argparse.Namespace,
|
|
218
|
+
compactor: "Compactor",
|
|
219
|
+
messages: list[dict],
|
|
220
|
+
dispatch: dict,
|
|
221
|
+
servers: dict,
|
|
222
|
+
tool_client: httpx.AsyncClient | None,
|
|
223
|
+
) -> None:
|
|
224
|
+
"""Run the tool-calling conversation until a text-only reply or context exhaustion."""
|
|
546
225
|
while True:
|
|
547
226
|
try:
|
|
548
227
|
completion, messages = await compactor.complete(messages)
|
|
549
228
|
except CompactionFailed:
|
|
550
229
|
# The context is exhausted and could not be summarized: end the run
|
|
551
230
|
# cleanly with what the conversation holds - still a trainable sample.
|
|
552
|
-
|
|
231
|
+
return
|
|
553
232
|
except APIStatusError as error:
|
|
554
233
|
# Null cannot compact, so context exhaustion ends it with the transcript so far.
|
|
555
234
|
if args.bash or not is_context_overflow(error):
|
|
@@ -558,7 +237,7 @@ async def main() -> None:
|
|
|
558
237
|
message = completion.choices[0].message
|
|
559
238
|
messages.append(message.model_dump(exclude_none=True))
|
|
560
239
|
if not message.tool_calls:
|
|
561
|
-
|
|
240
|
+
return
|
|
562
241
|
tool_result_tokens = 0
|
|
563
242
|
for call in message.tool_calls:
|
|
564
243
|
name = call.function.name
|
|
@@ -633,10 +312,88 @@ async def main() -> None:
|
|
|
633
312
|
try:
|
|
634
313
|
messages = await compactor.compact(messages)
|
|
635
314
|
except CompactionFailed:
|
|
636
|
-
|
|
315
|
+
return
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def parse_args() -> argparse.Namespace:
|
|
319
|
+
parser = argparse.ArgumentParser()
|
|
320
|
+
parser.add_argument("--base-url", required=True)
|
|
321
|
+
parser.add_argument("--api-key", required=True)
|
|
322
|
+
parser.add_argument("--model", required=True)
|
|
323
|
+
parser.add_argument("--system-prompt", default="")
|
|
324
|
+
parser.add_argument("--prompt", default="")
|
|
325
|
+
parser.add_argument("--initial-messages-file", default="")
|
|
326
|
+
parser.add_argument("--mcp-config", default="")
|
|
327
|
+
parser.add_argument("--tool-interception-url", default="")
|
|
328
|
+
parser.add_argument("--bash", action="store_true")
|
|
329
|
+
parser.add_argument("--compaction", action="store_true")
|
|
330
|
+
parser.add_argument("--summarize-at-tokens", type=int)
|
|
331
|
+
parser.add_argument("--edit", action="store_true")
|
|
332
|
+
parser.add_argument("--search", action="store_true")
|
|
333
|
+
parser.add_argument("--serper-key", default="")
|
|
334
|
+
return parser.parse_args()
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
async def main() -> None:
|
|
338
|
+
args = parse_args()
|
|
339
|
+
initial = []
|
|
340
|
+
if args.initial_messages_file:
|
|
341
|
+
path = Path(args.initial_messages_file)
|
|
342
|
+
payload = path.read_bytes()
|
|
343
|
+
path.unlink()
|
|
344
|
+
initial = json.loads(payload)
|
|
345
|
+
client = AsyncOpenAI(
|
|
346
|
+
base_url=args.base_url,
|
|
347
|
+
api_key=args.api_key,
|
|
348
|
+
timeout=httpx.Timeout(600.0 if args.bash else None, connect=5.0),
|
|
349
|
+
)
|
|
350
|
+
tool_client = (
|
|
351
|
+
httpx.AsyncClient(timeout=httpx.Timeout(None, connect=5.0))
|
|
352
|
+
if args.tool_interception_url
|
|
353
|
+
else None
|
|
354
|
+
)
|
|
355
|
+
config = json.loads(args.mcp_config or "{}")
|
|
356
|
+
tools = [BASH_TOOL] if args.bash else []
|
|
357
|
+
reserved = {"bash"} if args.bash else set()
|
|
358
|
+
if args.edit:
|
|
359
|
+
tools.append(EDIT_TOOL)
|
|
360
|
+
reserved.add("edit")
|
|
361
|
+
if args.search:
|
|
362
|
+
tools.append(SEARCH_TOOL)
|
|
363
|
+
reserved.add("search")
|
|
364
|
+
if config.get("mcpServers"):
|
|
365
|
+
mcp_tools, dispatch, servers = await asyncio.wait_for(
|
|
366
|
+
connect_mcp(config, reserved), timeout=None if args.bash else 60
|
|
367
|
+
)
|
|
368
|
+
else:
|
|
369
|
+
mcp_tools, dispatch, servers = [], {}, {}
|
|
370
|
+
tools += mcp_tools
|
|
371
|
+
messages = (
|
|
372
|
+
[{"role": "system", "content": args.system_prompt}]
|
|
373
|
+
if args.system_prompt
|
|
374
|
+
else []
|
|
375
|
+
)
|
|
376
|
+
if initial:
|
|
377
|
+
messages.extend(initial)
|
|
378
|
+
elif args.prompt:
|
|
379
|
+
messages.append({"role": "user", "content": args.prompt})
|
|
380
|
+
compactor = Compactor(
|
|
381
|
+
client,
|
|
382
|
+
args.model,
|
|
383
|
+
tools,
|
|
384
|
+
args.compaction,
|
|
385
|
+
args.summarize_at_tokens,
|
|
386
|
+
)
|
|
387
|
+
if compactor.enabled and compactor.threshold is None:
|
|
388
|
+
compactor.threshold = await discover_threshold(client, args.model)
|
|
389
|
+
# The initial conversation is the floor for checkpoint fallbacks: a first-turn
|
|
390
|
+
# checkpoint must never retry from an empty base.
|
|
391
|
+
compactor.note_good(messages)
|
|
392
|
+
await run_chat_loop(args, compactor, messages, dispatch, servers, tool_client)
|
|
637
393
|
if tool_client is not None:
|
|
638
394
|
await tool_client.aclose()
|
|
639
395
|
|
|
640
396
|
|
|
397
|
+
# Inert on package import; the entry point once this module ends the bundled script.
|
|
641
398
|
if __name__ == "__main__":
|
|
642
399
|
asyncio.run(main())
|
|
@@ -1,23 +1,37 @@
|
|
|
1
1
|
import inspect
|
|
2
2
|
import json
|
|
3
3
|
from collections.abc import Sequence
|
|
4
|
+
from types import ModuleType
|
|
4
5
|
|
|
5
6
|
from verifiers.v1.clients import ModelContext
|
|
6
7
|
from verifiers.v1.configs.harness import HarnessConfig
|
|
7
8
|
from verifiers.v1.dialects.chat import message_to_wire
|
|
8
|
-
from verifiers.v1.
|
|
9
|
+
from verifiers.v1.harnesses.utils import compaction, core, mcp
|
|
9
10
|
from verifiers.v1.runtimes import ProgramResult, Runtime
|
|
10
11
|
from verifiers.v1.trace import Trace
|
|
11
12
|
from verifiers.v1.types import Messages
|
|
12
13
|
|
|
13
|
-
MCP_CLIENT_SOURCE = inspect.getsource(mcp_client)
|
|
14
14
|
PEP_723_END = "# ///\n"
|
|
15
15
|
|
|
16
16
|
|
|
17
|
-
def
|
|
18
|
-
"""Embed
|
|
17
|
+
def bundle_program(program: str, *modules: ModuleType) -> str:
|
|
18
|
+
"""Embed utils modules so PEP 723 programs need only their declared packages."""
|
|
19
19
|
metadata, body = program.split(PEP_723_END, 1)
|
|
20
|
-
|
|
20
|
+
sources = "\n".join(inspect.getsource(module) for module in modules)
|
|
21
|
+
return f"{metadata}{PEP_723_END}{sources}\n{body}"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
# The shared Null/Bash chat program is the utils modules themselves: `core` ends with
|
|
25
|
+
# the `__main__` entry point, so the program text is only the script metadata. Secrets
|
|
26
|
+
# use argv so tools do not inherit them.
|
|
27
|
+
CHAT_PROGRAM_SOURCE = bundle_program(
|
|
28
|
+
'# /// script\n# requires-python = ">=3.10"\n'
|
|
29
|
+
'# dependencies = ["openai", "mcp==2.0.0", "httpx", "httpx2", "tenacity"]\n'
|
|
30
|
+
"# ///\n",
|
|
31
|
+
mcp,
|
|
32
|
+
compaction,
|
|
33
|
+
core,
|
|
34
|
+
)
|
|
21
35
|
|
|
22
36
|
|
|
23
37
|
async def launch_chat_program(
|
verifiers/v1/mcp/__init__.py
CHANGED
|
@@ -1,10 +1,3 @@
|
|
|
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
|
-
)
|
|
8
1
|
from verifiers.v1.mcp.launch import (
|
|
9
2
|
SharedToolServer,
|
|
10
3
|
serve,
|
|
@@ -20,12 +13,7 @@ __all__ = [
|
|
|
20
13
|
"SharedToolsetConfig",
|
|
21
14
|
"Toolset",
|
|
22
15
|
"ToolsetConfig",
|
|
23
|
-
"call_mcp",
|
|
24
|
-
"connect_mcp",
|
|
25
|
-
"mcp_client",
|
|
26
|
-
"mcp_content_to_chat_content",
|
|
27
16
|
"serve",
|
|
28
17
|
"serve_shared",
|
|
29
18
|
"serve_tools",
|
|
30
|
-
"with_retry",
|
|
31
19
|
]
|
|
@@ -7,7 +7,8 @@ from mcp.server.mcpserver import Context, MCPServer
|
|
|
7
7
|
from mcp.types import CallToolResult, TextContent, Tool
|
|
8
8
|
from pydantic import Field
|
|
9
9
|
|
|
10
|
-
from verifiers.v1.mcp import
|
|
10
|
+
from verifiers.v1.harnesses.utils.mcp import mcp_client
|
|
11
|
+
from verifiers.v1.mcp import SharedToolsetConfig, Toolset
|
|
11
12
|
from verifiers.v1.state import State
|
|
12
13
|
|
|
13
14
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: verifiers
|
|
3
|
-
Version: 0.3.2.
|
|
3
|
+
Version: 0.3.2.dev27
|
|
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
|
|
@@ -81,12 +81,11 @@ verifiers/v1/gepa/reflection.py,sha256=ptHhx0lcDLcWhWhXuslh9T8gPVNpnX5XLPtXoneW1
|
|
|
81
81
|
verifiers/v1/gepa/runner.py,sha256=fGEyFzejdQKBzBbvdiTDHV3JtRhXMXMGSBU5y8C8i3w,6054
|
|
82
82
|
verifiers/v1/harnesses/__init__.py,sha256=0FVi-mPF36fF0vpLY4H2vbK3U_om1Svz3KgJ3i-phs0,1918
|
|
83
83
|
verifiers/v1/harnesses/node.py,sha256=_-7NofTl-TNuwgEg8qxrD28shlQuyBWgiVHwCCwbdVo,2410
|
|
84
|
-
verifiers/v1/harnesses/standalone.py,sha256=4y5Mg0fFCdCBLIxbTIpfiNbJFqbM2kPrD4_K_W5SIYI,2358
|
|
85
84
|
verifiers/v1/harnesses/bash/__init__.py,sha256=IAV4eMMqDHSl-9ANb0Q3kxmBZ22SeHZFBM448X4gQio,140
|
|
86
|
-
verifiers/v1/harnesses/bash/harness.py,sha256=
|
|
85
|
+
verifiers/v1/harnesses/bash/harness.py,sha256=nsjLKFMGFSya4s9fMHiNVrO92RRCTS3VHqTK3rv3AFA,5233
|
|
87
86
|
verifiers/v1/harnesses/browser_use/__init__.py,sha256=yxm2IG5TDLadxZEkX8SL26XWbcPcODXcrJfPfm1GqwU,171
|
|
88
|
-
verifiers/v1/harnesses/browser_use/harness.py,sha256=
|
|
89
|
-
verifiers/v1/harnesses/browser_use/program.py,sha256=
|
|
87
|
+
verifiers/v1/harnesses/browser_use/harness.py,sha256=eGdLDRbTF8hg4NUwU1jVJcsUei0Y-gTqbGcj3eFJ7XI,4926
|
|
88
|
+
verifiers/v1/harnesses/browser_use/program.py,sha256=3dSFHSDIW3R5ZejV23sXReEKnGQjvPAAdzU-N2RrHpw,9822
|
|
90
89
|
verifiers/v1/harnesses/claude_code/__init__.py,sha256=JkZQylMSA3o1fvBx_NM41y_umuahmOSqFjTrJ2hryTw,171
|
|
91
90
|
verifiers/v1/harnesses/claude_code/harness.py,sha256=bkYbQe0tih9tIGTUp-keSjUlx4DFGXYjX7Lisd212do,4620
|
|
92
91
|
verifiers/v1/harnesses/codex/__init__.py,sha256=ocyBvlpSO8c3pT6D1ebrQohoXYESQcCyPT5kN3j1-N4,132
|
|
@@ -99,10 +98,8 @@ verifiers/v1/harnesses/kimi_code/harness.py,sha256=3SSIty3JtQmvbItutjXJRGrh86KSA
|
|
|
99
98
|
verifiers/v1/harnesses/mini_swe_agent/__init__.py,sha256=1OBu2Y-XqL72-dGhFdgB6sr5uX_peEEXT9vEjPy1ovU,182
|
|
100
99
|
verifiers/v1/harnesses/mini_swe_agent/harness.py,sha256=7HHismhmfCtahlLtQdQyp_fTKidHfco-MdeWp7B9xCo,2522
|
|
101
100
|
verifiers/v1/harnesses/mini_swe_agent/program.py,sha256=Beej-JLIgSqnqIqB746oKU6kJYcynvppIbmwGa3nJJ0,167
|
|
102
|
-
verifiers/v1/harnesses/minimal/__init__.py,sha256=f_dKnFqgeypSh3t7EoPpx0lvosvn1UbsR6_zLpiSsBM,224
|
|
103
|
-
verifiers/v1/harnesses/minimal/program.py,sha256=Y8sUZjwyu05ZnLuQtdmUr6DMsAJYBqk03yP1DhZJ2K0,24810
|
|
104
101
|
verifiers/v1/harnesses/null/__init__.py,sha256=XDeKOPeoXUQi9US9_Z3_yH9YaZ4EiOMKJmUtNNdtD7s,127
|
|
105
|
-
verifiers/v1/harnesses/null/harness.py,sha256=
|
|
102
|
+
verifiers/v1/harnesses/null/harness.py,sha256=Bq19j8Bh_d4VvpFx9nwv6BKnG1tKweEk-2BSmaXWLkU,1330
|
|
106
103
|
verifiers/v1/harnesses/openclaw/__init__.py,sha256=kNyfPB1sGwEf4K3mTfKN0VEyxun3SGvNpvArVKvH-x8,160
|
|
107
104
|
verifiers/v1/harnesses/openclaw/harness.py,sha256=LcdfnP_wYvWUQWIt6d4sE0TnXaxt5Ne5r_f7R0lKkAc,9535
|
|
108
105
|
verifiers/v1/harnesses/pi/__init__.py,sha256=1mSnzOf-RdEchdeg6IHtcdobG5KIpAhuTdUIgsCIn74,117
|
|
@@ -116,6 +113,11 @@ verifiers/v1/harnesses/rlm/harness.py,sha256=OpbPCObGg9BQnNw9njI5iLELRGwoMySMrsE
|
|
|
116
113
|
verifiers/v1/harnesses/terminus_2/__init__.py,sha256=l1pwfg1HyVDEqT9efdnFWcXqaZwtKwe7TrplkyxZSA0,166
|
|
117
114
|
verifiers/v1/harnesses/terminus_2/harness.py,sha256=kXKhi-aqqsoXGnvet0Tq_v7LYYpRYEzARyQL2MTEGWs,3101
|
|
118
115
|
verifiers/v1/harnesses/terminus_2/program.py,sha256=X8MZdyItU3gbXGXnGOlJ9LWcUTnqIDaxlhkZvoRiqKY,2703
|
|
116
|
+
verifiers/v1/harnesses/utils/__init__.py,sha256=eTS-Ft2HwoLiYn5u1t_KueLmaZB_W12cdYmcVsE-G5A,364
|
|
117
|
+
verifiers/v1/harnesses/utils/compaction.py,sha256=DeY6CYLEsv7-vJm26sT2mRaPHu3W2ywiZhvFr_pi6Hg,10495
|
|
118
|
+
verifiers/v1/harnesses/utils/core.py,sha256=_FYeBvp506JWsya0vKYbka9ZYqUwJC7Gm7fnwammwug,14993
|
|
119
|
+
verifiers/v1/harnesses/utils/launch.py,sha256=vCDrrT64LgSoBWCCi8n7Y0eXyNBkTcv7_Wvf0h-o1BA,2866
|
|
120
|
+
verifiers/v1/harnesses/utils/mcp.py,sha256=Sss-DVMtxdE1eGEfq1ycdi1v7SBsmUU5UcpcIY6dGTY,4572
|
|
119
121
|
verifiers/v1/interception/__init__.py,sha256=5Kvo7tcBUVaa65s9A1NiOH3CPpzw-P5btXwxB4Nbbvs,4251
|
|
120
122
|
verifiers/v1/interception/base.py,sha256=Mg16Y104lyZilF9shdivdqYoqz4OYp978i_myyrulu8,2529
|
|
121
123
|
verifiers/v1/interception/pool.py,sha256=sk_zcdTV8EVRuzqlYMXxon_42tSDAlFvwcyOO2EF7hw,6473
|
|
@@ -130,8 +132,7 @@ verifiers/v1/judges/reference.py,sha256=iEVHw-iJ6dbwLOOqrvWrEMJOcUEYJ0YspT04rZz7
|
|
|
130
132
|
verifiers/v1/judges/reference.txt,sha256=Ej35kGXiT2uJ0LcHIeez49rCS_9uHmCQKoVdn93V6A8,353
|
|
131
133
|
verifiers/v1/judges/rubric.py,sha256=qwBjJCWfaUUcQA9A4EXFQK0NumGjoevSFT2HjgBZut4,12019
|
|
132
134
|
verifiers/v1/judges/rubric.txt,sha256=3KA2ZeYYdcDweJhUGopxu9EFgARhu2aWft5S5cj8Bc8,323
|
|
133
|
-
verifiers/v1/mcp/__init__.py,sha256=
|
|
134
|
-
verifiers/v1/mcp/client.py,sha256=Sss-DVMtxdE1eGEfq1ycdi1v7SBsmUU5UcpcIY6dGTY,4572
|
|
135
|
+
verifiers/v1/mcp/__init__.py,sha256=pm8ZWBiL1q1tY4wHvJzM_QrZ9oR8aGm-bIRWiRJsgHI,408
|
|
135
136
|
verifiers/v1/mcp/launch.py,sha256=dqi5UCE-ShPn663glL4DwnTHk4_VBLG_0qUUwlr3p10,23776
|
|
136
137
|
verifiers/v1/mcp/server.py,sha256=q2uB4rMz_f3qpHPwduVN9V4B9HZUHfAjuBFHV8PjfdE,13380
|
|
137
138
|
verifiers/v1/mcp/toolset.py,sha256=G2wzNdEMGLXoQUcrwF0TartJkqokNPI3o7YUOAaaa6U,1007
|
|
@@ -160,7 +161,7 @@ verifiers/v1/tasksets/nemo_gym/__init__.py,sha256=654gAvG3Wd_Z_nh6mypeKn4s_IIQ0G
|
|
|
160
161
|
verifiers/v1/tasksets/nemo_gym/response.py,sha256=u_-qvmcyVHRC9fLJx5ED7BjCCUv5JttuTxM_GzZObkM,4382
|
|
161
162
|
verifiers/v1/tasksets/nemo_gym/server.py,sha256=33C-VDZxPtMV2TFxJVIKijmtBLNlVeRs92ctPE3qAsM,2036
|
|
162
163
|
verifiers/v1/tasksets/nemo_gym/taskset.py,sha256=71h5GGbkbMmUbt4O8eUB8y3z5wZRGQu9lH6ekQcw-Wk,6365
|
|
163
|
-
verifiers/v1/tasksets/nemo_gym/toolset.py,sha256=
|
|
164
|
+
verifiers/v1/tasksets/nemo_gym/toolset.py,sha256=7iaRooFIfCN16wdSJbYFAOsc9q-haTivINO4S65UY6U,3715
|
|
164
165
|
verifiers/v1/tasksets/openenv/__init__.py,sha256=G726meYYDplC3QE3AyjdSShq7FUcb4NkVqowuwPPuJk,303
|
|
165
166
|
verifiers/v1/tasksets/openenv/taskset.py,sha256=1Wc9-5eN2HMKAwL34yTNex3zYOvXNXibF5wCROoMbFI,6075
|
|
166
167
|
verifiers/v1/tasksets/textarena/__init__.py,sha256=Os2OlBY_pSH0B1DP32RitumgSLpq2LtcI7VDUHYPzRE,329
|
|
@@ -184,8 +185,8 @@ verifiers/v1/utils/prime.py,sha256=UTYRjp9cbjNb6CVmBHda-1wWZAIIfxNOmTyNuT7_wL4,9
|
|
|
184
185
|
verifiers/v1/utils/retries.py,sha256=Y2ZgrAjn-qNkRKZP_RVNL_7EK0iaRcZeCa404lpGYi4,5417
|
|
185
186
|
verifiers/v1/utils/score.py,sha256=493yJVMw8teCu9JxapxMFPFzI0hNUqdo0Y2nGW4kckk,6200
|
|
186
187
|
verifiers/v1/utils/version.py,sha256=-obEo_-l9-D8FLef4hYxncOe-uJpxrM1g2Hig_37Sgs,1607
|
|
187
|
-
verifiers-0.3.2.
|
|
188
|
-
verifiers-0.3.2.
|
|
189
|
-
verifiers-0.3.2.
|
|
190
|
-
verifiers-0.3.2.
|
|
191
|
-
verifiers-0.3.2.
|
|
188
|
+
verifiers-0.3.2.dev27.dist-info/METADATA,sha256=ID30D23Wsj1llbngswzqtMp-x51s4uLAKYOcttx0PZY,4144
|
|
189
|
+
verifiers-0.3.2.dev27.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
190
|
+
verifiers-0.3.2.dev27.dist-info/entry_points.txt,sha256=uqQje0TMsr7k6nXlWxlPs13Si0evb3pVCEDF6c-YL80,241
|
|
191
|
+
verifiers-0.3.2.dev27.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
|
|
192
|
+
verifiers-0.3.2.dev27.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|