Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ no provider key; see [trajectory assurance](trajectory-assurance.md),

| Flag | Default | Does |
|---|---|---|
| `--provider`, `-p` | none | `mock`, `openai`, `atlascloud`, `minimax`, `openrouter`, `orcarouter`, `requesty`, `llmtr`, `cloudflare`, `vercel`, `anthropic`, `gemini`, `azure`, `bedrock`, `huggingface`, `litellm`, `http`, `langchain`. |
| `--provider`, `-p` | none | `mock`, `openai`, `atlascloud`, `minimax`, `openrouter`, `orcarouter`, `requesty`, `llmtr`, `worldrouter`, `cloudflare`, `vercel`, `anthropic`, `gemini`, `azure`, `bedrock`, `huggingface`, `litellm`, `http`, `langchain`. |
| `--api-key`, `-k` | provider's env var | SUT API key. Without it, read from the provider's env var (e.g. `OPENAI_API_KEY`). Required for `http` unless `--auth-method none`. |
| `--auth-method` | `bearer` | `http` only: `bearer`, `basic`, `api_key`, or `none`. |
| `--model`, `-m` | provider default | Model identifier override. |
Expand Down
1 change: 1 addition & 0 deletions docs/testing-your-agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ provider's env var below; `--api-key` / `-k` overrides it, and `http` always nee
| `orcarouter` | `.[orcarouter]` | `ORCAROUTER_API_KEY` | `--provider orcarouter -k "$ORCAROUTER_API_KEY" --model openai/gpt-4o` plus explicit judge |
| `requesty` | `.[requesty]` | `REQUESTY_API_KEY` | `--provider requesty -k "$REQUESTY_API_KEY" --model openai/gpt-4o-mini` plus explicit judge; `--endpoint https://router.eu.requesty.ai/v1` for EU data residency |
| `llmtr` | `.[llmtr]` | `LLMTR_API_KEY` | `--provider llmtr -k "$LLMTR_API_KEY" --model qwen/qwen3.8-27b-free` plus explicit judge |
| `worldrouter` | `.[worldrouter]` | `WORLDROUTER_API_KEY` | `--provider worldrouter -k "$WORLDROUTER_API_KEY" --model claude-sonnet-5-5` plus explicit judge |
| `cloudflare` | `.[cloudflare]` | `CLOUDFLARE_API_TOKEN` plus `CLOUDFLARE_ACCOUNT_ID` | `--provider cloudflare -k "$CLOUDFLARE_API_TOKEN" --model workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast` plus explicit judge |
| `vercel` | `.[vercel]` | `AI_GATEWAY_API_KEY` | `--provider vercel -k "$AI_GATEWAY_API_KEY" --model openai/gpt-4o-mini` plus explicit judge |
| `gemini` | `.[gemini]` | `GEMINI_API_KEY` or `GOOGLE_API_KEY` | `--provider gemini -k "$GEMINI_API_KEY"` |
Expand Down
1 change: 1 addition & 0 deletions ifixai/cli/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"orcarouter": "ORCAROUTER_API_KEY",
"requesty": "REQUESTY_API_KEY",
"llmtr": "LLMTR_API_KEY",
"worldrouter": "WORLDROUTER_API_KEY",
"vercel": "AI_GATEWAY_API_KEY",
"gemini": "GEMINI_API_KEY",
"azure": "AZURE_OPENAI_API_KEY",
Expand Down
7 changes: 7 additions & 0 deletions ifixai/cli/model_catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def _minimax_pricing_summary(model_id: str) -> str:
"orcarouter": "openai/gpt-4o",
"requesty": "openai/gpt-4o-mini",
"llmtr": "qwen/qwen3.8-27b-free",
"worldrouter": "claude-sonnet-5-5",
"cloudflare": "workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast",
"vercel": "openai/gpt-4o-mini",
"openai": "gpt-4o",
Expand Down Expand Up @@ -78,6 +79,12 @@ def _minimax_pricing_summary(model_id: str) -> str:
("deepseek/deepseek-chat", "DeepSeek Chat — strong, low cost"),
("openai/gpt-4o-mini", "OpenAI GPT-4o Mini — cheap and fast"),
],
"worldrouter": [
("claude-sonnet-5-5", "Anthropic Claude Sonnet 5.5 — strong reasoning & safety"),
("claude-opus-5-5", "Anthropic Claude Opus 5.5 — most capable, pricier"),
("deepseek-v4-pro", "DeepSeek V4 Pro — strong reasoning, low cost"),
("deepseek-v4-flash", "DeepSeek V4 Flash — very low cost"),
],
"cloudflare": [
("workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast", "Meta Llama 3.3 70B on Workers AI — free plan covers about one small inspection a day"),
("openai/gpt-4.1-mini", "OpenAI GPT-4.1 Mini — cheap and fast (needs Unified Billing credits or a stored key)"),
Expand Down
1 change: 1 addition & 0 deletions ifixai/cli/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ def _governance_source_warning(source: str) -> str | None:
"orcarouter",
"requesty",
"llmtr",
"worldrouter",
"cloudflare",
"vercel",
]
Expand Down
2 changes: 2 additions & 0 deletions ifixai/cli/setup_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"orcarouter": "OpenAI-compatible gateway — many models, one key",
"requesty": "Requesty gateway — one key → 400+ models (OpenAI, Anthropic, Google…)",
"llmtr": "LLMTR prepaid OpenAI-compatible gateway — many models, one key",
"worldrouter": "WorldRouter OpenAI-compatible gateway — Claude, GPT, Gemini, DeepSeek on one key",
"cloudflare": "Cloudflare AI Gateway — one token → Workers AI plus OpenAI, Anthropic, Google…",
"vercel": "Vercel AI Gateway — one key → hundreds of models (OpenAI, Anthropic, Google…)",
"openai": "OpenAI API — GPT-4o / o-series",
Expand Down Expand Up @@ -60,6 +61,7 @@
"orcarouter",
"requesty",
"llmtr",
"worldrouter",
"cloudflare",
"vercel",
"openai",
Expand Down
8 changes: 8 additions & 0 deletions ifixai/providers/resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@
except ImportError:
LLMTRProvider = None # type: ignore[assignment,misc]

try:
from ifixai.providers.worldrouter import WorldRouterProvider
except ImportError:
WorldRouterProvider = None # type: ignore[assignment,misc]

try:
from ifixai.providers.cloudflare import CloudflareAIGatewayProvider
except ImportError:
Expand All @@ -91,6 +96,7 @@
"orcarouter",
"requesty",
"llmtr",
"worldrouter",
"cloudflare",
"vercel",
"anthropic",
Expand All @@ -115,6 +121,7 @@
"orcarouter": OrcaRouterProvider,
"requesty": RequestyProvider,
"llmtr": LLMTRProvider,
"worldrouter": WorldRouterProvider,
"cloudflare": CloudflareAIGatewayProvider,
"vercel": VercelAIGatewayProvider,
"anthropic": AnthropicProvider,
Expand Down Expand Up @@ -224,6 +231,7 @@ def resolve_provider(provider: str | object) -> object:
"orcarouter": ("ORCAROUTER_API_KEY",),
"requesty": ("REQUESTY_API_KEY",),
"llmtr": ("LLMTR_API_KEY",),
"worldrouter": ("WORLDROUTER_API_KEY",),
"cloudflare": ("CLOUDFLARE_API_TOKEN",),
"vercel": ("AI_GATEWAY_API_KEY",),
"litellm": ("LITELLM_API_KEY",),
Expand Down
162 changes: 162 additions & 0 deletions ifixai/providers/worldrouter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import asyncio

import openai

from ifixai.core.types import ChatMessage, ProviderConfig
from ifixai.providers.base import (
ChatProvider,
ProviderAuthError,
ProviderConnectionError,
ProviderEmptyContentError,
ProviderRateLimitError,
ProviderResponseError,
ProviderTimeoutError,
create_chat_completion_json_fallback,
openai_http_client,
raise_for_http_status,
raise_if_choice_errored,
raise_if_truncated,
sdk_error_text,
)
from ifixai.providers.client_pool import close_cached_clients

DEFAULT_MODEL = "claude-sonnet-5-5"
DEFAULT_BASE_URL = "https://inference-api.worldrouter.ai/v1"
# Hard ceiling on max_tokens for WorldRouter calls. Per-call ``config.max_tokens``
# is clamped to this value; unset config falls through to the ceiling. Prevents
# verbose generations from blowing wall-time and credits on long fixtures. Mirrors
# the OpenRouter provider ceiling so judge/SUT replies aren't truncated mid-verdict.
MAX_TOKENS_CEILING: int = 8192

ClientCacheKey = tuple[str, str | None, float, int]


class WorldRouterProvider(ChatProvider):
def __init__(self) -> None:
self._clients: dict[ClientCacheKey, openai.AsyncOpenAI] = {}
self._client_lock = asyncio.Lock()

async def get_client(self, config: ProviderConfig) -> openai.AsyncOpenAI:
"""Return a long-lived AsyncOpenAI client keyed on connection params.

Caching by (base_url, api_key, timeout, max_retries) lets the
underlying httpx pool reuse TCP/TLS across LLM calls instead of
paying a handshake per request.
"""
base_url = config.endpoint or DEFAULT_BASE_URL
key: ClientCacheKey = (
base_url,
config.api_key,
float(config.timeout),
config.max_retries,
)
cached = self._clients.get(key)
if cached is not None:
return cached
async with self._client_lock:
cached = self._clients.get(key)
if cached is not None:
return cached
client = openai.AsyncOpenAI(
api_key=config.api_key,
base_url=base_url,
timeout=float(config.timeout),
max_retries=config.max_retries,
http_client=openai_http_client(openai),
)
self._clients[key] = client
return client

async def aclose(self) -> None:
await close_cached_clients(self._clients)

async def send_message(
self,
messages: list[ChatMessage],
config: ProviderConfig,
) -> str:
base_url = config.endpoint or DEFAULT_BASE_URL
model = config.model or DEFAULT_MODEL
formatted = [{"role": m.role, "content": m.content} for m in messages]

client = await self.get_client(config)
try:
effective_max_tokens = (
min(config.max_tokens, MAX_TOKENS_CEILING)
if config.max_tokens is not None
else MAX_TOKENS_CEILING
)
create_kwargs: dict = {
"model": model,
"messages": formatted, # type: ignore[arg-type]
"max_tokens": effective_max_tokens,
"temperature": config.temperature,
}
if config.seed is not None:
create_kwargs["seed"] = config.seed
if config.json_output:
# Constrain judge calls to valid JSON so cheap models reliably emit
# a parseable verdict instead of breaking the contract. Falls back to
# free text (json-repair handles parsing) if the model does not
# support response_format.
#
# No `reasoning` suppression here, unlike OpenRouter. `reasoning` is
# OpenRouter's own gateway extension, not an OpenAI-SDK parameter,
# and WorldRouter documents no equivalent. Sending an undocumented
# field on the judge path risks a 400 for no confirmed benefit.
create_kwargs["response_format"] = {"type": "json_object"}
response = await create_chat_completion_json_fallback(
client, **create_kwargs
)
choices = response.choices
if not choices:
raise ProviderResponseError(
provider="worldrouter",
endpoint=base_url,
details=f"No choices in response (id={response.id})",
)
choice = choices[0]
finish_reason = choice.finish_reason or "unknown"
if choice.message is None:
raise ProviderResponseError(
provider="worldrouter",
endpoint=base_url,
details=f"Missing message in choice (finish_reason={finish_reason})",
)
content = choice.message.content
raise_if_choice_errored("worldrouter", base_url, choice, content or "")
if config.reject_truncated:
raise_if_truncated("worldrouter", base_url, finish_reason, content or "")
if not content:
raise ProviderEmptyContentError(
provider="worldrouter",
endpoint=base_url,
details=f"Empty content in response (finish_reason={finish_reason})",
)
except openai.AuthenticationError as exc:
raise ProviderAuthError(
provider="worldrouter", endpoint=base_url, details=sdk_error_text(exc)
) from exc
except openai.RateLimitError as exc:
raise ProviderRateLimitError(
provider="worldrouter", endpoint=base_url, details=sdk_error_text(exc)
) from exc
except openai.APITimeoutError as exc:
raise ProviderTimeoutError(
provider="worldrouter", endpoint=base_url, details=sdk_error_text(exc)
) from exc
except openai.APIConnectionError as exc:
raise ProviderConnectionError(
provider="worldrouter", endpoint=base_url, details=sdk_error_text(exc)
) from exc
except openai.APIStatusError as exc:
# WorldRouter is an OpenAI-compatible gateway. Retryable statuses (408,
# 500, 502, 503, 504) are treated as transient overload; everything
# else stays a response error.
raise_for_http_status("worldrouter", base_url, exc)
except openai.APIError as exc:
raise ProviderResponseError(
provider="worldrouter", endpoint=base_url, details=sdk_error_text(exc)
) from exc
else:
return content
7 changes: 6 additions & 1 deletion ifixai/reporting/scorecard.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ def b22_determinism_warning(
# Requesty, Cloudflare AI Gateway or Vercel AI Gateway) is recognized as
# independent instead of mislabeled "self-judge".
_AGGREGATOR_PROVIDERS: Final[frozenset[str]] = frozenset(
{"openrouter", "orcarouter", "requesty", "llmtr", "cloudflare", "vercel", "atlascloud", "litellm", "http", "langchain", "huggingface"}
{"openrouter", "orcarouter", "requesty", "llmtr", "worldrouter", "cloudflare", "vercel", "atlascloud", "litellm", "http", "langchain", "huggingface"}
)

# Namespaces that sit in front of the author, as in the Workers AI ids
Expand Down Expand Up @@ -411,6 +411,11 @@ def grading_vendor(provider: str, model: str | None) -> str:
if parts[0] in {"us", "eu", "apac", "global"}:
parts = parts[1:]
raw = parts[0] if len(parts) > 1 else p
elif p == "worldrouter" and model and "/" not in model:
# WorldRouter model IDs are bare ("claude-sonnet-5-5", "deepseek-v4-flash"),
# so the vendor comes from the family named before the first dash.
family = model.lower().partition("-")[0]
raw = _MODEL_FAMILY_VENDORS.get(family, family)
elif p in _AGGREGATOR_PROVIDERS and model and "/" in model:
raw, _, rest = model.lower().partition("/")
while raw in CATALOG_NAMESPACE_PREFIXES and "/" in rest:
Expand Down
85 changes: 85 additions & 0 deletions ifixai/tests/providers/test_worldrouter_registration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""WorldRouter is reachable from every surface that names a provider."""

from __future__ import annotations

import pytest

pytest.importorskip("openai")

from ifixai.cli.init import PROVIDER_ENV_KEYS, detect_available_providers
from ifixai.cli.model_catalog import default_model, suggestions
from ifixai.cli.run import PROVIDER_CHOICES
from ifixai.cli.setup_cmd import _ALL_PROVIDERS, _PROVIDER_DESCRIPTIONS, _missing_keys
from ifixai.providers.resolver import (
REGISTERED_PROVIDERS,
credential_env_vars,
detect_available_credentials,
resolve_credential,
resolve_provider,
select_cross_provider_judge,
)
from ifixai.providers.worldrouter import DEFAULT_MODEL, WorldRouterProvider
from ifixai.reporting.scorecard import grading_vendor

KEY_VARIABLE = "WORLDROUTER_API_KEY"
OWNED_KEY = "owned-synthetic-worldrouter-key"


def test_the_name_resolves_to_the_adapter() -> None:
assert isinstance(resolve_provider("worldrouter"), WorldRouterProvider)
assert isinstance(resolve_provider("WorldRouter"), WorldRouterProvider)


def test_the_cli_and_the_registry_both_accept_the_name() -> None:
assert "worldrouter" in REGISTERED_PROVIDERS
assert "worldrouter" in PROVIDER_CHOICES


def test_the_key_is_read_from_worldrouter_s_own_variable() -> None:
assert credential_env_vars("worldrouter") == (KEY_VARIABLE,)
assert resolve_credential("worldrouter", {KEY_VARIABLE: OWNED_KEY}) == OWNED_KEY
assert resolve_credential("worldrouter", {"OPENAI_API_KEY": "owned-other-key"}) is None
assert PROVIDER_ENV_KEYS["worldrouter"] == KEY_VARIABLE


def test_a_gateway_key_alone_never_auto_selects_a_judge() -> None:
available = detect_available_credentials({KEY_VARIABLE: OWNED_KEY})

assert available == ["worldrouter"]
assert select_cross_provider_judge("openai", available) is None


def test_the_wizard_offers_the_gateway_with_a_description() -> None:
assert "worldrouter" in _ALL_PROVIDERS
assert "WorldRouter" in _PROVIDER_DESCRIPTIONS["worldrouter"]


def test_the_wizard_default_is_the_adapter_default() -> None:
assert default_model("worldrouter") == DEFAULT_MODEL
assert DEFAULT_MODEL == "claude-sonnet-5-5"


def test_every_suggested_model_is_a_bare_model_id() -> None:
suggested = [model for model, _ in suggestions("worldrouter")]

assert DEFAULT_MODEL in suggested
assert len(suggested) == len(set(suggested))
for model in suggested:
assert model and "/" not in model, model


def test_missing_and_present_keys_are_explained(monkeypatch) -> None:
monkeypatch.delenv(KEY_VARIABLE, raising=False)
assert _missing_keys([("system", "worldrouter")]) == [("system", "worldrouter", KEY_VARIABLE)]
monkeypatch.setenv(KEY_VARIABLE, OWNED_KEY)
assert ("worldrouter", KEY_VARIABLE) in detect_available_providers()
assert _missing_keys([("system", "worldrouter")]) == []


def test_grading_uses_the_model_family_of_a_bare_id() -> None:
assert grading_vendor("worldrouter", "claude-sonnet-5-5") == "anthropic"
assert grading_vendor("worldrouter", "gemini-4-neon") == "google"
assert grading_vendor("worldrouter", "gpt-5.5") == "openai"
assert grading_vendor("worldrouter", "deepseek-v4-flash") == "deepseek"
assert grading_vendor("worldrouter", "openai/gpt-4o-mini") == "openai"
assert grading_vendor("worldrouter", None) == "worldrouter"
1 change: 1 addition & 0 deletions ifixai/tests/test_sdk_pool_teardown.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
("orcarouter", "OrcaRouterProvider", "_clients"),
("requesty", "RequestyProvider", "_clients"),
("llmtr", "LLMTRProvider", "_clients"),
("worldrouter", "WorldRouterProvider", "_clients"),
("cloudflare", "CloudflareAIGatewayProvider", "clients"),
("vercel", "VercelAIGatewayProvider", "clients"),
]
Expand Down
1 change: 1 addition & 0 deletions ifixai/tests/test_sdk_timeout_native.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
("orcarouter", "OrcaRouterProvider", "openai"),
("requesty", "RequestyProvider", "openai"),
("llmtr", "LLMTRProvider", "openai"),
("worldrouter", "WorldRouterProvider", "openai"),
("cloudflare", "CloudflareAIGatewayProvider", "openai"),
("vercel", "VercelAIGatewayProvider", "openai"),
("anthropic", "AnthropicProvider", "anthropic"),
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ openrouter = ["openai>=1.0"]
orcarouter = ["openai>=1.0"]
requesty = ["openai>=1.0"]
llmtr = ["openai>=1.0"]
worldrouter = ["openai>=1.0"]
cloudflare = ["openai>=1.0"]
vercel = ["openai>=1.0"]
gemini = ["google-generativeai>=0.3"]
Expand Down