Building AI Agents in Pure Python: Is It Practical for Production?

    Building an AI agent without an orchestration framework is practical when tools and workflows have clear boundaries. This article explains the core components, presents a framework-free Python implementation, and examines the state management, execution controls, observability, security, and testing needed to move from a working prototype to a production system. It also outlines when a framework may be the better choice.

    1. The Short Answer: Yes, but Not Without Engineering Costs

    In real-world projects, building an AI agent manually with Python and a general-purpose large language model API—without an orchestration framework—is entirely feasible. It can also be a better choice when the number of tools is manageable, workflow boundaries are clear, and compliance and observability requirements are demanding.

    “Better” does not necessarily mean less code. It means more complete control, clearer failure boundaries, fewer dependencies, and a shorter debugging path.

    An agent is not inherently mysterious. Beneath the framework abstractions, a working agent typically needs five components:

    1. Model interface: Sends messages to an LLM API and receives natural-language or structured responses.
    2. Tool layer: Registers business functions as capabilities the model can select, while enforcing argument validation and access controls.
    3. Execution loop: Advances the task through a cycle of planning, tool calls, observations, and further reasoning.
    4. State and memory: Stores conversations, plans, tool results, task context, and checkpoints.
    5. Operational controls: Handles timeouts, retries, budgets, logging, auditing, rate limits, security, and human takeover.

    These components can be implemented with the Python standard library and application code. Orchestration frameworks primarily provide abstractions, visualization, ecosystem integrations, and shared conventions for teams. For a single agent with well-defined boundaries, however, their additional layers can make troubleshooting harder.

    Whether an agent is ready for production depends less on its framework choice than on how thoroughly these five components are implemented.

    2. The Minimum Agent Loop: One Loop and Three Types of State

    From an engineering perspective, an agent can be represented as the following loop:

    1. Receive task -> Assemble context -> Call model -> Parse intent/tool call
    2. -> Execute tool -> Record observation -> Update state
    3. -> Check termination conditions
    4. -> Return result or request human takeover

    The most important element in this loop is state, not the prompt. A maintainable agent should track at least three types of state:

    • Short-term conversation state: User inputs, model messages, tool calls, and tool results.
    • Task execution state: The current objective, completed steps, pending steps, failure reasons, and retry counts.
    • Long-term reusable state: User preferences, business rules, summaries of previous tasks, and auditable execution history.

    Without explicit state, an agent can become a chatbot that reconstructs its understanding from scratch on every call. Without termination conditions, it can enter infinite loops, repeat tool calls, or exceed its budget.

    The first principle of a pure-Python implementation is therefore straightforward: make the loop explicit, represent state directly, and enforce termination conditions in code.

    3. Why Pure Python Can Be a Better Fit

    Clearer Failure Boundaries

    Framework abstractions can hide details of model calls, tool routing, and state persistence. When the model does not call the expected tool, arguments fail to parse, or context is truncated, developers may need to understand both their application and the framework’s internals.

    In a pure-Python implementation, each layer is explicit. Logs can identify the exact step, tool name, argument summary, elapsed time, and error code, reducing the effort required to locate a failure.

    Fewer Dependencies

    Production systems must account for dependency upgrades, supply-chain security, licensing, and long-term maintenance. Removing an orchestration framework removes one source of version compatibility risk.

    This is particularly valuable for long-lived systems, restricted deployment environments, and applications that require detailed audits.

    More Room for Business-Specific Controls

    Business agents often need to integrate with internal authorization systems, approval workflows, ticketing systems, data redaction, human review, and risk controls. These requirements do not always fit neatly into general-purpose abstractions.

    Pure Python allows tool execution, permission checks, and human confirmation points to be implemented as ordinary functions and middleware, then composed around the application’s needs.

    More Direct Control over Cost and Latency

    A manual implementation can precisely control context trimming, tool-result summaries, retry policies, concurrency, and budget cutoffs.

    For example, it can check the remaining budget before each model call, request human takeover after two consecutive tool failures, or retain only a task summary and recent observations when context exceeds a threshold. These policies are not especially complicated, but they benefit from code-level control.

    Pure Python still has costs. The team must implement state persistence, observability, concurrency scheduling, tool protocols, and tests. Mature frameworks remain useful when a project needs complex multi-agent collaboration, visual orchestration, or many prebuilt integrations.

    The conclusion is not to reject frameworks, but to choose based on the workload. A custom implementation can offer greater predictability for agents of simple to moderate complexity. More complex systems involving multiple teams or visual orchestration may benefit from a framework or platform.

    4. A Pure-Python Skeleton: Model, Tools, Loop, and Controls

    The following example uses no third-party orchestration framework. It relies on the standard library and abstract interfaces to illustrate the engineering structure rather than a specific provider’s API.

    1. from __future__ import annotations
    2. import json
    3. import logging
    4. import time
    5. import uuid
    6. from dataclasses import dataclass, field
    7. from typing import Any, Callable, Protocol
    8. logger = logging.getLogger("agent")
    9. class LLMClient(Protocol):
    10. def complete(self, messages: list[dict], tools: list[dict]) -> dict:
    11. """Illustrative response structure:
    12. {
    13. "type": "tool_call" | "final",
    14. "tool_name": "...",
    15. "arguments": {...},
    16. "content": "...",
    17. "usage": {"input_tokens": 0, "output_tokens": 0}
    18. }
    19. """
    20. ...
    21. @dataclass
    22. class ToolSpec:
    23. name: str
    24. description: str
    25. input_schema: dict
    26. handler: Callable[[dict], Any]
    27. timeout_seconds: float = 5.0
    28. requires_confirmation: bool = False
    29. class ToolRegistry:
    30. def __init__(self) -> None:
    31. self._tools: dict[str, ToolSpec] = {}
    32. def register(self, spec: ToolSpec) -> None:
    33. if spec.name in self._tools:
    34. raise ValueError(f"duplicate tool: {spec.name}")
    35. self._tools[spec.name] = spec
    36. def schema(self) -> list[dict]:
    37. return [
    38. {
    39. "name": t.name,
    40. "description": t.description,
    41. "input_schema": t.input_schema,
    42. }
    43. for t in self._tools.values()
    44. ]
    45. def execute(self, name: str, arguments: dict) -> dict:
    46. if name not in self._tools:
    47. return {"ok": False, "error": "tool_not_found"}
    48. spec = self._tools[name]
    49. # Production code should enforce schema validation, authorization,
    50. # data redaction, timeouts, and sandbox isolation.
    51. try:
    52. started = time.time()
    53. result = spec.handler(arguments)
    54. return {
    55. "ok": True,
    56. "result": result,
    57. "elapsed_ms": int((time.time() - started) * 1000),
    58. }
    59. except Exception as exc:
    60. logger.exception("tool failed: %s", name)
    61. return {"ok": False, "error": type(exc).__name__}

    The agent loop should explicitly limit steps, budget consumption, and failures, while recording observations:

    1. @dataclass
    2. class AgentState:
    3. trace_id: str
    4. task: str
    5. messages: list[dict] = field(default_factory=list)
    6. step: int = 0
    7. max_steps: int = 8
    8. max_tool_failures: int = 2
    9. tool_failures: int = 0
    10. budget_tokens: int = 20000
    11. used_tokens: int = 0
    12. observations: list[dict] = field(default_factory=list)
    13. def run_agent(
    14. task: str,
    15. llm: LLMClient,
    16. registry: ToolRegistry,
    17. store: Any,
    18. ) -> dict:
    19. state = AgentState(trace_id=str(uuid.uuid4()), task=task)
    20. state.messages.append({"role": "user", "content": task})
    21. while state.step < state.max_steps:
    22. state.step += 1
    23. if state.used_tokens >= state.budget_tokens:
    24. return {"status": "budget_exceeded", "trace_id": state.trace_id}
    25. response = llm.complete(state.messages, registry.schema())
    26. usage = response.get("usage", {})
    27. state.used_tokens += int(usage.get("input_tokens", 0))
    28. state.used_tokens += int(usage.get("output_tokens", 0))
    29. if response["type"] == "final":
    30. result = {"status": "ok", "content": response.get("content", "")}
    31. store.save(state.trace_id, state, result)
    32. return result
    33. tool_name = response.get("tool_name", "")
    34. arguments = response.get("arguments", {})
    35. observation = registry.execute(tool_name, arguments)
    36. if not observation.get("ok"):
    37. state.tool_failures += 1
    38. if state.tool_failures >= state.max_tool_failures:
    39. result = {"status": "manual_takeover", "reason": "tool_failures"}
    40. store.save(state.trace_id, state, result)
    41. return result
    42. state.observations.append({
    43. "step": state.step,
    44. "tool": tool_name,
    45. "arguments_digest": json.dumps(arguments, ensure_ascii=False)[:500],
    46. "observation": observation,
    47. })
    48. state.messages.append({
    49. "role": "tool",
    50. "name": tool_name,
    51. "content": json.dumps(observation, ensure_ascii=False)[:4000],
    52. })
    53. store.checkpoint(state.trace_id, state)
    54. result = {"status": "max_steps_reached", "trace_id": state.trace_id}
    55. store.save(state.trace_id, state, result)
    56. return result

    Although illustrative rather than production-ready, this code shows several core operational controls: a tool allowlist, duplicate-registration protection, failure counting, step limits, token-budget checks, checkpoints, and result persistence.

    A real system must also implement argument-schema validation, tool-level timeouts, concurrency limits, sensitive-field redaction, human confirmation points, and audit logging. The timeout and confirmation fields in this skeleton describe intended controls; they are not enforced by the example.

    5. What Separates a Working Prototype from a Production Agent

    1. Keep the Tool Protocol Stable

    Version tool names, descriptions, argument structures, and return structures. A tool description is not merely prompt decoration: it helps the model decide which tool to select.

    Validate arguments before execution. Never pass model output directly into business functions without checks. High-risk tools should require human confirmation and operate with least-privilege permissions.

    2. Enforce Loop Controls in Code

    Maximum steps, tool failures, budget, elapsed time, and repeated-call detection should be hard constraints.

    If the same tool is called repeatedly with identical arguments, stop execution or require a change in strategy rather than allowing the agent to keep cycling without progress.

    3. Make Persisted State Recoverable

    Save a checkpoint after each tool call. At a minimum, it should include the trace ID, task objective, message summary, tool observations, budget consumption, and failure count.

    This allows execution to resume—or be reviewed—after a process restart or human takeover.

    At the deployment layer, general-purpose infrastructure such as object storage, centralized logging, monitoring and alerting, and container platforms can support trace storage, logs, and runtime metrics. These infrastructure services do not change the agent’s core implementation.

    4. Design Observability for Troubleshooting

    Logs should capture:

    • Step number
    • Model-call latency
    • Tool-execution latency
    • Argument and response summaries
    • Error codes
    • Budget consumption
    • Termination reason

    Useful metrics include task success rate, average step count, tool failure rate, human takeover rate, cost per task, and P95 latency.

    Without these measurements, agent optimization becomes guesswork.

    5. Build Security Controls In from the Start

    Account for prompt injection, unauthorized tool calls, sensitive-data leakage, and malicious arguments.

    Tools should run with minimum necessary permissions. External inputs and tool results should be redacted as needed before entering model context, and high-risk operations must require human confirmation.

    Audit logs should be tamper-resistant or, at minimum, support traceability.

    6. Test at Multiple Levels

    Use distinct test layers:

    • Unit tests: Cover tool-argument validation and execution failure paths.
    • Replay tests: Use fixed model responses to verify loop controls.
    • Integration tests: Cover real API timeouts, rate limits, and abnormal responses.
    • Evaluation sets: Measure task success, tool-selection accuracy, cost, and latency.

    One advantage of pure Python is that these tests can target ordinary functions directly.

    6. Where Pure Python Fits—and When to Choose a Framework

    A pure-Python agent is a strong fit when:

    • The number of tools is limited and their boundaries are clear.
    • Business workflows require substantial customization.
    • Compliance and audit requirements are demanding.
    • The team has backend engineering experience.
    • Reducing framework dependencies is a priority.

    It is less suitable when the project requires many prebuilt integrations, complex multi-agent collaboration, visual orchestration, rapid configuration by nontechnical teams, or adherence to an established organization-wide framework.

    A practical approach is to start with a minimal pure-Python loop and establish clear tool protocols, state structures, execution controls, and logging. Introduce a framework or platform when concrete needs emerge for reuse, more complex collaboration, or visual orchestration.

    Do not add abstractions merely to make the system look like an agent, and do not sacrifice control simply to reduce code volume.

    Ultimately, an agent’s engineering quality depends on clear state, safe tools, controlled execution, and sufficient observability—not on whether it uses an orchestration framework.