Can You Build an AI Agent in Pure Python Without Frameworks?

    This article explores how to build a production-grade AI agent in pure Python without relying on general-purpose orchestration frameworks. It explains the core concept of agents, a three-layer architecture covering tool abstraction, model capability, and orchestration, how to decouple the LLM from the agent loop, and the engineering value of an explicit ReAct loop. It also covers observability, common pitfalls, and why owning the core pipeline while reusing generic capabilities is a sustainable engineering path.

    Can You Build an AI Agent in Pure Python Without Frameworks?

    As agent development enters deeper waters, many engineering teams are revisiting a fundamental question: as business complexity grows, is continuing to rely on a general-purpose orchestration framework still the best choice? More and more practitioners are leaning toward building the core pipeline from scratch. This is not about showing off. It is because almost no truly production-grade agent has been assembled by simply stacking generic frameworks together. Look at the well-regarded intelligent coding tools and code generation platforms in the industry, and their technical architectures are uniformly highly customized. The reason is straightforward: production environments demand a great deal in terms of efficiency, personalization, and robustness, and a generic abstraction layer often cannot satisfy all three at once.

    The core argument of this article is: build the core pipeline yourself, and reuse generic capabilities. For prototype validation, common retrieval-augmented generation (RAG) flows, or standardized automation tasks, mature frameworks can indeed speed things up significantly. But when the agent becomes a core business asset, handing control back to code and writing the scheduling loop by hand in pure Python is the sustainable engineering path.

    1. First, Clarify the Concept: From Chatbot to Agent

    Early conversational applications were essentially one-question-one-answer text interactions: input a question, output an answer, and the flow ends. The essential difference of an agent is that it has “tools”: it can retrieve external knowledge, call business APIs, execute computations, and operate on the file system. The complexity depends entirely on the task goal.

    The simplest form of agent might just be a customer service assistant: connect one knowledge retrieval tool and one ticket creation tool, and automatically hand off to a human when confidence is insufficient for a question. The structure is minimal, but it is already a complete agent.

    Stripping away the marketing language, the essence of an agent can be condensed into eight words: perceive, reason, act, learn.

    • Perceive: Receive user input, environment state, and tool return values, and normalize them into a structured form.
    • Reason: Based on the current context, decide what to do next and why.
    • Act: Invoke a specific tool to produce a real side effect, and write the result back into the context.
    • Learn: Through long-term memory, vector storage, and feedback samples, make subsequent decisions better.

    This article focuses on implementing the first three stages, using the widely accepted ReAct paradigm (Reasoning + Acting) in the industry. Its essence is “explicit thinking, explicit acting”: the intent and result of each step are recorded to disk, so when problems occur they can be traced, replayed, and evaluated. The learning stage involves vector databases and long-term memory layering, which belongs to more advanced follow-up content.

    2. Architecture First: Three Layers That Must Be Separated

    Before writing the first line of code, draw the boundaries clearly. A maintainable agent contains at least three layers:

    1. Tool Abstraction Layer

    Unify all external capabilities into the same contract: name, natural language description, parameter schema, and execution function. Adding a database query or a report export only requires registering one record, with zero changes to the core loop code. This is the open-closed principle applied to agents — open for extension, closed for modification.

    1. from dataclasses import dataclass
    2. from typing import Callable, Any
    3. @dataclass
    4. class Tool:
    5. name: str
    6. description: str
    7. schema: dict # Parameter JSON Schema
    8. handler: Callable[..., Any]
    9. class ToolRegistry:
    10. def __init__(self) -> None:
    11. self._tools: dict[str, Tool] = {}
    12. def register(self, tool: Tool) -> None:
    13. self._tools[tool.name] = tool
    14. def specs(self) -> list[dict]:
    15. return [{"name": t.name, "description": t.description,
    16. "parameters": t.schema} for t in self._tools.values()]
    17. def invoke(self, name: str, **kwargs: Any) -> Any:
    18. if name not in self._tools:
    19. raise KeyError(f"Unregistered tool: {name}")
    20. return self._tools[name].handler(**kwargs)

    2. Model Capability Layer

    Treat the large language model as a replaceable “brain” that exposes only two actions: given a list of messages, return text; given tool specifications, return a structured call intent. Business code never directly depends on a specific vendor’s payload format.

    3. Agent Orchestration Layer

    This is the “commander,” responsible for maintaining state, driving the loop, controlling termination conditions, and recording the trace. It does not care who built the brain, nor how the tools are implemented internally.

    This layering brings two direct benefits: when switching model vendors, the orchestration logic does not change; and when a vendor is rate-limited or times out, the system can automatically switch to a backup channel for failover.

    3. How to Decouple the Model from the Agent

    Coupling is the most common technical debt in agent projects. Once you write a specific platform’s authentication, field names, and streaming protocol into the main loop, migration costs rise exponentially. The right approach is to define a minimal protocol:

    1. class LLMClient:
    2. def complete(self, messages: list[dict], tools: list[dict]) -> dict:
    3. """Returns {"content": str, "tool_calls": [...]}"""
    4. class FallbackLLM:
    5. def __init__(self, primary: LLMClient, backup: LLMClient, retries: int = 2):
    6. self.primary, self.backup, self.retries = primary, backup, retries
    7. def complete(self, messages, tools):
    8. for attempt in range(self.retries):
    9. try:
    10. return self.primary.complete(messages, tools)
    11. except Exception:
    12. if attempt == self.retries - 1:
    13. return self.backup.complete(messages, tools)
    14. raise RuntimeError("All model channels are unavailable")

    Each concrete vendor implementation only needs to complete field mapping and error normalization. The upper layer always sees a unified structure. This design also supports cost control: simple requests go to a small-parameter model, complex reasoning goes to a large-parameter model, with the orchestration layer routing by rules.

    4. The Core Loop: The Engineering Value of an Explicit Trace

    The ReAct loop can be written as a function of fewer than fifty lines, but every detail determines production readiness:

    1. def run(agent, goal: str, max_steps: int = 12) -> str:
    2. messages = [{"role": "user", "content": goal}]
    3. trace = []
    4. for step in range(max_steps):
    5. decision = agent.llm.complete(messages, agent.tools.specs())
    6. trace.append({"step": step, "decision": decision})
    7. if not decision.get("tool_calls"):
    8. return decision["content"]
    9. for call in decision["tool_calls"]:
    10. try:
    11. result = agent.tools.invoke(call["name"], **call["arguments"])
    12. except Exception as exc:
    13. result = f"Tool execution failed: {exc}" # Feed the error back so the model can self-correct
    14. messages.append({"role": "tool", "content": str(result)})
    15. return "Maximum steps reached, handing off to a human"

    There are four key engineering points:

    First, a step limit must exist. A loop without a circuit breaker will burn through quota indefinitely when the model repeatedly calls the same tool.

    Second, tool exceptions should be fed back rather than thrown. Returning the error text to the model as an observation usually leads it to retry with different arguments or take another path, which is far more robust than terminating the task outright.

    Third, the trace must be persisted in a structured form. Recording the input, output, latency, and token consumption of each step allows production issues to be located in minutes, and also lets you accumulate an evaluation set.

    Fourth, termination conditions should be diverse. In addition to the model giving a final answer, it should support three types of exits: a confidence threshold, a human takeover signal, and a timeout.

    5. Observability and Debugging

    The biggest advantage of a hand-built architecture is fully autonomous observability. It is recommended to integrate three types of common infrastructure capabilities by default: a logging service for trace retrieval, monitoring and alerting for failure-rate and latency dashboards, and object storage for archiving large intermediate artifacts. Metrics should cover at least four dimensions: task success rate, average number of steps, tool failure rate, and cost per task. Without this data, optimization can only rely on guesswork.

    6. Common Pitfalls

    • Pitfall 1: Frameworks eliminate the need for architecture design. Frameworks only provide building blocks; boundary division, state design, and failure strategies still have to be decided by you.
    • Pitfall 2: Longer prompts are more stable. Context bloat dilutes key instructions, so you should apply retrieval trimming and summary compression.
    • Pitfall 3: More tools means a stronger agent. As the number of tools rises, selection accuracy drops significantly; fewer and more precise is better.
    • Pitfall 4: Connect to production first, optimize later. An agent without an evaluation set cannot iterate, so you should build regression cases from day one.

    Conclusion

    Building an agent by hand in pure Python is not only feasible, but also the shortest path to understanding the essence of an agent. Only by owning the core pipeline yourself and confidently reusing generic components can you strike a balance among efficiency, personalization, and robustness. When you can swap the brain at any time, extend tools at any time, and replay every decision at any time, the system truly belongs to your business.