fix(eval): resolve endpoints and credentials through Verifiers clients (#3827)

Use Verifiers' client configuration and resolvers for Prime-RL
endpoints, credentials, headers, and timeouts. Standalone evaluation
honors an explicit URL, then `PRIME_INFERENCE_URL`, the Prime CLI
config, and the default Prime endpoint. Partial overrides retain the
correct defaults for each run type.

## Before

Prime-RL owned a separate client schema and credential/header resolvers.
Standalone eval supplied a hardcoded Prime endpoint, so changing
`PRIME_INFERENCE_URL` did not change that default. Client setup resolved
environment headers into static values, prefill scoring constructed its
own SDK client, and admin authentication reused the inference
configuration instead of resolving against the admin URL.

```mermaid
flowchart TD
    Eval["Standalone eval hardcodes Prime URL and key defaults"] --> Config["Prime-RL ClientConfig"]
    Config --> Local["Prime-RL credential and header resolvers"]
    Local --> Inference["Construct Verifiers client with resolved static headers"]
    Inference --> Prefill["Prefill builds its own OpenAI SDK client"]
    Local --> Admin["Admin client resolves using inference config"]
    AdminURL["Separate admin URL"] --> Admin
```

## After

```mermaid
flowchart TD
    Eval["Standalone eval: Prime endpoint defaults"] --> Config["Verifiers BaseClientConfig"]
    Train["Training and online eval: localhost vLLM defaults"] --> Config
    Config --> Inference["Inference client configuration"]
    Config --> Prefill["Shared SDK builder for prefill scoring"]
    Config --> Admin["Admin configuration with its own URL"]
    Inference --> Resolve["Resolve credentials and headers for actual destination"]
    Prefill --> Resolve
    Admin --> Resolve
    Runtime["Environment values and Prime CLI config"] --> Resolve
    Resolve --> Endpoint["Target endpoint"]
```

Training and online evaluation retain their vLLM defaults, including
when only part of the client config is overridden. Frozen models require
an explicit endpoint. Environment-backed headers remain references in
saved configs, and header overrides compare names case-insensitively.
Admin authentication uses the admin destination. Prefill scoring uses
the shared SDK builder's timeout and retry policy.

Depends on [Verifiers
#2766](https://github.com/PrimeIntellect-ai/verifiers/pull/2766). When
combining this with
[#3782](https://github.com/PrimeIntellect-ai/prime-rl/pull/3782) and
[#3808](https://github.com/PrimeIntellect-ai/prime-rl/pull/3808), pin a
Verifiers revision containing all three companion fixes.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how eval and inference clients pick URLs, API keys, and
headers at runtime; mis-resolution could break eval or admin traffic,
though behavior is covered by new default-preservation tests.
> 
> **Overview**
> **Client configuration now delegates to Verifiers** instead of a
duplicate Prime-RL schema and local credential/header resolvers.
`ClientConfig` extends Verifiers' `BaseClientConfig`; training and
online eval use `VLLMClientConfig` (`localhost:8000` / `VLLM_API_KEY`).
Standalone `uv run eval` drops the hardcoded Prime URL and inherits
Prime Inference defaults from Verifiers (honoring `PRIME_INFERENCE_URL`,
Prime CLI, then the standard endpoint). Frozen external models require
an explicit `base_url`.
> 
> **Runtime client setup** forwards unresolved config into Verifiers
train/eval clients (`setup_client` dumps `BaseClientConfig` fields),
resolves auth per destination in admin clients (including separate admin
URLs), and builds prefill scoring via `build_async_openai`. Docs
describe the eval endpoint precedence; tests assert partial `[client]`
overrides keep the right defaults per run type.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c643ef25637bfafb13af555d56167fdbd3525e57. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
This commit is contained in:
Florian Brand
2026-10-06 15:49:52 -07:00
committed by GitHub
parent 51879014fc
commit b9c0bfe87b
9 changed files with 78 additions and 76 deletions
+1 -1
+2
View File
@@ -25,6 +25,8 @@ uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Infe
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
```
The default endpoint comes from `PRIME_INFERENCE_URL`, then the Prime CLI's `inference_url`, then the standard Prime Inference URL. An explicit `client.base_url` wins. API keys and environment-backed headers are resolved when clients are built; Prime CLI credential and team fallbacks apply only to Prime Inference hosts, including for a separate admin URL.
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
```bash
@@ -40,11 +40,11 @@ import verifiers.v1 as vf
from pydantic import Field, model_validator
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.configs.shared import VLLMClientConfig
from prime_rl.utils.config import BaseConfig
class FrozenModelConfig(ClientConfig):
class FrozenModelConfig(VLLMClientConfig):
"""An externally hosted model behind an OpenAI-compatible endpoint: the
client config plus the served model's ``name``.
@@ -57,14 +57,7 @@ class FrozenModelConfig(ClientConfig):
name: str
"""Served model name, sent as the ``model`` field of every request."""
@model_validator(mode="after")
def require_explicit_endpoint(self):
if "base_url" not in self.model_fields_set:
raise ValueError(
"a frozen model reference needs base_url — frozen models are externally "
"hosted; prime-rl only ever hosts the trainable policy."
)
return self
base_url: str
ModelReference: TypeAlias = Literal["policy"] | FrozenModelConfig
@@ -6,7 +6,14 @@ from pydantic import AliasChoices, Field, model_validator
from prime_rl.configs.monitors import EvalMonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig, WeightBroadcastConfig
from prime_rl.configs.shared import (
ClientConfig,
HeartbeatConfig,
LogConfig,
RunConfig,
VLLMClientConfig,
WeightBroadcastConfig,
)
from prime_rl.utils.config import default_output_dir
@@ -14,7 +21,7 @@ class ServedEvalConfig(EvalSourcesConfig):
"""Eval sources run against a live inference server: the server's client and the
adaptive concurrency band."""
client: ClientConfig = ClientConfig()
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
"""Client of the inference server evals run against."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
@@ -43,9 +50,6 @@ class ServedEvalConfig(EvalSourcesConfig):
return {("eval", source.resolved_name): source.serve.address for source in self.source}
PRIME_INFERENCE_URL = "https://api.pinference.ai/api/v1"
class EvalConfig(ServedEvalConfig):
"""``uv run eval``: evaluate the configured sources once against a live inference
server, then exit. Every source's env server is spawned by the eval process unless
@@ -55,7 +59,7 @@ class EvalConfig(ServedEvalConfig):
model: str = Field("deepseek/deepseek-v4.1-flash", validation_alias=AliasChoices("model", "m"))
"""Model id — the ``model`` field of every eval request and the startup model check."""
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
client: ClientConfig = Field(default_factory=ClientConfig)
"""Client of the inference server. Defaults to Prime Inference."""
select: vf.SelectCLIConfig = vf.SelectCLIConfig()
@@ -14,13 +14,13 @@ from prime_rl.configs.algorithm import (
from prime_rl.configs.monitors import TrainMonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
ClientConfig,
EnvVars,
FileSystemWeightBroadcastConfig,
HeartbeatConfig,
LogConfig,
ResumeConfig,
TransportConfig,
VLLMClientConfig,
WeightBroadcastConfig,
ZMQTransportConfig,
)
@@ -40,7 +40,7 @@ class ModelConfig(BaseModelConfig):
lora: LoRAConfig | None = None
"""Per-run LoRA configuration. If None, LoRA is disabled."""
client: ClientConfig = ClientConfig()
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
"""Client of the live deployment (``[orchestrator.model.client]``)."""
@@ -4,6 +4,7 @@ from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import AfterValidator, Field, model_validator
from verifiers.v1.configs.client import BaseClientConfig
from prime_rl.utils.config import BaseConfig
@@ -212,22 +213,10 @@ class DynamoConfig(BaseConfig):
"""Dynamo frontend URL used to discover inference workers for RL control."""
class ClientConfig(BaseConfig):
class ClientConfig(BaseClientConfig):
wait_for_ready_timeout: int = 3600
"""Seconds to wait at startup for the inference pool to become ready."""
base_url: str = "http://localhost:8000/v1"
"""Base URL for the OpenAI API. For multi-replica deployments, point this at a router in front of the replicas."""
api_key_var: str = "VLLM_API_KEY"
"""Environment variable name containing the API key, resolved via ``os.getenv``. Can be any string when the server is not protected by an API key; the same key is used for every URL."""
headers: dict[str, str] = {}
"""Static headers sent with every request."""
headers_from_env: dict[str, str] = {}
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
skip_model_check: bool = False
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
@@ -238,6 +227,13 @@ class ClientConfig(BaseConfig):
"""Dynamo RL worker-discovery configuration."""
class VLLMClientConfig(ClientConfig):
"""Client defaults for the live inference deployment managed by training."""
base_url: str = "http://localhost:8000/v1"
api_key_var: str = "VLLM_API_KEY"
class LogConfig(BaseConfig):
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
"""Log level for the process. Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``."""
+14 -44
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
import asyncio
import os
from collections.abc import Callable
from pathlib import Path
from typing import Literal
@@ -12,40 +11,19 @@ from httpx import AsyncClient
from openai import AsyncOpenAI
from renderers import RendererConfig
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
from verifiers.v1.configs.client import EvalClientConfig, TrainClientConfig
from verifiers.v1.clients.base import build_async_openai
from verifiers.v1.configs.client import (
BaseClientConfig,
EvalClientConfig,
TrainClientConfig,
resolve_api_key,
resolve_headers,
)
from prime_rl.configs.eval import PRIME_INFERENCE_URL
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.logger import get_logger
def resolve_api_key(api_key_var: str) -> str:
"""The API key named by ``api_key_var``; ``PRIME_API_KEY`` also falls back to the prime
CLI config (``prime login``), like the verifiers client does. ``"EMPTY"`` when unset."""
api_key = os.environ.get(api_key_var)
if not api_key and api_key_var == "PRIME_API_KEY":
from prime_sandboxes import Config as PrimeConfig
api_key = PrimeConfig().api_key
return api_key or "EMPTY"
def resolve_headers(client_config: ClientConfig) -> dict[str, str]:
"""The static headers plus those read from the environment. A Prime Inference client
without a team header gets the team from ``$PRIME_TEAM_ID`` or the prime CLI config,
like the verifiers client: a team's internal models are served only under it."""
env_headers = {
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
}
headers = {**client_config.headers, **env_headers}
if client_config.base_url.startswith(PRIME_INFERENCE_URL) and "X-Prime-Team-ID" not in headers:
from prime_sandboxes import Config as PrimeConfig
if team_id := os.environ.get("PRIME_TEAM_ID") or PrimeConfig().team_id:
headers["X-Prime-Team-ID"] = team_id
return headers
class PrefillScorer:
"""Prefill-scores token ids against a pool's endpoint, lazily resolving
a single OpenAI client from the pool's train client config."""
@@ -55,14 +33,8 @@ class PrefillScorer:
async def score(self, config: vf.ClientConfig, model: str, token_ids: list[int]) -> list[float]:
if self._client is None:
# Build the OpenAI client straight from the config fields — works for any
# ClientConfig type; resolve_client would hand back an EvalClient (no `.openai`)
# for these chat-completions teacher configs.
self._client = AsyncOpenAI(
base_url=config.base_url,
api_key=resolve_api_key(config.api_key_var),
default_headers=config.headers or None,
)
# Prefill scoring uses the SDK even when generation uses the eval relay.
self._client = build_async_openai(config)
return await prefill_logprobs(self._client, model, token_ids)
async def aclose(self) -> None:
@@ -274,10 +246,7 @@ def setup_client(
"renderer": renderer_config,
"renderer_model_name": renderer_model_name,
}
headers = resolve_headers(client_config)
return config_cls(
base_url=client_config.base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra
)
return config_cls(**client_config.model_dump(include=set(BaseClientConfig.model_fields)), **renderer_extra)
def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
@@ -290,8 +259,9 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
urls = client_config.admin_base_url if client_config.admin_base_url else [client_config.base_url]
def _setup_admin_client(base_url: str) -> httpx.AsyncClient:
headers = resolve_headers(client_config)
api_key = resolve_api_key(client_config.api_key_var)
config = client_config.model_copy(update={"base_url": base_url})
headers = resolve_headers(config)
api_key = resolve_api_key(config)
if api_key != "EMPTY":
headers["Authorization"] = f"Bearer {api_key}"
+4
View File
@@ -93,6 +93,8 @@ def test_setup_client_creates_renderer_client():
base_url="http://worker-a:8000/v1",
api_key_var="PRIME_API_KEY",
headers={"X-Test": "test"},
headers_from_env={"X-Token": "PROVIDER_TOKEN"},
timeout={"read": 12},
)
renderer_settings = Qwen3VLRendererConfig()
@@ -108,6 +110,8 @@ def test_setup_client_creates_renderer_client():
assert client.base_url == "http://worker-a:8000/v1"
assert "X-data-parallel-rank" not in client.headers
assert client.headers["X-Test"] == "test"
assert client.headers_from_env == {"X-Token": "PROVIDER_TOKEN"}
assert client.timeout.read == 12
def test_check_health_retries_non_success_status():
+33
View File
@@ -18,6 +18,9 @@ from prime_rl.configs.orchestrator import (
ScheduledEvalConfig,
TrainConfig,
)
from prime_rl.configs.orchestrator import (
ModelConfig as OrchestratorModelConfig,
)
from prime_rl.configs.rl import RLConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.trainer import ModelConfig as TrainerModelConfig
@@ -393,6 +396,36 @@ def test_resolved_json_roundtrips_explicit_none(tmp_path):
assert reloaded == config
@pytest.mark.parametrize(
"config_class,source_args,expected_url,expected_key",
[
(
EvalConfig,
["--source", '[{"env":{"id":"single_agent"}}]'],
"https://configured.pinference.ai/api/v1",
"PRIME_API_KEY",
),
(
SFTOnlineEvalConfig,
["--source", '[{"env":{"id":"single_agent"}}]'],
"http://localhost:8000/v1",
"VLLM_API_KEY",
),
(OrchestratorModelConfig, [], "http://localhost:8000/v1", "VLLM_API_KEY"),
],
)
@pytest.mark.parametrize("overrides", [[], ["--client.skip-model-check"], ["--client.wait-for-ready-timeout", "10"]])
def test_client_defaults_survive_partial_overrides(
monkeypatch, config_class, source_args, expected_url, expected_key, overrides
):
monkeypatch.setenv("PRIME_INFERENCE_URL", "https://configured.pinference.ai/api/v1")
config = cli(config_class, args=source_args + overrides)
assert config.client.base_url == expected_url
assert config.client.api_key_var == expected_key
reloaded = config_class.model_validate_json(config.model_dump_json())
assert reloaded.client == config.client
def test_env_algo_inherits_the_group_algo():
config = OrchestratorConfig.model_validate(
{