Skip to main content
The 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.
import { createAgent, tool } from "langchain";
import { z } from "zod";

const search = tool(
  ({ query }) => `Results for: ${query}`,
  {
    name: "search",
    description: "Search for information",
    schema: z.object({
      query: z.string().describe("The search query"),
    })
  }
);

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [search],
});

const result = await agent.invoke({
  messages: [{ role: "user", content: "Search for ReAct agents" }],
});
Parameters:
options.model
string
The language model as a string identifier (e.g., "openai:gpt-4o", "anthropic:claude-3-opus-20240229"). See Models for more details.
options.llm
BaseChatModel
The language model as an instance of a chat model. Use this for full control over model configuration.
options.tools
Array<Tool> | ToolNode
Array of tools created with the tool function, or a configured ToolNode for custom error handling.
options.prompt
string | SystemMessage | Function
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
options.responseFormat
ZodSchema
Zod schema for structured output. When provided, the agent will return typed responses that conform to the schema.
options.stateSchema
StateDefinitionInit
Custom state schema for memory. Allows the agent to remember information across interactions.
options.middleware
AgentMiddleware[]
Array of middleware for extending agent behavior. See Middleware for available options.
Returns: 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.
import { createMiddleware } from "langchain";

const customMiddleware = createMiddleware({
  beforeModelCall: async (state, runtime) => {
    // Add pre-processing logic
    return state;
  },
  afterModelCall: async (state, runtime) => {
    // Add post-processing logic
    return state;
  },
});

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [search],
  middleware: [customMiddleware],
});
Source: libs/langchain/src/agents/middleware.ts

Examples

Basic Agent with Tools

import { createAgent, tool } from "langchain";
import { z } from "zod";

const search = tool(
  ({ query }) => `Results for: ${query}`,
  {
    name: "search",
    description: "Search for information",
    schema: z.object({
      query: z.string().describe("The search query"),
    })
  }
);

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [search],
});

const result = await agent.invoke({
  messages: [{ role: "user", content: "Search for ReAct agents" }],
});

Structured Output

import { createAgent } from "langchain";
import { z } from "zod";

const ContactInfo = z.object({
  name: z.string(),
  email: z.string(),
  phone: z.string(),
});

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [],
  responseFormat: ContactInfo,
});

const result = await agent.invoke({
  messages: [{
    role: "user",
    content: "Extract: John Doe, [email protected], (555) 123-4567"
  }],
});

console.log(result.structuredResponse);
// { name: 'John Doe', email: '[email protected]', phone: '(555) 123-4567' }

Streaming Responses

const stream = await agent.stream(
  { messages: [{ role: "user", content: "What's the weather?" }] },
  { streamMode: "values" }
);

for await (const chunk of stream) {
  console.log(chunk);
}

With Custom State Schema

import { createAgent } from "langchain";
import { StateSchema, ReducedValue } from "@langchain/langgraph";
import { z } from "zod";

const AgentState = new StateSchema({
  userId: z.string(),
  count: z.number().default(0),
  history: new ReducedValue(
    z.array(z.string()).default(() => []),
    { inputSchema: z.string(), reducer: (c, n) => [...c, n] }
  ),
});

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [searchTool],
  stateSchema: AgentState,
});

Type Exports

ReactAgent

The agent instance returned by createAgent. Provides methods for invoking and streaming. Methods:
  • invoke(input, options?) - Single invocation
  • stream(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:
const AgentState = new StateSchema({
  userId: z.string(),
  sessionData: z.record(z.unknown()).default(() => ({})),
});

Error Handling

Agents provide comprehensive error handling:
import { ToolCallLimitExceededError } from "langchain";

try {
  await agent.invoke({ messages });
} catch (error) {
  if (error instanceof ToolCallLimitExceededError) {
    console.log("Tool call limit exceeded");
  }
}

  • Middleware - Built-in middleware for agents
  • Models - Chat model initialization
  • Tools - Creating tools for agents

Build docs developers (and LLMs) love