Pydantic AIPydantic AI 2.43 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
23 small wins to finish your pathNext lesson

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.

Example
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:

Example
export OPENAI_API_KEY="sk-..."
Model nameInstallKey
openai:gpt-5.2pydantic-ai-slim[openai]OPENAI_API_KEY
anthropic:claude-sonnet-4-6pydantic-ai-slim[anthropic]ANTHROPIC_API_KEY
google:gemini-2.5-flashpydantic-ai-slim[google]GOOGLE_API_KEY
groq:llama-3.3-70b-versatilepydantic-ai-slim[groq]GROQ_API_KEY

Choosing the model when you run

Example
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:

Example
agent = Agent(instructions="You answer support tickets.")
agent.run_sync("My parcel never arrived")

Creating an agent before the key exists

Example
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:

Example
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.

Try it yourself
  • Set OPENAI_API_KEY=not-a-real-key and create the agent again. What happens on run_sync?
  • Pass model="test" to run_sync on the agent without a model.
  • Look up KnownModelName in pydantic_ai.models to see every model name the library knows.

Every expert started right here.