How to Build Reliable AI Agents from Scratch Without a Framework
Building an AI agent without a framework requires more than connecting a language model to tools. This article explains the core architecture, execution controls, state management, security boundaries, recovery strategies, and evaluation practices needed to build a reliable system—and when a custom implementation makes sense.
1. Can You Build an Agent Without a Framework?
Yes—but making an agent run and making it production-ready are different challenges.
An AI agent does not inherently depend on a framework. Its core mechanism is a controlled decision-and-execution loop: the system receives a goal and the current state, asks a large language model to propose the next step, validates and executes permitted actions, and feeds the results back to the model. The loop continues until the task is complete or a stopping condition is reached.
A general-purpose programming language, a model API, and the necessary infrastructure are enough to implement this mechanism. Frameworks typically provide orchestration, state storage, tool wrappers, and observability. These are useful capabilities, not prerequisites for an agent to exist.
However, avoiding a framework does not mean those capabilities can be omitted. Developers move from using existing abstractions to defining and maintaining their own.
A custom implementation can be more direct when the task scope is clear, the tool set is small, and execution paths are short. Code boundaries remain visible, debugging is transparent, and permissions and auditing can be tailored to the business. Maintenance becomes more demanding for long-running tasks, complex branches, and multi-role collaboration.
The real question is not whether you can write an agent yourself. It is how much autonomous decision-making you need, and whether your team is prepared to take on the corresponding engineering responsibilities.
2. Distinguish Model Calls, Fixed Workflows, and Agents
These three types of systems are often grouped together, but they differ in how execution is controlled.
A model call performs one inference
For example, a program sends text to a model to extract topics or generate a summary. It submits the request, receives the result, and completes the task.
The main concerns are input quality, output validation, and model performance. A scheduling loop or complex execution state is usually unnecessary.
A fixed workflow follows a predefined sequence
A workflow might read a document, extract fields, and then generate a report. A model may participate in several steps, but the program determines their order.
For stable business processes, fixed workflows are often easier to test and better suited to deterministic requirements. Using an LLM does not, by itself, make a workflow an agent.
An agent chooses its next step within defined limits
An agent can use intermediate results to decide whether to retrieve more information, call a tool, ask the user for clarification, or finish the task.
Autonomous decision-making does not imply unrestricted access. A sound design lets the model propose an action while the program retains execution authority. Tool access, data scope, and stopping conditions should be enforced by application logic and business rules.
A useful principle is: if deterministic logic can handle a step, there is no need to ask the model to guess.
3. A Minimal Architecture: Six Modules for the Control Loop
A clear baseline implementation can be divided into six modules.
1. Model adapter
The adapter sends requests, assembles context, and parses responses. It isolates model API differences from business logic.
Application code should ideally depend on a normalized internal decision structure—such as “finish,” “call a tool,” or “request clarification”—rather than a provider’s complete response format.
The goal is not unlimited model interchangeability. It is to reduce the impact of API changes on execution logic and make it easier to substitute mock responses during testing.
2. Tool registry
The registry stores each tool’s name, purpose, parameter constraints, execution entry point, and permission requirements.
Tool descriptions should accurately define their scope. “Query the status of orders the current user is authorized to access” is more precise than “handle order issues.” Vague descriptions make incorrect tool selection and unsuitable arguments more likely.
Only approved tools should appear in the registry. Never use a model-generated function name to dynamically invoke arbitrary objects in the application.
3. Argument and permission validation
Treat model-generated arguments as untrusted input.
Validation should check, at minimum:
- Whether required fields are present.
- Whether types are valid.
- Whether values fall within allowed ranges.
- Whether resource identifiers belong to resources the current user may access.
- Whether the operation is permitted for the current task.
Format validation and authorization are separate concerns. A correctly formatted resource ID does not establish that the user has permission to read that resource.
4. State management
State tracks the current goal, task phase, completed actions, intermediate results, remaining budgets, and errors.
State should not be synonymous with chat history. Conversation captures meaning, while structured state is better suited to determining whether an action has completed, whether execution may continue, and where recovery should begin after a failure.
5. Execution controller
The controller advances the loop, selects valid branches, handles tool results, and enforces stopping rules.
It is the agent’s control center. The model may suggest the next step, but it must not bypass the controller to access business systems directly.
6. Execution logging and auditing
Record the necessary details of model decisions, tool calls, authorization checks, and state changes.
These records support more than troubleshooting. They should help explain why an operation occurred, who authorized it, and what actually happened.
4. Example: The Control Loop Matters More Than the API Call
The following simplified example uses application-defined abstractions for model requests, argument validation, and tool execution. It does not correspond to any specific service API.
def run_agent(task, model, tools, policy, max_steps=6):state = {"task": task,"events": [],"status": "running",}for step in range(max_steps):# Implemented by the model adapter to normalize# model responses into internal decision objects.decision = model.decide(state, tools.descriptions())if not is_valid_decision(decision):state["status"] = "invalid_decision"return stateif decision["kind"] == "finish":answer = decision["answer"]# The application checks business completion criteria;# the model's claim of completion is not sufficient.if not completion_check(state, answer):state["status"] = "completion_check_failed"return statestate["status"] = "completed"state["answer"] = answerreturn stateif decision["kind"] == "clarify":state["status"] = "waiting_for_user"state["question"] = decision["question"]return stateif decision["kind"] != "tool":state["status"] = "unsupported_decision"return statetool = tools.get(decision["tool_name"])if tool is None:state["status"] = "unknown_tool"return stateargs = decision["arguments"]if not tool.validate(args):state["status"] = "invalid_arguments"return stateif not policy.authorize(task, tool, args):state["status"] = "permission_denied"return stateresult = execute_with_limits(tool, args)state["events"].append({"step": step,"tool": tool.name,"result": result,})state["status"] = "step_limit_reached"return state
The syntax is less important than three control principles:
- Model output must be parsed and validated, not turned directly into executable code.
- Tool authorization must be enforced by application logic, not by assurances in a prompt.
- Every task needs explicit exit paths; the loop must not run indefinitely.
The step limit is illustrative, not a universal recommendation. A real system should also limit total elapsed time, individual tool execution time, call counts, context size, and spending. These limits should reflect task risk.
Structured output does not guarantee semantic correctness, either. Arguments may parse successfully while still identifying the wrong resource or requesting an unreasonable operation.
5. Tool Design: Prefer Narrow Capabilities to Universal Access
The more powerful a tool is, the harder the system is to control.
Giving a model an “execute any command” or “access any resource” entry point may appear to cover many use cases quickly. It also increases the scope for unintended actions and data leakage.
A safer approach is to expose narrowly defined business capabilities:
- Search information within a specified scope.
- Retrieve the read-only status of a resource.
- Generate a proposed change for review.
- Submit an operation that has already been confirmed.
Separate read operations from write operations wherever practical. Information queries can often run directly, while actions with side effects—such as changing data, sending notifications, or deleting records—require stricter authorization and confirmation.
Tool results should use a consistent format that distinguishes success, business failure, insufficient permissions, and temporary faults. Feeding an error message back as ordinary reference material can cause the model to draw unsupported conclusions from a failed operation.
For tools that return large datasets, limit the response scope. Instead of placing every record in context, return the necessary summary, source identifiers, and pointers for further queries.
6. State Management: Chat History Is Not Enough
An early prototype may keep message history in memory. Production systems generally need to support interruption, recovery, and traceability.
Distinguish three categories of information:
Conversation context contains user requirements, model decisions, and tool feedback. Its primary purpose is to support the current inference.
Task state contains the current phase, pending items, authorization results, and execution progress. It supports scheduling and recovery.
Business facts contain confirmed data and its sources. Keeping them separate helps prevent model speculation from becoming a persistent fact.
As context grows, completed steps can be compressed. However, key constraints, source identifiers, unresolved questions, and actions awaiting confirmation must be preserved. Automatic summaries can omit information, so fields involving permissions, money, or critical business state should rely on structured records.
Resuming a task should involve more than resending the old conversation to the model. First verify which tool operations actually completed, which results remain unconfirmed, and whether the necessary permissions still apply.
7. Failure Recovery: Retries Are Not Always Safe
Both model requests and tool calls can fail, but different failures require different responses.
Temporary network problems or brief service outages may justify limited retries within the available budget, with delays between attempts. Invalid arguments, denied permissions, and unmet business conditions usually will not improve by repeating the same request.
Write-operation timeouts require particular care. A missing response does not mean the operation failed to execute. Retrying immediately may submit the same operation twice.
Operations with side effects should therefore use business-appropriate idempotency identifiers, operation records, or status-query mechanisms. Before retrying, determine whether the previous operation already completed.
The system should also detect unproductive loops. Examples include repeatedly calling the same tool without obtaining new information or repeatedly proposing the same invalid arguments. Stop, ask for clarification, or hand the task to a human rather than continuing to consume the budget.
8. Security Boundaries: External Content Is Data, Not Instructions
Documents, search results, and tool responses can contain manipulative text. A retrieved passage might tell the system to ignore its rules, invoke additional tools, or disclose sensitive information.
Entering the model’s context must not automatically give such content instructional authority.
Establish clear engineering boundaries:
- Organize system constraints, user goals, and external material separately.
- Expose only the tools and data scope required for the task.
- Perform independent authorization in the execution layer.
- Require confirmation for sensitive write operations.
- Apply appropriate sensitive-data handling to outputs and logs.
Prompts can help the model understand these boundaries, but they cannot replace programmatic access controls. Even if the model follows a malicious external instruction, the execution layer should block unauthorized actions.
Audit records also need protection. Logging every request body may simplify debugging, but it can increase exposure of sensitive data. Prefer necessary fields and define access permissions and retention periods.
9. Evaluation: Fluent Answers Are Not Enough
Agent quality depends on correct actions, not just readable output.
Test cases should cover normal tasks, missing information, empty tool results, permission denials, API timeouts, duplicate-execution risks, and malicious external content.
Useful evaluation measures include:
- Task success rate: whether predefined completion criteria are met.
- Tool-selection accuracy: whether the appropriate capability is selected.
- Argument validity: whether arguments are valid and appropriate.
- Unauthorized-action blocking: whether disallowed actions are correctly rejected.
- Average call count and completion time.
- Recovery correctness after interruption.
- Rate of human intervention.
Evaluation criteria should preferably come from business outcomes rather than model self-assessment alone. For tasks requiring citations, verify that conclusions are supported by sources, not merely that the answer appears complete.
Use controlled tool mocks for regression tests so that routine testing does not modify real business data. Before release, validate the system in a restricted environment and expand its task scope gradually.
10. When Does a Custom Implementation Make Sense?
A custom implementation is often valuable when task boundaries are stable, tools are few, and the team needs precise control over execution. It can remove unnecessary abstractions and align permission logic, state transitions, and error handling directly with business requirements.
As parallel execution, long-running task recovery, complex dependencies, and many collaborating roles enter the design, the custom orchestration layer becomes an infrastructure component that needs ongoing maintenance. Teams should evaluate that commitment, not just how quickly they can write the first few hundred lines.
A practical path is to:
- Use fixed workflows for deterministic steps, then introduce model decisions at a few key points.
- Start with read-only tools, then gradually add confirmed write operations.
- Establish evaluation and auditing before expanding autonomous execution.
This allows complexity to grow with actual needs rather than starting with an overly general system.
Conclusion
Building an AI agent without a framework is technically viable. A custom implementation, however, is not automatically simpler, cheaper, or more reliable.
System quality depends on keeping model uncertainty within manageable boundaries: clear tool contracts, program-enforced permissions, recoverable state, auditable operations, and safe termination when failures occur.
A reliable agent is not a loop that lets a model act freely. It is a system that allows the model to participate in decisions while engineering controls retain authority over execution.
