Building AI Agents in Pure Python: From Core Principles to Engineering Practice

    An AI agent is not a specific framework. This article explains how to implement a controllable agent loop in Python using model calls, tool execution, state management, and safety checks, and when a framework becomes worthwhile.

    In real engineering work, an AI agent is not the same as a particular framework or a complex runtime. At its core, an agent that can complete a task is usually composed of model invocation, context management, tool execution, result evaluation, and loop control. Those capabilities can be implemented with native Python plus a large language model API.

    Being able to implement an agent does not mean a few lines of code will be stable in production. The hard part of a hand-built agent is not sending one model request. It is bounding the task, managing state, handling failures, limiting cost, and ensuring the model cannot take unauthorized actions. A pure Python approach is therefore neither a drop-in replacement for every framework nor an exercise in writing everything by hand. It is a more transparent, more controllable engineering choice.

    Understand what an agent actually is

    A typical LLM application is a single input and a single output:

    1. User question → model → text answer

    An agent is closer to this flow:

    1. User goal
    2. ↓
    3. Model inspects current state
    4. ↓
    5. Chooses the next action
    6. ↓
    7. Calls a tool or continues reasoning
    8. ↓
    9. Receives the execution result
    10. ↓
    11. Updates state and judges again
    12. ↓
    13. Returns the final result

    The core of an agent is not “letting the model run on its own.” It is a decision loop under program control. The model proposes actions; the Python program validates them, calls tools, records results, and decides whether to continue.

    A minimal agent usually includes:

    1. Task input: user goal, business parameters, and constraints.
    2. Model invocation: send messages and parse the response.
    3. Tool registry: describe callable functions and their arguments.
    4. Tool execution: validate the model’s call request and run the operation.
    5. State management: history, tool results, and progress.
    6. Loop control: max steps and termination.
    7. Safety and observability: logs, exceptions, permissions, and cost.

    These modules do not need a large abstraction layer. For small and mid-size projects, clear Python functions and data structures are often enough.

    Why pure Python is attractive

    1. Transparent execution path

    With many abstraction layers, developers must understand prompt templates, message transforms, callbacks, memory components, and tool adapters at the same time. When something breaks, it is hard to tell whether the fault is in model output, argument parsing, or an internal conversion.

    A pure Python path is usually direct:

    1. response = call_model(messages)
    2. action = parse_response(response)
    3. if action["type"] == "tool_call":
    4. result = execute_tool(action)
    5. messages.append(result)
    6. else:
    7. return action["content"]

    Every step can be printed, logged, and tested. You can see what was sent to the model, the raw text it returned, and the arguments the tool actually received.

    2. Easier customization

    Business requirements vary. Some tasks need low latency, some need auditability, some need human confirmation, and some must follow a fixed workflow. General frameworks introduce conventions that may not fit every case.

    A hand-built agent can be designed for the actual need, for example:

    • Require human confirmation for high-risk tools.
    • Use different max-loop limits per task.
    • Strictly validate model output against a data schema.
    • Give each tool its own timeout and retry policy.
    • Write critical operations to an audit log.
    • Stop automatically when a budget cap is reached.

    3. Lower cost of early experimentation

    Early in a project the final workflow is often unknown. Introducing a full framework too soon can spend time on abstractions and configuration instead of proving a closed loop.

    Calling the API directly can answer:

    • Can the model complete the target task?
    • Are tool calls accurate enough?
    • Is a multi-step loop actually needed?
    • Which steps belong to the model, and which must stay in code?
    • What are typical call counts and failure types?

    After those answers are in place, it is safer to decide whether to add more infrastructure.

    A minimal viable agent structure

    The following is a schematic implementation. It is not bound to a specific vendor. In a real project, call_model must be implemented against your model API.

    1. import json
    2. from typing import Any, Callable
    3. def call_model(messages: list[dict[str, str]]) -> str:
    4. """
    5. Call the LLM API and return text.
    6. In a real project, add auth, timeouts, and error handling here.
    7. """
    8. raise NotImplementedError
    9. def get_time(city: str) -> dict[str, Any]:
    10. # Example tool, only to illustrate the call structure
    11. return {
    12. "city": city,
    13. "time": "10:30",
    14. "timezone": "example timezone"
    15. }
    16. TOOLS: dict[str, Callable[..., Any]] = {
    17. "get_time": get_time
    18. }
    19. def execute_tool(name: str, arguments: dict[str, Any]) -> str:
    20. if name not in TOOLS:
    21. return json.dumps({
    22. "error": f"Unregistered tool: {name}"
    23. }, ensure_ascii=False)
    24. try:
    25. result = TOOLS[name](**arguments)
    26. return json.dumps(result, ensure_ascii=False)
    27. except Exception as exc:
    28. return json.dumps({
    29. "error": "Tool execution failed",
    30. "detail": str(exc)
    31. }, ensure_ascii=False)
    32. def run_agent(user_input: str, max_steps: int = 6) -> str:
    33. messages = [
    34. {
    35. "role": "system",
    36. "content": (
    37. "You are a task assistant constrained by the program. "
    38. "When a tool is needed, output strict JSON: "
    39. '{"type":"tool_call","name":"tool_name","arguments":{}}; '
    40. "When the task is done, output: "
    41. '{"type":"final","content":"final answer"}.'
    42. )
    43. },
    44. {
    45. "role": "user",
    46. "content": user_input
    47. }
    48. ]
    49. for _ in range(max_steps):
    50. raw = call_model(messages)
    51. try:
    52. action = json.loads(raw)
    53. except json.JSONDecodeError:
    54. return "Model output could not be parsed. Task stopped."
    55. action_type = action.get("type")
    56. if action_type == "final":
    57. return str(action.get("content", ""))
    58. if action_type != "tool_call":
    59. return "Unknown action type from the model. Task stopped."
    60. tool_name = action.get("name")
    61. arguments = action.get("arguments", {})
    62. if not isinstance(tool_name, str) or not isinstance(arguments, dict):
    63. return "Invalid tool-call arguments. Task stopped."
    64. tool_result = execute_tool(tool_name, arguments)
    65. messages.append({
    66. "role": "assistant",
    67. "content": raw
    68. })
    69. messages.append({
    70. "role": "tool",
    71. "content": tool_result
    72. })
    73. return "Exceeded the maximum number of steps. Task stopped."

    The example encodes several principles:

    • The model can only propose actions; it does not get execution rights.
    • Tools must be registered; unknown tools are rejected.
    • Every loop has a hard step limit.
    • Model output is parsed and validated.
    • Tool exceptions are converted into results the model can read.
    • Termination is owned by the program, not fully delegated to the model.

    Tool calls cannot rely on prompts alone

    Beginners often assume that writing “do not perform dangerous operations” in the prompt solves safety. Prompts can guide behavior; they cannot replace permission control.

    1. Validate arguments

    If a tool takes a file path, a database query, or a network address, check:

    • Correct type
    • Non-empty
    • Length limits
    • Forbidden characters
    • Allowed directories or resources
    • Business rules

    A file-deletion tool must not accept an arbitrary path from the model. Restrict paths to a designated working directory and reject traversal and other malformed input.

    2. High-risk operations need human confirmation

    For money movement, account privileges, data deletion, or production config changes, use a two-stage flow:

    1. Model proposes an action
    2. ↓
    3. Program produces a preview and risk notes
    4. ↓
    5. Human confirms
    6. ↓
    7. Tool actually executes

    That is more reliable than letting the agent execute immediately and easier to audit later.

    3. Minimize tool permissions

    Do not give the agent one overly broad “do anything” function. Split into single-purpose tools—query, read, compute, submit—and assign permissions separately.

    State management is the key to stability

    Short tasks can keep history in memory. Production systems must deal with long context, restarts, and concurrent requests.

    Typical state includes:

    • Original user goal
    • Completed steps
    • Tool-call records
    • Tool results
    • Current task status
    • Errors
    • Human confirmation records
    • Usage statistics

    Represent it with an explicit structure:

    1. from dataclasses import dataclass, field
    2. @dataclass
    3. class AgentState:
    4. goal: str
    5. messages: list[dict] = field(default_factory=list)
    6. step_count: int = 0
    7. status: str = "running"
    8. errors: list[str] = field(default_factory=list)

    Once state is explicit, you can pause, resume, retry, and hand off to a human instead of hiding everything in a growing conversation transcript.

    Long tasks also need context compression. Keep the goal, key conclusions, unfinished items, and recent tool results; drop repeated intermediate text to control input length and cost.

    Exception handling and observability are not optional

    Agents fail in more ways than a typical API:

    • Network timeouts
    • Temporary API unavailability
    • Malformed model output
    • Invalid tool arguments
    • Long-running tools
    • Repeated calls to the same tool
    • Loops that never finish
    • Context overflow
    • Sensitive data in results

    At minimum, log:

    • Request ID
    • Task ID
    • Current step
    • Summaries of input and output
    • Tool name
    • Argument validation outcome
    • Latency
    • Error type
    • Final stop reason

    Do not log passwords, tokens, personal data, or full business payloads. In production, add metrics such as average steps, tool failure rate, task success rate, human takeover rate, and cost per task.

    How to keep the agent from running away

    A common failure is repeatedly calling the same tool or oscillating between actions. Do not rely on the model to be well-behaved; enforce constraints in code:

    1. Maximum step count
    2. Record of recent actions
    3. Detection of repeated tool names and arguments
    4. Per-tool call caps
    5. Total time and budget caps
    6. Immediate stop on repeated identical errors
    7. Require a summary or exit when no new information is obtained

    For example, if two consecutive calls use the exact same tool and arguments, return the previous result instead of calling again.

    When pure Python is enough, and when a framework helps

    Pure Python fits well when:

    • The agent flow is short
    • The tool set is small
    • The team wants full ownership of execution logic
    • Prompts and state need deep customization
    • The project is still in validation
    • Dependency count and debug transparency matter

    A framework or internal platform becomes more valuable when:

    • Many complex workflows must be managed
    • Multiple agents must collaborate
    • You need unified persistence, retries, and tracing
    • Several teams share tool registration and permissions
    • Boilerplate is already duplicating
    • Deployment and operations need a standard path

    The point is not “frameworks are always better” or “hand-written is always better.” Match the abstraction to complexity. Simple tasks should not be over-wrapped; complex systems should not live forever on scattered one-off code.

    A practical path to production

    A conservative sequence:

    1. Implement a single model call and confirm goal and output quality.
    2. Add one or two read-only tools and verify tool selection and result interpretation.
    3. Add loop control, max steps, and basic error handling.
    4. Introduce structured state and separate progress from raw dialogue.
    5. Add permissions, human confirmation, audit logs, and metrics.
    6. Build a test set from real failures: format errors, tool exceptions, repeated calls, and adversarial input.
    7. When duplication and complexity grow, extract shared components or adopt a suitable framework.

    This incremental path avoids an overbuilt system on day one and ensures each new capability is proven.

    Conclusion

    Building an AI agent with Python and a model API, without a dedicated framework, is technically feasible. The core is not mysterious: organize model calls, tool execution, state management, and loop control into a reliable closed loop.

    Hand-built agents are transparent, flexible, and easy to debug. The cost is that you own protocol design, error handling, security, and operations. The professional approach is neither to insist on “pure handwritten” code nor to dump every problem on a framework. Start from a minimal working loop and add abstraction when complexity actually appears.

    If you are explicit about which decisions belong to the model, which permissions stay in the program, and you put real bounds and observability in place, a pure Python agent can go from prototype to a stable engineering system.