Is a Pure-Python AI Agent Practical?

    Many teams start agent projects by picking an orchestration framework, but production quality often depends more on a clear decide-execute-write-back loop than on the framework itself. This article explains the minimal agent structure, when a handwritten Python loop is enough, and when graph-style orchestration is the better fit.

    An agent is not a black box. It is a controllable loop.

    Product stories often bundle multi-turn chat, tool use, memory, and planning into one mysterious package. In implementation, a working agent usually does three things: send the current task and context to a large language model; decide from the model output whether to call a tool or answer; append tool results or intermediate state to the context and continue. The loop runs until the task is done or a round limit is hit. An agent is closer to a bounded loop than to an invisible protocol.

    In plain terms: the user provides a goal; the system builds a message list; it calls a model that supports tool descriptions; if the model returns a tool call, the system runs the matching capability (search, database query, file I/O, business APIs) and writes the result back as a tool message; if the model has enough information, it returns a final answer and exits. Max rounds, timeouts, cost budgets, and permission boundaries are required safety valves, not optional decoration.

    For newcomers, every line of this model is explainable: how messages are appended, how tools are registered, how failures retry, and when the loop is forced to stop. Deeply customized systems benefit the same way. Approval flows, audit logs, multi-tenant isolation, and domain constraints can be ordinary functions in the loop rather than adapters to a framework’s graph-node semantics.

    A minimal implementation: a closed loop in about a hundred lines

    The following is schematic pseudocode. Real systems still need auth, timeouts, structured parsing, and observability.

    1. async def agent_loop(task, tools, max_rounds=20):
    2. messages = [{"role": "user", "content": task}]
    3. for _ in range(max_rounds):
    4. reply = await llm.chat(messages, tools=tools.schema())
    5. if reply.tool_call:
    6. result = await tools.run(reply.tool_call)
    7. messages.append(reply)
    8. messages.append({"role": "tool", "content": result})
    9. else:
    10. return reply.content
    11. return "Exceeded max rounds; task aborted"

    The LLM is the decision hub, tools are executors, and the message list is the only state. Add search and it is a research assistant; add analytics queries and it is a data assistant; add read/write and a code sandbox and it is a coding assistant. The differences are the tool set, prompt constraints, and stop conditions—not a different runtime philosophy.

    Production builds typically add input validation and idempotency, rejection of hallucinated tool calls, confirmation for sensitive actions, summarization when the context window is full, and per-round logging of tokens, latency, and tool success. Ordinary modules can do this without graph orchestration.

    Benefits of handwriting: transparency, control, and fit with existing systems

    First, lower cognitive load. Anyone who knows async calls, message protocols, and error handling can read the main loop. New teammates do not need graphs, state machines, and checkpoints on day one.

    Second, predictable customization. Enterprise knowledge bases, ticket systems, and internal permission models rarely look like tutorial demos. Domain rules as hooks around the loop are more direct than forcing business logic into generic node types. Queries that need approval, tools that may run only during business hours, and results that must be redacted before they return to the model are ordinary conditionals and middleware.

    Third, shorter debugging paths. Production issues often sit in prompt drift, tool timeouts, noisy context, or repeated identical tool calls. Logging inside and around the loop produces a timeline of round, call, and result. For internal systems that need stability, that path often matters more than a long feature list.

    Fourth, a smaller dependency surface. The core depends on model calls and business SDKs. Upgrades, security reviews, and air-gapped deploys lock fewer components.

    Handwriting is not inventing a new protocol. Tool descriptions should follow common function-calling conventions; roles should still distinguish user, assistant, and tool; outputs should be structured. You own orchestration and policy, not an incompatible interaction standard.

    Where orchestration frameworks belong

    When the problem grows from “one loop plus several tools” into multi-role collaboration, recoverable long workflows, visual editing, and reusable nodes across teams, a custom loop gets expensive. Signals include branching, parallelism, human confirmation and rollback; persisted state so a run can resume; the same subprocess reused across product lines; and operators who should edit a graph rather than code.

    Then a graph or workflow runtime is reasonable: nodes for local capabilities, edges for conditional jumps, the runtime for retries and checkpoints. The value is standardizing complex control flow, not wrapping a single model call. Teams should still be able to say where state lives, which steps are reentrant, and which have side effects.

    A practical split: use a pure-Python loop as the kernel for single-task, limited-tool, business-bound work; wrap that loop as a node in a longer cross-system workflow. You do not have to bet on “everything is a graph” or “everything is handwritten” on day one.

    Engineering details that matter in practice

    Context governance. Each extra round accumulates noise and repeated tool output. Cap tool-return length, dedupe and summarize retrieval, and compress history near the window limit instead of appending forever.

    Termination and anti-loops. Besides max rounds, trip a breaker on consecutive identical tool calls or no new information. Models sometimes idle to look busy; rules must catch that.

    Tool safety. Treat tools as external APIs: auth, quotas, sandboxes, and audit. For code execution, file writes, and production-database changes, reject high-risk parameters by default and add a human gate when needed.

    Observability and evaluation. Log per-round input summaries, tool names, latency, and success. Regress on a fixed task set (accuracy, average rounds, cost). Without evaluation it is hard to tell whether prompts improved or luck did.

    Knowledge bases. Retrieval should be a tool in the loop, not a dump of the whole corpus into the prompt. Retrieve then decide, or let the model decide whether to retrieve. That reduces hallucination and respects permission slices.

    Deployment. If the loop is stateless, session affinity at the gateway is enough. If work continues across requests, persist messages and a cursor in object storage or a database and drive the next round with a queue so request threads are not held. Alert on timeout piles, tool failure rate, and abnormal round counts.

    Conclusion: feasible, and often a better fit for one class of problems

    A pure-Python AI agent is feasible, and it is often friendlier on cognitive load, customization depth, and debugging. The theory is simple: agent = bounded loop + model decisions + tool execution + context write-back. Frameworks do not rewrite that law; they add a fuller runtime for complex control flow.

    Validate the business loop with a minimal cycle first, and harden tools, prompt constraints, and safety. When collaboration topology and persistence clearly outgrow a single loop, lift the mature parts into orchestration nodes. A simple kernel with clear boundaries is more likely to reach a maintainable production agent than heavy abstraction too early.