Building an AI Agent with Pure Python: Is It Feasible Without Heavy Frameworks?

    This article explores the feasibility of building an AI Agent using pure Python and general LLM APIs without relying on heavy frameworks. It argues that doing so often facilitates better debugging, evolution, and cost control. Covering the essential components of a minimal viable agent, a sample control loop, and key engineering practices, the article provides a comprehensive guide for developers deciding whether to implement agents from scratch or adopt existing frameworks based on their specific use cases.

    In real-world engineering projects, building an AI Agent manually using only Python and general LLM APIs—without relying on heavy Agent frameworks—is not only feasible but often more beneficial for debugging, evolution, and cost control. A common misconception needs clarification: an Agent is not some mysterious runtime. Its core is simply a control flow loop: “construct messages — call model — parse output — execute tool — backfill results — continue loop.” Organizing these steps using native Python capabilities is often more straightforward than introducing multiple layers of abstraction.

    1. Feasibility: The Essence of an Agent is Not Complex

    From an engineering perspective, a typical Agent’s minimal closed loop involves three things. First, organizing system prompts, user inputs, historical messages, and tool results into strings or structured messages acceptable by the model. Second, calling the LLM API via HTTP or SDK, handling timeouts, retries, and errors. Third, deciding the next step based on the model’s output—continue the conversation, call a tool, or end the task. These three correspond to string and data structure manipulation, network requests, and loop/conditional control, all of which are Python’s native strengths.

    Frameworks typically provide value by encapsulating common patterns, tool registration, state management, and multi-agent orchestration. However, encapsulation does not equate to necessity. For many business scenarios, the Agent’s complexity is far lower than imagined: a customer service assistant might only need three to five tools, and a data analysis assistant might only require a “query-calculate-summarize” three-step process. In these cases, writing a few hundred lines of control loop code exposes prompts, model responses, tool parameters, and exception paths directly to the developer.

    Some major model providers have expressed similar views in their engineering guidelines: developers should start by calling the model API directly because many patterns require only minimal code. While frameworks lower the entry barrier, they can add abstraction layers that obscure underlying prompts and response content, making debugging harder and tempting developers to introduce unnecessary complexity when simpler solutions suffice. This perspective is worth considering, but should be weighed against team size, delivery cycles, and maintenance capabilities.

    2. Hidden Costs of Frameworks: Abstraction Layers Often Become Debugging Walls

    The most immediate benefit of frameworks is that they “look fast.” However, when an Agent’s behavior deviates from expectations, the problem often lies not in the model but in the abstraction layer. Was the prompt rewritten by the framework? Were tool descriptions automatically concatenated? Were the tool call parameters returned by the model transformed by a middle layer? Was the context duplicated after a retry? If these steps are encapsulated too deeply, developers must simultaneously understand business logic, internal framework protocols, and model behavior, significantly lengthening the debugging chain.

    First, abstraction obscures critical inputs and outputs. The essence of Agent debugging is observing “what the model sees, what it outputs, and what the tool executes.” In a hand-written implementation, message arrays, tool schemas, raw responses, and parsed results can be fully logged before and after calls. If frameworks hide these details by default, troubleshooting costs rise.

    Second, abstraction imposes flexibility constraints. Business requirements frequently demand special handling: certain tools require human confirmation, certain outputs need strict JSON validation, some conversation turns require history compression, and a specific call might require switching models or downgrading. A hand-written loop allows hooks to be inserted as needed; frameworks might require bypassing default flows, increasing cognitive load.

    Third, abstraction introduces upgrade and lock-in risks. Framework version upgrades can alter behavior, requiring regression testing. If core logic heavily relies on framework-specific interfaces, migration costs accumulate. Some teams have chosen to remove frameworks after long-term production use—not because frameworks are useless, but because once business logic stabilizes and patterns clear up, direct control of the call chain is more efficient and conducive to team collaboration. This experience shows frameworks are suitable as transitional tools, not irreplaceable black boxes.

    3. Six Components of a Minimum Viable Agent

    Writing an Agent from scratch doesn’t mean writing sloppy code. To maintain it, the boundaries of the following six components must be clearly defined.

    First, the model calling layer. It is solely responsible for sending messages, receiving responses, handling timeout retries, and standardizing error codes. It exposes a stable function, like call_llm(messages, tools), allowing internal swaps between different model providers. The business loop doesn’t worry about network details.

    Second, the prompt and message layer. System prompts, tool descriptions, and history compression strategies should be centrally managed. Message roles must be clear, and the format for backfilling tool results must be fixed to prevent the model from misjudging due to context format drift.

    Third, tool registration and parameter validation. Each tool should have a name, description, parameter schema, and execution function. Parameters generated by the model are untrusted and must undergo type validation, mandatory field checks, and permission checks. Tool descriptions should be concise and accurate to avoid ambiguity.

    Fourth, the execution loop. The loop needs explicit termination conditions: the model no longer requests tools, the maximum number of turns is reached, a timeout occurs, or human takeover is triggered. An Agent without termination conditions easily falls into repetitive calls.

    Fifth, state and memory. Short-term state can be kept in message history, while long-term memory can be persisted to disk or general storage. The key isn’t “remembering more” but “controlling memory”: strategies should dictate what information enters the context, when to compress, and when to clear.

    Sixth, observability and error handling. Every model call, tool execution, parsing failure, and retry should be logged in a structured format. Logs should include request ID, turn count, latency, token estimation, tool name, and error type for easy replay.

    4. A Minimal Loop Example Without Frameworks

    The pseudo-code below demonstrates the core control flow, omitting specific network implementations. The focus is on separating model calls, tool execution, and message backfilling.

    1. import json
    2. MAX_TURNS = 8
    3. def run_agent(user_input, tools, call_llm, execute_tool):
    4. messages = [
    5. {"role": "system", "content": "You are a rigorous task assistant, use tools when necessary."},
    6. {"role": "user", "content": user_input},
    7. ]
    8. for turn in range(MAX_TURNS):
    9. resp = call_llm(messages=messages, tools=tools)
    10. if resp.get("type") == "final":
    11. return resp["content"]
    12. if resp.get("type") != "tool_call":
    13. raise ValueError("Unknown response type")
    14. call = resp["tool_call"]
    15. name = call["name"]
    16. args = call["arguments"]
    17. # Parameter validation, permission checks, and exception isolation should be done here
    18. try:
    19. result = execute_tool(name, args)
    20. tool_content = json.dumps({"ok": True, "data": result}, ensure_ascii=False)
    21. except Exception as exc:
    22. tool_content = json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False)
    23. messages.append({"role": "assistant", "content": json.dumps(call, ensure_ascii=False)})
    24. messages.append({"role": "tool", "name": name, "content": tool_content})
    25. return "Task not completed within the maximum turns, please check manually."

    This code has no complex dependencies, yet it possesses the key characteristics of an Agent: model decision-making, tool calling, result backfilling, turn limits, and exception isolation. Subsequent engineering only needs to add validation, logging, retries, and tests around it, without having to start over.

    5. Key Details for Production Engineering

    To truly use hand-written Agents in production, the following capabilities must be implemented.

    First, timeouts, retries, and idempotency. Both model calls and tool executions can time out. Retries must have limits and backoff strategies; write-operation tools must support idempotency keys to prevent side effects from duplicate executions.

    Second, structured output validation. Never assume the model will always return valid JSON. Use schema validation; if it fails, ask the model to fix it or enter a degradation path. Tool parameters must be strictly validated and never directly concatenated into commands or queries.

    Third, tool permissions and sandboxes. Tools define an Agent’s capability boundaries and risk boundaries. File, network, database, and external system operations should follow the principle of least privilege. Dangerous operations require human confirmation or read-only restrictions.

    Fourth, cost and context budgets. Each loop iteration increases token consumption. Set maximum turns, maximum context length, and per-task cost limits; historical messages can be compressed by importance, and tool results can be truncated or summarized.

    Fifth, logging and replay. Record complete messages, raw model responses, tool parameters, execution results, and latency. Being able to replay by request ID when issues arise is a significant advantage of hand-written solutions over frameworks.

    Sixth, evaluation sets and regression testing. Prepare typical tasks, boundary tasks, and failure tasks. Perform regression on the Agent’s completion rate, tool call accuracy, average turns, and cost. After model or prompt changes, validate with a fixed evaluation set to avoid deploying based on intuition.

    6. Applicable Boundaries: When Hand-writing is Better vs. When Frameworks Make Sense

    Hand-writing is more suitable when: the Agent flow is relatively clear, the number of tools is limited, the team wants full control over prompts and the call chain, debugging efficiency is prioritized, rapid validation of business hypotheses is needed, or avoiding long-term lock-in is desired. In these cases, a single-file loop with clear interfaces is sufficient for early iterations.

    Frameworks also have valid scenarios: multi-team collaboration requires unified orchestration standards, processes contain many parallel branches and human nodes, visual orchestration is needed, existing mature ecosystems can be reused, or the team lacks low-level API experience and wants a quick start. The key is not “never use frameworks,” but to avoid introducing complex abstractions prematurely for simple problems. A reasonable path is to run the business with a minimal implementation first, then extract common layers based on real pain points. If a framework solves emerging complexities, introducing it later is fine.

    7. Conclusion

    Building an AI Agent with pure Python and general LLM APIs without heavy frameworks is entirely feasible and, in many engineering scenarios, more transparent, controllable, and easier to debug. Its feasibility stems from the fact that an Agent is essentially a combination of message organization, API calls, and loop control—areas where Python excels. However, be cautious: hand-writing doesn’t mean writing rough code. Engineering practices must fill the gaps in the model calling layer, tool validation, execution loop, state management, observability, and test replay. For simple to moderately complex tasks, starting with direct model API calls is often a safer starting point. When complexity genuinely grows to require unified orchestration, introducing abstractions on demand prevents frameworks from becoming a debugging burden.