ExamplescriptIntermediateRunnableguided-flow
gpt-oss on Ollama: a local model with typed output through Pydantic AI
Run OpenAI's open-weight gpt-oss:20b locally through Ollama's OpenAI-compatible endpoint, and get a validated CityLocation back from a Pydantic AI agent.
Key Facts
- Level
- Intermediate
- Runtime
- Python • Pydantic
- Pattern
- Inspectable flow with visible system boundaries
- Interaction
- Live sandbox • Script
- Code last changed
- 17 January 2026
Navigate this example
Library
Browse examplesReopen the wider library to compare adjacent patterns and linked learning paths.Interaction
Run sandbox nowTry the interaction directly in this example’s guided sandbox surface.Source
Open full sourceRead the real implementation, highlighted checkpoints, and runtime requirements.MCP
Call via MCPUse the same resource inside agents, deterministic exports, and MCP setup flows.
Linked principles
gpt-oss.py
python
from pydantic import BaseModel
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai import OpenAIProvider
import nest_asyncio
nest_asyncio.apply()
class CityLocation(BaseModel):
city: str
country: str
ollama_model = OpenAIChatModel(
model_name="gpt-oss:20b",
provider=OpenAIProvider(base_url="http://localhost:11434/v1"),
)
agent = Agent(
ollama_model,
output_type=CityLocation,
)
result = agent.run_sync("Where were the olympics held in 2012?")
print(result.output)
Related principles
- P1DelegationDesign for delegation rather than direct manipulationDesign experiences around the assignment of work, the expression of intent, the setting of constraints, and the review of results, rather than requiring users to execute each step manually.Open principle →
- P2VisibilityEnsure that background work remains perceptibleWhen the system is operating asynchronously or outside the user’s immediate focus, it should provide persistent and proportionate signals that work is continuing.Open principle →
- P5DelegationReplace implied magic with clear mental modelsThe product should help users understand what the system can do, what it is currently doing, what it cannot do, and what conditions govern its behaviour.Open principle →
- P7TrustEstablish trust through inspectabilityUsers should be able to examine how a result was produced when confidence, accountability, or decision quality is important.Open principle →
- P9OrchestrationRepresent delegated work as a system, not merely as a conversationWhere work involves multiple steps, agents, dependencies, or concurrent activities, it should be represented as a structured system rather than solely as a message stream.Open principle →