PydanticAI
Use PydanticAI with Inference.net via OpenAIProvider and OpenAIChatModel for typed structured outputs, tool-calling agents, and streaming.
Last updated
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, generate a project key in API keys, install pydantic-ai, and export your key:
pip install pydantic-ai
export INFERENCE_API_KEY="inf_sk_..."Initialize OpenAIProvider with https://api.inference.net/v1 and pass it to OpenAIChatModel:
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:
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))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):
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):
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/1Mcached input vs.$0.08/1Mfresh input). Keepinstructionsand tool schemas static across runs, and do not sendprompt_cache_key.moonshotai/kimi-k3.1-pro: Automatic implicit prefix caching ($0.198/1Mcached input vs.$1.80/1Mfresh input).glm-5.3andglm-5.3-flash: Send a stableprompt_cache_keyinOpenAIChatModelSettings(extra_body={...})as shown above.
Model your expected savings with the 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 |
glm-5.3 | 1,048,576 / 943,718 | $0.084 / $0.079 / $3.00 | Yes | Text | 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 |
moonshotai/kimi-k3.1-pro | 1,048,576 / 1,048,576 | $1.80 / $0.198 / $9.00 | Yes | Text, image | Kimi K3.1 Pro |
Inference.net-hosted models listed above support default Zero Data Retention and US-only routing at https://us.api.inference.net/v1.
Troubleshooting
401 Unauthorized: ConfirmINFERENCE_API_KEYis exported and passed toOpenAIProvider(notOPENAI_API_KEY).404 Not Found: Verifybase_url="https://api.inference.net/v1"includes/v1and usesapi.inference.net, notinference.net.UnexpectedModelBehavioror validation retries exhausted: Confirm the model hassupports_tools: true, simplify ambiguous field descriptions on your Pydantic schema, or increaseretries=3onAgent(...).400 Bad Requeston DeepSeek withprompt_cache_key: Omitextra_body={"prompt_cache_key": ...}when usingdeepseek-v4.1-flash-1017.- Model not found: Keep exact owner prefixes returned by
GET https://api.inference.net/v1/models, such asmoonshotai/kimi-k3.1-pro.
Explore all supported editors, workflow builders, gateways, and SDKs in the Integrations hub.
Start building
One OpenAI-compatible API key for fast open-weight models.