Machine Learning Mastery shows how to build AI agents in Python with Pydantic AI
Machine Learning Mastery has walked through building AI agents in Python with Pydantic AI. The piece covers four basic building blocks: typed output via Pydantic models, tool calling with plain Python functions, dependency injection through RunContext, and built-in capabilities such as web search and extended thinking. It is a useful reference for developers who want to move from brittle glue code to more predictable agent logic.
AI-processed from Machine Learning Mastery; edited by Hamidun News
On April 29, 2026, Machine Learning Mastery published a detailed walkthrough of Pydantic AI, a Python framework for building AI agents with typing, validation and built-in tools. The article shows how to turn LLM work from a pile of fragile strings and parsers into a more predictable production process.
Why it matters
The article's core argument is simple: most agent scaffolding still looks like glue code. The model returns a string, the developer hopes it contains valid JSON, then parses the response by hand, catches errors and adds exception handling at every step.
Pydantic AI takes a different route. Instead of unstructured replies, it builds around Pydantic models, schemas, type checking and automatic retries when the model's output does not match the expected structure. For Python developers, that means less magic and more code that can be tested, read and maintained.
The article demonstrates this starting with the most basic example: an agent is created in just a few lines, and the model is specified with a string in the format provider:model-name. The author uses openai:gpt-4o-mini but stresses that the same pattern works with other providers, including Anthropic and Gemini. The agent's instructions are set once, after which you can run either a synchronous call via run_sync or an asynchronous variant with the same API. The barrier to entry stays low, and the architecture does not fall apart the first time the logic gets more complicated.
What the approach consists of
The most useful part of the piece is its breakdown of the four mechanisms behind a practical agent workflow in Pydantic AI. The author does not drift into abstraction or describe the framework in terms of promises: each block comes with a short code example and an explanation of which specific production pain point it addresses, without excess theory. As a result, the article reads like a map of the minimum set of solutions for a first working agent in Python.
- output_type forces the model to return data as a validated Python object rather than free-form text.
- @agent.tool_plain turns an ordinary Python function into a tool the agent can call while reasoning.
- deps_type and RunContext provide dependency injection without global state or hidden dependencies.
- capabilities add extras such as WebSearch and Thinking without overloading the constructor.
The author also shows what this looks like when extracting data from a job posting. The developer describes a JobPosting model with fields such as job title, company, list of skills, seniority level and a remote-work flag, and the agent returns a ready-made object instead of raw text. If a field is missing or a type does not match, the framework validates the response and retries before the error reaches the rest of the application. This removes the typical pain of any system where an LLM must produce data that code can use immediately.
How it leads to production
The second major example in the article covers tool calling. The author takes a simple nutrition database and registers a function that returns calories, protein, carbohydrates and fat per 100 grams for a given ingredient name. The agent then receives a request such as analyzing a dish, calls the tool for each ingredient itself, sums the values and returns the result as a MealSummary model. The output is not a free-form chat reply but a structured summary with totals, a verdict on the composition and a recommendation. One important detail: the function's docstring is not cosmetic but part of the contract, which the model uses to understand when and why to call the tool.
The section on dependency injection matters even more. Instead of a hardcoded dictionary, the author wraps the data source in a NutritionService service class and passes it to the agent through deps and a typed RunContext. That brings the code much closer to real-world operation: in place of the dictionary there could be a database, an API client, a user session or any other runtime dependency. Testability also improves. In the example, the service is easily swapped for a mock, and the agent keeps working with no changes to its core logic.
The final layer is built-in capabilities. The article covers at least two: WebSearch for access to current data from the internet and Thinking for deeper step-by-step reasoning on complex tasks. They can be combined in a single agent, for example a research assistant that decides what to search for, retrieves fresh results and only then composes an answer. At the end, the author points to the Logfire integration for observability: you can see model calls, tool invocations and validation retries.
What it means
The Machine Learning Mastery piece is useful because it moves the conversation about AI agents from demo mode to engineering practice. Pydantic AI is presented not as yet another LLM wrapper but as a way to bring discipline to types, dependencies and tools. For Python teams, it is a good signal: agents can be built without a heavy orchestrator if you rely from the start on validated schemas, explicit contracts and testable runtime components.
- Nov 2, 2026Karpathy builds a YouTube clone with 6454 videos from Hacker News recommendations in two hours
- Nov 2, 2026Karpathy used Claude to build HackerTube from 6,454 videos recommended on Hacker News
- Nov 2, 2026Arca gives AI agents finance tasks lasting up to 10 days, but leaves the trades to humans
- Nov 2, 2026Anthropic needs to grow revenue 32% a year to cover $850 billion in contracts
Key Questions Answered
Why it matters?
The article's core argument is simple: most agent scaffolding still looks like glue code. The model returns a string, the developer hopes it contains valid JSON, then parses the response by hand, catches errors and adds exception handling at every step. Pydantic AI takes a different route. Instead of unstructured replies, it builds around Pydantic models, schemas, type checking and automatic retries when the model's output does not match the expected structure. For Python developers, that means less magic and more code that can be tested, read and maintained. The article de
What the approach consists of?
The most useful part of the piece is its breakdown of the four mechanisms behind a practical agent workflow in Pydantic AI. The author does not drift into abstraction or describe the framework in terms of promises: each block comes with a short code example and an explanation of which specific production pain point it addresses, without excess theory. As a result, the article reads like a map of the minimum set of solutions for a first working agent in Python. output_type forces the model to return data as a validated Python object rather than free-form text. @agent.tool_pl
How it leads to production?
The second major example in the article covers tool calling. The author takes a simple nutrition database and registers a function that returns calories, protein, carbohydrates and fat per 100 grams for a given ingredient name. The agent then receives a request such as analyzing a dish, calls the tool for each ingredient itself, sums the values and returns the result as a MealSummary model. The output is not a free-form chat reply but a structured summary with totals, a verdict on the composition and a recommendation. One important detail: the function's docstring is not co
Test Frontier LLMs & Autonomous Agents in One Workspace
Run Claude Opus 5.5, GPT-6, Gemini 3.1, and DeepSeek side-by-side in Nomad AI (nomadnet.ai) — unified model routing, deep research, and multimodal workflows under one subscription.
The AI world, distilled — once a week
Seven stories that actually mattered, hand-picked. No noise, no reposts, no press releases.
Done! Check your inbox for a confirmation.