Autonomous Agent Development in Practice: Runtime Architecture, Tool Execution, and Production Rollout
This article examines how to move from large language model applications that generate answers to autonomous agents that execute tasks reliably. It covers the core runtime architecture, tool-call interface design, task loops, context assembly, long-term memory, skills, retrieval, secure execution, multi-agent collaboration, and two practical examples for code maintenance and research. It also outlines evaluation metrics and a progressive rollout path from read-only observation to limited autonomy, with an emphasis on controlled permissions, traceable evidence, bounded execution, and verifiable acceptance criteria.
1. From “Model Answers” to Task Execution Systems
The key difference between a large language model application and an autonomous agent system is whether the system forms a reliable execution loop. A standard conversational application mainly transforms input into output. An agent must also observe the environment, select tools, execute actions, inspect results, and adjust the next action when conditions change.
For example, “analyze test failures in a project and propose a fix” is not a pure text-generation task. The system needs to read relevant files, obtain test results, identify possible causes, generate modification suggestions, and then verify whether those suggestions are effective. Without state management, permission control, and result validation, a model may produce a plausible explanation without actually completing the task.
Therefore, the engineering goal of an agent should be defined as:
Complete a task with clear acceptance criteria through a limited number of actions, within a controlled environment, based on traceable evidence.
This goal contains four important constraints:
- Controlled environment: Actions must comply with permission, resource, and data-use rules.
- Traceable evidence: Key judgments can be linked to files, tool results, or retrieved materials.
- Bounded actions: Execution steps, time, and cost cannot grow without limit.
- Verifiable acceptance: Task completion cannot rely solely on the model’s own claim.
During development, define the task boundary and acceptance conditions first, then choose models and tools. Do not start by granting broad capabilities and add safety restrictions only at the end.
2. Runtime Architecture: Separate Reasoning, Execution, and State
A general agent runtime can be divided into six cooperating modules.
2.1 Task Entry and Session Management
The task entry point receives the goal, input materials, user identity, and execution constraints. Session management maintains task state across different stages and supports pause, resume, cancellation, and auditing.
It is important to distinguish “conversation history” from “task state.” The former records the communication process; the latter describes the current goal, completed steps, unresolved issues, and actions in progress. Saving only chat history does not guarantee that a task can be reliably resumed after an interruption.
A minimal task state can include:
Task IDTask goalAcceptance criteriaCurrent stageCompleted stepsOpen issuesAllowed toolsRemaining execution budgetAssociated evidenceActions pending approval
These fields are an illustrative internal design and do not correspond to any specific framework interface.
2.2 Model Inference Adapter Layer
The inference adapter layer assembles model input, processes model output, and distinguishes ordinary answers from tool-call requests. It should abstract differences in underlying model invocation methods so that task logic does not depend directly on a particular service implementation.
Model output should always be treated as a suggestion to be validated, not as inherently trusted execution instruction. This is especially important for external writes, deletions, and command execution, which must pass subsequent rule checks.
2.3 Tool Registry and Execution Layer
The tool layer provides capabilities such as file reading, restricted command execution, material retrieval, and network requests. Each tool should have a clear purpose, input constraints, output structure, and permission requirements.
Tool execution and model reasoning are best deployed separately, or at least separated by privilege. The model only proposes invocation requests. The execution layer determines whether a request is legitimate and how to complete the action in an isolated environment.
2.4 Context and Memory Layer
The context layer determines what information should be visible to the current round of reasoning. The memory layer stores information that is valuable across turns or tasks. The two should not be conflated: context is the material for the current decision, while memory is persistent knowledge that has been filtered and governed.
2.5 Policy and Security Control Layer
This layer handles tool permissions, approval rules, sensitive information protection, resource limits, and blocking of high-risk operations. Security policies should be enforced by the runtime, not written only in prompts.
2.6 Observability and Evaluation Layer
The system needs to record task state changes, tool calls, execution results, failure reasons, and resource consumption. The evaluation layer checks task results against acceptance rules rather than analyzing only whether the final answer is fluent.
3. Tool Calls: Interface Design Determines Execution Reliability
At its core, tool calling converts a model-generated action intention into constrained program execution. A reliable flow usually includes:
- The model proposes a tool name and parameters.
- The runtime validates whether the tool exists and whether the parameters meet requirements.
- The policy layer checks the permissions of the calling subject and the target object.
- The execution layer runs the tool and collects structured results.
- Results are returned to the task loop after necessary redaction.
- The agent decides whether to continue, retry, request assistance, or finish based on the results.
3.1 Parameters Must Be Strictly Validatable
Take file reading as an example. The interface should not accept only a free-text instruction. It should explicitly distinguish the path, read range, and size limit.
Tool: Read workspace fileInput:Relative path: required, must point only to an authorized workspaceStart position: optional, must be within the allowed rangeMaximum read size: optional, must not exceed the runtime limitOutput:Execution statusFile content snippetWhether truncation occurredVersion identifier or content digestError category
Path security checks cannot rely only on whether a string starts with a certain directory. They must also handle path normalization, directory traversal, and symbolic links. When necessary, an isolated environment should fundamentally limit the accessible range.
3.2 Tool Outputs Should Preserve Information Needed for Decisions
“Execution failed” is too vague to help the system recover correctly. More useful feedback includes:
- Invalid input: parameters need adjustment.
- Insufficient permission: approval or an alternative approach is needed.
- Resource not found: the path or object needs confirmation.
- Execution timeout: the task scope or strategy may need adjustment.
- Temporary failure: limited retries may be allowed within budget.
- Execution completed but verification failed: the problem needs to be analyzed again.
The clearer the error classification, the easier it is for the agent to make reasonable choices and for developers to troubleshoot.
3.3 Side-Effect Tools Must Not Be Retried Blindly
Reading a file can usually be repeated, but submitting changes, sending notifications, or writing to external systems may create duplicate side effects.
For such operations, design idempotency mechanisms or execution-status query capabilities. In particular, after a timeout, the system must not immediately assume the operation failed. The actual action may have completed even though the response did not return in time.
A safer approach is to confirm the result before deciding whether to retry. If the result cannot be confirmed, move the task to manual handling or a pending-verification state.
4. Task Loop: Let Observations Drive the Next Action
An agent task loop can be summarized as “observe—decide—execute—verify.” It does not imply unlimited attempts, nor does it require exposing the model’s internal reasoning process. The runtime should record auditable action rationale and results.
The following is an illustrative control flow:
Create task stateLoad execution policy and resource budgetWhile the task has not terminated:Check for cancellation requests, deadlines, and remaining budgetObtain current state and latest observationsSelect the context needed for this roundRequest the model to generate an answer or action proposalIf the proposal is to finish:Run acceptance checksIf passed, mark as completedIf not passed, record gaps and decide whether to continue or exitIf the proposal is a tool call:Validate parameters and permissionsWait for manual approval when necessaryExecute the tool and save resultsUpdate task stateCheck for repeated failures and lack of progressSave final state, deliverables, and audit records
4.1 Budgets Should Not Be Limited to Maximum Steps
A maximum step count only limits the number of calls. It cannot constrain the duration or impact of a single execution. In practice, set limits for total task duration, per-tool timeout, concurrency, output size, retry count, and compute resources.
These values should be determined by business risk and actual testing, not treated as a universal default set of numbers.
4.2 Detect “Busy but Not Progressing”
If the system repeatedly invokes the same tool, receives the same error, and adds no new evidence, continuing usually only increases cost.
Loops can be detected by normalizing tool parameters, recording error categories, and comparing state changes. When signs of no progress appear, the system should require a change of strategy, request more information, or terminate with a clear failure reason.
4.3 Terminal States Should Reflect Reality
At minimum, distinguish completed, partially completed, waiting for approval, intentionally cancelled, budget exhausted, and execution failed. This allows downstream systems to handle results correctly and prevents “generated a summary” from being mistaken for “task completed.”
5. Context Assembly: Keep Key Evidence, Not Accumulated History
Agent context usually comes from task instructions, runtime rules, tool definitions, recent conversation, tool results, retrieved materials, and long-term memory. Simple concatenation causes duplication, conflicts, and wasted budget.
A reasonable assembly order can be:
- Safety and runtime constraints.
- Current goal and acceptance criteria.
- Current task state.
- Tool descriptions available for this round.
- Evidence directly relevant to the current problem.
- Recent actions and observations.
- Necessary historical summaries.
This is a general organizing approach. The specific order still needs to be adjusted based on the model input mechanism and evaluation results.
5.1 Summaries Should Preserve Conclusions, Evidence, and Uncertainty
“Configuration has been analyzed” has almost no recovery value. An effective summary should state what was analyzed, what was found, what evidence supports it, and which questions remain unconfirmed.
For example:
Confirmed: The configuration file is readable and key fields are present.Evidence: Workspace file snippet and validation tool output.Unconfirmed: Whether the runtime environment overrides the configuration in the file.Next step: Obtain a permitted summary of the runtime configuration.
This reduces repeated work and prevents unverified guesses from being treated as facts in later rounds.
5.2 External Content Must Not Be Promoted to System Instructions
Web pages, documents, code comments, and tool outputs may contain persuasive instructions. The runtime should explicitly mark source and trust level and treat external content as data to be analyzed, not as authorization.
Reminders in prompts are only auxiliary measures. Real protection still depends on tool permissions, output filtering, and approval for high-risk actions.
6. Long-Term Memory, Skills, and Knowledge Retrieval
These three capabilities can all reduce repeated work, but they have different responsibilities.
6.1 Long-Term Memory Stores Stable Information
Long-term memory is suitable for confirmed user preferences, project constraints, and common handling experience. Each record should include source, scope, update time, and validity status where possible.
Temporary speculation from a task should not be written directly into long-term memory. Memory also needs deletion, correction, access control, and cross-task isolation so that outdated conclusions do not continue to affect later decisions.
6.2 Skills Encapsulate Reusable Workflows
A skill is not a prompt without boundaries. It should include applicable conditions, input requirements, steps, tool dependencies, acceptance rules, and failure handling.
For example, a “analyze test failure” skill can first collect failure summaries, then filter relevant files, propose candidate causes, make minimal changes, and finally verify. For known and stable processes, deterministic programs can control the flow. For steps that require semantic understanding, the model can be used.
6.3 Retrieval Augmentation Provides Citable Evidence
Knowledge retrieval usually includes document parsing, segmentation, indexing, recall, ranking, and answer generation. The real difficulty is not finding similar text, but finding evidence applicable to the current problem.
Engineering concerns include:
- Whether document permissions are enforced during retrieval and result return.
- Whether versions and applicability conditions are preserved.
- Whether duplicate or conflicting materials are identified.
- Whether answers can be linked to clear sources.
- Whether the system is allowed to refuse conclusions when evidence is insufficient.
Retrieved content is also untrusted input. It should not skip security checks simply because it comes from a knowledge base.
7. Secure Execution and Multi-Agent Collaboration
7.1 Command Execution Should Follow Least Privilege
An agent with command execution capability should not directly receive broad access to production environments. A more reasonable approach is to execute in temporary workspaces and isolated environments with restrictions on readable and writable directories, network access, process count, and resource usage.
Credentials should not enter the model context. When access to protected resources is required, it should be completed through a controlled execution layer with limited authorization scope and validity period.
Actions such as deleting data, modifying production configurations, and publishing content externally should have separate approval and audit processes.
7.2 Multi-Agent Systems Should First Solve Responsibility Division
Multiple agents are not inherently more reliable than a single agent. Collaboration can increase context-transfer costs, amplify errors, and cause duplicate execution.
Suitable division of labor includes planning, execution, and verification, but each role should hand off work through a clear task contract:
Subtask goalInput materialsAllowed operationsOutput requirementsEvidence requirementsCompletion conditionsFailure handling
Shared state also requires version checks or concurrency control to prevent different executors from modifying the same resource at the same time. Adding collaborative roles is more valuable only when subtask boundaries are clear and can be accepted independently.
8. Practice 1: Building a Code Maintenance Agent
A code maintenance task should aim for “verifiable changes” as the deliverable, not the number of files modified.
8.1 Define Scope and Acceptance Criteria
At the start of the task, confirm the directories that may be modified, files that must not be touched, the problem description, and the verification method. If information is incomplete, obtain key constraints first rather than immediately performing large-scale refactoring.
8.2 Observe First, Then Form Hypotheses
The system first reads relevant code and failure logs, forms candidate causes, and seeks evidence for each one. Unverified judgments should remain hypotheses and not be solidified into facts in later steps.
8.3 Make Minimal Changes in an Isolated Workspace
Changes should focus on the problem itself, preserve a diff record, and avoid overwriting new changes that appeared after the task began. Checking file versions before execution can reduce concurrent editing conflicts.
8.4 Use Layered Verification
Verification can cover syntax and static checks, relevant tests, regression tests, and business acceptance criteria in sequence. Passing one check only proves that no problem was found within the corresponding scope; it does not automatically prove that all behavior is correct.
The final report should list the modification scope, completed verification, unexecuted checks, and remaining risks. When verification cannot be run, state this clearly and do not describe the fix as confirmed.
9. Practice 2: Building a Research Agent
The core of research is to manage sources, facts, inferences, and conclusions separately.
First, split the research goal into several verifiable questions and clarify the time range, material types, and deliverable format. Then retrieve materials, record sources, publication dates, and acquisition times, and extract evidence directly relevant to the questions.
For conflicting information from different sources, examine definitions, versions, statistical methods, and applicability conditions rather than simply choosing the claim that appears most often.
The final report should distinguish:
- Facts supported by direct evidence.
- Analysis formed from multiple pieces of evidence.
- Inferences that still lack sufficient evidence.
- Questions that cannot currently be answered.
Long-running research tasks should also save a staged evidence catalog and a list of open questions. When resuming execution, first check whether materials have been updated rather than mechanically rerunning all retrieval steps.
10. Evaluation and Launch: From Demo to Operations
Before an agent goes live, build a test set covering normal tasks and exception paths, including permission denial, tool timeout, missing input, malicious content, execution interruption, and recovery.
Key metrics can include task success rate, manual takeover rate, invalid call ratio, evidence coverage, error recovery, latency and cost, and the effectiveness of security policy interception. Different businesses prioritize these metrics differently; final answer quality alone is not enough.
A progressive rollout is recommended:
- Read-only observation stage: Analyze and retrieve only, with no external writes.
- Suggestion stage: Output plans for humans to implement.
- Controlled execution stage: Allow low-risk actions and require approval for critical actions.
- Limited autonomy stage: Automatically complete the loop within validated task scopes.
During operation, retain records of task state changes, tool calls, approvals, and acceptance checks, and redact sensitive information. Observability is not an add-on feature; it is the foundation for diagnosing failures, controlling risk, and improving continuously.
Conclusion
A reliable autonomous agent is a task execution system composed of models, state, tools, evidence, and security policies. The key to development is not giving the model more permissions, but establishing clear action boundaries, structured feedback, and verifiable completion standards.
Starting with single tasks, read-only tools, and clear acceptance criteria, teams can gradually introduce state recovery, context governance, controlled writes, and collaboration mechanisms. This allows the system to remain explainable, auditable, and maintainable as complexity grows. An agent delivers real production value only when its task process is constrained and its deliverables are verified.
