Real models: providers, keys and model names
A real model is named with a provider and a model id, like openai:gpt-5.2. The provider's library reads the API key from an environment variable.
from pydantic_ai import Agent
agent = Agent("openai:gpt-5.2", instructions="You answer support tickets.")With no OPENAI_API_KEY set, creating the agent fails straight away, and the message says what to set. With the key exported, the same line works and run_sync sends the ticket to OpenAI:
export OPENAI_API_KEY="sk-..."| Model name | Install | Key |
|---|---|---|
openai:gpt-5.2 | pydantic-ai-slim[openai] | OPENAI_API_KEY |
anthropic:claude-sonnet-4-6 | pydantic-ai-slim[anthropic] | ANTHROPIC_API_KEY |
google:gemini-2.5-flash | pydantic-ai-slim[google] | GOOGLE_API_KEY |
groq:llama-3.3-70b-versatile | pydantic-ai-slim[groq] | GROQ_API_KEY |
Choosing the model when you run
agent = Agent(instructions="You answer support tickets.")
print(agent.run_sync("My parcel never arrived", model=shop_model).output)An agent does not need a model when it is created. model= on a run picks one for that run, and it also overrides the agent's own model. Without either, the run fails:
agent = Agent(instructions="You answer support tickets.")
agent.run_sync("My parcel never arrived")Creating an agent before the key exists
agent = Agent("openai:gpt-5.2", defer_model_check=True)
print(agent.run_sync("I was charged twice", model=shop_model).output)defer_model_check=True waits until the first run that uses the named model before creating it. Your app module can then be imported on a machine without keys, such as a test runner, as long as those runs use another model. Lessons 20 and 22 rely on this.
A model on your own machine
Ollama runs open models locally and speaks the OpenAI API, so Pydantic AI connects to it with the OpenAI model class and an Ollama provider:
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.ollama import OllamaProvider
model = OpenAIChatModel("qwen2.5:3b", provider=OllamaProvider(base_url="http://localhost:11434/v1"))
agent = Agent(model, instructions="You answer support tickets.")Small local models are much weaker at calling tools and filling typed output than hosted ones, so expect more retries, lesson 7, if you try the course with one.
- Set
OPENAI_API_KEY=not-a-real-keyand create the agent again. What happens onrun_sync? - Pass
model="test"torun_syncon the agent without a model. - Look up
KnownModelNameinpydantic_ai.modelsto see every model name the library knows.
Every expert started right here.