Open-Source Wikis

/

LangChain

/

Features

/

Agents

langchain-ai/langchain

Agents

langchain.agents.create_agent is the high-level entry point for building tool-using agents on top of langgraph. Source: libs/langchain_v1/langchain/agents/.

Purpose

An agent is a model that can call tools, observe their results, and decide what to do next. create_agent packages that loop into a compiled langgraph graph with built-in support for:

  • Multi-step tool use (model → tool → model → …) until the model is done.
  • Pluggable middleware that intercepts every model and tool call.
  • Structured-output strategies that constrain the final response shape.
  • Optional checkpointing for resumability and human-in-the-loop workflows.
  • Streaming via astream / astream_events.
  • LangSmith tracing through the inherited callback machinery.

Files

libs/langchain_v1/langchain/agents/
├── __init__.py             # Re-exports `create_agent`, `AgentState`
├── factory.py              # The agent factory itself (~1,875 lines)
├── structured_output.py    # ToolStrategy / ProviderStrategy / AutoStrategy / ResponseFormat
└── middleware/             # Built-in middleware (16 modules)

Key abstractions

Symbol File Description
create_agent libs/langchain_v1/langchain/agents/factory.py The factory; returns a CompiledStateGraph
AgentState libs/langchain_v1/langchain/agents/middleware/types.py The default state schema (messages, optional structured_response, jump_to)
AgentMiddleware libs/langchain_v1/langchain/agents/middleware/types.py Base class for middleware
ModelRequest, ModelResponse, ExtendedModelResponse libs/langchain_v1/langchain/agents/middleware/types.py Inputs/outputs that flow through wrap_model_call
ToolCallRequest libs/langchain_v1/langchain/agents/middleware/types.py Input to wrap_tool_call
ResponseFormat, ToolStrategy, ProviderStrategy, AutoStrategy libs/langchain_v1/langchain/agents/structured_output.py Structured-output shaping

How create_agent builds a graph

graph TD
    Start([START]) --> BAg[before_agent middleware]
    BAg --> BModel[before_model middleware]
    BModel --> ModelNode[Model call wrapped by wrap_model_call]
    ModelNode --> AModel[after_model middleware]
    AModel --> Decide{tool_calls?}
    Decide -->|yes| ToolNode[ToolNode wrapped by wrap_tool_call]
    ToolNode --> BModel
    Decide -->|no| AAg[after_agent middleware]
    AAg --> End([END])

The compiled graph is a langgraph.StateGraph[AgentState | UserState] with edges that loop while the latest AIMessage has tool calls and exit when it doesn't. Middleware hooks are wired into the appropriate transition points.

Calling an agent

from langchain.agents import create_agent

agent = create_agent(
    model="openai:gpt-5",       # or a BaseChatModel instance
    tools=[search, write_file],
)

# Synchronous
result = agent.invoke({"messages": [{"role": "user", "content": "..."}]})

# Async
result = await agent.ainvoke({"messages": [{"role": "user", "content": "..."}]})

# Streaming with fine-grained events
async for event in agent.astream_events({"messages": [...]}, version="v2"):
    print(event)

The returned object is a regular langgraph graph, so all langgraph features are available: checkpointers, time-travel, manual interruption, subgraphs, etc.

Arguments

The full create_agent signature accepts:

Arg Description
model A BaseChatModel, a Runnable[LanguageModelInput, AIMessage], or a string "<provider>:<model>" parsed by init_chat_model
tools A list of BaseTool / decorated functions / runnables
middleware An ordered list of AgentMiddleware instances
prompt A system prompt string, message, or callable returning messages
response_format A ResponseFormat (or ToolStrategy/ProviderStrategy/AutoStrategy) for structured output
state_schema A custom TypedDict extending AgentState
context_schema A TypedDict for arbitrary context propagated to middleware via Runtime
checkpointer A langgraph.checkpoint.base.Checkpointer for resumable runs
store A langgraph.store.base.BaseStore for cross-thread memory
cache A langgraph.cache.base.BaseCache for caching node results
interrupt_before / interrupt_after Lists of node names where the graph should pause
name A name for the compiled graph (shows up in traces)

Middleware composition

Middleware is composed outer-first: the first middleware in the list wraps every other middleware. The factory's internal _chain_model_call_handlers (in factory.py) folds the list into a single composed handler that calls them in order, accumulating any langgraph.Command outputs from each layer.

A middleware that wraps wrap_model_call looks like:

class LoggingMiddleware(AgentMiddleware):
    def wrap_model_call(self, request: ModelRequest, handler):
        print("model call:", request.messages[-1])
        response = handler(request)
        print("model returned:", response.result[-1])
        return response

The full hook menu (declared as decorators on AgentMiddleware) is before_agent, before_model, wrap_model_call (sync + async), wrap_tool_call (sync + async), after_model, after_agent. Each hook can short-circuit the loop by setting state["jump_to"] to a target node name.

Structured output

response_format= accepts:

  • A Pydantic class — wrapped in AutoStrategy, which picks the best method based on model capabilities.
  • A ToolStrategy(schema) — bind a tool, parse the tool call.
  • A ProviderStrategy(schema) — use the provider's native structured-output endpoint (OpenAI's JSON Schema, Anthropic's tool-with-strict-schema).
  • A ResponseFormat(...) — explicit configuration with strategy choice and error template.

When the model returns the structured response, the agent stores it in state["structured_response"] and exits the loop. See features/structured-output for details.

Error handling

By default, an unhandled exception in a tool propagates out of the agent. Recovery patterns:

  • ToolException — let the tool raise it; the tool node converts it to a ToolMessage and lets the model retry.
  • ToolRetryMiddleware — wraps wrap_tool_call and retries on configured exception types.
  • ModelRetryMiddleware — retries the model call.
  • ModelFallbackMiddleware — tries alternative models on failure.

Integration points

  • Depends on langgraph for graph compilation, ToolNode, Command, Send, Runtime, checkpointers.
  • Depends on langchain-core for messages, content blocks, tools, callbacks.
  • Builds on init_chat_model (libs/langchain_v1/langchain/chat_models/base.py) for string-based model specifications.

Entry points for modification

  • For a new agent-level capability that should be on by default, add it as a built-in middleware under libs/langchain_v1/langchain/agents/middleware/ and include it in the default middleware list (currently empty — every middleware is opt-in).
  • For a new state field, extend AgentState in middleware/types.py and update factory.py's graph wiring.
  • For a new structured-output strategy, subclass ResponseFormat in structured_output.py and add a branch to factory.py's strategy-selection logic.

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

Agents – LangChain wiki | Factory