Back to News
RSS feedmachinelearningmastery.com

How to Build an AI Agent from Scratch in Python

Summary

This tutorial explains how to build a basic AI agent in plain Python with the Anthropic API, without an orchestration framework. It uses Python 3.10 or later, the Anthropic SDK, and an API key, with examples based on Claude Sonnet 4.5. The article first shows why tool calling is needed when an answer depends on external data, then defines an order-status function and a schema that tells the model when and how to request it. When the model returns a tool-use request, the application executes the function, sends the result back as a tool result, and makes another API call so the model can answer from the returned data. The tutorial generalizes this pattern into a loop that can handle multiple sequential tool calls, while a maximum-iteration limit prevents runaway execution. It then wraps the conversation in an Agent class whose message history persists across calls, allowing follow-up questions to use earlier context. The author notes that in-memory history still has context-window and process-restart limitations, so production systems may need trimming, summarization, and external persistence. The article also points readers toward testing tool selection, handling failures, and adding logging. Code is available in a companion GitHub repository. The examples use Claude Sonnet 4.5, which the article says Anthropic plans to retire on November 30, 2026, requiring a newer model string afterward.