LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
LangChain
  • Universal
  • Hub
  • Node
  • Load
  • Serializable
  • Encoder Backed
  • File System
  • In Memory
LangChain Core
  • Agents
  • Caches
  • Base
  • Dispatch
  • Web
  • Manager
  • Promises
  • Chat History
  • Context
  • Base
  • Langsmith
  • Documents
  • Embeddings
  • Errors
  • Example Selectors
  • Indexing
  • Base
  • Chat Models
  • Llms
  • Profile
  • Load
  • Serializable
  • Memory
  • Messages
  • Tool
  • Output Parsers
  • Openai Functions
  • Openai Tools
  • Outputs
  • Prompt Values
  • Prompts
  • Retrievers
  • Document Compressors
  • Runnables
  • Graph
  • Singletons
  • Stores
  • Structured Query
  • Tools
  • Base
  • Console
  • Log Stream
  • Run Collector
  • Tracer Langchain
  • Stream
  • Async Caller
  • Chunk Array
  • Context
  • Env
  • Event Source Parse
  • Format
  • Function Calling
  • Hash
  • Json Patch
  • Json Schema
  • Math
  • Ssrf
  • Stream
  • Testing
  • Tiktoken
  • Types
  • Vectorstores
Text Splitters
MCP Adapters
⌘I

LangChain Assistant

Ask a question to get started

Enter to send•Shift+Enter new line

Menu

LangChain
UniversalHubNodeLoadSerializableEncoder BackedFile SystemIn Memory
LangChain Core
AgentsCachesBaseDispatchWebManagerPromisesChat HistoryContextBaseLangsmithDocumentsEmbeddingsErrorsExample SelectorsIndexingBaseChat ModelsLlmsProfileLoadSerializableMemoryMessagesToolOutput ParsersOpenai FunctionsOpenai ToolsOutputsPrompt ValuesPromptsRetrieversDocument CompressorsRunnablesGraphSingletonsStoresStructured QueryToolsBaseConsoleLog StreamRun CollectorTracer LangchainStreamAsync CallerChunk ArrayContextEnvEvent Source ParseFormatFunction CallingHashJson PatchJson SchemaMathSsrfStreamTestingTiktokenTypesVectorstores
Text Splitters
MCP Adapters
Language
Theme
JavaScriptlangchainindexcreateAgent
Function●Since v1.1

createAgent

Copy
createAgent<
  StructuredResponseFormat extends Record<string, any> = Record<string

Used in Docs

  • Agents
  • Build a multi-source knowledge base with routing
  • Build a personal assistant with subagents
  • Build a RAG agent with LangChain
  • Build a SQL agent
(23 more not shown)
View source on GitHub
,
any
>
,
TStateSchema
extends
StateDefinitionInit
|
undefined
=
undefined
,
ContextSchema
extends
InteropZodObject
|
AnyAnnotationRoot
=
AnyAnnotationRoot
,
TMiddleware
extends
readonly
AgentMiddleware
<
any
,
any
,
any
,
readonly
ClientTool
|
ServerTool
[
]
>
[
]
=
readonly
AgentMiddleware
<
any
,
any
,
any
,
readonly
ClientTool
|
ServerTool
[
]
>
[
]
,
TTools
extends
readonly
ClientTool
|
ServerTool
[
]
=
readonly
ClientTool
|
ServerTool
[
]
>
(
params
:
CreateAgentParams
<
StructuredResponseFormat
,
TStateSchema
,
ContextSchema
,
InteropZodType
<
StructuredResponseFormat
>
>
__type
)
:
ReactAgent
<
AgentTypeConfig
<
StructuredResponseFormat
,
TStateSchema
,
ContextSchema
,
TMiddleware
,
readonly
[
TTools
,
InferMiddlewareToolsArray
<
TMiddleware
>
]
>
>

Parameters

NameTypeDescription
params*CreateAgentParams<StructuredResponseFormat, TStateSchema, ContextSchema, InteropZodType<StructuredResponseFormat>> & __type

Example 1

Example 2

Example 3

Example 4

Creates a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools and middleware to create systems that can reason about tasks, decide which tools to use, and iteratively work towards solutions.

The agent follows the ReAct pattern, interleaving reasoning steps with tool calls to iteratively work towards solutions. It can handle multiple tool calls in sequence or parallel, maintain state across interactions, and provide auditable decision processes.

Core Components

Model

The reasoning engine can be specified as:

  • String identifier: "openai:gpt-4o" for simple setup
  • Model instance: Configured model object for full control
  • Dynamic function: Select models at runtime based on state

Tools

Tools give agents the ability to take actions:

  • Pass an array of tools created with the tool function
  • Or provide a configured ToolNode for custom error handling

Prompt

Shape how your agent approaches tasks:

  • String for simple instructions
  • SystemMessage for structured prompts
  • Function for dynamic prompts based on state

Middleware

Middleware allows you to extend the agent's behavior:

  • Add pre/post-model processing for context injection or validation
  • Add dynamic control flows, e.g. terminate invocation or retries
  • Add human-in-the-loop capabilities
  • Add tool calls to the agent
  • Add tool results to the agent

Advanced Features

  • Structured Output: Use responseFormat with a Zod schema to get typed responses
  • Memory: Extend the state schema to remember information across interactions
  • Streaming: Get real-time updates as the agent processes
Copy
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({
  llm: "openai:gpt-4o",
  tools: [search],
});

const result = await agent.invoke({
  messages: [{ role: "user", content: "Search for ReAct agents" }],
});
Copy
import { createAgent } from "langchain";
import { z } from "zod";

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

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

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

console.log(result.structuredResponse);
// { name: 'John Doe', email: 'john@example.com', phone: '(555) 123-4567' }
Copy
const stream = await agent.stream(
  { messages: [{ role: "user", content: "What's the weather?" }] },
  { streamMode: "values" }
);

for await (const chunk of stream) {
  // ...
}
Copy
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,
});