PydanticAI, smolagents, Agno and Python Comparison

Typed outputs, code-writing agents and a service platform: three different bets on what matters.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Versions used

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.

Beginner Three styles

Different centers of gravity

PydanticAItypes and validation around the loop
smolagentsthe model writes code as its action
Agnoagents plus a runtime to serve them
Each can build a simple tool-using agent; they differ in what they make easy.

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.

Intermediate Code agents and platforms

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.

Use an isolated sandbox

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.

AspectTool-calling agentCode agent
Action formStructured callProgram text
Combining resultsExtra model turnsInside one program
Review and approvalSimple, per callHarder; one program may call many tools
Main safeguardArgument validation and permissionsSandbox, 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.

Telemetry

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

ConcernPydanticAIsmolagentsAgno
Bounding a runUsage limits and retry countsMaximum stepsTool call limits and run settings
Dangerous actionsTool approvalSandbox and narrow toolsHuman approval features
Keeping historyStore messages yourself or use durable integrationsStore the agent's memory steps yourselfDatabase-backed storage
Surviving restartsDurable execution integrationsYour own designThe runtime's durable features
Seeing what happenedOpenTelemetry-based instrumentationMemory log and telemetry integrationsTracing 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.

Expert Comparing and selecting

Python agent frameworks compared

LibraryOrganizing ideaConsider it whenCheck first
OpenAI Agents SDKAgents and handoffsRouting between specialistsPre-1.0 changes; tracing default
Claude Agent SDKClaude Code's tools and loopWork on files and systemsPermissions and isolation
LangChain and LangGraphAgent over a graph runtimeExplicit state and pausesState changes across releases
CrewAIRoles, tasks and flowsWork that divides into rolesCall counts and limits
Agent FrameworkAgents and workflowsMicrosoft platforms, .NET tooProvider feature differences
LlamaIndex, Haystack, DSPyEvents, pipelines, optimizationData-centered systemsEvaluation data available
Google ADKAgents and graph workflowsGoogle Cloud, several languagesChanges in 2.0
PydanticAITyped agentsStrong validation and testingRetry cost
smolagentsCode agentsCompact multi-step actionsSandbox
AgnoAgents plus runtimeYou want a ready service layerHow 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 metadataPackages
MITopenai-agents, claude-agent-sdk, langchain, langgraph, crewai, agent-framework-core, llama-index-workflows, dspy, pydantic-ai
Apache 2.0haystack-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 needStart a trial with
Understand agentsA hand-written loop, then one small library
Validated data for other systemsPydanticAI, or typed output in your current choice
Long processes with approvalA graph or workflow runtime, or a durable engine
Document-heavy answersHaystack or LlamaIndex tooling
Measurable prompt improvementDSPy, with held-out data
Data analysis through codeA code agent inside a strict sandbox
A cloud platform already chosenThat provider's kit, plus one independent option
  1. Pick two candidates for your main need.
  2. Run the same trial, including a tool failure and an approval.
  3. Keep tools and rules in plain functions.
  4. Record the decision with the evidence and a review date six months on.
Illustrative choice, not a real team

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

MistakeBetter practice
Treating a restricted interpreter as a sandboxIsolate generated code properly
Assuming validated output is correctCheck it against source data
Adopting a whole platform for one agentUse the smallest part that meets the need
Ignoring default telemetryRead and set it deliberately
Choosing from a yearly listTrial 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

Next steps