---
url: 'https://docs.byesu.com/en/clients/pydantic-ai.md'
description: >-
  Build type-safe PydanticAI agents on byesu API using OpenAIProvider or
  AnthropicProvider: structured BaseModel outputs with Claude 5.5 and GPT-6.2.
---

# Connect PydanticAI to byesu API

Build type-safe, dependency-injected Python agents with **PydanticAI** (`pydantic-ai`) on **byesu** using either `OpenAIProvider` (for all vendors via `/v1`) or `AnthropicProvider` (for native `/v1/messages` and `0.1x` prompt caching) under one pay-as-you-go API key.

::: tip Quick configuration

* **`OpenAIProvider` `base_url`**: `https://byesu.com/v1` (all vendors via `OpenAIModel`)
* **`AsyncAnthropic` `base_url`**: `https://byesu.com` (**without `/v1`** — passed to `AnthropicProvider` for native `/v1/messages`)
* **Environment variable**: `BYESU_API_KEY=sk-...` (created in the default `auto` group)
* **Recommended models**: `claude-sonnet-5-5`, `claude-opus-5-5`, `gpt-6.2-sol`, `deepseek-v4-pro`, `gemini-4-argon`
  :::

## Prerequisites

1. Generate an `sk-...` token in the [byesu Console](https://byesu.com) under the default **`auto`** group (see [Choosing a Group](/en/guide/groups)).
2. Install PydanticAI with OpenAI and Anthropic extras:

```bash
pip install "pydantic-ai-slim[openai,anthropic]"
export BYESU_API_KEY="sk-your-byesu-token"
```

## Option 1: Multi-Vendor Structured Output Agent (`OpenAIModel` + `OpenAIProvider`)

Point `OpenAIProvider` at `https://byesu.com/v1` to run validated `BaseModel` structured output agents across Claude, GPT, DeepSeek, Gemini, and Grok:

```python
import os
from typing import Literal
from pydantic import BaseModel, Field
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider


class IncidentTriage(BaseModel):
    severity: Literal['SEV-1', 'SEV-2', 'SEV-3']
    suspected_component: str
    immediate_mitigation: str = Field(description='Single concrete first action for on-call')
    rollback_recommended: bool


model = OpenAIModel(
    'claude-sonnet-5-5',  # swap to 'gpt-6.2-sol', 'deepseek-v4-pro', 'gemini-4-argon'
    provider=OpenAIProvider(
        base_url='https://byesu.com/v1',
        api_key=os.environ['BYESU_API_KEY'],
    ),
)

triage_agent = Agent(
    model,
    output_type=IncidentTriage,
    system_prompt='You are an on-call SRE triage agent. Produce concise, actionable incident classifications.',
)


@triage_agent.tool_plain
def recent_deploys(service: str) -> str:
    """Return the latest deployment timestamp and commit SHA for a service."""
    return f'{service}: deployed v2026.12.03-rc4 (sha 9f3c1a2) 11 minutes ago.'


result = triage_agent.run_sync(
    'payment-gateway 502 rate jumped from 0.02% to 6.8% right after the latest rollout.'
)
print(result.output.model_dump_json(indent=2))
```

*(Using an older `pydantic-ai` `0.0.x` release? Replace `output_type=` with `result_type=` and read `result.data` instead of `result.output`.)*

## Option 2: Native Anthropic Messages (`AnthropicModel` + `AnthropicProvider`)

For Claude-specific features — native tool-use blocks, thinking blocks, and `0.1x` prompt cache reads via `/v1/messages` — inject a configured `AsyncAnthropic` client into `AnthropicProvider`:

::: warning Base URL contrast: `OpenAIProvider` vs `AsyncAnthropic`
`OpenAIProvider` expects **`https://byesu.com/v1`**, whereas `AsyncAnthropic` automatically appends `/v1/messages` and expects **`https://byesu.com`** without `/v1`.
:::

```python
import asyncio
import os
from anthropic import AsyncAnthropic
from pydantic import BaseModel
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel
from pydantic_ai.providers.anthropic import AnthropicProvider


class MigrationPlan(BaseModel):
    steps: list[str]
    backwards_compatible: bool
    verification_query: str


claude_model = AnthropicModel(
    'claude-opus-5-5',
    provider=AnthropicProvider(
        anthropic_client=AsyncAnthropic(
            base_url='https://byesu.com',
            api_key=os.environ['BYESU_API_KEY'],
            timeout=120.0,
        )
    ),
)

architect_agent = Agent(
    claude_model,
    output_type=MigrationPlan,
    system_prompt='Design zero-downtime relational schema migrations.',
)


async def main() -> None:
    res = await architect_agent.run(
        'Split users.full_name into given_name and family_name on a 90M-row Postgres table.'
    )
    print(res.output)
    print('Token usage:', res.usage())


if __name__ == '__main__':
    asyncio.run(main())
```

See [Prompt Caching](/en/guide/prompt-caching) for structuring long system prompts so repeated agent turns benefit from **`0.1x`** cache reads.

## Production Engineering Notes

* **Omit `temperature` / `top_p` in `ModelSettings`**: Anthropic API version `2026-10-21` rejects `temperature`, `top_p`, and `top_k` with HTTP `400`, and GPT-6.2 reasoning models reject fixed sampling overrides as well. Leave `model_settings` without sampling keys ([Claude 400 sampling fix](/en/errors/claude-api-400-temperature-top-p-not-supported)).
* **Timeouts on reasoning turns**: Pass `timeout=120.0` on `AsyncAnthropic(...)` (or inject a custom `AsyncOpenAI(..., timeout=120.0)` via `OpenAIProvider(openai_client=...)`) when running `claude-opus-5-5`, `gpt-6.2-sol`, or `deepseek-v4-pro`.
* **Token groups & billing**: Default `auto` tokens cover Claude, GPT, Gemini, DeepSeek, and Grok; create dedicated tokens in `Glm` (`glm-5.3`), `Kimi` (`kimi-k3`), or `media` (`gpt-image-2`, `gemini-3.1-flash-image-ultra`) when needed. Billing is pay-as-you-go per token with live rates visible in the [byesu Console](https://byesu.com) after sign-in.

## Troubleshooting & Benchmarks

* **`401 authentication_error` / `invalid_api_key`**: check `https://byesu.com/v1` on `OpenAIProvider` vs `https://byesu.com` on `AsyncAnthropic` ([OpenAI 401 fix](/en/errors/openai-api-401-invalid-api-key), [Claude 401 fix](/en/errors/claude-api-401-authentication-error)).
* **`404` / `no available channel`**: confirm the exact model ID in the console and verify your token group ([no available channel](/en/errors/no-available-channel-error), [Claude 404 fix](/en/errors/claude-api-model-not-found-404)).
* **Timeouts or dropped streams**: raise client read timeouts to `>= 120`s ([Anthropic timeout](/en/errors/anthropic-api-timeout), [streaming connection dropped](/en/errors/streaming-connection-dropped)).
* **`429` & latency benchmarks**: see [OpenAI 429 rate limit vs quota](/en/errors/openai-api-429-rate-limit-vs-quota) and [weekly production benchmarks](https://byesu.com/benchmarks).
