langchain package provides a powerful agent system based on the ReAct (Reasoning + Acting) pattern. Agents combine language models with tools and middleware to create systems that can reason about tasks, decide which tools to use, and iteratively work towards solutions.
Core Functions
createAgent
Creates a production-ready ReAct agent that combines language models with tools and middleware.The language model as a string identifier (e.g.,
"openai:gpt-4o", "anthropic:claude-3-opus-20240229"). See Models for more details.The language model as an instance of a chat model. Use this for full control over model configuration.
Array of tools created with the
tool function, or a configured ToolNode for custom error handling.System instructions that shape how the agent approaches tasks. Can be:
- String for simple instructions
- SystemMessage for structured prompts
- Function for dynamic prompts based on state
Zod schema for structured output. When provided, the agent will return typed responses that conform to the schema.
Custom state schema for memory. Allows the agent to remember information across interactions.
Array of middleware for extending agent behavior. See Middleware for available options.
ReactAgent - An agent instance with invoke and stream methods.
Source: libs/langchain/src/agents/index.ts:168
createMiddleware
Creates custom middleware for extending agent behavior.libs/langchain/src/agents/middleware.ts
Examples
Basic Agent with Tools
Structured Output
Streaming Responses
With Custom State Schema
Type Exports
ReactAgent
The agent instance returned bycreateAgent. Provides methods for invoking and streaming.
Methods:
invoke(input, options?)- Single invocationstream(input, options?)- Streaming invocation
AgentMiddleware
Type definition for agent middleware. See Middleware for details.Runtime
The agent runtime context available in middleware and dynamic functions.Advanced Features
Response Formats
Agents support multiple response format strategies:- Zod Schema: Type-safe structured output
- JSON Schema: For broader compatibility
- Tool Strategy: Use tools to generate structured responses
- Provider Strategy: Provider-specific structured output
State Management
Extend the state schema to add memory and context:Error Handling
Agents provide comprehensive error handling:Related
- Middleware - Built-in middleware for agents
- Models - Chat model initialization
- Tools - Creating tools for agents
