Building an AI Agent from Scratch: A Pure Python Guide
This guide walks through building an AI agent in pure Python without third-party orchestration frameworks. It explains why owning the core scheduling and tool layers matters, how to separate tool abstraction, model integration, and orchestration, and how to implement the ReAct loop as a state machine with step limits and error handling. It also covers context engineering, observability, evaluation, and when a custom agent is worth the maintenance cost.
1. Why Build an Agent from Scratch
Most public material on agents starts from a general-purpose orchestration framework: a few lines of configuration and you have a running workflow. Those tools are genuinely efficient for prototyping, general retrieval-augmented generation pipelines, and fixed automation flows. But what they abstract away is exactly the hardest and most valuable part of agent engineering: how to trim context, how to recover from tool-call failures, how to control the reasoning budget, and how to persist and replay state.
A telling pattern: the best-performing coding assistants and code agents on the market almost all describe in-house architectures in their public technical talks, not applications of a general framework. The reason is simple. The competitiveness of a production agent concentrates on three points—execution efficiency, scenario-specific personalization, and robustness. To cover as many scenarios as possible, a general framework has to compromise at the abstraction layer, which makes it hard to max out all three at once. The so-called “big companies build their own wheels” is not about reinventing the wheel; it is that general abstractions cannot carry the constraints of a specific path.
So the position of this article is: keep the core scheduling and tool layers in your own hands, and reuse common industry solutions for general capabilities (vector retrieval, text chunking, embedding calls, and other mature pipelines). Below is an implementation path with no third-party framework dependencies.
2. Aligning the Concepts: Agent vs. Chatbot
A traditional conversational model responds passively: one question, one answer, stateless and side-effect-free. An agent differs in that it can produce side effects—retrieving external information, writing data, calling business APIs, generating files. The complexity does not depend on how strong the model is, but on what you allow it to do.
Here is a minimal usable example: an after-sales support agent with only two tools attached (knowledge base retrieval and ticket creation) that escalates to a human when retrieval fails. The logic is minimal, yet it is already a complete agent, because it can autonomously decide “what to do next.”
The essence of an agent can be compressed into four stages: Perceive — Reason — Act — Learn. This article implements the first three; the learning stage involves vectorization and long-term memory and is left as a later extension.
The interleaved pattern of reasoning and acting is commonly known in the industry as ReAct: write out the model’s thinking explicitly, choose a tool accordingly, observe the result, and continue thinking. Its engineering value is not “making the model smarter,” but that every step has a readable intermediate state, so when something goes wrong you can pinpoint exactly which reasoning step or which tool returned an error.
3. Architecture: Three Things That Must Be Decoupled
Set the architecture before coding, otherwise the code will rot by the third requirement change.
Layer 1: Tool abstraction. Adding a capability should not modify the main loop. All tools implement the same contract and are mounted through a registry:
from dataclasses import dataclassfrom typing import Callable, Any@dataclassclass Tool:name: strdescription: strschema: dict # JSON Schema of parameters, so the model understands the inputshandler: Callable[..., Any]class ToolRegistry:def __init__(self):self._tools: dict[str, Tool] = {}def register(self, tool: Tool):self._tools[tool.name] = tooldef get(self, name: str) -> Tool | None:return self._tools.get(name)def manifest(self) -> list[dict]:return [{"name": t.name, "description": t.description,"parameters": t.schema} for t in self._tools.values()]
To add a database query or email sending, you just call register once. That is the extensibility principle.
Layer 2: Model integration. The model is the replaceable “brain”; the agent is the “commander.” If you use one vendor’s model today and another tomorrow, the logic should not be rewritten. The approach is to converge the differences into a minimal interface:
class LLMClient:def complete(self, messages: list[dict], tools: list[dict]) -> dict: ...
Each vendor’s authentication, field naming, and streaming protocol are all encapsulated in the implementation class; the upper layer depends only on complete. This layer also handles fault tolerance: when the primary model times out or is rate-limited, it switches to a backup implementation by priority, and the agent loop is unaware.
class FallbackLLM:def __init__(self, clients): self.clients = clientsdef complete(self, messages, tools):last = Nonefor c in self.clients:try:return c.complete(messages, tools)except Exception as e:last = eraise last
Layer 3: Orchestration control. It maintains state, drives the loop, and constrains the budget. It imports no specific tool or model and only does orchestration.
4. The Core Loop: ReAct as a State Machine
The skeleton of the main loop is a finite state machine with a termination condition, not while True:
def run(task: str, registry: ToolRegistry, llm: LLMClient,max_steps: int = 8) -> list[dict]:messages = [{"role": "user", "content": task}]trace = []for step in range(max_steps):resp = llm.complete(messages, registry.manifest())messages.append({"role": "assistant", "content": resp["content"]})trace.append({"step": step, "thought": resp["content"]})calls = resp.get("tool_calls") or []if not calls:return trace # no tool calls means convergencefor call in calls:tool = registry.get(call["name"])if tool is None: # hallucinated tool name: don't crash, but keep a recordobservation = {"error": "unknown tool"}else:try:observation = tool.handler(**call["arguments"])except Exception as e:observation = {"error": str(e)}messages.append({"role": "tool","content": str(observation)})trace.append({"step": step, "tool": call["name"],"observation": observation})return trace
A few details that are easy to overlook but decide success or failure:
- The step limit is a safety valve, not an option. Without it, a single loop hiccup can burn a whole day’s quota.
- Tool exceptions must be fed back as observations, not thrown to terminate. Let the model see the failure reason; it will usually retry with different arguments.
- Unknown tool names must be recorded. This is a direct signal for evaluating prompt quality and the clarity of tool descriptions.
- Keep trace and messages separate. The former is for humans and for persistence; the latter is for the model. Their trimming strategies differ.
5. Context Engineering: The Real Performance Bottleneck
Getting the loop running takes two hours; keeping it stable for a week takes two weeks, and the gap is almost entirely context management. In practice you need four things: sliding-window trimming of history by token budget; sending large tool return values to external storage and passing back only a summary and a reference; keeping the tool list in the system prompt concise, with descriptions that state clearly “when not to use”; and deduplicating repeatedly failing calls so the model does not keep circling the same spot.
6. Observability and Evaluation
An agent is a probabilistic system; without observability you cannot iterate. The minimal set includes structured logs (a summary of each step’s input, tool name, latency, token count), full-chain traces persisted for replay, and a regression test set of fixed tasks. Track four metrics: task success rate, average number of steps, cost per task, and tool error rate. A rising average step count is usually the earliest signal that the prompt or tool descriptions have degraded.
7. Boundaries and Selection Advice
Writing from scratch is not a posture. The criteria are practical: if the requirement is a standard retrieval-augmented pipeline or a fixed automation flow, a mature general solution is faster; if it involves multi-step autonomous decisions, strict latency and cost constraints, a deeply customized tool ecosystem, or private deployment with data staying in-house, the payoff of a self-built orchestration layer will quickly exceed the maintenance cost.
To run it in the cloud, the common approach is: deploy the stateless orchestration in containers with elastic scaling, decouple long-running tasks and tool-call results through a message queue, put traces and artifacts in object storage, and connect logs and metrics to logging services and monitoring alerts. These are general product categories; evaluate specific choices against your own compliance and scale. You may also look at general cloud infrastructure capabilities such as those offered by Baidu AI Cloud.
In one sentence: frameworks are good for getting an idea running quickly; hand-writing is good for making the system truly stable. Write it once by hand to understand the mechanism, then decide what to use long term—you will rarely choose wrong.
