"""Benchmark recipes on Legion's native Harbor launcher, including Pi's three API formats.""" import importlib import os from contextlib import contextmanager from functools import wraps from typing import Literal from pydantic import Field, model_validator _config = importlib.import_module("legion.harbor.config") LegionConfig = _config.Config InferenceSettings = LegionConfig.model_fields["inference"].annotation PI_VERSION = _config.PI_VERSION _URLS_INFERENCE = "urls" in InferenceSettings.model_fields API_FORMATS = ("openai_chat_completions", "openai_responses", "anthropic_messages") class Inference(InferenceSettings): api_format: Literal["openai_chat_completions", "openai_responses", "anthropic_messages"] = ( "openai_chat_completions" ) if _URLS_INFERENCE: @model_validator(mode="before") @classmethod def recipe_endpoint(cls, value): """Keep published base_url recipes while using main's native endpoint model.""" if isinstance(value, dict) and "base_url" in value: value = dict(value) if value.get("urls") is not None: raise ValueError("Set base_url or urls, not both") value["urls"] = [value.pop("base_url")] return value @property def base_url(self): return self.endpoints[0] if self.endpoints else "" def request_model(self, model): # Published recipes use Harbor's provider/model spelling; main sends raw IDs. from harbor.agents.agent_auth_resolution import parse_model_name return parse_model_name(model)[1] class Config(LegionConfig): inference: Inference = Field(default_factory=Inference) def check_model_connection(self, api_key): if not _URLS_INFERENCE: return super().check_model_connection(api_key) # Main's preflight currently fixes the API to chat; validate the chosen Pi API instead. from legion.models import NO_KEY_ENV from harbor.agents.installed.pi import Pi name = self.inference.key_env or NO_KEY_ENV environment = {**os.environ, name: api_key} Pi.resolve_model_connection_config( self.inference.request_model(self.model), lambda key, *others: next( ((key, environment[key]) for key in (key, *others) if environment.get(key)), None ), skip_model_parsing=True, base_url=self.inference.base_url, model_api_key_name=name, model_api_format=self.inference.api_format, ) @contextmanager def launcher(config): """Select Pi's wire API for this one-shot CLI; restore the native builder on exit. Current main fixes new Trials to chat completions. The benchmark already validates one evaluated agent, and every sweep case runs in a separate CLI process. """ launch = importlib.import_module("legion.harbor.launch") if not _URLS_INFERENCE: yield launch.run_experiment return from harbor.models.model_api_format import ModelApiFormat original = launch.build_trial_config @wraps(original) def build(*args, **kwargs): trial = original(*args, **kwargs) trial.agent.model_api_format = ModelApiFormat(config.inference.api_format) return trial launch.build_trial_config = build try: yield launch.run_experiment finally: launch.build_trial_config = original