Building AI Agents in Pure Python: An Engineering Perspective

    This article examines whether AI agents can be built for production using only Python and a general-purpose LLM API, without an orchestration framework. It describes the minimal agent loop, the engineering reasons pure Python often improves debugging, flexibility, dependency control, cost control, and team comprehension, and the cases in which frameworks may still be justified. It also outlines production requirements—structured output, state management, tool security, observability, error handling, testing, and cost/latency controls—together with a progressive rollout path and common anti-patterns.

    Building AI Agents in Pure Python: An Engineering Perspective

    In real engineering projects, implementing an AI agent manually with plain Python and a general-purpose LLM API—without an orchestration framework—is not only feasible but, in many cases, a better fit. The key question is not whether a framework is used. It is whether you understand the minimal structure of an agent and have the engineering capability to take it into production.

    Some model vendors’ documentation also recommends that developers start by calling the LLM API directly. The reason is simple: orchestration frameworks lower the barrier to entry by encapsulating underlying tasks, but the extra abstraction layers often obscure prompts, model responses, tool inputs, and tool outputs, making the debugging chain longer. When a simple approach is sufficient, frameworks can also encourage developers to add unnecessary complexity. Some engineering teams have used orchestration frameworks in production for a period of time and then chosen to remove them, reporting that the system became more transparent and the team iterated more efficiently. Reduced to one sentence, these experiences suggest that the core of many LLM applications is often just string assembly, API calls, action parsing, and loop control—capabilities that native Python already provides.

    Of course, this does not mean frameworks are useless. It means you should understand the fundamentals first and then introduce abstractions as needed.

    1. First Clarify: What Is the Minimal Structure of an Agent?

    A runnable agent usually needs only six parts:

    1. Input organization: Assemble the task, constraints, historical steps, and available tool descriptions into a prompt.
    2. Model invocation: Call the LLM API through a thin adapter layer and return text or structured content.
    3. Action parsing: Parse the model output into either a “call a tool” action or a “provide the final answer” action.
    4. Tool execution: Dispatch to the concrete function based on the action name and capture the result or exception.
    5. State update: Append observations to history and control context length.
    6. Termination decision: Stop when the final answer is reached, the step limit is hit, the budget limit is hit, or human takeover conditions are met.

    Below is an illustrative loop that does not depend on any third-party orchestration framework:

    1. from dataclasses import dataclass, field
    2. from typing import Any, Callable
    3. @dataclass
    4. class AgentState:
    5. task: str
    6. history: list[dict[str, Any]] = field(default_factory=list)
    7. step: int = 0
    8. def build_prompt(state: AgentState, tools: dict[str, str]) -> list[dict[str, str]]:
    9. # Organize the task, tool descriptions, and historical observations into messages the model can understand
    10. return [
    11. {"role": "system", "content": "You are a task execution assistant and may only output structured actions."},
    12. {"role": "user", "content": f"Task: {state.task}\nTools: {tools}\nHistory: {state.history}"}
    13. ]
    14. def call_llm(messages: list[dict[str, str]]) -> str:
    15. # The single external adapter point: implemented by a concrete LLM API call
    16. ...
    17. def parse_action(raw: str) -> dict[str, Any]:
    18. # Parse and validate: {"type": "tool", "name": "...", "args": {...}}
    19. # or {"type": "final", "content": "..."}
    20. ...
    21. def dispatch(action: dict[str, Any], tools: dict[str, Callable[..., Any]]) -> Any:
    22. if action["type"] != "tool":
    23. raise ValueError("not a tool action")
    24. name = action["name"]
    25. if name not in tools:
    26. raise ValueError(f"unknown tool: {name}")
    27. return tools[name](**action.get("args", {}))
    28. def run_agent(task: str, tools: dict[str, Callable[..., Any]], max_steps: int = 8) -> str:
    29. state = AgentState(task=task)
    30. tool_desc = {name: fn.__doc__ or "" for name, fn in tools.items()}
    31. for _ in range(max_steps):
    32. state.step += 1
    33. raw = call_llm(build_prompt(state, tool_desc))
    34. action = parse_action(raw)
    35. if action["type"] == "final":
    36. return action["content"]
    37. try:
    38. observation = dispatch(action, tools)
    39. except Exception as exc:
    40. observation = {"error": type(exc).__name__, "message": str(exc)}
    41. state.history.append({
    42. "step": state.step,
    43. "action": action,
    44. "observation": observation
    45. })
    46. return "Reached the maximum number of steps; handing off to a human"

    This code is not complete, but it reveals a core fact: the main agent loop is short, and the complexity mainly comes from engineering constraints rather than the loop itself. What really requires careful design is tool contracts, structured output, state management, security boundaries, and observability.

    2. Why Pure Python Is Often Better

    1. Shorter Debugging Chain

    When prompts, model responses, parsed results, and tool inputs are all visible in the same process, troubleshooting costs drop significantly. Developers can directly print or log the raw response at each step and determine whether the issue is in the prompt, the parser, or the tool. If a framework’s abstraction layer hides these intermediate states, debugging can easily become a matter of guessing at configuration.

    2. Greater Flexibility

    In real business scenarios, tool protocols, approval workflows, context compression strategies, and model routing rules often require significant customization. A pure Python implementation can adapt through functions, classes, decorators, or the standard library without distorting the design to fit a framework’s extension points.

    3. Simpler Dependency Governance

    With one less orchestration framework, there is one less layer of version upgrades, behavior changes, and supply-chain risk. For agents with short core paths and a limited number of tools, native implementations usually have a smaller maintenance surface.

    4. More Controllable Cost and Latency

    A pure Python implementation makes it easier to precisely control the context window, caching strategy, parallel calls, model tiering, and budget caps. Which history to retain, which observations to summarize, and which tools can run in parallel can all be tailored to business needs.

    5. Lower Cognitive Load for the Team

    Python engineers can usually read a several-hundred-line agent loop directly. By contrast, if the team is unfamiliar with a particular orchestration abstraction, the framework can increase cognitive load. For small teams, a transparent implementation is often more important than “full-featured” tooling.

    3. Where the Value of Frameworks Begins and Ends

    Frameworks are not without value. They may be a better fit in scenarios such as complex multi-agent topologies; requirements for a unified interface and persistence; visual orchestration; multi-person collaboration where conventions must be standardized; and environments that already have mature platform governance capabilities. Frameworks can provide ready-made state management, tool registration, callbacks, tracing, and deployment integration, reducing duplicated work.

    However, the benefits of a framework must exceed its abstraction cost. Abstraction costs include the learning curve, the impact of version upgrades, a longer troubleshooting chain, limited customization, and hidden behavior that is difficult to reproduce. When choosing, ask several questions: Is the task really complex enough to require multiple agents? Does state need to be persisted across processes? Does the team need a unified orchestration protocol? Must observability depend on capabilities built into the framework? If the answers are no, starting with pure Python is usually more stable.

    4. Key Capabilities That Must Be Added for Production

    Pure Python is feasible, but that does not mean any arbitrary loop is ready for production. The following capabilities need to be added.

    1. Structured Output and Contract Validation

    Tool-calling actions must have a clear schema. There must be a repair or retry strategy when parsing fails. Parameters must be validated for type, range, and required fields. Do not concatenate model output directly into dangerous operations.

    2. State and Memory Management

    Short-term history cannot grow indefinitely. You can use window truncation, summary compression, key-fact extraction, and external storage. State must be replayable so that issues can be reproduced. For long-running tasks, design an explicit state machine rather than relying only on chat history.

    3. Tool Security

    The tool registry should be whitelist-based; parameters must be validated; permissions should follow the principle of least privilege; high-risk operations require approval or human confirmation; tool calls need timeouts, retries, and idempotency design; sensitive inputs and outputs should be redacted in logs.

    4. Observability

    At a minimum, record trace_id, step count, model call latency, token usage, tool name, input summary, output summary, error category, and termination reason. Logs should be structured and support replay by task. An agent without observability is difficult to run stably.

    5. Error Handling

    Distinguish between model errors, parsing errors, tool errors, and business errors. Set retry budgets, circuit breaking, and degradation strategies. When the step or budget limit is reached, hand off to a human. Do not use infinite retries to hide problems.

    6. Testing and Evaluation

    Tools must be mockable; parsers must have unit tests; agents need scenario regression suites and offline evaluation sets; releases should be rolled out gradually with key metrics monitored. Evaluation should not look only at the final answer. It should also consider step count, cost, tool success rate, and human handoff rate.

    7. Cost and Latency Control

    You can use model tiering, result caching, parallel tool calls, context compression, and budget caps. At every step, the system should know how much was spent and why.

    5. Progressive Rollout Path

    Start with a single-file prototype: one model adapter function, one tool registry, one loop, and one set of structured logs. Then extract the LLM client, tool interfaces, state storage, and tracing interfaces while keeping the implementation transparent. After entering the production stage, add queues, persistence, permissions, approvals, monitoring and alerting, and auditing as needed. General-purpose container platform, logging, monitoring and alerting, and object storage capabilities offered by Baidu AI Cloud can serve as a runtime and observability foundation; specific choices should still be driven by business constraints.

    Only when the benefits of multi-agent orchestration, visualization, unified persistence, and similar capabilities clearly outweigh the abstraction cost should you introduce an orchestration framework. By then, the team already understands the essence of agents and is better able to judge whether the complexity and hidden behavior introduced by a framework are acceptable.

    6. Common Anti-Patterns

    Forcing a multi-agent architecture onto a simple task; lacking a structured output contract; lacking step and budget limits; stuffing the full history into the context; granting excessive tool permissions; missing logs that make replay impossible; prompts hidden by an abstraction layer; launching without offline evaluation; prematurely pursuing a general-purpose platform. These problems are unrelated to whether a framework is used, but a pure Python implementation makes them easier to expose and easier to fix in time.

    Conclusion

    Building AI agents by hand in pure Python is entirely feasible, and it should be one of the default starting points. Its advantages are transparency, flexibility, fewer dependencies, and easier debugging. The precondition is to add structured output, state management, tool security, observability, testing and evaluation, and cost control. Frameworks are not the enemy; premature abstraction is. Mastering the minimal loop first and then introducing orchestration capabilities as needed is often more stable than starting with a heavy framework.