LLM Agents: From Q&A Tools to Autonomous Task Execution
This article explains how large language model applications are evolving from simple question-answering tools into agents that can autonomously execute multi-step tasks. It covers the five core components of a working agent, a reproducible methodology for measuring agent accuracy, key engineering practices for production deployment (tool interface design, sandboxing, human confirmation, observability), a reference implementation of an execution loop with termination conditions and confirmation gates, and common risks such as hallucinated tool calls, infinite loops, context bloat, and error accumulation, along with mitigation strategies for each.
1. From Answering Questions to Completing Tasks
Over the past two years, most LLM applications have remained at the question-answering level: a user submits a question, the model returns a text answer, and the task ends inside the chat window. More recently, the industry’s focus has shifted toward a different class of application: the model receives a goal, breaks it down into steps on its own, calls external tools, reads the returned results, and adjusts its next action based on those results until the task is complete. Systems of this kind are commonly called agents.
The key change in this transition is that the model’s output shifts from “a piece of text” to “a sequence of executable actions.” For example, if a user asks the system to organize a week of customer tickets and produce a weekly report, the system must first query ticket data, then aggregate it by category, and finally generate a document and send it to the relevant people. Each step depends on the result of the previous one, and an error at any step affects the final deliverable.
Evaluation criteria change accordingly. Simply comparing model scores on knowledge QA or language understanding benchmarks no longer reflects real business performance. Developers care more about: whether the model can reliably complete multi-step tasks, whether it can select the right tools and parameters, whether it can recover from errors, and whether the overall cost and latency are acceptable.
2. Core Components of an Agent
A usable agent typically consists of the following components. Missing any one of them can cause the system to fail in complex scenarios.
1. Goal understanding and planning
The model must convert a natural-language goal into an executable sequence of subtasks. Good planning ability shows up in three ways: it can recognize implicit constraints in the goal, such as time ranges, data definitions, and output formats; it can determine which subtasks can run in parallel and which must run sequentially; and it can revise the plan when intermediate results do not match expectations, rather than mechanically executing the original steps.
2. Tool definition and invocation
Tools are the agent’s only channel for interacting with the outside world. Every tool needs a clear name, a functional description, parameter definitions, and a return format. The more accurate the description, the lower the probability that the model picks the wrong tool. Common tool categories include database queries, file read/write, web or API requests, message sending, and code execution.
3. Memory and state management
In multi-step tasks, the system must track completed steps, retrieved data, and current progress. Short-term state can live in the conversation context; long-term or cross-session information requires external storage, such as a relational database or a key-value store. The core principle of state design is: write key facts into structured storage instead of relying entirely on the model’s memory of conversation history, because the longer the context grows, the higher the risk of information loss and confusion.
4. Execution and feedback loop
An agent runs as a loop: the model decides an action, the system executes it, the result is returned to the model, and the model decides the next step. The loop must have termination conditions, including a maximum step count, a timeout, a budget cap, and an explicit completion signal. Without these limits, the model may repeatedly call the same tool down a wrong path, wasting resources.
5. Security and permission control
Because agents can invoke tools, permission design matters far more than in a plain Q&A system. Read and write operations should be managed separately. Write operations, financial operations, and externally visible actions (such as sending messages) should require human confirmation. Tool credentials should be assigned following the principle of least privilege and bound to specific tasks, avoiding a single credential that covers all resources.
3. How to Measure Agent Accuracy
“Accuracy” figures published by different teams are often not directly comparable, usually because the test tasks, tool environments, and scoring criteria differ. To determine whether a model or approach is genuinely more reliable in agent scenarios, you need reproducible evaluation under identical conditions.
1. Build a fixed test set
The test set should cover typical tasks from real business scenarios, including simple tasks, multi-step tasks, and tasks containing exceptions. In terms of scale, a few hundred samples is a reasonable minimum, stratified by difficulty and task type. Each sample needs a clearly defined input goal, available tools, expected outcome, and scoring method.
2. Unify the runtime environment
Tool response data, timeout settings, and retry policies must be identical across all systems being compared. Otherwise, performance differences may come from the environment rather than model capability. For models with inherent randomness, run the same task multiple times and measure the variance in success rate.
3. Break down the evaluation metrics
Using only “task completed or not” hides many problems. It is recommended to record the following metrics as well:
- Task completion rate: does the final result meet the acceptance criteria;
- Tool selection accuracy: whether each call selected the correct tool;
- Parameter correctness: whether tool parameter types, values, and definitions are correct;
- Wasted-step ratio: the proportion of repeated calls, meaningless queries, and similar steps;
- Average step count and failure recovery rate: how many steps a task takes on average, and whether the agent can correct itself after errors;
- Per-task cost and latency: including model invocation fees, tool call overhead, and end-to-end latency.
4. Distinguish correct results from correct processes
Some tasks end with the correct answer by coincidence while the intermediate steps contain errors—for example, a misread data field that happens to yield the same number. Key intermediate results should be checked during evaluation; otherwise, these errors will surface in production under different inputs.
4. Key Engineering Practices for Production Deployment
1. Tool interface design
Tool granularity directly affects success rates. If the granularity is too coarse, parameters become complex and the model fills them in incorrectly; if it is too fine, completing one task requires a large number of calls, lengthening the chain and accumulating errors. A common practice is: design read operations around business entities—for example, query tools per order, user, or ticket; design write operations separately, explicitly requiring a business document ID and an operation reason in the parameters.
Tool return values should also be structured. Stable field names, clear semantics, and readable error messages help the model make correct decisions in the next turn. If the return value is a large block of unstructured text, the model can easily miss key information.
2. Sandboxing and isolation
Agents that involve code execution or file operations should run in isolated environments. Isolation should cover the file system, network access, process resources, and system permissions. Outbound network access should be governed by a whitelist to prevent the agent from being guided to untrusted addresses and leaking data.
3. Human confirmation
For irreversible or high-impact operations—such as deleting data, modifying prices, sending external emails, or changing permissions—human confirmation should be required before execution. The confirmation UI needs to display the operation target, the changes, and the scope of impact, rather than just a one-sentence summary generated by the model.
4. Observability
The agent’s execution should be fully logged: the input of each turn, model output, tool calls, returned results, latency, and cost. Logs are the foundation for troubleshooting and for optimizing prompts and tool descriptions. Logs should be routed to a logging service, with monitoring alerts for abnormal thresholds—for example, too many consecutive failures, a task exceeding its step limit, or abnormal cost growth.
5. Example Code: An Execution Loop with Termination Conditions and a Confirmation Mechanism
The following code shows the basic structure of an agent execution loop. The model invocation is abstracted as a function; in a real implementation it can be replaced with any model service that follows the interface contract.
import jsonTOOLS = {"query_order": {"description": "Query order status by order ID","params": ["order_id"],"readonly": True,},"refund_order": {"description": "Initiate a refund for a specified order","params": ["order_id", "amount"],"readonly": False, # write operation, requires human confirmation},}def dispatch(name, args):"""Actual tool dispatch logic: call the corresponding business API by tool name."""raise NotImplementedErrordef run_agent(goal, llm, max_steps=8, confirm=None):"""goal: user goal textllm: model call function returning {"tool": name, "args": params} or {"final": result}confirm: human confirmation function; returns True to allow a write operation"""history = [{"role": "user", "content": goal}]for _ in range(max_steps):action = llm(history, list(TOOLS))if "final" in action:return action["final"]name, args = action.get("tool"), action.get("args", {})if name not in TOOLS:history.append({"role": "system", "content": f"Unknown tool: {name}"})continuespec = TOOLS[name]missing = [p for p in spec["params"] if p not in args]if missing:history.append({"role": "system", "content": f"Missing parameters: {missing}"})continueif not spec["readonly"]:if confirm is None or not confirm(name, args):history.append({"role": "system", "content": "Write operation not confirmed, skipped"})continueresult = dispatch(name, args)history.append({"role": "tool", "content": json.dumps(result, ensure_ascii=False)})return "Maximum step count exceeded; task not completed"
This code has three design points worth noting. First, the tool table centrally declares parameters and read/write attributes, making auditing and permission management easier. Second, parameter validation happens before invocation, and error messages are written back to the model so it has a chance to correct itself. Third, write operations must pass the confirmation function; when confirmation is absent, they are not executed, and the reason for skipping is communicated to the model so it does not repeatedly attempt the same operation.
6. Common Risks and Mitigations
1. Hallucinated calls
The model may call tools that do not exist or fabricate parameter values. Mitigations include: strictly validating tool names and parameter types at the system level; providing enumerated values or format constraints for critical parameters; and double-checking key fields in returned results.
2. Loops and repetition
When a tool returns unexpected results, the model may repeat the same call. Besides setting a maximum step count, you can record the signatures of historical calls; when the same tool with the same parameters appears consecutively, force an interruption and hand off to a human.
3. Context bloat
As the number of steps grows, the history becomes longer, the model’s attention is diluted, and key early information is easily overlooked. It is recommended to summarize or trim tool outputs and write confirmed facts into structured state, putting only the necessary information into the context each turn.
4. Error accumulation
In multi-step tasks, a small error in an earlier step affects every subsequent step. Setting validation rules at critical checkpoints—for example, whether a total amount matches its line items, or whether a time range falls within a reasonable interval—helps catch problems early and reduces wasted execution.
5. Data and privacy
Agents read large volumes of business data. Sensitive fields should be masked at the tool layer, the scope of sensitive information visible to the model should be restricted, and externally transmitted data should be encrypted and access-audited.
7. Conclusion
Agents extend LLM capability from text generation to task execution, which raises both their value and their risk. When judging whether an agent solution is reliable, do not rely on a one-off demo or a single advertised number. Instead, evaluate task completion rate, tool-call correctness, step efficiency, and cost under a unified test set and runtime environment—and implement solid engineering practices around tool design, permission isolation, human confirmation, and end-to-end logging. Only with these foundations in place can the system run reliably in real business scenarios.
