PydanticAI, smolagents, Agno and Python Comparison
Typed outputs, code-writing agents and a service platform: three different bets on what matters.
PydanticAI centers on typed dependencies, validated outputs and testability. smolagents, from Hugging Face, is a small library whose signature agent writes its actions as Python code, which needs a sandbox. Agno offers agents, teams and workflows together with a platform for running them as services. For other Python choices, see the dedicated guides and the comparison below.
What you will learn: the idea behind each of the three, a runnable example of each, how code-writing agents change the risk, how Python options compare, what open source does and does not give you, and a selection method for 2027 planning.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect and Choosing Frameworks: Lock-In, Upgrades and Benchmarks.
Checked in November 2026 and run with pydantic-ai-slim 2.77.0, smolagents 1.26.0 and agno 3.2.1. Scripted models replace real ones, so no key or network is needed.
Different centers of gravity
All three turn ordinary functions into tools using names, type hints and descriptions. The differences show up in how results are checked, how actions are carried out and what surrounds the agent in production.
PydanticAI: typed and testable
PydanticAI comes from the team behind the Pydantic validation library. You declare the type of the dependencies your tools need and the type of the answer you expect. The framework validates arguments and output, and asks the model to try again when validation fails. Version 2.0 arrived in June 2026 and introduced the capability as a building block for bundling behavior.
import os
from dataclasses import dataclass
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext, UsageLimits
from pydantic_ai.messages import ModelResponse, ToolCallPart
from pydantic_ai.models.function import AgentInfo, FunctionModel
os.environ["PYDANTIC_AI_NO_BANNER"] = "1"
@dataclass
class Deps:
orders: dict # injected, so tests can pass fake data
class Answer(BaseModel):
order_id: str
days_late: int = Field(ge=0)
message: str
CALLS = []
def scripted(messages, info: AgentInfo) -> ModelResponse:
"""Offline stand-in. Its first final answer is invalid on purpose."""
CALLS.append(1)
if len(CALLS) == 1:
return ModelResponse(parts=[
ToolCallPart("days_late", {"order_id": "A-17"})])
days = -3 if len(CALLS) == 2 else 3
return ModelResponse(parts=[ToolCallPart(
info.output_tools[0].name,
{"order_id": "A-17", "days_late": days,
"message": "Your order is running late."})])
agent = Agent(FunctionModel(scripted), deps_type=Deps, output_type=Answer,
instructions="Report delays using the records only.",
retries=2)
@agent.tool
def days_late(ctx: RunContext[Deps], order_id: str) -> int:
"""Return how many days late an order is."""
return ctx.deps.orders[order_id]
result = agent.run_sync("How late is A-17?",
deps=Deps(orders={"A-17": 3}),
usage_limits=UsageLimits(request_limit=5))
print(repr(result.output))
print("model requests:", result.usage.requests)
for message in result.all_messages():
for part in message.parts:
if part.part_kind == "tool-return":
print(f"{part.tool_name}: {part.outcome}")
Output:
Answer(order_id='A-17', days_late=3, message='Your order is running late.')
model requests: 3
days_late: success
final_result: retried
final_result: success
The scripted model first answers with a negative number of days. The output type forbids that, so the attempt is marked as retried and the second answer is accepted. Three model requests were made, one of them only to repair an invalid answer: count retries in your cost figures. deps carries the order records into the tool, which lets a test supply fake data without patching globals.
Checking the answer against data
A value of 30 days would pass that schema even though the record says 3. An output validator closes the gap by comparing the answer with the records. Here the library's test model is told to claim two different values.
import os
from pydantic_ai import Agent, ModelRetry, RunContext
from pydantic_ai.models.test import TestModel
os.environ["PYDANTIC_AI_NO_BANNER"] = "1"
RECORDS = {"A-17": 3}
agent = Agent(deps_type=dict, output_type=int)
@agent.output_validator
def matches_records(ctx: RunContext[dict], days: int) -> int:
if days != ctx.deps["A-17"]:
raise ModelRetry("The number does not match the record.")
return days
for claimed in (3, 30):
model = TestModel(custom_output_args=claimed)
try:
result = agent.run_sync("Days late for A-17?", deps=RECORDS,
model=model)
print(claimed, "accepted:", result.output)
except Exception as error:
print(claimed, "rejected:", type(error).__name__)
Output:
3 accepted: 3
30 rejected: UnexpectedModelBehavior
The true value is accepted. The false one is sent back for another try; the test model repeats itself, the retries run out and the run fails with an error. That is the behavior you want, provided your application catches the error and tells the user something honest. The validator here is written for one known order to keep it short. A real one reads the identifier from the output and looks up that record.
The library also offers tool approval, usage limits, test and function models, and integration with durable execution systems. The project's policy states that minor releases contain no intentional breaking changes.
smolagents: actions written as code
A conventional agent emits one structured tool call at a time. A smolagents CodeAgent asks the model to write a short Python program that calls tools, loops and combines results. That can save model round trips. It also means running text produced by a model.
from smolagents import CodeAgent, LogLevel, Model, tool
from smolagents.models import ChatMessage, MessageRole
SCRIPT = [
"<code>\nimport os\nprint(os.listdir('.'))\n</code>",
"<code>\ntotal = 0\nfor order_id in ['A-17', 'B-02']:\n"
" total += order_value(order_id=order_id)\n"
"final_answer(total)\n</code>",
]
class ScriptedModel(Model):
"""Offline stand-in: replies with prepared code blocks."""
def generate(self, messages, stop_sequences=None, **kwargs):
return ChatMessage(role=MessageRole.ASSISTANT,
content=SCRIPT.pop(0))
@tool
def order_value(order_id: str) -> int:
"""Return the value of an order in pounds.
Args:
order_id: The order reference.
"""
return {"A-17": 40, "B-02": 25}[order_id]
agent = CodeAgent(tools=[order_value], model=ScriptedModel(),
max_steps=4, verbosity_level=LogLevel.OFF)
print("answer:", agent.run("What are A-17 and B-02 worth together?"))
for step in agent.memory.steps[1:]:
if step.error:
reason = str(step.error).split("due to: ")[-1]
print(f"step {step.step_number} blocked:", reason.split(".")[0])
else:
print(f"step {step.step_number} ran:",
step.code_action.splitlines()[0])
Output:
answer: 65
step 1 blocked: InterpreterError: Import of os is not allowed
step 2 ran: total = 0
The first scripted program tries to list files and is refused, because the default local executor limits imports. The second calls the tool twice in a loop and returns the sum in a single step. The refusal is helpful but must not be mistaken for a security boundary.
The project documents sandboxed execution through Docker and hosted services such as E2B, Modal and Blaxel. For anything beyond local experiments with trusted input, run generated code in an isolated environment with no secrets, limited network and resource limits. Remember that a tool you expose still acts with its own permissions, wherever the code runs.
| Aspect | Tool-calling agent | Code agent |
|---|---|---|
| Action form | Structured call | Program text |
| Combining results | Extra model turns | Inside one program |
| Review and approval | Simple, per call | Harder; one program may call many tools |
| Main safeguard | Argument validation and permissions | Sandbox, plus permissions on tools |
smolagents is model-agnostic and also includes a conventional tool-calling agent. It can load tools from MCP servers and from the Hugging Face Hub; loading shared tools means running someone else's code, so review it first.
Agno: from agent to service
Agno describes itself as a platform for building agents, teams and workflows and running them as durable services. Its AgentOS runtime provides an API and an MCP server, with authentication, roles, approvals, scheduling and tracing. The library can be used on its own, as here.
import os
os.environ["AGNO_TELEMETRY"] = "false"
from agno.agent import Agent # noqa: E402
from agno.models.base import Model # noqa: E402
from agno.models.response import ModelResponse # noqa: E402
SCRIPT = [
ModelResponse(role="assistant", tool_calls=[{
"id": "c1", "type": "function",
"function": {"name": "order_status",
"arguments": '{"order_id": "A-17"}'}}]),
ModelResponse(role="assistant", content="A-17 is due on Friday."),
]
class ScriptedModel(Model):
"""Offline stand-in implementing Agno's model interface."""
def invoke(self, *args, **kwargs):
return SCRIPT.pop(0)
async def ainvoke(self, *args, **kwargs):
return SCRIPT.pop(0)
def invoke_stream(self, *args, **kwargs):
yield SCRIPT.pop(0)
async def ainvoke_stream(self, *args, **kwargs):
yield SCRIPT.pop(0)
def _parse_provider_response(self, response, **kwargs):
return response
def _parse_provider_response_delta(self, response):
return response
def order_status(order_id: str) -> str:
"""Look up the delivery status of one order."""
return f"{order_id}: due Friday"
agent = Agent(model=ScriptedModel(id="scripted"), tools=[order_status],
instructions="Use the records only.", tool_call_limit=3)
run = agent.run("When will A-17 arrive?")
for call in run.tools:
print("tool:", call.tool_name, call.tool_args, "->", call.result)
print("answer:", run.content)
Output:
tool: order_status {'order_id': 'A-17'} -> A-17: due Friday
answer: A-17 is due on Friday.
The run object lists each tool call with its arguments and result, and tool_call_limit bounds them. The custom model class implements the library's model interface; real projects use a provided provider class instead. This listing does not exercise AgentOS.
Agno's package description says it sends a telemetry event per agent to learn which model providers are used, without prompts or outputs, and that setting AGNO_TELEMETRY=false disables it. The example does so. Check the defaults of every library you adopt.
What each needs before production
| Concern | PydanticAI | smolagents | Agno |
|---|---|---|---|
| Bounding a run | Usage limits and retry counts | Maximum steps | Tool call limits and run settings |
| Dangerous actions | Tool approval | Sandbox and narrow tools | Human approval features |
| Keeping history | Store messages yourself or use durable integrations | Store the agent's memory steps yourself | Database-backed storage |
| Surviving restarts | Durable execution integrations | Your own design | The runtime's durable features |
| Seeing what happened | OpenTelemetry-based instrumentation | Memory log and telemetry integrations | Tracing in the platform |
Treat each cell as a question to verify in current documentation and in your own trial. A feature that exists may still need a database, a separate service or paid hosting before it does what you assume.
Keeping a way out
The same function, order_value or order_status, could be registered with any of these libraries. Write tools as plain functions in their own module with their own tests, and add the library's decorator or registration in a thin layer beside them. Then changing libraries means rewriting the thin layer and the agent configuration, while rules and data access stay put. Prompts and saved histories are harder to move, so keep examples of real requests and expected results that any replacement can be judged against.
Python agent frameworks compared
| Library | Organizing idea | Consider it when | Check first |
|---|---|---|---|
| OpenAI Agents SDK | Agents and handoffs | Routing between specialists | Pre-1.0 changes; tracing default |
| Claude Agent SDK | Claude Code's tools and loop | Work on files and systems | Permissions and isolation |
| LangChain and LangGraph | Agent over a graph runtime | Explicit state and pauses | State changes across releases |
| CrewAI | Roles, tasks and flows | Work that divides into roles | Call counts and limits |
| Agent Framework | Agents and workflows | Microsoft platforms, .NET too | Provider feature differences |
| LlamaIndex, Haystack, DSPy | Events, pipelines, optimization | Data-centered systems | Evaluation data available |
| Google ADK | Agents and graph workflows | Google Cloud, several languages | Changes in 2.0 |
| PydanticAI | Typed agents | Strong validation and testing | Retry cost |
| smolagents | Code agents | Compact multi-step actions | Sandbox |
| Agno | Agents plus runtime | You want a ready service layer | How much of the platform you need |
These descriptions summarize each project's focus. They are not a ranking, and most can be stretched to do the others' work.
Open-source comparison
| License in package metadata | Packages |
|---|---|
| MIT | openai-agents, claude-agent-sdk, langchain, langgraph, crewai, agent-framework-core, llama-index-workflows, dspy, pydantic-ai |
| Apache 2.0 | haystack-ai, smolagents, agno, google-adk, bedrock-agentcore |
A license on a library does not cover everything around it. The Claude Agent SDK documentation says its use is governed by Anthropic's commercial terms, with components under their own licenses. Hosted platforms, tracing services and enterprise features often carry separate terms, and model use is billed and governed by the provider. Have the licenses and terms reviewed by whoever handles that in your organization.
- License of the package and of the add-ons you will use
- Who maintains it, and how quickly security reports are handled
- Release history, deprecation policy and open critical issues
- Whether the core works without the vendor's hosted service
- Number and quality of transitive dependencies
Selection guide for 2027 planning
This page was written in November 2026. Nobody can say which framework will be best during 2027, and releases in this section show how quickly positions change: major versions from Haystack, PydanticAI and Google ADK arrived within months of each other, and AutoGen was archived. Plan to choose well now and to revisit.
| Your main need | Start a trial with |
|---|---|
| Understand agents | A hand-written loop, then one small library |
| Validated data for other systems | PydanticAI, or typed output in your current choice |
| Long processes with approval | A graph or workflow runtime, or a durable engine |
| Document-heavy answers | Haystack or LlamaIndex tooling |
| Measurable prompt improvement | DSPy, with held-out data |
| Data analysis through code | A code agent inside a strict sandbox |
| A cloud platform already chosen | That provider's kit, plus one independent option |
- Pick two candidates for your main need.
- Run the same trial, including a tool failure and an approval.
- Keep tools and rules in plain functions.
- Record the decision with the evidence and a review date six months on.
A two-person team needs to turn supplier emails into validated records. They try PydanticAI and a plain client call with schema output. Both reach the quality bar on their test set; the library saves retry and testing code, so they adopt it and keep the extraction function independent of it.
One testing habit for all of them
Each example replaces the model with a script. Use that seam to test limits, bad arguments, tool failures and forbidden actions on every commit. Then run a separate evaluation with the real model, many times per case, because a script cannot tell you how a model behaves. Agent Evaluation Framework covers the second part.
Common mistakes
| Mistake | Better practice |
|---|---|
| Treating a restricted interpreter as a sandbox | Isolate generated code properly |
| Assuming validated output is correct | Check it against source data |
| Adopting a whole platform for one agent | Use the smallest part that meets the need |
| Ignoring default telemetry | Read and set it deliberately |
| Choosing from a yearly list | Trial against your own requirements |
Checklist
- The library matches the main need
- Retries, tool calls and run length are bounded
- Generated code runs only in an isolated environment
- Outputs that matter are checked against data
- Licenses, terms and telemetry have been reviewed
- Tests run without a live model, and evaluations run with one
- A review date is recorded
Frequently asked questions
Which Python library is easiest to learn?
Small libraries and provider SDKs show the loop most clearly. Ease also depends on your habits: developers who like types often find PydanticAI natural.
Are code agents better than tool-calling agents?
They can need fewer turns for multi-step work. They also need stronger isolation and make per-action approval harder. Measure both on your task.
Can I use local models with these libraries?
Each can connect to models beyond one provider, including local servers in many setups. Smaller models often struggle with tool calls or code, so evaluate before relying on them.
Do I need a platform to put an agent in production?
No. A web service, a database, queues and monitoring can host any of these. A platform saves building them, in exchange for its constraints.
References and further reading
- PydanticAI V2 announcement
- PydanticAI version policy
- smolagents documentation
- Agno documentation
- Claude Agent SDK overview and terms
Next steps
Google ADK and Amazon Bedrock AgentCore
Cloud provider options.
TypeScript: Mastra and Vercel AI SDK
The TypeScript side.
Tool Permissions, Approvals and Abuse Risks
Limit what agents can do.