Can You Build an Agent in Pure Python Without a Framework?

    This article explores whether a stable, usable AI agent can be built using only Python's standard capabilities and an LLM API, without any third-party orchestration framework. It breaks down the minimal agent loop, context management, tool-layer design, fault tolerance, observability, and cost control, then explains when a framework is still the better choice. The conclusion is that a pure Python agent is not only feasible but often preferable for projects that need deep customization, precise control, and lower long-term maintenance risk.

    1. The Question: Is a Framework a Must-Have?

    In real engineering projects, many teams reach for a heavyweight orchestration framework as soon as an agent requirement comes up. Frameworks do lower the barrier during the demo phase. But once a project enters long-term evolution, problems start to surface: a bloated dependency tree, too many layers of abstraction, and behavior that is hard to trace. So a practical question emerges: without any third-party orchestration framework, using only standard Python plus an LLM API, can you build a stable, usable agent? The answer is yes, and in many scenarios it is the better option. The reason is not mysterious: an agent is essentially a “perceive-decide-act-feedback” loop. That loop can be expressed clearly in a few dozen lines of code; a framework merely packages this logic into configuration and callbacks.

    2. The Minimal Agent Core: One Loop Is Enough

    Any agent can be abstracted into the following pseudocode:

    1. def run_agent(goal, tools, model, max_steps=12):
    2. messages = [{"role": "system", "content": SYSTEM_PROMPT},
    3. {"role": "user", "content": goal}]
    4. for _ in range(max_steps):
    5. resp = model.chat(messages, tools=tools) # returns text or tool-call intent
    6. messages.append(resp)
    7. if resp.tool_calls:
    8. for call in resp.tool_calls:
    9. result = dispatch(tools, call) # execute locally and catch exceptions
    10. messages.append({"role": "tool", "content": result})
    11. continue
    12. return resp.content # no tool call means convergence
    13. return "Maximum steps reached, task not completed"

    This code reveals three key facts. First, we control the flow ourselves, and when something goes wrong we can set breakpoints line by line. Second, tools are ordinary Python functions, so signatures, validation, and rate limiting are all under our control. Third, the termination condition is declared explicitly, which avoids “infinite thinking.” The value of a framework is that it standardizes these details, but standardization also means you must accept its abstraction boundaries.

    3. Context Management: The Engineering Detail That Really Matters

    A demo may run fine while production fails, and most of those problems come from context. This is exactly where a hand-written implementation shines, because you can trim things precisely according to business semantics:

    • Layered memory: store the system prompt, long-term constraints, short-term dialogue, and tool results in separate zones; when compressing, trim raw tool output first and keep the summary of conclusions.
    • Budget control: set separate token budgets for input and output; when a limit is exceeded, trigger summarization instead of a hard truncation, so key constraints are not lost.
    • Structured write-back: return all tool results in a unified {ok, data, error} structure, which makes it easier for the model to correctly decide the next step.
    1. def trim(messages, budget):
    2. while estimate_tokens(messages) > budget:
    3. # keep system and the most recent turns, compress middle tool output
    4. messages = compress_middle(messages)
    5. return messages

    4. Tool Layer Design: Caging the Uncertainty

    Tools are the only channel through which an agent touches the real world, and they are also the source of risk. Engineering practice suggests four rules. First, whitelist registration: any function that is not registered cannot be called. Second, parameter schema validation: field types and value ranges are intercepted at the entry point. Third, idempotency and deduplication: write operations carry a request identifier to prevent duplicate submissions. Fourth, separate timeouts from retries: only retryable errors are retried, while parameter errors are returned to the model immediately for self-correction. Writing these constraints into local functions is more direct than searching for the corresponding switch in a framework’s configuration.

    5. Fault Tolerance, Observability, and Cost Control

    A production system must be able to answer “what just happened.” A hand-written approach is naturally suited to plugging into general observability capabilities: log structured records for every step (goal, model output, tool inputs, latency, token usage) and send them uniformly to a logging service; set monitoring and alerting thresholds for failure rate, average number of steps, and cost per task; and carry a trace identifier across all steps of a task. For cost control, you can adopt a tiered strategy where a small model handles intent classification and routing while a large model handles complex reasoning, and cache results for high-frequency repeated requests. If you need to persist intermediate artifacts, you can store them in object storage; if you need asynchronous decoupling, you can introduce a message queue. These are all general cloud capability categories, independent of any specific vendor.

    6. When You Should Still Choose a Framework

    To be fair, frameworks are not useless. When a team needs to validate ideas quickly, when multiple people need a unified paradigm for collaboration, or when requirements are highly standardized, a framework can significantly shorten the startup time. The sweet spot for a hand-written approach is: workflows that need deep customization, sensitivity to latency and cost, the need to precisely control every step of behavior, and projects that must evolve long-term while reducing dependency coupling. The deciding factor is not technical preference, but the balance between the benefit of abstraction and its cost.

    7. Practical Advice and Summary

    Start with a “minimal core + pluggable tools + explicit budget + full logging” foundation: first get single-step tool calling working, then gradually add multi-step planning, parallel tools, and human-in-the-loop confirmation. If you run on a cloud environment such as Baidu AI Cloud, you can directly reuse general capabilities like the container platform, logging service, monitoring and alerting, and object storage, and focus your energy on the business logic itself. The conclusion is clear: building an agent in pure Python without an orchestration framework is entirely feasible; what it buys you is not less code, but stronger control and lower long-term maintenance risk.