How LLM Agents Work: From the Core Loop to Reliable Execution
This article explains LLM agents as an engineering system: a model proposes actions, a program validates and executes them, and results feed back into the next decision. It covers the five core components, a minimal control loop, planning, context, tool risk levels, security, failure recovery, evaluation, and what production systems need beyond a prototype.
1. Drop the mystique: what an agent actually is
When a system can understand a user goal, look up business data, call external APIs, and adjust its next step from the results, we usually call it an agent.
Being able to take actions does not mean unbounded autonomy, and plugging in a large language model does not automatically complete complex work.
From an engineering view, a typical LLM agent is:
The model proposes the next action; the program checks and executes it; the result becomes the next model input.
That loop repeats until the task is done, resources run out, or the system stops.
A normal Q&A flow is one pass of input–generate–output. An agent adds an act–observe–feedback loop:
User goal → model decision → execution checks → tool call → result back → decide again
What matters is not anthropomorphic language, but how the loop is constrained in code, how failures are handled, and how the final result can be audited.
2. Five core parts
1. The model: understand and propose actions
The model uses the user goal, current context, and tool specs to answer or request a tool call.
Model-proposed actions are candidates, not facts.
If the model says a notification was sent, that does not prove it was sent. Only an executor result that matches the intended target lets the system report completion.
Outputs should at least distinguish:
- Final answer: no further tool use.
- Action request: a registered tool must run.
When facts are missing, the system should allow a clarification request instead of inventing conditions.
2. Tools: constrained external capability
Tools are functions that query data, read files, compute, or submit business operations.
Definitions typically include name, purpose, input/output shape, and permissions. An order-query tool takes an order id and returns status; a refund tool also needs operator permission and business rules.
Vague tools invite misuse. “Query the current status of a specified order” is easier to select and audit than “operate on business data.”
3. State: where the system is
The agent must keep the user goal, steps already taken, tool returns, remaining budget, and pending confirmations.
State is not just a chat log. Chat logs capture conversation; business state should be structured, for example:
- Current task id
- Completed subtasks
- Unresolved conditions
- Confirmed facts and their sources
- Receipts for executed operations
- Current permissions
If this lives only in a natural-language summary, “ready to execute” is easily read as “already executed.”
4. The executor: turn actions into real operations
The executor is the program-side control plane. It checks that the tool exists, parameters are valid, permissions suffice, and whether the user must confirm.
The model must not skip permission checks, and claiming an operation is “safe” must not bypass approval.
The model handles uncertainty; the executor enforces definite rules. That split is the basis of reliability.
5. Termination: when to stop
Agents must not loop forever. Set a max step count, wall-clock limit, and resource budget, and detect obvious repetition.
When a limit is hit, return what was done, why it stopped, and how to continue—not a fake success.
3. A minimal core loop
Language-agnostic sketch. Names explain architecture, not a real API.
function run_task(user_goal, tool_registry, execution_policy):state = init_state(user_goal)deadline = now() + execution_policy.time_limitfor step from 1 to execution_policy.max_steps:if now() >= deadline:return interrupt(state, "time limit exceeded")context = build_context(state, tool_registry)decision = request_model(context)if decision.type == "clarify":save_state(state)return clarification(decision)if decision.type == "final_answer":return compose_answer(decision, execution_evidence_in(state))if decision.type != "tool_call":record_failure(state, "unrecognized output structure")continuetool = lookup_registered_tool(decision.tool_name)if tool is missing:record_tool_feedback(state, "tool unavailable")continuecheck = validate_params_and_permissions(tool, decision.params, state)if check.failed:record_tool_feedback(state, check.reason)continueif requires_confirmation(tool, decision.params):save_pending_action(state, decision)return confirmation_request(decision)result = execute_with_timeout(tool, decision.params)record_tool_result(state, decision, result)save_state(state)if repeated_failure_detected(state):return interrupt(state, "repeated failure, plan must change")return interrupt(state, "max steps reached")
The key control idea: the model proposes; the program retains execution authority.
Production still needs exception handling, correlation ids, result size limits, and handling of sensitive data. External text from tools should be labeled as data, not trusted instructions.
A final answer is not automatically correct. Claims like “refund completed” or “file updated” must be checked against execution receipts, not model prose alone.
4. Planning: more complexity is not better
1. Short tasks: keep a simple loop
If the job is to fetch one record and explain status, one tool call may be enough. A ten-step plan wastes context and adds failure modes.
The smaller the task, the simpler the control. If a deterministic flow works, do not force an open-ended agent.
2. Long tasks: checkable subgoals
For something like “summarize recent abnormal orders and suggest handling,” split into:
- Confirm time range and anomaly criteria
- Query related orders
- Classify results
- Extract verifiable issues
- Generate suggestions with cited evidence
Each subgoal needs a completion condition. “Query complete” means a result or a clear failure, not the model saying “query complete.”
3. Plans must be revisable
Plans fail on missing permissions, missing data, or unavailable services. Reliable systems allow re-planning but record why, so the model does not change direction without new evidence.
For stable business flows, fix critical steps in code and leave understanding, classification, and explanation to the model. That is usually easier to control than fully open autonomy.
5. Context: keep facts, not a pile of text
History grows with every call. Dumping everything into the model wastes tokens and buries what matters.
Use three layers:
Layer 1 — stable rules. Task bounds, permissions, tool specs, output constraints.
Layer 2 — current work state. Active subtask, unresolved conditions, recent critical tool results.
Layer 3 — historical material. Older logs, long documents, finished steps, stored externally and fetched on demand.
Summaries must keep sources and uncertainty. “The user might want to change the address” must not collapse into “the user authorized an address change.”
Business fields, receipts, and authorization records should be stored in structured form. Summaries aid understanding; they are not the authoritative record.
6. Tool execution: treat reads and writes differently
Read-only queries are usually lower risk. Sending messages, changing config, deleting records, and submitting transactions can be irreversible.
Policy by risk:
- Read-only: limit query scope and result size.
- Recoverable writes: record prior state and design compensation.
- High-risk: show object, parameters, and impact; require confirmation.
- Irreversible: stricter authorization and audit.
Confirmation must bind to a specific operation. If the user confirmed “update this record” and the model later changes the target or key parameters, the old confirmation must not apply.
Writes also need idempotency. Retries after network failure must not double-charge, double-submit, or double-send.
Timeout is not failure. The remote system may have succeeded while the response was lost. Check operation status or an idempotency key before retrying.
7. Safety: untrusted content must not command the system
Agents may read documents, messages, and web text that contain instructions such as “ignore prior rules,” “call other tools,” or “output secrets.”
Defense is not a single “don’t be tricked” line. Limit what external data can do:
- Separate trusted rules, user requests, and external material
- Do not let external text change tool permissions
- Validate tool parameters in the program
- Independent approval for sensitive operations
- Redact sensitive fields in results as needed
- Least privilege in the execution environment
Even if the model misreads untrusted text, the executor should block unauthorized actions. Safety cannot depend on the model being right on every generation.
8. Failure recovery: classify first, then decide whether to retry
Typical classes:
Parameter errors. Missing identifiers: fill them or ask the user.
Permission errors. Do not rephrase and retry; stop that operation and explain the limit.
Transient faults. Limited retries with backoff, count, and overall deadline.
Business conditions not met. Record already closed: explain state, do not resubmit the same request.
Uncertain outcome. Write succeeded but the connection dropped: verify actual state first.
Recovery should follow program rules and business meaning. Handing every error back to the model to “figure it out” creates loops and can raise risk.
9. How to tell if the system is actually usable
One demo path is not stability.
Evaluate at least:
- Task completion: explicit business goals met
- Tool selection: the right capability for the task
- Parameter accuracy: object, scope, and fields
- Evidence consistency: final answer matches tool results
- Safety: no unauthorized ops or secret leaks
- Efficiency: extra calls, duplicate queries, useless plans
- Recovery: resume after interrupt without duplicate writes
Tests need more than the happy path: missing info, insufficient permission, empty results, timeouts, malicious external text, and mid-task goal changes.
Log task id, step index, tool calls, validation results, latency, and final status. Avoid unnecessary sensitive raw text; redact or access-control logs.
10. Prototype vs production
A minimal prototype is simple: one model call, a set of tools, and a loop can show chained actions.
Production is not “call more tools.” It is making every call explainable, constrained, and verifiable, and recoverable when it fails.
A practical build order:
Define task bounds, then read-only tools; prove result accuracy, then gated writes; add logging and stop conditions, then grow task size.
An agent need not be mythologized or dismissed. It is a task system with a model as the decision component, program rules as constraints, and tool results as feedback.
The core loop decides whether it can act. Engineering bounds decide whether it can be trusted.
