Building AI Agents with Pure Python: Feasibility and Engineering Practices

    This article explores the feasibility of building AI Agents using pure Python without relying on heavy orchestration frameworks. It details the minimal Agent model, provides a practical engineering checklist covering tool validation, error handling, and observability, and outlines a progressive path for deciding when to introduce an orchestration framework based on system complexity and team capabilities.

    Building AI Agents with Pure Python: Feasibility and Engineering Practices

    When teams consider building AI Agents by directly calling general-purpose LLM APIs in Python without heavy orchestration frameworks, a common question arises: Is this merely a toy implementation? The answer depends on how well the problem is defined. The core of an Agent is not mysterious: maintaining messages and state, calling the model, parsing structured output, executing tools, feeding results back to the model, and looping until termination conditions are met. These tasks are essentially string manipulation, network API calls, state machines, and loop control—native Python capabilities are fully capable of handling them. What truly requires careful design is the engineering boundary: observability, error recovery, security, budget control, and evaluation systems.

    1. Reducing the Agent to a Minimal Model

    A working Agent typically consists of four components: the model, message history, tool registry, and execution loop. The model handles reasoning and generating structured actions; the message history saves the context; the tool registry exposes external capabilities via name, description, and parameter schema to the model; and the execution loop manages calling the model, parsing actions, executing tools, feeding back results, and determining termination.

    The illustrative code below focuses on control flow rather than a specific API:

    1. from dataclasses import dataclass, field
    2. from typing import Any, Callable
    3. import json
    4. @dataclass
    5. class Tool:
    6. name: str
    7. description: str
    8. schema: dict
    9. func: Callable[..., Any]
    10. class ToolRegistry:
    11. def __init__(self):
    12. self.tools = {}
    13. def register(self, tool: Tool):
    14. self.tools[tool.name] = tool
    15. def specs(self):
    16. return [
    17. {"name": t.name, "description": t.description, "input_schema": t.schema}
    18. for t in self.tools.values()
    19. ]
    20. def call(self, name: str, args: dict):
    21. if name not in self.tools:
    22. raise ValueError(f"unknown tool: {name}")
    23. return self.tools[name].func(**args)
    24. @dataclass
    25. class AgentState:
    26. messages: list = field(default_factory=list)
    27. step: int = 0
    28. max_steps: int = 12
    29. budget: float = 1.0
    30. def run_agent(user_input: str, registry: ToolRegistry, call_llm, state: AgentState = None):
    31. state = state or AgentState()
    32. state.messages.append({"role": "user", "content": user_input})
    33. while state.step < state.max_steps and state.budget > 0:
    34. state.step += 1
    35. resp = call_llm(messages=state.messages, tools=registry.specs(), timeout=30)
    36. state.budget -= resp.get("cost", 0)
    37. msg = resp["message"]
    38. state.messages.append(msg)
    39. if msg.get("type") == "final":
    40. return msg["content"]
    41. for call in msg.get("tool_calls", []):
    42. try:
    43. result = registry.call(call["name"], call["arguments"])
    44. state.messages.append({
    45. "role": "tool",
    46. "name": call["name"],
    47. "content": json.dumps(result, ensure_ascii=False)
    48. })
    49. except Exception as e:
    50. state.messages.append({
    51. "role": "tool",
    52. "name": call["name"],
    53. "content": f"ERROR: {type(e).__name__}: {e}"
    54. })
    55. return "Max steps or budget reached, returning current result or routing to human"

    This skeleton has no heavy abstraction dependencies but already possesses the critical closed-loop of an Agent. Its value lies in the fully explicit control flow: every input, output, tool parameter, exception, and budget consumption can be recorded and tested. The common debugging pitfalls of frameworks often stem from these control flows being obscured by abstraction layers.

    2. Engineering Checklist for the Pure Python Approach

    First, tool registration and parameter validation. Tools are not just randomly exposed functions; they should have stable names, clear descriptions, input schemas, and return value contracts. Parameter validation must be front-loaded to avoid passing illegal parameters to external systems. High-risk tools should have whitelists, least privilege, and human approval mechanisms.

    Second, error handling and retries. The model might generate non-existent tool names, incorrect parameters, or unparseable structures; tools might also timeout, rate-limit, or return business errors. The correct approach is to structure the error and feed it back to the model for correction, while setting maximum retries and circuit breakers. Error messages should not leak sensitive data.

    Third, state and persistence. Short tasks can keep messages in memory; long tasks should snapshot state to databases or object storage for breakpoint recovery, auditing, and replay. State should include step counts, budget consumption, tool result summaries, and trace IDs, rather than an infinitely growing full context.

    Fourth, budget, timeout, and termination conditions. Agents must have maximum steps, maximum duration, maximum cost, and loop detection. An autonomous loop without termination conditions is a breeding ground for production incidents. Termination can be triggered by the model outputting a final answer, or by a rule engine routing to a human when the budget is exhausted.

    Fifth, observability. Every step should record trace IDs, model request summaries, response types, tool names, masked parameter values, duration, error codes, and costs. Logging services, monitoring alerts, and object storage can serve as generic infrastructure to carry this data. Being able to restore the complete trajectory by trace ID during troubleshooting is much more efficient than “guessing what happened inside the framework.”

    Sixth, testing and evaluation. Tool functions can undergo unit testing; Agent loops can use record-and-replay testing; prompt and process changes should run regression evaluation sets to observe task success rates, tool call accuracy, average steps, and cost. Evaluation should look not only at the final text but also at whether the process is compliant.

    3. What Frameworks Actually Solve, and When They Are Worth Introducing

    Mainstream orchestration frameworks attempt to solve unified model interfaces, chained composition, tool abstraction, memory management, state graph orchestration, conditional branching, checkpoint recovery, human-in-the-loop, and multi-agent collaboration. These capabilities have real value, especially for teams with complex process branches, long runtimes, requirements for breakpoint recovery, multi-person collaboration, and visual orchestration, where mature frameworks can reduce redundant infrastructure costs.

    However, the benefits of frameworks have a threshold. For scenarios with few tools, linear processes, simple states, and an emphasis on strong auditing, extra abstraction layers often bring implicit control flows, version coupling, and troubleshooting costs. In industry practices, some teams removed orchestration frameworks after reviewing their production systems, citing shorter paths and faster problem localization. A model provider’s agent building guide suggests starting with direct API calls, warning that abstraction layers might obscure prompts and responses, tempting developers to add unnecessary complexity. Different providers have different attitudes toward frameworks, which indicates that selection should return to matching complexity with team capability.

    4. Progressive Selection Path

    It is recommended to adopt a progressive path: first implement the minimal loop and tool registry in pure Python, solidifying logging, budgeting, error feedback, and evaluation; when multi-branch long processes, breakpoint recovery, visual orchestration, or multi-person collaboration emerge, introduce a lightweight orchestration layer while keeping tools and state structures migratable. If adopting a mature framework, retain the ability to call APIs directly as a bypass to avoid being locked into a single abstraction. When deploying on cloud platforms like Baidu AI Cloud, general container platforms, logging services, monitoring alerts, and object storage can be used to carry runtime and operational data, but the Agent’s core control flow should remain clear and testable.

    The conclusion is that building AI Agents in pure Python is not only feasible but often a better starting point for understanding the problem, controlling complexity, and improving debugging efficiency. Frameworks are not necessities but optional choices once complexity reaches a threshold. Designing the loop, state, tools, observability, and security well is more important than choosing which abstraction layer to use.