Guide

PydanticAI With an OpenAI-Compatible API: AtmoRouter Setup Guide

Set up PydanticAI with AtmoRouter's OpenAI-compatible API: OpenAICompatibleProvider config, typed outputs, usage tracking, fallbacks and per-run cost math.

PydanticAI is a Python agent framework built on Pydantic types: you declare an Agent with typed tools and a typed output, and it runs the model loop, validation and retries for you. A PydanticAI OpenAI compatible setup through AtmoRouter keeps that ergonomics and puts 150+ models behind one base URL and one prepaid balance, so switching models is a string change rather than a new integration.

This is an AtmoRouter-authored guide. It covers the provider configuration that works today, how to read token usage per run, what a fallback chain does to your bill, and the traps the PydanticAI documentation itself flags for third-party endpoints. Every number below is illustrative math on catalogue rates at writing time, not a benchmark. Rates change; the model page is authoritative.

Install and the Minimum Working Agent

PydanticAI ships integrations as optional groups. For anything that speaks the OpenAI protocol, including gateways, you need the openai extra:

bashpip install "pydantic-ai-slim[openai]"
export ATMOROUTER_API_KEY="ar-xxxxxxxxxxxx"

The smallest agent that talks to AtmoRouter over Chat Completions:

pythonimport os

from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai_compatible import OpenAICompatibleProvider

model = OpenAIChatModel(
    "zai/glm-5.4",
    provider=OpenAICompatibleProvider(
        "atmorouter",
        base_url="https://atmorouter.dev/v1",
        api_key=os.environ["ATMOROUTER_API_KEY"],
    ),
)

agent = Agent(model, instructions="Answer in one sentence.")
result = agent.run_sync("What is a prepaid balance?")
print(result.output)

Two details matter. OpenAIChatModel is the class for a Chat Completions endpoint; the bare 'openai:' model prefix resolves to the Responses API instead, which is a different endpoint and a different feature set, so do not rely on it here. And the first argument to the provider, "atmorouter", is a stable service name: the docs say it is recorded as provider_name on every response and decides which response data is safe to send back to the same service, so pick a name and keep it.

Why OpenAICompatibleProvider and Not OpenAIProvider

OpenAIProvider also accepts a base_url, so it is tempting to use it. The PydanticAI docs are explicit that this path is for OpenAI itself or a transparent proxy to it: it assumes OpenAI's models and features, including OpenAI-specific reasoning and compaction items. OpenAICompatibleProvider is the class for everyone else.

The compatible provider also picks a model profile from the model name. A vendor/model spelling gets the profile of the family that vendor makes; anything else gets the shared OpenAI-compatible profile without OpenAI-only features. AtmoRouter IDs such as zai/glm-5.4 or cc/claude-sonnet-5-5 carry a catalogue prefix, not a vendor the framework recognises, so expect the shared profile. In practice that means tool calling and prompted or tool-based structured output work; if a feature is ignored or rejected, the fix is a custom OpenAIModelProfile, not a different base URL.

Structured Output and Tools

The main reason to reach for PydanticAI is typed results. Declaring an output_type makes the agent validate the model's reply and retry when it does not match:

pythonfrom dataclasses import dataclass
from pydantic_ai import Agent, RunContext

@dataclass
class Ticket:
    category: str
    urgent: bool
    summary: str

@dataclass
class Deps:
    queue: str

agent = Agent(
    model,
    output_type=Ticket,
    deps_type=Deps,
)

@agent.tool
def queue_size(ctx: RunContext[Deps]) -> int:
    """Return the number of open items in the queue."""
    return 12

result = agent.run_sync(
    "Classify this message: 'Payment failed twice tonight, need help now.'",
    deps=Deps(queue="billing"),
)
print(result.output.urgent)

The framework will issue as many model requests as the tool loop needs, and each one is billed as a normal request. That is the next section's problem.

Reading Usage and Cost per Run

Every run exposes aggregated usage through result.usage(), with input_tokens, output_tokens, cache_read_tokens (included in input) and requests, the number of model responses in the run. result.cost() exists too, but it is a best-effort figure from a bundled price list and returns None when the model is unknown, which it will be for catalogue IDs like these. Compute it yourself from the live rates:

pythonRATES = {  # USD per million tokens: (input, output), from the live catalogue
    "zai/glm-5.4": (0.0035, 0.011),
    "cc/claude-sonnet-5-5": (0.445, 2.225),
    "cx/gpt-6.2-sol": (0.75, 3.75),
}

def estimate_usd(model_name: str, usage) -> float | None:
    rates = RATES.get(model_name)
    if rates is None:
        return None
    pin, pout = rates
    return (usage.input_tokens * pin + usage.output_tokens * pout) / 1_000_000

usage = result.usage()
print(usage.requests, usage.input_tokens, usage.output_tokens)
print(estimate_usd("zai/glm-5.4", usage))

This estimate ignores caching. Where a model supports cached input, AtmoRouter bills it at 10% of the input rate, so a long agent session that re-sends the same prefix is cheaper than the flat calculation. If usage was omitted from a response, unmeasured_requests is non-zero and your totals are a lower bound.

You can also cap a run before it spirals: Agent(model, usage_limits=UsageLimits(request_limit=5, total_tokens_limit=50_000)) raises UsageLimitExceeded once a run crosses either bound. Failed requests are never billed; the tokens a model processed before a limit still are.

What It Costs at 10,000 Runs

Assume a classification agent that needs three model requests per run, each sending 12,000 input tokens and receiving 600 output tokens, with no cache hits. That is 30,000 requests, 360 million input tokens and 18 million output tokens in total.

| Model | From price per million input / output | 360M in + 18M out | |---|---|---| | zai/glm-5.4 | $0.0035 / $0.011 | $1.46 | | cc/claude-haiku-5-5 | $0.04975 / $0.24875 | $22.39 | | cc/claude-sonnet-5-5 | $0.445 / $2.225 | $200.25 | | cx/gpt-6.2-sol | $0.75 / $3.75 | $337.50 |

The spread is two orders of magnitude for the same request count. That is the whole argument for a typed agent framework against a gateway: because the provider config is the only thing tied to a model, you can run the evaluation suite on the cheap row, keep the expensive row for the cases that need it, and prove the difference with your own data instead of a vendor's. There are no seat fees on AtmoRouter; the table is token math only.

Adding a Fallback Chain

The framework's FallbackModel tries each model in order and moves to the next on an API error, or when a model class raises ModelRequestRejectedError before sending a request it knows the endpoint will refuse:

pythonfrom pydantic_ai.models.fallback import FallbackModel
from pydantic_ai.models.openai import OpenAIChatModel

provider = OpenAICompatibleProvider(
    "atmorouter",
    base_url="https://atmorouter.dev/v1",
    api_key=os.environ["ATMOROUTER_API_KEY"],
)

model = FallbackModel(
    OpenAIChatModel("cc/claude-sonnet-5-5", provider=provider),
    OpenAIChatModel("zai/glm-5.4", provider=provider),
)
agent = Agent(model)

Be deliberate about the order. A chain that falls from an expensive model to a cheap one saves money only when the first model fails; a chain that runs the cheap model first and "escalates" on failure does not escalate on bad answers, only on errors. Failed attempts are not billed, so the cost of a fallback is latency, not tokens. Also note the OpenAI SDK client retries on its own with max_retries=2 by default, so one agent request can hit the network up to three times before the fallback layer ever sees an error.

FAQ

Does PydanticAI need the Responses API?

No. OpenAIChatModel uses Chat Completions, which is what https://atmorouter.dev/v1 serves. Use the 'openai:' prefix only when you really mean OpenAI's Responses endpoint.

Why is result.cost() returning None?

The bundled price list does not know AtmoRouter's catalogue IDs. Read result.usage() and multiply by the rates on the model page, as in the snippet above.

Can I use Claude models through this setup?

Yes. IDs such as cc/claude-sonnet-5-5 are served over the OpenAI protocol at the same base URL. For the Anthropic SDK or Claude Code, the base URL is https://atmorouter.dev instead; see the setup guides on the AtmoRouter blog.

My structured output request is rejected. Now what?

The shared OpenAI-compatible profile assumes response_format is accepted. If the model ignores or rejects it, switch to tool output or prompted output, or pass an OpenAIModelProfile that matches what the model supports.

Next Step

Create a key at atmorouter.dev, pull current IDs and rates from the pricing page, and run the 20-line agent above against your own task. For the same pattern in an editor rather than a script, the Continue.dev guide covers the OpenAI-compatible settings there; for how retries change the numbers, see LLM API retry and fallback patterns. More guides live on the AtmoRouter blog.

Older

Small vs Large LLM: What Model Routing Actually Saves

Build with AtmoRouter.