Engineering AI Agents: Tool Calling, Memory, and Long-Running Tasks
This article outlines practical engineering patterns for LLM-driven agent systems. It covers the core components of an agent, controlled tool invocation, context and memory management, checkpoint-based recovery for long-running tasks, common application scenarios, and production design principles such as least privilege, human confirmation, observability, evaluation, and fallback planning.
1. Basic Components of an Agent System
An agent system is a software system driven by a large language model that can autonomously break down tasks around a goal, call external tools, and adjust its actions based on feedback. Unlike one-off question answering, an agent maintains state across multiple steps until the task is complete or a stopping condition is triggered.
From an engineering perspective, a usable agent usually consists of four parts. The model reasoning layer understands the goal and generates decisions. The tool layer encapsulates access to external systems, such as file read/write, API calls, and database queries. The state and memory layer stores task progress and historical information. The orchestration layer controls loop counts, retry strategies, and termination conditions. The clearer the boundaries among these four parts, the easier the system is to debug and the easier it is to replace an individual component.
2. Tool Calling: Turning Model Decisions into Controlled Actions
Tool calling is the only channel through which an agent interacts with external systems, which also makes it the most risk-concentrated part. Three principles should guide its design.
First, tool interfaces must have explicit input schemas and output structures. Parameters generated by the model need to be validated and must not be passed directly to the execution layer. Second, tools should be split by function. If the granularity is too coarse, permissions become difficult to constrain; if it is too fine, the model faces a heavier burden when selecting tools. Third, every call should leave a log, including call time, parameter summary, returned result, and elapsed time, to support later auditing.
The following is a generic tool-calling flow:
def run_tool_call(call, registry, policy):tool = registry.get(call["name"])if tool is None:return {"error": "unknown_tool"}if not policy.allows(tool.name, call["args"]):return {"error": "permission_denied"}validated = tool.schema.validate(call["args"])try:result = tool.run(**validated)except TimeoutError:return {"error": "timeout"}audit_log.write(tool.name, validated, result)return {"result": result}
This code reflects three key steps: first check whether the tool exists and whether the call is permitted, then validate the parameters, and finally record an audit log. The model’s output should not be trusted by default at any step.
3. Context Management and Memory Mechanisms
During long tasks, an agent continuously accumulates tool return values, intermediate conclusions, and user feedback. The context window has limited capacity. Without management, key information from earlier stages can be pushed out of the window, while irrelevant content can interfere with later decisions.
A common approach is layered handling. Short-term context retains the instructions required for the current step and the most recent interactions. Mid-term state is stored as structured summaries, such as completed subtasks, items awaiting confirmation, and the location of key data. Long-term memory is stored in external storage and retrieved on demand. Retrieval should combine relevance ranking with time decay to prevent outdated information from outweighing new constraints.
Context editing is another common technique. When a tool returns a large volume of raw data, the original text can be replaced with a summary, or intermediate results that are no longer needed can be removed. This saves window space and reduces interference from irrelevant content.
Memory content also needs governance. Content involving personal information or sensitive business data should have retention periods and support on-demand deletion. Treating memory as ordinary cache and writing to it freely is a common hidden risk in enterprise deployment.
4. Long-Running Task Execution and State Recovery
The longer a task runs, the more likely it is to encounter unexpected situations such as network jitter, API rate limiting, and permission changes. Long-running tasks should be split into independently verifiable stages, and a checkpoint should be written after each stage. After a failure, execution should resume from the most recent checkpoint rather than starting over from the beginning.
A concrete implementation can follow these ideas:
- Define the task as an ordered list of steps, with explicit completion criteria for each step.
- Record state snapshots before and after each step to make it easier to trace where a problem occurred.
- Use exponential backoff for retryable errors and move non-retryable errors to a manual handling queue.
- Set upper limits on total elapsed time and total call count to prevent loops from consuming excessive resources.
5. Typical Application Scenarios
Automated workflows are the easiest place to start, such as ticket classification, report generation, and data cleaning. The rules in these scenarios are relatively clear, making them suitable for initial pilots.
Enterprise productivity scenarios include meeting-notes organization, document retrieval and question answering, and cross-system information aggregation. The focus here is permission isolation and data masking, ensuring that the agent can only access content that the current user is authorized to view.
UI operation tasks refer to an agent completing work in a graphical interface through simulated actions. The reliability of such tasks is easily affected by interface changes. It is advisable to run them in an isolated environment and require secondary confirmation for critical operations.
Batch resource management refers to using orchestration capabilities to create, configure, and deploy cloud services in batches. Such tasks should be incorporated into the review process for infrastructure as code, so that the agent does not directly obtain write permissions for production environments.
6. Key Design Principles for Production Deployment
Least privilege is the first principle. Each agent should have only the minimum set of permissions required to complete its task, with read-only and write permissions separated.
Human confirmation is used to constrain irreversible operations. Operations such as deleting data, releasing versions, transferring funds, and sending external messages must be executed only after explicit human confirmation.
Observability requires recording input/output summaries for each reasoning step, tool-call chains, elapsed time, and cost, and setting alert thresholds for abnormal metrics. These data can be integrated into an enterprise’s existing logging and monitoring systems.
The evaluation system needs a fixed test set for typical tasks, measuring task completion rate, error-type distribution, and average number of steps. Regression tests should be rerun whenever the model version is changed or the prompt is modified.
Fallback plans ensure that the system remains controllable when dependencies are unavailable. When the model service or a tool is unavailable, the system should queue tasks and prompt for human takeover rather than failing silently.
7. Availability and Service Dependencies
Agents depend heavily on upstream model services. Once the service is interrupted, all businesses that rely on it are affected. The industry has seen global service outages lasting more than a day, showing that the risk of a single dependency is real.
From an architectural perspective, this can be addressed in three ways. First, set timeouts and circuit-breaker mechanisms for model calls to prevent request pileups from bringing down the entire system. Second, retain fallback paths in critical processes that do not depend on the agent, such as manual tickets or a rules engine. Third, evaluate the feasibility of alternatives in advance and clarify the switching conditions and the functional scope after switching.
8. Practical Recommendations
It is advisable to start with a single scenario that has clear boundaries and quantifiable results. In the initial phase, expose only read-only tools, and gradually enable write capabilities after stability has been validated.
Expand usage only after an evaluation set and regression process have been established. At the same time, the agent should be treated as a service that requires ongoing operations rather than a one-time deployment script. The team needs to assign an owner, regularly review failure cases, and turn the review findings into new test cases.
