AI AgentsLangChain

How does the LangChain create_agent execution loop work?

Question 284 of 324 · Updated

On this page

Direct answer#

LangChain's modern create_agent API constructs a stateful model-and-tool execution graph. On invocation, the runtime calls the selected chat model with the current messages and available tool definitions. If the resulting AIMessage contains tool calls, the runtime dispatches the requested calls, records their results as ToolMessages, and invokes the model again with the updated state. When the model returns a response without further tool calls, the ordinary model-tool loop can finish. Middleware, structured-output handling, interrupts, execution limits and errors can alter that path.

The application remains responsible for validating authorization, checking the business outcome, configuring budgets and persistence, and deciding what an unsuccessful or incomplete run means.

Earlier AI Agents lessons #5 and #30 explain the generic observe-decide-act cycle; #83 covers the general tool-calling mechanism; #267 covers outcome validation. The first three LangChain lessons cover installation, the architecture layers and framework adoption. This lesson specifically follows the message contract, state transitions and observable execution behavior of create_agent.

1. What is created when you call create_agent?#

A typical modern LangChain agent is configured with a chat model or model identifier, a collection of tools, instructions and optional middleware. Internally, the agent runs on LangGraph. The builder assembles an executable graph that coordinates the model, tool execution and state updates. You usually call invoke, ainvoke or a supported streaming interface on the resulting agent.

The configuration is not itself a task execution. A run begins when the caller supplies an input, typically a messages field containing a user message. The builder configuration and per-run state play different roles.

ComponentResponsibility
ModelGenerates an AIMessage containing text, tool calls or both
Tool definitionsDescribe the callable capabilities and their input schemas
Message stateRetains the conversation and observations used in subsequent model calls
Agent graphRoutes execution between model, tools and completion or other configured transitions
MiddlewareExtends or intercepts selected steps in the run
Runtime contextSupplies trusted application dependencies or context through supported mechanisms
CheckpointerOptionally persists state for a thread and supports recovery or continuation
ApplicationEnforces identity, authorization, domain invariants and acceptance criteria

Exact graph nodes and middleware internals may differ by version; the following is a conceptual explanation of the ordinary tool loop, not a fixed internal source-code graph.

Loading diagram…

The completion checks shown here represent application or configured runtime behavior; they are not a claim that create_agent automatically verifies external business outcomes.

2. State and message types#

The default agent interface centers on a message history. The message list is not just a transcript displayed to the user. It is part of the protocol used to pass observations and decisions between the model and runtime.

Message or fieldMeaning
HumanMessageUser input or other human-originated content
SystemMessage or system promptTrusted instructions supplied to the model
AIMessageModel-generated response, potentially containing tool requests
AIMessage.tool_callsParsed requests, typically with a name, arguments and an ID
ToolMessageThe observation produced for a specific requested tool call
ToolMessage.tool_call_idCorrelates that observation with the original tool request
messagesOrdered message state available to the agent
structured_responseA validated structured result when the configured response-format path provides it

The conceptual example below uses ordinary JSON-like values rather than serializing exact SDK classes.

JSON
{ "type": "ai", "content": "", "tool_calls": [ { "id": "call_01", "name": "lookup_order", "args": {"order_id": "A12"} } ] }

The corresponding observation must preserve the call correlation:

JSON
{ "type": "tool", "tool_call_id": "call_01", "content": "{\"status\":\"shipped\"}" }

A tool response may be represented using supported message content and metadata fields rather than precisely this JSON. The key invariant is the association between the requested action and the resulting observation.

A model message may contain multiple tool calls. A subsequent model request should receive the tool responses required by that provider's message protocol, including their IDs. Independent tool calls may execute concurrently depending on the runtime and configuration. Do not assume execution order equals response arrival order. Correlate by ID and preserve valid message sequencing.

For long conversations, context management may select or transform messages before model invocation. That is distinct from deleting durable task state. Trimming must preserve valid tool request/result groups, essential instructions, outstanding approvals and evidence required for the current decision.

3. Step-by-step execution trace#

Suppose a user asks, "Has order A12 shipped, and where is it?"

Two synthetic read-only tools are available: lookup_order and lookup_tracking. The latter requires a tracking number returned by the first tool. Assume the authenticated caller has already been authorized to read the order.

StepObservable eventState change
0User invokes the agentAppend user message
1Model requests lookup_order with order_id A12 and ID c1Append AIMessage containing c1
2Tool returns status shipped and tracking number T9Append ToolMessage correlated to c1
3Model requests lookup_tracking with tracking number T9 and ID c2Append AIMessage containing c2
4Tool returns location "regional distribution center"Append ToolMessage correlated to c2
5Model returns a final answer without tool callsAppend final AIMessage and finish the ordinary loop

This example has three model invocations and two tool invocations. The second tool must wait for the first because it needs a value from that result. It is not a good candidate for speculative parallel execution.

Loading diagram…

The trace describes externally observable messages and calls; it does not require access to a model's hidden reasoning. The model could choose a different valid sequence, ask for clarification or stop early. Test outcomes and protocol invariants rather than assume one exact natural-language response.

4. What happens when the model selects a tool?#

Tool selection is a model output, not permission to execute anything. The runtime maps the requested name to an available callable. A tool definition provides a schema and description; schema validation and dispatch are separate from domain authorization.

A safe dispatch path checks several independent conditions:

  • The requested tool exists and is exposed to this agent in this context.
  • Required arguments have acceptable types and domain constraints.
  • The authenticated principal may access the requested resource or perform the action.
  • The operation fits the current task, budget and risk policy.
  • Sensitive actions have any required approval bound to the exact request.
  • A write operation has an appropriate idempotency or reconciliation strategy.

Framework schemas can help reject malformed arguments, but they do not prove ownership of an order, verify an approval, or guarantee that a query is safe. The trusted application should derive identity outside the model and enforce permissions inside or immediately before the tool.

For instance, a valid-looking order_id string must not authorize retrieval of another customer's order. Return a bounded, non-sensitive error rather than exposing another tenant's data or the internal exception trace.

5. Middleware and control around the loop#

Modern LangChain agents provide middleware extension points. Conceptually these can surround model requests, tool execution and lifecycle transitions. Depending on the installed release, relevant hooks may include before_model, after_model, wrap_model_call, wrap_tool_call, before_agent and after_agent.

Extension pointTypical purpose
Before modelTrim history, attach relevant context, enforce model-call budget
Wrap model callSelect model dynamically, measure latency, apply compatible retry or fallback behavior
After modelInspect proposed actions, validate output or select a configured route
Wrap tool callEnforce policy, instrument execution, handle expected tool failures
Agent lifecycleInitialize per-run metadata and record final status or cleanup

Exact hook signatures and ordering depend on the middleware configuration and installed version. Do not rely on a prompt-only restriction where a deterministic enforcement boundary is needed.

For example, before invoking a model, remove inaccessible tool definitions. Then enforce authorization again at tool execution time, because the model could still emit a disallowed tool name or a stale action request. If an authorized tool fails temporarily, convert the failure into a limited observation where appropriate. A controlled retry should be explicitly bounded, and uncertain writes require reconciliation rather than blind repetition.

Loading diagram…

This is a conceptual middleware placement diagram. It deliberately does not prescribe exact middleware scheduling or the behavior of a specific release.

6. Practical LangChain example#

The following SDK example illustrates inspecting the resulting message history rather than displaying only the final answer. The tool uses synthetic data. It does not access a real customer database or execute external writes.

PYTHON
from langchain.agents import create_agent from langchain_core.messages import AIMessage, ToolMessage def lookup_order(order_id: str) -> str: """Look up the shipping status of a synthetic order.""" return "shipped; tracking T9" if order_id == "A12" else "not found" def lookup_tracking(tracking_id: str) -> str: """Look up the location of a synthetic shipment.""" return "regional distribution center" if tracking_id == "T9" else "not found" agent = create_agent( model="openai:gpt-4o-mini", tools=[lookup_order, lookup_tracking], system_prompt=( "Use available evidence to answer the shipping question. " "Do not invent a tracking number or shipment location." ), ) result = agent.invoke({ "messages": [{ "role": "user", "content": "Has order A12 shipped, and where is it?" }] }) for message in result["messages"]: if isinstance(message, AIMessage): print("AI", message.content, message.tool_calls) elif isinstance(message, ToolMessage): print("TOOL", message.tool_call_id, message.content)

Configure a supported model provider, dependencies and credentials separately. This snippet uses the established modern agent interface; verify exact model identifiers, imports and method signatures with the installed version. LangChain, LangGraph and langchain_core are not installed in the available execution environment, and provider credentials were unavailable. The SDK example was not executed. The earlier trace describes an expected possible protocol path, not observed SDK output.

Do not print raw message contents in production without an approved logging policy. They can contain confidential documents, personal information, internal tool results and user-provided secrets. Prefer structured event metadata and redacted error classifications.

7. Locally tested loop simulation: preserve the protocol and enforce budgets#

This dependency-free Python example isolates the core protocol: accept scripted model outputs, correlate tool results, reject duplicate IDs, bound model and tool requests, validate arguments and convert timeouts into observations. It is a teaching model of the execution contract, not a reimplementation of LangChain, LangGraph persistence or provider-specific message validation.

PYTHON
from dataclasses import dataclass @dataclass(frozen=True) class Call: id: str name: str args: dict @dataclass(frozen=True) class Turn: calls: tuple[Call, ...] = () text: str = "" def run(turns, allowed, max_model_calls=4, max_tools=4): messages = [("human", "Check order status")] seen = set() executed = 0 for index, turn in enumerate(turns): if index >= max_model_calls: return "model_budget", messages, executed messages.append(("ai", turn)) if not turn.calls: return "finished", messages, executed ids = [c.id for c in turn.calls] if len(set(ids)) != len(ids) or seen.intersection(ids): return "protocol_error", messages, executed if len(seen) + len(ids) > max_tools: return "tool_budget", messages, executed for call in turn.calls: seen.add(call.id) if call.name not in allowed: result = {"error": "tool_not_allowed"} elif (set(call.args) != {"order_id"} or not isinstance(call.args["order_id"], str)): result = {"error": "invalid_arguments"} else: executed += 1 try: result = allowed[call.name](call.args["order_id"]) except TimeoutError: result = {"error": "temporary_unavailable"} messages.append(("tool", call.id, result)) return "incomplete", messages, executed def lookup(order_id): return {"status": "shipped" if order_id == "A12" else "not_found"} def timeout(order_id): raise TimeoutError() ok = Call("c1", "lookup", {"order_id": "A12"}) finish = Turn(text="The order is shipped.") status, log, count = run([Turn((ok,)), finish], {"lookup": lookup}) assert (status, count) == ("finished", 1) assert log[2] == ("tool", "c1", {"status": "shipped"}) bad = Call("c2", "lookup", {"order_id": 123}) assert run([Turn((bad,)), finish], {"lookup": lookup})[1][2][2] == {"error": "invalid_arguments"} assert run([Turn((ok,)), finish], {})[2] == 0 assert run([Turn((ok,)), finish], {"lookup": timeout})[1][2][2] == {"error": "temporary_unavailable"} assert run([Turn((ok, ok))], {"lookup": lookup})[0] == "protocol_error" assert run([Turn((ok,)), Turn((ok,))], {"lookup": lookup})[0] == "protocol_error" assert run([Turn((ok,)), finish], {"lookup": lookup}, max_model_calls=1)[0] == "model_budget" assert run([Turn((ok,))], {"lookup": lookup}, max_tools=0)[2] == 0 assert run([Turn((ok,))], {"lookup": lookup})[0] == "incomplete" print("10 assertions passed")

Actual local result (Python 3.13.5): 10 assertions passed.

The model output sequence is a deterministic test fixture, so the assertions do not depend on an LLM provider. The simulation counts requested tool calls toward the budget even when arguments or authorization fail. Its count of executed calls includes timed-out attempts. A duplicate ID causes a protocol error rather than a second execution. It distinguishes a completed protocol from a fixture that ends without a final model response.

The example is intentionally limited: it supports a single read-only argument schema, does not validate real customer ownership, and does not persist a production idempotency record. In an actual runtime, call identifiers are useful for message correlation but should not automatically be assumed to be stable business-operation idempotency keys across retries. A trusted operation identifier should bind the tenant, action, resource and relevant parameters.

Also, the simulation accepts any final turn with no calls as protocol completion. An actual application should separately validate the answer against task acceptance criteria. If a model asserts success after a tool timeout, the application should not treat that assertion as evidence that an external operation succeeded.

8. How and why does the loop terminate?#

The common stopping condition is an AIMessage without tool calls. That means the ordinary loop has no more requested tools to dispatch, not that the real-world task is necessarily complete.

Other terminal or suspended states include:

ConditionCorrect application interpretation
No further tool callsNormal loop termination; validate outcome separately
Structured output acceptedConfigured response-format condition satisfied
Model or tool-call budget exhaustedIncomplete or limited run; return useful partial status
Graph recursion or execution limitSafety limit reached; diagnose repeated transitions
Human approval requiredSuspended, not completed
Tool requests configured to return directlyMay end or change normal loop according to runtime configuration
Provider error, deadline or cancellationControlled failure or incomplete run
Invalid state or protocolStop or recover through a tested error path

Graph recursion limits and model-call limits are different units. A graph may execute multiple nodes or supersteps per model invocation. A single model response may request more than one tool. Track each separately, along with elapsed time and token usage. Use supported middleware and runtime options for the installed version rather than assuming a single universal limit parameter.

9. Failure recovery and state integrity#

A timeout on a read-only tool often allows a bounded retry if the operation remains useful and the deadline permits. A timeout on a write is different: the external system might have completed the write even though the caller did not receive confirmation. Query the authoritative system using a durable operation key before deciding whether retry is safe.

Failure scenarioSafe response
Unknown or unavailable toolReject the call and return a controlled observation when protocol permits
Invalid argumentsDo not invoke external operation; expose a bounded validation error
Duplicate or orphaned call IDDetect inconsistent history and stop or restore a valid checkpoint
Provider rate limitBounded backoff with jitter and deadline awareness
Read-only timeoutRetry selectively or report unavailable evidence
Uncertain write outcomeReconcile with authoritative external state
Repeated unsuccessful callsEnforce request and progress limits
Prompt injection in a tool responseTreat the content as untrusted data; never expand permissions based on it
Process crash after tool executionRecover persisted state and reconcile any external side effects

A configured checkpointer can preserve agent state associated with a thread. It does not make all external side effects exactly once. If a tool call completes in an external system and the process crashes before checkpointing its observation, the recovered agent may encounter a replay boundary. Idempotency and reconciliation must be designed in the domain service.

Session identifiers must be authorized and isolated per tenant. Never let a user-controlled thread ID expose another customer's messages or approval state. Limit retention and control access to checkpoints.

10. Performance: count calls, tokens and critical-path latency#

The two-tool trace uses three model requests. Suppose the first request carries 600 input tokens, the second carries 850 and the third carries 1,050. Total input usage is 2,500 tokens, not 1,050, because each request can include repeated context. If output usage across the three calls is 80, 90 and 120 tokens, total output usage is 290.

At illustrative prices of $2 per million input tokens and $8 per million output tokens, the model cost is $0.005 + $0.00232 = $0.00732 for the run, excluding external tool and infrastructure charges. This is an example calculation, not a measured LangChain benchmark. Actual billing may distinguish cached input, reasoning tokens, provider-specific usage and retries.

If model calls take 0.9, 1.1 and 0.8 seconds and dependent tool calls take 0.2 and 0.4 seconds, the serial critical path is approximately 3.4 seconds before orchestration, network and queue overhead. Parallel tools can reduce critical-path time only when independent and safe to execute together. They may increase provider concurrency and resource consumption.

Monitor:

  • model invocations, requested tool calls and actual executed calls;
  • per-tool latency, errors and validation rejections;
  • call/result correlation errors and orphaned messages;
  • input/output tokens per model request and total per run;
  • budget exhaustion, repeated calls, cancellations and interruptions;
  • outcome correctness, source provenance and unsafe actions prevented.

These measurements help distinguish slow provider calls from tool latency, context growth and inefficient loop behavior.

11. Test the actual agent in layers#

The offline simulation verifies protocol logic only. A production test suite should add deterministic model substitutes or scripted responses using interfaces compatible with the installed LangChain version. Verify that the real runtime creates correctly correlated messages, that middleware handles invalid arguments and tool failures, and that limits terminate the run predictably.

Then run controlled integration tests using the actual provider. Compare tool schema support, structured output, streaming events, concurrent calls, checkpoint recovery and cancellation. Use synthetic records or a sandbox, not real customer writes. Test authorization and outcome verification independently of the model.

Interview-ready answer#

create_agent builds a LangGraph-backed agent execution graph. It receives messages, invokes a tool-capable chat model and appends the returned AIMessage. If that message contains tool requests, the runtime resolves and executes the allowed tools, appends ToolMessages correlated to the original call IDs and repeats the model invocation. When no further tool calls are requested, the ordinary loop finishes, unless configuration or middleware defines another transition. Middleware can enforce budgets, intercept model or tool calls and handle controlled failures. Application code must enforce domain authorization, validate outcomes and make external writes idempotent; checkpointing and a final model message do not prove that a business operation succeeded.

References and verification status#

Official documentation entry points for further verification:

Authorized offline research exception applied. These documentation references were not live-accessed, so current version-specific API behavior and link availability were not independently verified. The standard-library simulation was executed on Python 3.13.5 and passed 10 assertions. The SDK example was not executed because LangChain, LangGraph and langchain_core were absent. Mermaid diagrams are standard fenced blocks; live rendering was unavailable. Numerical costs and latency are illustrative, not measured.

References

  1. 1.
    LangChain agentsdocs.langchain.com
  2. 2.
    LangChain messagesdocs.langchain.com
  3. 3.
    LangChain toolsdocs.langchain.com
  4. 4.
  5. 5.
    LangGraph overviewdocs.langchain.com
  6. 6.
    LangChain API referencereference.langchain.com

Related questions

Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps

Machinoai Logo
Machinoai

Your edge in the AI era. Deep dives into machine learning concepts, paper explainers, verified industry jobs, and developer tools.

© 2026 Machinoai. All rights reserved.