verifiers 0.4.2.dev109__py3-none-any.whl → 0.4.2.dev111__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/__init__.py CHANGED
@@ -57,7 +57,7 @@ if TYPE_CHECKING:
57
57
  SubprocessConfig,
58
58
  )
59
59
  from verifiers.v1.configs.sampling import SamplingConfig
60
- from verifiers.v1.configs.scoring import ScoringConfig
60
+ from verifiers.v1.configs.scoring import ScoringConfig, ScoringJudgeConfig
61
61
  from verifiers.v1.configs.select import (
62
62
  SelectCLIConfig,
63
63
  SelectConfig,
@@ -298,6 +298,7 @@ _NAME_TO_MODULE = {
298
298
  "SamplerSupport": "verifiers.v1.types",
299
299
  "SandboxError": "verifiers.v1.errors",
300
300
  "ScoringConfig": "verifiers.v1.configs.scoring",
301
+ "ScoringJudgeConfig": "verifiers.v1.configs.scoring",
301
302
  "ServicesSpec": "verifiers.v1.runtimes.deployment",
302
303
  "Segment": "verifiers.v1.agent",
303
304
  "SelectCLIConfig": "verifiers.v1.configs.select",
@@ -588,6 +589,7 @@ __all__ = [ # noqa: RUF022 - grouped by public API area
588
589
  "DeploymentConfig",
589
590
  "ServicesSpec",
590
591
  "ScoringConfig",
592
+ "ScoringJudgeConfig",
591
593
  ]
592
594
 
593
595
 
@@ -30,9 +30,8 @@ from verifiers.v1.cli.resume import distribute
30
30
  from verifiers.v1.configs.cli.validate import ValidateConfig
31
31
  from verifiers.v1.errors import TaskError, boundary
32
32
  from verifiers.v1.grading import (
33
- bind_scoring_env,
34
33
  grade_task,
35
- scoring_network,
34
+ score_shared,
36
35
  verifier_runtime,
37
36
  )
38
37
  from verifiers.v1.runtimes import make_backend
@@ -283,13 +282,9 @@ async def _score_untouched(
283
282
  await grade_task(grader, trace, grading_config, timeouts, policy, deployment)
284
283
  else:
285
284
  async with asyncio.timeout(task.data.timeout.scoring):
286
- runtime = bind_scoring_env(runtime, policy)
287
- await invoke(grader.stage_verifier, {"trace": trace, "runtime": runtime})
288
- if policy.network is not None:
289
- await runtime.set_network(
290
- scoring_network(config.runtime, policy.network)
291
- )
292
- await grader.score(trace, runtime, deployment)
285
+ await score_shared(
286
+ grader, trace, runtime, config.runtime, policy, deployment
287
+ )
293
288
  if not trace.rewards:
294
289
  return None
295
290
  return trace.reward < SOLVED
@@ -88,7 +88,7 @@ class ModelContext:
88
88
  """Model, endpoint config, and sampling for one rollout."""
89
89
 
90
90
  model: str
91
- client: ClientConfig
91
+ client: BaseClientConfig
92
92
  sampling: SamplingConfig = field(default_factory=SamplingConfig)
93
93
 
94
94
 
@@ -67,7 +67,8 @@ class BaseClientConfig(BaseConfig):
67
67
  "base_url" not in self.model_fields_set
68
68
  and self.base_url == DEFAULT_PRIME_INFERENCE_URL
69
69
  ):
70
- self.base_url = prime_base_url
70
+ # A discovered default must not become an explicit endpoint override.
71
+ object.__setattr__(self, "base_url", prime_base_url)
71
72
  return self
72
73
 
73
74
 
@@ -2,12 +2,36 @@
2
2
 
3
3
  from typing import Literal
4
4
 
5
- from pydantic import SerializationInfo, field_serializer
5
+ from pydantic import Field, SerializationInfo, field_serializer
6
6
  from pydantic_config import BaseConfig
7
7
 
8
+ from verifiers.v1.configs.client import BaseClientConfig
8
9
  from verifiers.v1.configs.retries import RetryConfig
9
10
  from verifiers.v1.configs.runtime import NetworkPolicyConfig, RuntimeConfig
10
- from verifiers.v1.utils.generic import merge_defaults
11
+ from verifiers.v1.configs.sampling import SamplingConfig
12
+ from verifiers.v1.utils.generic import deep_merge, merge_defaults
13
+
14
+
15
+ class ScoringJudgeConfig(BaseClientConfig):
16
+ """Host inference for a packaged grader, reached through a temporary endpoint."""
17
+
18
+ model: str | None = None
19
+ """Override the grader's model; None preserves each request's model."""
20
+ sampling: SamplingConfig = SamplingConfig()
21
+ """Explicit settings override the grader's request, including provider parameters."""
22
+ env: dict[str, Literal["base_url", "api_key"]] = Field(
23
+ default_factory=lambda: {
24
+ "OPENAI_BASE_URL": "base_url",
25
+ "OPENAI_API_BASE": "base_url",
26
+ "OPENAI_API_KEY": "api_key",
27
+ }
28
+ )
29
+ """Grader environment names mapped to the temporary endpoint or session token."""
30
+
31
+ @field_serializer("sampling")
32
+ def serialize_sampling(self, sampling: SamplingConfig) -> dict:
33
+ # Omitted settings must stay omitted after task/config transport.
34
+ return sampling.model_dump(exclude_unset=True)
11
35
 
12
36
 
13
37
  class ScoringConfig(BaseConfig):
@@ -17,6 +41,8 @@ class ScoringConfig(BaseConfig):
17
41
  """Fresh verifier provider/configuration. None uses the agent's provider policy."""
18
42
  env: dict[str, str] | None = None
19
43
  """Scoring-only variables, merged over task defaults and resolved at scoring time."""
44
+ judge: ScoringJudgeConfig | None = None
45
+ """Route a packaged grader's inference through the host; None leaves it unmanaged."""
20
46
  retries: RetryConfig = RetryConfig(max_retries=2)
21
47
  """Retry rules for fresh isolated scoring attempts; shared scoring is not retried."""
22
48
  network: NetworkPolicyConfig | None = None
@@ -63,4 +89,10 @@ def resolve_scoring(task: ScoringConfig, agent: ScoringConfig) -> ScoringConfig:
63
89
  else {},
64
90
  )
65
91
  )
92
+ if task.judge is not None and agent.judge is not None:
93
+ updates["judge"] = ScoringJudgeConfig.model_validate(
94
+ deep_merge(
95
+ task.judge.model_dump(), agent.judge.model_dump(exclude_unset=True)
96
+ )
97
+ )
66
98
  return task.model_copy(update=updates)
@@ -464,8 +464,8 @@ class AnthropicDialect(Dialect[AnthropicMessage]):
464
464
  "output_config",
465
465
  }
466
466
  )
467
- routes = ("/v1/messages",)
468
- aux_routes = ("/v1/messages/count_tokens",)
467
+ routes = ("/v1/messages", "/v1/v1/messages")
468
+ aux_routes = ("/v1/messages/count_tokens", "/v1/v1/messages/count_tokens")
469
469
  upstream_path = "/v1/messages"
470
470
  response_type = ModdedAnthropicMessage
471
471
 
@@ -691,11 +691,16 @@ class AnthropicDialect(Dialect[AnthropicMessage]):
691
691
  return SamplingConfig.model_validate(settings)
692
692
 
693
693
  def apply_overrides(
694
- self, body: RawRequest, model: str, sampling: SamplingConfig
694
+ self,
695
+ body: RawRequest,
696
+ model: str,
697
+ sampling: SamplingConfig,
698
+ *,
699
+ authoritative: bool = True,
695
700
  ) -> RawRequest:
696
- # Preserve native fields except the eval's model + sampling. `temperature`/`top_p` are
697
- # authoritative (always dropped, the eval's applied if set); `max_tokens` is required by
698
- # the API, so the program's is kept unless the eval sets one.
701
+ # Preserve native fields except `model` + `sampling`. When `authoritative`,
702
+ # `temperature`/`top_p` are dropped unless set in `sampling`; `max_tokens` is
703
+ # required by the API, so the caller's is kept unless `sampling` sets one.
699
704
  s = sampling.model_dump(exclude_none=True)
700
705
  reasoning_effort = s.pop("reasoning_effort", None)
701
706
  sampling_output_config = s.pop("output_config", None)
@@ -707,9 +712,8 @@ class AnthropicDialect(Dialect[AnthropicMessage]):
707
712
  }
708
713
  if reasoning_effort is not None:
709
714
  overrides["output_config"]["effort"] = reasoning_effort
715
+ drop = ("temperature", "top_p") if authoritative else ()
710
716
  steered = {
711
- k: v
712
- for k, v in body.items()
713
- if k not in ("temperature", "top_p") and k not in overrides
717
+ k: v for k, v in body.items() if k not in drop and k not in overrides
714
718
  }
715
719
  return {**steered, **overrides}
@@ -398,8 +398,14 @@ class Dialect(ABC, Generic[RespT]):
398
398
 
399
399
  @abstractmethod
400
400
  def apply_overrides(
401
- self, body: RawRequest, model: str, sampling: SamplingConfig
401
+ self,
402
+ body: RawRequest,
403
+ model: str,
404
+ sampling: SamplingConfig,
405
+ *,
406
+ authoritative: bool = True,
402
407
  ) -> RawRequest:
403
- """Return `body` with the eval's `model` + `sampling` imposed in this protocol's shape —
404
- model overlays; sampling is authoritative (the program's sampling keys are dropped, the
405
- eval's applied). Capability mediation may subsequently remove restricted fields."""
408
+ """Return `body` with `model` + `sampling` imposed in this protocol's shape.
409
+ When `authoritative` is true (eval rollouts), the program's sampling keys are
410
+ dropped and replaced by `sampling`; when false (packaged graders), unset
411
+ sampling keys in `sampling` preserve the caller's request."""
@@ -604,7 +604,12 @@ class ChatDialect(Dialect[ChatCompletion]):
604
604
  return ChatStreamParser()
605
605
 
606
606
  def apply_overrides(
607
- self, body: RawRequest, model: str, sampling: SamplingConfig
607
+ self,
608
+ body: RawRequest,
609
+ model: str,
610
+ sampling: SamplingConfig,
611
+ *,
612
+ authoritative: bool = True,
608
613
  ) -> RawRequest:
609
614
  # Preserve the program's native fields, overlaying only what the eval owns: the model and
610
615
  # the sampling knobs it set. The selected model is authoritative even if a permissive
@@ -750,17 +750,23 @@ class ResponsesDialect(Dialect[OpenAIResponse]):
750
750
  return ResponsesStreamParser()
751
751
 
752
752
  def apply_overrides(
753
- self, body: RawRequest, model: str, sampling: SamplingConfig
753
+ self,
754
+ body: RawRequest,
755
+ model: str,
756
+ sampling: SamplingConfig,
757
+ *,
758
+ authoritative: bool = True,
754
759
  ) -> RawRequest:
755
- # Preserve native fields except the eval's model + sampling, mapped to the Responses shape
756
- # (`max_tokens` -> `max_output_tokens`); sampling is authoritative.
760
+ # Preserve native fields except `model` + `sampling`, mapped to the Responses shape
761
+ # (`max_tokens` -> `max_output_tokens`).
757
762
  s = sampling.model_dump(exclude_none=True)
758
763
  max_tokens = s.pop("max_tokens", None)
759
764
  reasoning_effort = s.pop("reasoning_effort", None)
760
765
  sampling_reasoning = s.pop("reasoning", None)
761
766
  name = model.rsplit("/", 1)[-1]
762
767
  reasoning_model = (
763
- name.startswith(("gpt-5", "o1", "o3", "o4"))
768
+ authoritative
769
+ and name.startswith(("gpt-5", "o1", "o3", "o4"))
764
770
  and "-chat" not in name
765
771
  and ("/" not in model or model.startswith("openai/"))
766
772
  )
@@ -782,9 +788,16 @@ class ResponsesDialect(Dialect[OpenAIResponse]):
782
788
  reasoning["effort"] = reasoning_effort
783
789
  if reasoning:
784
790
  overrides["reasoning"] = reasoning
791
+ drop = (
792
+ _SAMPLING_KEYS
793
+ if authoritative
794
+ else (
795
+ {"max_tokens", "max_output_tokens"}
796
+ if "max_output_tokens" in overrides
797
+ else set()
798
+ )
799
+ )
785
800
  steered = {
786
- k: v
787
- for k, v in body.items()
788
- if k not in _SAMPLING_KEYS and k not in overrides
801
+ k: v for k, v in body.items() if k not in drop and k not in overrides
789
802
  }
790
803
  return {**steered, **overrides}
verifiers/v1/grading.py CHANGED
@@ -3,7 +3,7 @@
3
3
  import asyncio
4
4
  import copy
5
5
  import logging
6
- from contextlib import AsyncExitStack, contextmanager
6
+ from contextlib import AsyncExitStack, asynccontextmanager, contextmanager
7
7
  from pathlib import PurePosixPath
8
8
 
9
9
  from verifiers.v1.configs.scoring import ScoringConfig
@@ -101,7 +101,101 @@ def scoring_network(
101
101
 
102
102
  def bind_scoring_env(runtime: Runtime, policy: ScoringConfig) -> Runtime:
103
103
  """Bind scoring variables without changing the solver's runtime or backend."""
104
- return runtime.with_env({**runtime.env, **resolve_env(policy.env or {})})
104
+ env = dict(policy.env or {})
105
+ if policy.judge is not None:
106
+ # Setup must not resolve provider credentials that the proxy replaces.
107
+ env.update(dict.fromkeys(policy.judge.env, ""))
108
+ return runtime.with_env({**runtime.env, **resolve_env(env)})
109
+
110
+
111
+ @asynccontextmanager
112
+ async def scoring_session(
113
+ trace: Trace,
114
+ runtime: Runtime,
115
+ policy: ScoringConfig,
116
+ *,
117
+ interception=None,
118
+ network: NetworkPolicyConfig | None = None,
119
+ ):
120
+ """Bind a revocable inference capability for this scoring attempt only."""
121
+ policy_network = (
122
+ network
123
+ if network is not None
124
+ else runtime.config
125
+ if isinstance(runtime.config, NetworkPolicyConfig)
126
+ else NetworkPolicyConfig()
127
+ )
128
+ if policy.judge is None:
129
+ if network is not None:
130
+ await runtime.set_network(network)
131
+ yield runtime
132
+ return
133
+
134
+ from verifiers.v1.clients import ModelContext, ModelRoute
135
+ from verifiers.v1.interception import serve_interception
136
+ from verifiers.v1.session import RolloutSession
137
+
138
+ judge = policy.judge
139
+ session = RolloutSession(
140
+ ModelRoute(
141
+ ModelContext(model=judge.model or "", client=judge, sampling=judge.sampling)
142
+ ),
143
+ trace,
144
+ network_policy=policy_network,
145
+ network_policy_source=lambda: (
146
+ getattr(runtime.backend, "active_network", None) or policy_network
147
+ ),
148
+ judge_only=True,
149
+ )
150
+ async with serve_interception(interception, runtime, session, [], {}) as (
151
+ base_url,
152
+ token,
153
+ _,
154
+ ):
155
+ connection = {
156
+ "base_url": runtime.host_url(f"{base_url.rstrip('/')}/v1"),
157
+ "api_key": token,
158
+ }
159
+ bound = runtime.with_env(
160
+ {
161
+ **runtime.env,
162
+ **{key: connection[value] for key, value in judge.env.items()},
163
+ }
164
+ )
165
+ if network is not None or runtime.network_restricted:
166
+ await runtime.set_network(policy_network, routes=[connection["base_url"]])
167
+ yield bound
168
+
169
+
170
+ async def score_shared(
171
+ task: Task,
172
+ trace: Trace,
173
+ runtime: Runtime,
174
+ base_runtime: RuntimeConfig,
175
+ policy: ScoringConfig,
176
+ deployment,
177
+ *,
178
+ interception=None,
179
+ on_score=None,
180
+ ) -> None:
181
+ """Prepare and score a task inside an existing runtime."""
182
+ scoring_runtime = bind_scoring_env(runtime, policy)
183
+ await invoke(task.stage_verifier, {"trace": trace, "runtime": scoring_runtime})
184
+ network = (
185
+ scoring_network(base_runtime, policy.network)
186
+ if policy.network is not None
187
+ else None
188
+ )
189
+ async with scoring_session(
190
+ trace,
191
+ scoring_runtime,
192
+ policy,
193
+ interception=interception,
194
+ network=network,
195
+ ) as scoring_runtime:
196
+ await task.score(trace, scoring_runtime, deployment)
197
+ if on_score is not None:
198
+ await on_score(trace, scoring_runtime)
105
199
 
106
200
 
107
201
  async def stage_verifier(task: Task, trace: Trace, runtime: Runtime) -> None:
@@ -123,6 +217,7 @@ async def grade_task(
123
217
  *,
124
218
  scoring_elapsed: float = 0.0,
125
219
  on_score=None,
220
+ interception=None,
126
221
  ) -> None:
127
222
  await deployment.prepare_verifier()
128
223
  # Provisioning, scoring, and retry backoff share the remaining scoring budget.
@@ -156,15 +251,23 @@ async def grade_task(
156
251
  runtime = bind_scoring_env(runtime, policy)
157
252
  await runtime.backend.prepare_setup()
158
253
  await stage_verifier(grader, result, runtime)
159
- await runtime.backend.prepare_execution([])
160
254
  try:
161
255
  async with (
162
256
  asyncio.timeout_at(deadline),
163
257
  boundary(TaskError, "verifier scoring"),
258
+ scoring_session(
259
+ result,
260
+ runtime,
261
+ policy,
262
+ interception=interception,
263
+ network=config
264
+ if isinstance(config, NetworkPolicyConfig)
265
+ else None,
266
+ ) as scoring_runtime,
164
267
  ):
165
- await grader.score(result, runtime, deployment)
268
+ await grader.score(result, scoring_runtime, deployment)
166
269
  if on_score is not None:
167
- await on_score(result, runtime)
270
+ await on_score(result, scoring_runtime)
168
271
  finally:
169
272
  # Preserve failed attempts' evidence and accounting without
170
273
  # committing partial rewards/state.
@@ -77,7 +77,8 @@ async def serve_interception(
77
77
  """A slot on the shared interception when one was injected (its owner keeps the
78
78
  lifecycle), else on a per-rollout `InterceptionServer` owned — brought up and torn
79
79
  down — by the caller's context."""
80
- if interception is not None:
80
+ # A remote runtime cannot reach a loopback-only shared interception.
81
+ if interception is not None and (runtime.is_local or interception.requires_tunnel):
81
82
  async with interception.acquire(session) as slot:
82
83
  yield slot
83
84
  return
@@ -30,8 +30,9 @@ class Interception(ABC):
30
30
  even if one teardown fails; `async with` wraps the two. Each rollout `acquire`s a slot
31
31
  and frees it on exit."""
32
32
 
33
- def __init__(self) -> None:
33
+ def __init__(self, *, requires_tunnel: bool = False) -> None:
34
34
  self.stack = AsyncExitStack()
35
+ self.requires_tunnel = requires_tunnel
35
36
 
36
37
  @abstractmethod
37
38
  async def start(self) -> None:
@@ -44,7 +44,7 @@ class StaticInterceptionPool(Interception):
44
44
  requires_tunnel: bool = False,
45
45
  state_service_secrets: tuple[str, ...] = (),
46
46
  ) -> None:
47
- super().__init__()
47
+ super().__init__(requires_tunnel=requires_tunnel)
48
48
  self.config = config
49
49
  self.servers = [
50
50
  InterceptionServer(server, requires_tunnel, state_service_secrets)
@@ -80,9 +80,8 @@ class ElasticInterceptionPool(Interception):
80
80
  requires_tunnel: bool = False,
81
81
  state_service_secrets: tuple[str, ...] = (),
82
82
  ) -> None:
83
- super().__init__()
83
+ super().__init__(requires_tunnel=requires_tunnel)
84
84
  self.config = config or ElasticInterceptionPoolConfig()
85
- self.requires_tunnel = requires_tunnel
86
85
  self.state_service_secrets = state_service_secrets
87
86
  self.servers: list[InterceptionServer] = []
88
87
  self._lock = asyncio.Lock()