# PydanticAI (https://inference.net/docs/integrations/pydantic-ai)

Connect PydanticAI to Inference.net using `OpenAIProvider(base_url="https://api.inference.net/v1", api_key=os.environ["INFERENCE_API_KEY"])` and `OpenAIChatModel`. You get strict Pydantic `output_type` validation, dependency-injected tool calling, and async streaming across fast open-weight models (`deepseek-v4.1-flash-1017`, `glm-5.3`, and `moonshotai/kimi-k3.1-pro`) with one API key.

## Quick start

Create an account at [/register](/register/?model=deepseek-v4-1-flash-1017), generate a project key in [API keys](/dashboard/api-keys/), install `pydantic-ai`, and export your key:

```bash
pip install pydantic-ai
export INFERENCE_API_KEY="inf_sk_..."
```

Initialize `OpenAIProvider` with `https://api.inference.net/v1` and pass it to `OpenAIChatModel`:

```python
import os
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai import OpenAIProvider

provider = OpenAIProvider(
    base_url="https://api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
)
model = OpenAIChatModel("deepseek-v4.1-flash-1017", provider=provider)

agent = Agent(
    model,
    instructions="Answer in two concise sentences.",
)

result = agent.run_sync("What is prefix caching in LLM inference?")
print(result.output)
print(result.usage())
```

## Typed structured outputs

Pass any Pydantic `BaseModel` as `output_type` to validate responses automatically and trigger model retries if validation fails:

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


class IncidentTriage(BaseModel):
    severity: Literal["low", "medium", "high"]
    component: str = Field(description="Affected subsystem or API route")
    summary: str = Field(description="One-sentence summary of the issue")


provider = OpenAIProvider(
    base_url="https://api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
)
model = OpenAIChatModel("deepseek-v4.1-flash-1017", provider=provider)

triage_agent = Agent(
    model,
    output_type=IncidentTriage,
    instructions="Classify incoming production alerts into a structured triage record.",
)

result = triage_agent.run_sync(
    "Alert: p95 latency on /v1/chat/completions spiked to 4.2s after deploy 184."
)
triage: IncidentTriage = result.output
print(triage.model_dump_json(indent=2))
```

<Callout title="Dedicated HTML-to-JSON extraction with Schematron" tone="info">

PydanticAI's default structured output path relies on tool calling, so pair `Agent` with models that report `supports_tools: true`. For high-volume HTML-to-JSON extraction without an agent tool loop, call [`inference-net/schematron-v2-small`](/models/inference-net-schematron-v2-small/) or [`inference-net/schematron-v2-turbo`](/models/inference-net-schematron-v2-turbo/) directly via the OpenAI Python SDK. See the [Schematron guide](/docs/api/models/schematron/).

</Callout>

## Tool-calling agents with dependency injection

Use `@agent.tool` with `RunContext` and any Inference.net model with `supports_tools: true` (`deepseek-v4.1-flash-1017`, `glm-5.3`, `glm-5.3-flash`, or `moonshotai/kimi-k3.1-pro`):

```python
import os
from dataclasses import dataclass
from pydantic import BaseModel
from pydantic_ai import Agent, RunContext
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai import OpenAIProvider


@dataclass
class OrderDeps:
    orders: dict[str, str]


class SupportReply(BaseModel):
    order_id: str
    status: str
    customer_message: str


provider = OpenAIProvider(
    base_url="https://api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
)
model = OpenAIChatModel("moonshotai/kimi-k3.1-pro", provider=provider)

support_agent = Agent(
    model,
    deps_type=OrderDeps,
    output_type=SupportReply,
    instructions="Look up the customer's order status using the tool before writing a reply.",
)


@support_agent.tool
def get_order_status(ctx: RunContext[OrderDeps], order_id: str) -> str:
    """Look up the shipping status for an order ID."""
    return ctx.deps.orders.get(order_id, "not_found")


deps = OrderDeps(orders={"ORD-402": "shipped"})
result = support_agent.run_sync(
    "Where is order ORD-402?",
    deps=deps,
)
print(result.output.model_dump())
```

## Streaming, custom headers, and prompt caching

Supply a configured `AsyncOpenAI` client to `OpenAIProvider(openai_client=...)` to attach Inference.net usage headers (`x-inference-task-id`, `x-inference-environment`) or pin the US-only host (`https://us.api.inference.net/v1`):

```python
import asyncio
import os
from openai import AsyncOpenAI
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel, OpenAIChatModelSettings
from pydantic_ai.providers.openai import OpenAIProvider

client = AsyncOpenAI(
    base_url="https://api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
    default_headers={
        "x-inference-task-id": "support-agent",
        "x-inference-environment": "production",
    },
)

provider = OpenAIProvider(openai_client=client)
model = OpenAIChatModel("glm-5.3", provider=provider)
agent = Agent(model, instructions="Be direct and concise.")

settings = OpenAIChatModelSettings(
    extra_body={"prompt_cache_key": "support-agent-v1"},
)


async def main() -> None:
    async with agent.run_stream(
        "List three checks before deploying an LLM agent to production.",
        model_settings=settings,
    ) as result:
        async for delta in result.stream_text(delta=True):
            print(delta, end="", flush=True)
    print()


asyncio.run(main())
```

Prompt caching depends on the model family:

- **`deepseek-v4.1-flash-1017`:** Automatic implicit prefix caching (`$0.007/1M` cached input vs. `$0.08/1M` fresh input). Keep `instructions` and tool schemas static across runs, and do **not** send `prompt_cache_key`.
- **`moonshotai/kimi-k3.1-pro`:** Automatic implicit prefix caching (`$0.198/1M` cached input vs. `$1.80/1M` fresh input).
- **`glm-5.3` and `glm-5.3-flash`:** Send a stable `prompt_cache_key` in `OpenAIChatModelSettings(extra_body={...})` as shown above.

Model your expected savings with the [Prompt cache calculator](/tools/prompt-cache-calculator/).

## Verified models for PydanticAI

All model IDs, limits, and per-1M-token rates below are verified against `GET https://api.inference.net/v1/models` (**2026-12-06**):

| Model ID | Context / max output | Input / cached / output (per 1M) | Tools | Modalities | Model page |
| --- | --- | --- | --- | --- | --- |
| `deepseek-v4.1-flash-1017` | 1,040,000 / 393,216 | `$0.08` / `$0.007` / `$0.635` | Yes | Text, image | [DeepSeek V4.1 Flash](/models/deepseek-v4-1-flash-1017/) |
| `glm-5.3` | 1,048,576 / 943,718 | `$0.084` / `$0.079` / `$3.00` | Yes | Text | [GLM-5.3](/models/glm-5-3/) |
| `glm-5.3-flash` | 1,048,576 / 262,144 | `$0.10` / `$0.03` / `$0.35` | Yes | Text, image, video | [GLM-5.3 Flash](/models/glm-5-3-flash/) |
| `moonshotai/kimi-k3.1-pro` | 1,048,576 / 1,048,576 | `$1.80` / `$0.198` / `$9.00` | Yes | Text, image | [Kimi K3.1 Pro](/models/kimi-k3-1-pro/) |

Inference.net-hosted models listed above support default [Zero Data Retention](/docs/data-retention/) and US-only routing at `https://us.api.inference.net/v1`.

## Troubleshooting

- **`401 Unauthorized`:** Confirm `INFERENCE_API_KEY` is exported and passed to `OpenAIProvider` (not `OPENAI_API_KEY`).
- **`404 Not Found`:** Verify `base_url="https://api.inference.net/v1"` includes `/v1` and uses `api.inference.net`, not `inference.net`.
- **`UnexpectedModelBehavior` or validation retries exhausted:** Confirm the model has `supports_tools: true`, simplify ambiguous field descriptions on your Pydantic schema, or increase `retries=3` on `Agent(...)`.
- **`400 Bad Request` on DeepSeek with `prompt_cache_key`:** Omit `extra_body={"prompt_cache_key": ...}` when using `deepseek-v4.1-flash-1017`.
- **Model not found:** Keep exact owner prefixes returned by `GET https://api.inference.net/v1/models`, such as `moonshotai/kimi-k3.1-pro`.

Explore all supported editors, workflow builders, gateways, and SDKs in the [Integrations hub](/docs/integrations/).