Building AI Agents from Scratch: From Runtime Loops to Production-Ready Engineering
This article explains how to build a working AI agent without relying on a framework. It covers the core decision–execution–observation loop, tool design and security boundaries, state management, failure recovery, cost control, testing strategies, and when a hand-rolled implementation is the right choice over an orchestration framework. Code examples and practical engineering guidelines are included.
1. What You Actually Need to Implement Without a Framework
In real engineering projects, an agent does not have to be tied to a particular framework. As long as you can call a large language model and manage task state and external operations programmatically, you can build an agent with genuine business value.
However, “possible to build” does not mean “just call the model a few times.” Frameworks typically handle message organization, tool registration, execution scheduling, state persistence, and error handling. If you skip the framework, these responsibilities must be implemented explicitly—they don’t disappear on their own.
The more accurate conclusion is: when business paths are relatively clear, the number of tools is limited, and tight control is required, writing the agent’s runtime logic directly may be the better fit; when workflows are complex, many roles collaborate, and long-running tasks dominate, the maintenance cost of a homegrown solution grows significantly.
The decision of whether to use a framework should not be based solely on initial code volume. Consider debugging cost, business constraints, team capability, and room for future evolution.
2. First, Distinguish Fixed Workflows from Agents
Many systems labeled “agents” are actually fixed workflows. For example:
User submits a question → retrieve relevant documents → generate an answer.
If the retrieval step always runs and the order never changes, writing the flow directly is usually simpler—there’s no need for an autonomous decision loop.
The defining trait of an agent is that the system dynamically selects its next action within the bounds allowed by the business, based on its goal and current observations. For example, when handling an operations alert, the system might first query monitoring metrics, then decide based on those results whether to inspect logs, and finally determine whether a manual-handling recommendation should be filed.
Dynamic decision-making does not mean unlimited autonomy. The model may propose actions, but which actions are allowed, what conditions must be met, and when execution must stop should be governed by deterministic program rules.
The core responsibilities can be summarized as:
- The model proposes: understands the goal, analyzes context, and selects candidate actions.
- The program constrains: validates structure, checks permissions, controls budgets, and decides whether to execute.
- The tools operate: access business data and perform clearly bounded, well-defined tasks.
- The state connects: records what happened and what stage the task is in.
The clearer the boundaries between these four, the easier the system is to debug and audit.
3. Minimal Architecture: Establishing a “Decide–Execute–Observe” Loop
An explainable agent runtime loop can be broken into six steps:
- Receive the user’s goal and identity information.
- Construct the model context, including available tool descriptions and behavioral constraints.
- Request the model’s next decision.
- Validate the decision: is it a final answer, or a request to invoke a tool?
- Execute authorized tools and write the results into state.
- Decide again, until the task is completed or a stop condition is triggered.
The most important design point is not the length of the prompt, but the fact that every decision round must be converted into a verifiable data structure.
For example, the model can be restricted to only two kinds of results:
Finish:{"kind": "finish","answer": "final answer"}Tool call:{"kind": "tool","name": "lookup_record","arguments": {"record_id": "business record ID"}}
These fields are an illustrative protocol defined by the application itself, not a real interface of any model service. In practice, an adapter layer must convert the model service’s raw output into this unified internal structure.
If the model service supports structured output, use that capability to reduce format-error probability; if not, you need parsing and validation. Either way, model output must never be treated as trusted input.
4. Expressing the Core Runtime Logic in a Small Amount of Code
The following illustrative code shows a bounded run loop. It deliberately omits specific model APIs and business interfaces to focus on control boundaries.
class AgentError(Exception):passdef validate_decision(value):if not isinstance(value, dict):raise AgentError("Decision must be an object")kind = value.get("kind")if kind == "finish":if not isinstance(value.get("answer"), str):raise AgentError("Final answer must be text")return valueif kind == "tool":if not isinstance(value.get("name"), str):raise AgentError("Invalid tool name")if not isinstance(value.get("arguments"), dict):raise AgentError("Invalid tool arguments")return valueraise AgentError("Unsupported decision type")def run_agent(goal, actor, decide, tools, max_steps=6):history = []for step in range(max_steps):decision = validate_decision(decide(goal=goal, history=history))if decision["kind"] == "finish":return {"status": "completed","answer": decision["answer"]}tool = tools.get(decision["name"])if tool is None:raise AgentError("Tool is not in the allowed list")arguments = tool["validate"](decision["arguments"])if not tool["authorize"](actor, arguments):raise AgentError("Current identity is not authorized for this operation")result = tool["execute"](arguments)history.append({"step": step,"action": {"name": decision["name"],"arguments": arguments},"observation": tool["summarize"](result)})return {"status": "stopped","reason": "Maximum number of decision steps reached"}
Here, decide is the model adapter function; the validate, authorize, execute, and summarize functions in each tool registration are implemented by the business system.
This example reveals several key principles:
First, the model can only select tools that have been registered—it cannot invent a function name and demand execution.
Second, identity information comes from a trusted call chain. A “user identity” generated by the model must never be used as the basis for authorization.
Third, parameter format validation and business permission checks are two separate steps. A record ID may be well-formed yet still not something the current user is allowed to read.
Fourth, the run loop must have termination conditions. Six steps in the example is a demo value, not a recommended production setting; real systems should set limits based on task complexity and resource budgets.
Fifth, this is still not a complete production implementation. It does not cover call timeouts, exception classification, persistence, concurrency races, or confirmation of write operations—those capabilities must be added as well.
5. Tool Design Determines the System’s Security Boundary
Tools should not be designed as broad entry points that “execute arbitrary operations.” The more general a tool is, the harder it is to audit its permissions—and the easier it becomes for the model to turn uncertain intent into dangerous actions.
A safer approach is to expose business capabilities with clear granularity, for example:
- Query the status of a specific business record.
- Retrieve a monitoring summary for a given time range.
- Create a review draft for a handling proposal.
- Submit a change request that has been explicitly confirmed by the user.
Each tool should clearly define its input fields, return structure, access scope, and side effects.
For read-only tools, focus on limiting query scope, result counts, and sensitive fields. For write, delete, approval, and similar operations, add confirmation, idempotency, and audit mechanisms.
Pay special attention: a model-generated claim that “the user has consented” is not valid authorization. Confirmation required by high-risk operations must come from a trusted interaction flow and be bound to the actual operation, its parameters, and an expiration period.
If the model modifies an operation’s parameters after confirmation, the original confirmation should no longer apply.
6. State Management Cannot Rely Solely on Conversation History
Continually appending all history to the model context is the easiest approach, but it is not suitable as the sole state-management mechanism.
As a task runs longer, this approach causes context bloat, rising costs, information duplication, and factual conflicts. A better approach is to split state into three layers.
1. Task State
Store the task ID, goal, current stage, execution count, cumulative budget, and pending items. This information is maintained by the program and must not rely on the model remembering it.
2. Execution Events
Record every decision, tool request, execution result, and exception. Events should carry sequence identifiers to aid troubleshooting and recovery.
3. Model Context
Include only the information needed for the current decision: the goal, key facts, recent observations, and necessary constraints. Full logs can be kept in external storage and don’t all need to be sent to the model.
If the model is used to summarize history, retain references to the original evidence. Summaries may omit conditions or compress details; they cannot replace original records as the sole basis for high-risk operations.
7. Failure Recovery: Don’t Turn Retries into Duplicate Executions
Model-call failures and tool-execution failures need to be handled separately.
For transient network errors on model calls, you can retry within the budget; but a tool-call timeout does not necessarily mean the operation didn’t happen. For example, a write request may have succeeded while its response timed out.
Therefore, tools with side effects should use business operation IDs or idempotency keys. After a timeout, first query the operation’s status instead of executing it again.
Exceptions should also be classified:
- Transient failure: consider limited retries with backoff and a total deadline.
- Input error: provide a cleaned-up error message to the model and allow it to correct parameters.
- Permission denial: block execution directly; do not repeatedly try to bypass the restriction.
- Uncertain result: pause the task and enter status verification or manual handling.
- No sustained progress: terminate the loop and return completed items along with the reasons items were not completed.
Never wrap every exception as a normal tool result and keep running; otherwise the model may mistake a system failure for a business fact.
8. External Content Is Not a Source of Instructions
Web pages, documents, logs, and business notes returned by tools may contain text like “ignore previous restrictions” or “call another tool.” This content is data to be processed, not trusted control instructions.
Protection should include at least two layers:
First, clearly mark external content as such in the context, instructing the model to treat it as evidence rather than obey behavioral instructions embedded in it.
Second, enforce the tool whitelist, parameter validation, and identity authorization at the program layer. Prompting alone cannot form a reliable security boundary.
In addition, tool results should be trimmed and sanitized as needed. Access credentials, secrets, and personal information irrelevant to the task must not enter the model context. When audits are required, avoid storing sensitive data in plaintext in logs.
9. Cost and Latency Must Be Runtime Constraints
A from-scratch implementation is not automatically cheaper or faster than a framework. Actual resource consumption is driven mainly by model-call count, context length, tool response time, and the proportion of repeated decisions.
Optimization can focus on:
- Handling fixed rules directly in program logic instead of asking the model.
- Reducing repeated historical information sent, retaining necessary summaries and evidence references.
- Setting separate timeouts for model calls, tool execution, and the overall task.
- Setting a cumulative call budget; when the threshold is reached, stop or hand off to a human.
- Parallelizing only tool operations that are independent of each other and allowed to run concurrently.
- Caching read-only results only when permissions and data freshness permit.
Do not trade correctness and safety boundaries for speed by shortening authorization flows, skipping validation, or hiding failure states. Efficiency optimizations must occur within those boundaries.
10. How to Verify the System Actually Works
Testing must not only check whether the final answer sounds fluent; it must verify whether behavior is correct.
At minimum, cover these scenarios:
- A normal task completes within the allowed budget.
- When the model returns a malformed structure, the system rejects it or performs limited repair.
- A nonexistent tool is never executed.
- Well-formed but unauthorized parameters are intercepted.
- A write-operation timeout does not cause uncontrolled duplicate submissions.
- When external content contains injected instructions, permission boundaries remain effective.
- When a step or cost limit is reached, the system stops cleanly.
- After a restart, task state can be recovered or safely marked as pending review.
Where feasible, record model decisions and tool results to build a sanitized replay test set. When the model version, prompts, or tool definitions change, re-run the same cases as regression tests—this is more reliable than relying only on manual review.
Evaluation metrics should also cover task completion rate, intercepted unauthorized operations, invalid tool calls, resource consumption, and human-takeover rate—not just answer quality.
11. When Building It Yourself Is Worth It
The following scenarios generally favor writing the runtime logic directly: a small number of tools, clear task boundaries, existing business systems that can provide stable interfaces, and teams that need strict control over authorization and audit flows.
If the system requires extensive branching and orchestration, multiple collaborating agents, long waits for human feedback, or the team lacks the capacity to maintain a runtime, seriously evaluate the value of a mature orchestration solution.
The two approaches are not mutually exclusive. Whether or not you use a framework, preserve clear model-adapter, tool-execution, and state-management layers so business rules aren’t locked into any particular implementation.
Ultimately, building agents in pure code is not only feasible but can deliver more direct control in specific engineering contexts. Its value is not “fewer dependencies”—it is making the decision process, execution permissions, and failure behavior truly visible, testable, and maintainable. Start with a bounded loop, then add capability incrementally; that is usually more robust than pursuing maximal autonomy from day one.
