{"owner":"langchain-ai","repo":"langgraphjs","hasSkills":true,"totalSkillsCount":15,"totalTokensCount":17215,"categories":["subagent-persona"],"hasMcp":true,"mcpConfig":{"mcpServers":{"langgraphjs":{"command":"npx","args":["-y","@modelcontextprotocol/server-langgraphjs"]}}},"found":["docs/docs/agents/agents.md","docs/docs/agents/evals.md","docs/docs/agents/deployment.md","docs/docs/agents/mcp.md","docs/docs/agents/human-in-the-loop.md","docs/docs/agents/context.md","docs/docs/agents/models.md","docs/docs/agents/prebuilt.md","docs/docs/agents/memory.md","docs/docs/agents/multi-agent.md","docs/docs/agents/overview.md","docs/docs/agents/run_agents.md","docs/docs/agents/streaming.md","docs/docs/agents/tools.md","docs/docs/agents/ui.md"],"skills":{"docs/docs/agents/agents.md":"# LangGraph quickstart\n\nThis guide shows you how to set up and use LangGraph's **prebuilt**, **reusable** components, which are designed to help you construct agentic systems quickly and reliably.\n\n## Prerequisites\n\nBefore you start this tutorial, ensure you have the following:\n\n- An [Anthropic](https://console.anthropic.com/settings/keys) API key\n\n## 1. Install dependencies\n\nIf you haven't already, install LangGraph and LangChain:\n\n```\nnpm install langchain @langchain/langgraph @langchain/anthropic\n```\n\n## 2. Create an agent\n\nUse [`createReactAgent`](/langgraphjs/reference/functions/langgraph_prebuilt.createReactAgent.html) to instantiate an agent:\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst getWeather = tool( // (1)!\n  async (input: { city: string }) => {\n    return `It's always sunny in ${input.city}!`;\n  },\n  {\n    name: \"getWeather\",\n    schema: z.object({\n      city: z.string().describe(\"The city to get the weather for\"),\n    }),\n    description: \"Get weather for a given city.\",\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\"); // (2)!\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather], // (3)!\n  prompt: \"You are a helpful assistant\", // (4)!\n});\n\n// Run the agent\nawait agent.invoke({\n  messages: [{ role: \"user\", content: \"what is the weather in sf\" }],\n});\n```\n\n1. Define a tool for the agent to use. For more advanced tool usage and customization, check the [tools](./tools.md) page.\n2. Provide a language model for the agent to use. To learn more about configuring language models for the agents, check the [models](./models.md) page.\n3. Provide a list of tools for the model to use.\n4. Provide a system prompt (instructions) to the language model used by the agent.\n\n## 3. Configure an LLM\n\nUse [`initChatModel`](https://api.js.langchain.com/functions/langchain.chat_models_universal.initChatModel.html) to configure an LLM with specific parameters, such as temperature:\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\n// highlight-next-line\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\", {\n  // highlight-next-line\n  temperature: 0,\n});\n\nconst agent = createReactAgent({\n  // highlight-next-line\n  llm,\n  tools: [getWeather],\n});\n```\n\nSee the [models](./models.md) page for more information on how to configure LLMs.\n\n## 4. Add a custom prompt\n\nPrompts instruct the LLM how to behave. They can be:\n\n- **Static**: A string is interpreted as a **system message**\n- **Dynamic**: a list of messages generated at **runtime** based on input or configuration\n\n=== \"Static prompt\"\n\n    Define a fixed prompt string or list of messages.\n\n    ```ts\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // A static prompt that never changes\n      // highlight-next-line\n      prompt: \"Never answer questions about the weather.\",\n    });\n\n    await agent.invoke({\n      messages: \"what is the weather in sf\",\n    });\n    ```\n\n=== \"Dynamic prompt\"\n\n    Define a function that returns a message list based on the agent's state and configuration:\n\n    ```ts\n    import { BaseMessageLike } from \"@langchain/core/messages\";\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { MessagesAnnotation } from \"@langchain/langgraph\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n    const prompt = (\n      state: typeof MessagesAnnotation.State,\n      config: RunnableConfig\n    ): BaseMessageLike[] => { // (1)!\n      const userName = config.configurable?.userName;\n      const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;\n      return [{ role: \"system\", content: systemMsg }, ...state.messages];\n    };\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // highlight-next-line\n      prompt,\n    });\n\n    await agent.invoke(\n      { messages: [{ role: \"user\", content: \"what is the weather in sf\" }] },\n      // highlight-next-line\n      { configurable: { userName: \"John Smith\" } }\n    );\n    ```\n\n    1. Dynamic prompts allow including non-message [context](./context.md) when constructing an input to the LLM, such as:\n\n      - Information passed at runtime, like a `userId` or API credentials (using `config`).\n      - Internal agent state updated during a multi-step reasoning process (using `state`).\n\n      Dynamic prompts can be defined as functions that take `state` and `config` and return a list of messages to send to the LLM.\n\nFor more information, see [Context](./context.md).\n\n## 5. Add memory\n\nTo allow multi-turn conversations with an agent, you need to enable [persistence](../concepts/persistence.md) by providing a `checkpointer` when creating an agent. At runtime you need to provide a config containing `thread_id` — a unique identifier for the conversation (session):\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { MemorySaver } from \"@langchain/langgraph-checkpoint\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\n// highlight-next-line\nconst checkpointer = new MemorySaver();\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather],\n  // highlight-next-line\n  checkpointer, // (1)!\n});\n\n// Run the agent\n// highlight-next-line\nconst config = { configurable: { thread_id: \"1\" } };\nconst sfResponse = await agent.invoke(\n  { messages: [{ role: \"user\", content: \"what is the weather in sf\" }] },\n  config // (2)!\n);\nconst nyResponse = await agent.invoke(\n  { messages: [{ role: \"user\", content: \"what about new york?\" }] },\n  config\n);\n```\n\n1. `checkpointer` allows the agent to store its state at every step in the tool calling loop. This enables [short-term memory](./memory.md#short-term-memory) and [human-in-the-loop](./human-in-the-loop.md) capabilities.\n2. Pass configuration with `thread_id` to be able to resume the same conversation on future agent invocations.\n\nWhen you enable the checkpointer, it stores agent state at every step in the provided checkpointer database (or in memory, if using `InMemorySaver`).\n\nNote that in the above example, when the agent is invoked the second time with the same `thread_id`, the original message history from the first conversation is automatically included, together with the new user input.\n\nFor more information, see [Memory](./memory.md).\n\n## 6. Configure structured output\n\nTo produce structured responses conforming to a schema, use the `responseFormat` parameter. The schema can be defined with a `zod` schema. The result will be accessible via the `structuredResponse` field.\n\n```ts\nimport { z } from \"zod\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\nconst WeatherResponse = z.object({\n  conditions: z.string(),\n});\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather],\n  // highlight-next-line\n  responseFormat: WeatherResponse, // (1)!\n});\n\nconst response = await agent.invoke({\n  messages: [{ role: \"user\", content: \"what is the weather in sf\" }],\n});\n// highlight-next-line\nresponse.structuredResponse;\n```\n\n1. When `responseFormat` is provided, a separate step is added at the end of the agent loop: agent message history is passed to an LLM with structured output to generate a structured response.\n\n   To provide a system prompt to this LLM, use an object `{ prompt, schema }`, e.g., `responseFormat: { prompt, schema: WeatherResponse }`.\n\n!!! Note \"LLM post-processing\"\n\n    Structured output requires an additional call to the LLM to format the response according to the schema.\n\n## Next steps\n\n- [Deploy your agent locally](../tutorials/langgraph-platform/local-server.md)\n- [Learn more about prebuilt agents](../agents/overview.md)\n- [LangGraph Platform quickstart](../cloud/quick_start.md)\n","docs/docs/agents/evals.md":"# Evals\n\nTo evaluate your agent's performance you can use `LangSmith` [evaluations](https://docs.smith.langchain.com/evaluation). You would need to first define an evaluator function to judge the results from an agent, such as final outputs or trajectory. Depending on your evaluation technique, this may or may not involve a reference output:\n\n```ts\nconst evaluator = async (params: {\n  inputs: Record<string, unknown>;\n  outputs: Record<string, unknown>;\n  referenceOutputs?: Record<string, unknown>;\n}) => {\n  // compare agent outputs against reference outputs\n  const outputMessages = params.outputs.messages;\n  const referenceMessages = params.referenceOutputs.messages;\n  const score = compareMessages(outputMessages, referenceMessages);\n  return { key: \"evaluator_score\", score: score };\n};\n```\n\nTo get started, you can use prebuilt evaluators from `AgentEvals` package:\n\n```bash\nnpm install agentevals @langchain/core\n```\n\n## Create evaluator\n\nA common way to evaluate agent performance is by comparing its trajectory (the order in which it calls its tools) against a reference trajectory:\n\n```ts\n// highlight-next-line\nimport { createTrajectoryMatchEvaluator } from \"agentevals\";\n\nconst outputs = [\n  {\n    role: \"assistant\",\n    tool_calls: [\n      {\n        function: {\n          name: \"get_weather\",\n          arguments: JSON.stringify({ city: \"san francisco\" }),\n        },\n      },\n      {\n        function: {\n          name: \"get_directions\",\n          arguments: JSON.stringify({ destination: \"presidio\" }),\n        },\n      },\n    ],\n  },\n];\n\nconst referenceOutputs = [\n  {\n    role: \"assistant\",\n    tool_calls: [\n      {\n        function: {\n          name: \"get_weather\",\n          arguments: JSON.stringify({ city: \"san francisco\" }),\n        },\n      },\n    ],\n  },\n];\n\n// Create the evaluator\nconst evaluator = createTrajectoryMatchEvaluator({\n  // highlight-next-line\n  trajectoryMatchMode: \"superset\",  // (1)!\n})\n\n// Run the evaluator\nconst result = await evaluator({\n  outputs,\n  referenceOutputs,\n});\n```\n\n1. Specify how the trajectories will be compared. `superset` will accept output trajectory as valid if it's a superset of the reference one. Other options include: [strict](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#strict-match), [unordered](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#unordered-match) and [subset](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#subset-and-superset-match)\n\n\nAs a next step, learn more about how to [customize trajectory match evaluator](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#agent-trajectory-match).\n\n### LLM-as-a-judge\n\nYou can use LLM-as-a-judge evaluator that uses an LLM to compare the trajectory against the reference outputs and output a score:\n\n```ts\nimport {\n  // highlight-next-line\n  createTrajectoryLLMAsJudge,\n  TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE\n} from \"agentevals\";\n\nconst evaluator = createTrajectoryLLMAsJudge({\n  prompt: TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE,\n  model: \"openai:o3-mini\",\n});\n```\n\n## Run evaluator\n\nTo run an evaluator, you will first need to create a [LangSmith dataset](https://docs.smith.langchain.com/evaluation/concepts#datasets). To use the prebuilt AgentEvals evaluators, you will need a dataset with the following schema:\n\n- **input**: `{ messages: [...] }` input messages to call the agent with.\n- **output**: `{ messages\": [...] }` expected message history in the agent output. For trajectory evaluation, you can choose to keep only assistant messages.\n\n```ts\nimport { evaluate } from \"langsmith/evaluation\";\nimport { createTrajectoryMatchEvaluator } from \"agentevals\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\nconst agent = createReactAgent({ ... })\nconst evaluator = createTrajectoryMatchEvaluator({ ... })\nawait evaluate(\n  async (inputs) => await agent.invoke(inputs),\n  {\n    // replace with your dataset name\n    data: \"<Name of your dataset>\",\n    evaluators: [evaluator],\n  }\n);\n```","docs/docs/agents/deployment.md":"# Deployment\n\nTo deploy your LangGraph agent, create and configure a LangGraph app. This setup supports both local development and production deployments.\n\nFeatures: \n\n* 🖥️ Local server for development\n* 🧩 Studio Web UI for visual debugging\n* ☁️ Cloud and 🔧 self-hosted deployment options\n* 📊 LangSmith integration for tracing and observability\n\n!!! info \"Requirements\" \n\n    - ✅ You **must** have a [LangSmith account](https://www.langchain.com/langsmith). You can sign up for **free** and get started with the free tier.\n\n## Create a LangGraph app\n\n```bash\nnpm install -g create-langgraph\ncreate-langgraph path/to/your/app\n```\n\nFollow the prompts and select `New LangGraph Project`. This will create an empty LangGraph project. You can modify it by replacing the code in `src/agent/graph.ts` with your agent code. For example:\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst getWeather = tool(\n  async (input: { city: string }) => {\n    return `It's always sunny in ${input.city}!`;\n  },\n  {\n    name: \"getWeather\",\n    schema: z.object({\n      city: z.string().describe(\"The city to get the weather for\"),\n    }),\n    description: \"Get weather for a given city.\",\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n// make sure to export the graph that will be used in the LangGraph API server\n// highlight-next-line\nexport const graph = createReactAgent({\n  llm,\n  tools: [getWeather],\n  prompt: \"You are a helpful assistant\"\n})\n```\n\n### Install dependencies\n\nIn the root of your new LangGraph app, install the dependencies:\n\n```shell\nyarn\n# install these to use initChatModel with Anthropic\nyarn add langchain\nyarn add @langchain/anthropic\n```\n\n### Create an `.env` file\n\nYou will find a `.env.example` in the root of your new LangGraph app. Create\na `.env` file in the root of your new LangGraph app and copy the contents of the `.env.example` file into it, filling in the necessary API keys:\n\n```bash\nLANGSMITH_API_KEY=lsv2...\nANTHROPIC_API_KEY=sk-\n```\n\n## Launch LangGraph server locally\n\n```shell\nnpx @langchain/langgraph-cli dev\n```\n\nThis will start up the LangGraph API server locally. If this runs successfully, you should see something like:\n\n>    Welcome to LangGraph.js!\n> \n>    - 🚀 API: http://localhost:2024\n>     \n>    - 🎨 Studio UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024\n\n## LangGraph Studio Web UI\n\nLangGraph Studio Web is a specialized UI that you can connect to LangGraph API server to enable visualization, interaction, and debugging of your application locally. Test your graph in the LangGraph Studio Web UI by visiting the URL provided in the output of the `npx @langchain/langgraph-cli dev` command.\n\n>    - LangGraph Studio Web UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024\n\n## Deployment\n\nOnce your LangGraph app is running locally, you can deploy it using LangSmith Deployment or self-hosted options. Refer to the [deployment options guide](https://langchain-ai.github.io/langgraph/tutorials/deployment/) for detailed instructions on all supported deployment models.\n","docs/docs/agents/mcp.md":"# MCP Integration\n\n[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open protocol that standardizes how applications provide tools and context to language models. LangGraph agents can use tools defined on MCP servers through the `@langchain/mcp-adapters` library.\n\n![MCP](./assets/mcp.png)\n\nInstall the `@langchain/mcp-adapters` library to use MCP tools in LangGraph:\n\n```bash\nnpm install @langchain/mcp-adapters\n```\n\n## Use MCP tools\n\nThe `@langchain/mcp-adapters` package enables agents to use tools defined across one or more MCP servers.\n\n```ts\n// highlight-next-line\nimport { MultiServerMCPClient } from \"@langchain/mcp-adapters\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n// highlight-next-line\nconst client = new MultiServerMCPClient({\n  mcpServers: {\n    \"math\": {\n      command: \"python\",\n      // Replace with absolute path to your math_server.py file\n      args: [\"/path/to/math_server.py\"],\n      transport: \"stdio\",\n    },\n    \"weather\": {\n      // Ensure your start your weather server on port 8000\n      url: \"http://localhost:8000/sse\",\n      transport: \"sse\",\n    }\n  }\n})\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  // highlight-next-line\n  tools: await client.getTools()\n});\n \nconst mathResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what's (3 + 5) x 12?\" } ] }\n);\nconst weatherResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what is the weather in nyc?\" } ] }\n);\nawait client.close();\n```\n\n## Custom MCP servers\n\nTo create your own MCP servers, you can use the `mcp` library in Python (or `@modelcontextprotocol/sdk` in TypeScript). These libraries provide a simple way to define tools and run them as servers.\n\nInstall the MCP library:\n\n```bash\npip install mcp\n```\nUse the following reference implementations to test your agent with MCP tool servers.\n\n```python title=\"Example Math Server (stdio transport)\"\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"Math\")\n\n@mcp.tool()\ndef add(a: int, b: int) -> int:\n    \"\"\"Add two numbers\"\"\"\n    return a + b\n\n@mcp.tool()\ndef multiply(a: int, b: int) -> int:\n    \"\"\"Multiply two numbers\"\"\"\n    return a * b\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"stdio\")\n```\n\n```python title=\"Example Weather Server (SSE transport)\"\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"Weather\")\n\n@mcp.tool()\nasync def get_weather(location: str) -> str:\n    \"\"\"Get weather for location.\"\"\"\n    return \"It's always sunny in New York\"\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"sse\")\n```\n\n## Additional resources\n\n- [MCP documentation](https://modelcontextprotocol.io/introduction)\n- [MCP Transport documentation](https://modelcontextprotocol.io/docs/concepts/transports)","docs/docs/agents/human-in-the-loop.md":"# Human-in-the-loop\n\nTo review, edit and approve tool calls in an agent you can use LangGraph's built-in [human-in-the-loop](../concepts/human_in_the_loop.md) features, specifically the [`interrupt()`](/langgraphjs/reference/functions/langgraph.interrupt-1.html) primitive.\n\nLangGraph allows you to pause execution **indefinitely** — for minutes, hours, or even days—until human input is received.\n\nThis is possible because the agent state is **checkpointed into a database**, which allows the system to persist execution context and later resume the workflow, continuing from where it left off.\n\nFor a deeper dive into the **human-in-the-loop** concept, see the [concept guide](../concepts/human_in_the_loop.md).\n\n<figure markdown=\"1\">\n![image](../concepts/img/human_in_the_loop/tool-call-review.png){: style=\"max-height:400px\"}\n<figcaption>\nA human can review and edit the output from the agent before proceeding. This is particularly critical in applications where the tool calls requested may be sensitive or require human oversight.\n</figcaption>\n</figure>\n\n\n## Review tool calls\n\nTo add a human approval step to a tool:\n\n1. Use `interrupt()` in the tool to pause execution.\n2. Resume with a `Command({ resume: ... })` to continue based on human input.\n\n```ts\nimport { MemorySaver } from \"@langchain/langgraph-checkpoint\";\nimport { interrupt } from \"@langchain/langgraph\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\n// An example of a sensitive tool that requires human review / approval\nconst bookHotel = tool(\n  async (input: { hotelName: string; }) => {\n    let hotelName = input.hotelName;\n    // highlight-next-line\n    const response = interrupt(  // (1)!\n      `Trying to call \\`book_hotel\\` with args {'hotel_name': ${hotelName}}. ` +\n      `Please approve or suggest edits.`\n    )\n    if (response.type === \"accept\") {\n      // proceed to execute the tool logic\n    } else if (response.type === \"edit\") {\n        hotelName = response.args[\"hotel_name\"]\n    } else {\n        throw new Error(`Unknown response type: ${response.type}`)\n    }\n    return `Successfully booked a stay at ${hotelName}.`;\n  },\n  {\n    name: \"bookHotel\",\n    schema: z.object({\n      hotelName: z.string().describe(\"Hotel to book\"),\n    }),\n    description: \"Book a hotel.\",\n  }\n);\n\n// highlight-next-line\nconst checkpointer = new MemorySaver();  // (2)!\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [bookHotel],\n  // highlight-next-line\n  checkpointer  // (3)!\n});\n```\n\n1. The [`interrupt` function](/langgraphjs/reference/functions/langgraph.interrupt-1.html) pauses the agent graph at a specific node. In this case, we call `interrupt()` at the beginning of the tool function, which pauses the graph at the node that executes the tool. The information inside `interrupt()` (e.g., tool calls) can be presented to a human, and the graph can be resumed with the user input (tool call approval, edit or feedback).\n2. The `InMemorySaver` is used to store the agent state at every step in the tool calling loop. This enables [short-term memory](./memory.md#short-term-memory) and [human-in-the-loop](./human-in-the-loop.md) capabilities. In this example, we use `InMemorySaver` to store the agent state in memory. In a production application, the agent state will be stored in a database.\n3. Initialize the agent with the `checkpointer`.\n\nRun the agent with the `stream()` method, passing the `config` object to specify the thread ID. This allows the agent to resume the same conversation on future invocations.\n\n```ts\nconst config = {\n   configurable: {\n      // highlight-next-line\n      \"thread_id\": \"1\"\n   }\n}\n\nfor await (const chunk of await agent.stream(\n  { messages: \"book a stay at McKittrick hotel\" },\n  // highlight-next-line\n  config\n)) {\n  console.log(chunk);\n  console.log(\"\\n\");\n};\n```\n\n> You should see that the agent runs until it reaches the `interrupt()` call, at which point it pauses and waits for human input.\n\nResume the agent with a `Command({ resume: ... })` to continue based on human input.\n\n```ts\nimport { Command } from \"@langchain/langgraph\";\n\nfor await (const chunk of await agent.stream(\n  new Command({ resume: { type: \"accept\" } }),  // (1)!\n  // new Command({ resume: { type: \"edit\", args: { \"hotel_name\": \"McKittrick Hotel\" } } }),\n  // highlight-next-line\n  config\n)) {\n  console.log(chunk);\n  console.log(\"\\n\");\n};\n```\n\n1. The [`interrupt` function](/langgraphjs/reference/functions/langgraph.interrupt-1.html) is used in conjunction with the [`Command`](/langgraphjs/reference/classes/langgraph.Command.html) object to resume the graph with a value provided by the human.\n\n## Additional resources\n\n* [Human-in-the-loop in LangGraph](../concepts/human_in_the_loop.md)","docs/docs/agents/context.md":"# Context\n\nAgents often require more than a list of messages to function effectively. They need **context**.\n\nContext includes *any* data outside the message list that can shape agent behavior or tool execution. This can be:\n\n- Information passed at runtime, like a `user_id` or API credentials.\n- Internal state updated during a multi-step reasoning process.\n- Persistent memory or facts from previous interactions.\n\nLangGraph provides **three** primary ways to supply context:\n\n| Type                                                                         | Description                                   | Mutable? | Lifetime                |\n|------------------------------------------------------------------------------|-----------------------------------------------|----------|-------------------------|\n| [**Config**](#config-static-context)                                         | data passed at the start of a run             | ❌        | per run                 |\n| [**State**](#state-mutable-context)                                          | dynamic data that can change during execution | ✅        | per run or conversation |\n| [**Long-term Memory (Store)**](#long-term-memory-cross-conversation-context) | data that can be shared between conversations | ✅        | across conversations    |\n\nYou can use context to:\n\n- Adjust the system prompt the model sees\n- Feed tools with necessary inputs\n- Track facts during an ongoing conversation\n\n## Providing Runtime Context\n\nUse this when you need to inject data into an agent at runtime.\n\n### Config (static context)\n\nConfig is for immutable data like user metadata or API keys. Use\nwhen you have values that don't change mid-run.\n\nSpecify configuration using a key called **\"configurable\"** which is reserved\nfor this purpose:\n\n```ts\nawait agent.invoke(\n  { messages: \"hi!\" },\n  // highlight-next-line\n  { configurable: { userId: \"user_123\" } }\n)\n```\n\n### State (mutable context)\n\nState acts as short-term memory during a run. It holds dynamic data that can evolve during execution, such as values derived from tools or LLM outputs.\n\n```ts\nconst CustomState = Annotation.Root({\n  ...MessagesAnnotation.spec,\n  userName: Annotation<string>,\n});\n\nconst agent = createReactAgent({\n  // Other agent parameters...\n  // highlight-next-line\n  stateSchema: CustomState,\n})\n\nawait agent.invoke(\n  // highlight-next-line\n  { messages: \"hi!\", userName: \"Jane\" }\n)\n```\n\n!!! tip \"Turning on memory\"\n\n    Please see the [memory guide](./memory.md) for more details on how to enable memory. This is a powerful feature that allows you to persist the agent's state across multiple invocations.\n    Otherwise, the state is scoped only to a single agent run.\n\n\n\n### Long-Term Memory (cross-conversation context)\n\nFor context that spans *across* conversations or sessions, LangGraph allows access to **long-term memory** via a `store`. This can be used to read or update persistent facts (e.g., user profiles, preferences, prior interactions). For more, see the [Memory guide](./memory.md).\n\n## Customizing Prompts with Context\n\nPrompts define how the agent behaves. To incorporate runtime context, you can dynamically generate prompts based on the agent's state or config.\n\nCommon use cases:\n\n- Personalization\n- Role or goal customization\n- Conditional behavior (e.g., user is admin)\n\n=== \"Using config\"\n\n    ```ts\n    import { BaseMessageLike } from \"@langchain/core/messages\";\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { MessagesAnnotation } from \"@langchain/langgraph\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n    const prompt = (\n      state: typeof MessagesAnnotation.State,\n      // highlight-next-line\n      config: RunnableConfig\n    ): BaseMessageLike[] => {\n      // highlight-next-line\n      const userName = config.configurable?.userName;\n      const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;\n      return [{ role: \"system\", content: systemMsg }, ...state.messages];\n    };\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // highlight-next-line\n      prompt\n    });\n\n    await agent.invoke(\n      { messages: \"hi!\" },\n      // highlight-next-line\n      { configurable: { userName: \"John Smith\" } }\n    );\n    ```\n\n=== \"Using state\"\n\n    ```ts\n    import { BaseMessageLike } from \"@langchain/core/messages\";\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { Annotation, MessagesAnnotation } from \"@langchain/langgraph\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n    const CustomState = Annotation.Root({\n      ...MessagesAnnotation.spec,\n      // highlight-next-line\n      userName: Annotation<string>,\n    });\n\n    const prompt = (\n      // highlight-next-line\n      state: typeof CustomState.State,\n    ): BaseMessageLike[] => {\n      // highlight-next-line\n      const userName = state.userName;\n      const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;\n      return [{ role: \"system\", content: systemMsg }, ...state.messages];\n    };\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // highlight-next-line\n      prompt,\n      // highlight-next-line\n      stateSchema: CustomState,\n    });\n\n    await agent.invoke(\n      // highlight-next-line\n      { messages: \"hi!\", userName: \"John Smith\" },\n    );\n    ```\n\n## Tools\n\nTools can access context through:\n\n* Use `RunnableConfig` for config access\n* Use `runtime.state` (the second argument, typed as `ToolRuntime`) for agent state\n\n!!! tip \"Browser / web environments\"\n\n    When a tool runs inside a `ToolNode` (including in `createReactAgent`), the `ToolNode` forwards its input (the current graph state) to the tool via `runtime.state`. This works in every runtime, including web browsers.\n\n    An older alternative, `getCurrentTaskInput()`, relies on [`AsyncLocalStorage`](https://nodejs.org/api/async_hooks.html), which is available in Node.js, Deno, and Cloudflare Workers, but **not** in web browsers. Prefer `runtime.state` for portability.\n\n=== \"Using config\"\n\n    ```ts\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { tool } from \"@langchain/core/tools\";\n    import { z } from \"zod\";\n\n    const getUserInfo = tool(\n      async (input: Record<string, any>, config: RunnableConfig) => {\n        // highlight-next-line\n        const userId = config.configurable?.userId;\n        return userId === \"user_123\" ? \"User is John Smith\" : \"Unknown user\";\n      },\n      {\n        name: \"get_user_info\",\n        description: \"Look up user info.\",\n        schema: z.object({}),\n      }\n    );\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getUserInfo],\n    });\n\n    await agent.invoke(\n      { messages: \"look up user information\" },\n      // highlight-next-line\n      { configurable: { userId: \"user_123\" } }\n    );\n    ```\n\n=== \"Using state\"\n\n    ```ts\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { Annotation, MessagesAnnotation } from \"@langchain/langgraph\";\n    import { tool, type ToolRuntime } from \"@langchain/core/tools\";\n    import { z } from \"zod\";\n\n    const CustomState = Annotation.Root({\n      ...MessagesAnnotation.spec,\n      // highlight-next-line\n      userId: Annotation<string>(),\n    });\n\n    const getUserInfo = tool(\n      async (\n        input: Record<string, any>,\n        // highlight-next-line\n        runtime: ToolRuntime<typeof CustomState.State>,\n      ) => {\n        // Read the graph state directly from the second argument.\n        // This works in web browsers too (no AsyncLocalStorage required).\n        // highlight-next-line\n        const userId = runtime.state.userId;\n        return userId === \"user_123\" ? \"User is John Smith\" : \"Unknown user\";\n      },\n      {\n        name: \"get_user_info\",\n        description: \"Look up user info.\",\n        schema: z.object({})\n      }\n    );\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getUserInfo],\n      // highlight-next-line\n      stateSchema: CustomState,\n    });\n\n    await agent.invoke(\n      // highlight-next-line\n      { messages: \"look up user information\", userId: \"user_123\" }\n    );\n    ```\n\n\n## Update context from tools\n\nTools can modify the agent's state during execution. This is useful for persisting intermediate results or making information accessible to subsequent tools or prompts.\n\n```ts\nimport { Annotation, MessagesAnnotation, LangGraphRunnableConfig, Command } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\nconst CustomState = Annotation.Root({\n  ...MessagesAnnotation.spec,\n  // highlight-next-line\n  userName: Annotation<string>(), // Will be updated by the tool\n});\n\nconst getUserInfo = tool(\n  async (\n    _input: Record<string, never>,\n    config: LangGraphRunnableConfig\n  ): Promise<Command> => {\n    const userId = config.configurable?.userId;\n    if (!userId) {\n      throw new Error(\"Please provide a user id in config.configurable\");\n    }\n\n    const toolCallId = config.toolCall?.id;\n\n    const name = userId === \"user_123\" ? \"John Smith\" : \"Unknown user\";\n    // Return command to update state\n    return new Command({\n      update: {\n        // highlight-next-line\n        userName: name,\n        // Update the message history\n        // highlight-next-line\n        messages: [\n          new ToolMessage({\n            content: \"Successfully looked up user information\",\n            tool_call_id: toolCallId,\n          }),\n        ],\n      },\n    });\n  },\n  {\n    name: \"get_user_info\",\n    description: \"Look up user information.\",\n    schema: z.object({}),\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getUserInfo],\n  // highlight-next-line\n  stateSchema: CustomState,\n});\n\nawait agent.invoke(\n  { messages: \"look up user information\" },\n  // highlight-next-line\n  { configurable: { userId: \"user_123\" } }\n);\n```\n\nFor more details, see [how to update state from tools](../how-tos/update-state-from-tools.ipynb).","docs/docs/agents/models.md":"# Models\n\nThis page describes how to configure the chat model used by an agent.\n\n## Tool calling support\n\nTo enable tool-calling agents, the underlying LLM must support [tool calling](https://js.langchain.com/docs/concepts/tool_calling/).\n\nCompatible models can be found in the [LangChain integrations directory](https://js.langchain.com/docs/integrations/chat/).\n\n## Using `initChatModel`\n\nThe [`initChatModel`](https://js.langchain.com/docs/how_to/chat_models_universal_init/) utility simplifies model initialization with configurable parameters:\n\n```ts\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\nconst llm = await initChatModel(\n  \"anthropic:claude-3-7-sonnet-latest\",\n  {\n    temperature: 0,\n    maxTokens: 2048\n  }\n);\n```\n\nRefer to the [API reference](https://api.js.langchain.com/functions/langchain.chat_models_universal.initChatModel.html) for advanced options.\n\n## Using provider-specific LLMs \n\nIf a model provider is not available via `initChatModel`, you can instantiate the provider's model class directly. The model must implement the [`BaseChatModel`](https://api.js.langchain.com/classes/_langchain_core.language_models_chat_models.BaseChatModel.html) interface and support tool calling:\n\n```ts\nimport { ChatAnthropic } from \"@langchain/anthropic\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n// highlight-next-line\nconst llm = new ChatAnthropic({\n  modelName: \"claude-3-7-sonnet-latest\",\n  temperature: 0,\n  maxTokens: 2048\n});\n\nconst agent = createReactAgent({\n  // highlight-next-line\n  llm,\n  // other parameters\n});\n```\n\n!!! note \"Illustrative example\" \n\n    The example above uses `ChatAnthropic`, which is already supported by `initChatModel`. This pattern is shown to illustrate how to manually instantiate a model not available through `initChatModel`.\n\n## Additional resources\n\n- [Model integration directory](https://js.langchain.com/docs/integrations/chat/)\n- [Universal initialization with `initChatModel`](https://js.langchain.com/docs/how_to/chat_models_universal_init/)","docs/docs/agents/prebuilt.md":"# Community Agents\n\nTo share your project, simply open a Pull Request adding an entry for your package in our [packages.yml](https://github.com/langchain-ai/langgraph/blob/main/docs/_scripts/third_party_page/packages.yml) file.\n\n[//]: # (This file is stub. Do not edit this file directly!)\n[//]: # (1. Update the `packages.yml` file in the `docs/_scripts/third_party_page` directory.)\n[//]: # (2. From the /docs directory, run `make build-prebuilt` to generate an updated version of this file for testing locally.)\n","docs/docs/agents/memory.md":"# Memory\n\nLangGraph supports two types of memory essential for building conversational agents:\n\n- **[Short-term memory](#short-term-memory)**: Tracks the ongoing conversation by maintaining message history within a session.\n- **[Long-term memory](#long-term-memory)**: Stores user-specific or application-level data across sessions.\n\nThis guide demonstrates how to use both memory types with agents in LangGraph. For a deeper\nunderstanding of memory concepts, refer to the [LangGraph memory documentation](../concepts/memory.md).\n\n<figure markdown=\"1\">\n![image](./assets/memory.png){: style=\"max-height:400px\"}\n<figcaption>Both <strong>short-term</strong> and <strong>long-term</strong> memory require persistent storage to maintain continuity across LLM interactions. In production environments, this data is typically stored in a database.</figcaption>\n</figure>\n\n!!! note \"Terminology\"\n\n    In LangGraph:\n\n    - *Short-term memory* is also referred to as **thread-level memory**.\n    - *Long-term memory* is also called **cross-thread memory**.\n\n    A [thread](../concepts/persistence.md#threads) represents a sequence of related runs\n    grouped by the same `thread_id`.\n\n## Short-term memory\n\nShort-term memory enables agents to track multi-turn conversations. To use it, you must:\n\n1. Provide a `checkpointer` when creating the agent. The `checkpointer` enables [persistence](../concepts/persistence.md) of the agent's state.\n2. Supply a `thread_id` in the config when running the agent. The `thread_id` is a unique identifier for the conversation session.\n\n```ts\n// highlight-next-line\nimport { MemorySaver } from \"@langchain/langgraph-checkpoint\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\n// highlight-next-line\nconst checkpointer = new MemorySaver();  // (1)!\n\nconst getWeather = tool(\n  async (input: { city: string }) => {\n    return `It's always sunny in ${input.city}!`;\n  },\n  {\n    name: \"getWeather\",\n    schema: z.object({\n      city: z.string().describe(\"The city to get the weather for\"),\n    }),\n    description: \"Get weather for a given city.\",\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather],\n  // highlight-next-line\n  checkpointer  // (2)!\n});\n\n// Run the agent\n// highlight-next-line\nconst config = { configurable: { thread_id: \"1\" } };  // (3)!\nconst sfResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what is the weather in sf\" } ] },\n  config  // (4)!\n);\nconst nyResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what about new york?\" } ] },\n  config\n);\n```\n\n1. The `MemorySaver` is a checkpointer that stores the agent's state in memory. In a production setting, you would typically use a database or other persistent storage. Please review the [checkpointer documentation](https://langchain-ai.github.io/langgraphjs/reference/index.html) for more options. If you're deploying with **LangGraph Platform**, the platform will provide a production-ready checkpointer for you.\n2. The `checkpointer` is passed to the agent. This enables the agent to persist its state across invocations. Please note that \n3. A unique `thread_id` is provided in the config. This ID is used to identify the conversation session. The value is controlled by the user and can be any string.\n4. The agent will continue the conversation using the same `thread_id`. This will allow the agent to infer that the user is asking specifically about the **weather** in New York. \n\nWhen the agent is invoked the second time with the same `thread_id`, the original message history from the first conversation is automatically included, allowing the agent to infer that the user is asking specifically about the **weather** in New York.\n\n!!! Note \"LangGraph Platform providers a production-ready checkpointer\"\n\n    If you're using [LangGraph Platform](./deployment.md), during deployment your checkpointer will be automatically configured to use a production-ready database.\n\n## Long-term memory\n\nUse long-term memory to store user-specific or application-specific data across conversations. This is useful for applications like chatbots, where you want to remember user preferences or other information.\n\nTo use long-term memory, you need to:\n\n1. [Configure a store](../how-tos/cross-thread-persistence.ipynb) to persist data across invocations.\n2. Use the `config.store` to access the store from within tools or prompts.\n\n### Reading\n\n```ts title=\"A tool the agent can use to look up user information\"\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n// highlight-next-line\nimport { InMemoryStore } from \"@langchain/langgraph-checkpoint\";\n// highlight-next-line\nimport { getStore } from \"@langchain/langgraph\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst store = new InMemoryStore(); // (1)!\n\nawait store.put(  // (2)!\n  [\"users\"],  // (3)!\n  \"user_123\",  // (4)!\n  {\n    name: \"John Smith\",\n    language: \"English\",\n  } // (5)!\n);\n\n// Look up user info tool\nconst getUserInfo = tool(\n  async (input: Record<string, any>, config: LangGraphRunnableConfig): Promise<string> => {\n    // Same as that provided to `createReactAgent`\n    const store = config.store; // (6)!\n    if (!store) {\n      throw new Error(\"store is required when compiling the graph\");\n    }\n\n    const userId = config.configurable?.userId;\n    if (!userId) {\n      throw new Error(\"userId is required in the config\");\n    }\n\n    const userInfo = await store.get([\"users\"], userId); // (7)!\n    return userInfo ? JSON.stringify(userInfo.value) : \"Unknown user\";\n  },\n  {\n    name: \"get_user_info\",\n    description: \"Look up user info.\",\n    schema: z.object({}),\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getUserInfo],\n  store, // (8)!\n});\n\n// Run the agent\nconst response = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"look up user information\" } ] },\n  { configurable: { userId: \"user_123\" } }\n);\n```\n\n1. The `InMemoryStore` is a store that stores data in memory. In a production setting, you would typically use a database or other persistent storage. Please review the [documentation](https://langchain-ai.github.io/langgraphjs/reference/index.html) for more options. If you're deploying with **LangGraph Platform**, the platform will provide a production-ready store for you.\n2. For this example, we write some sample data to the store using the `put` method. Please see the [BaseStore.put](https://langchain-ai.github.io/langgraphjs/reference/classes/checkpoint.BaseStore.html#put) API reference for more details.\n3. The first argument is the namespace. This is used to group related data together. In this case, we are using the `users` namespace to group user data.\n4. A key within the namespace. This example uses a user ID for the key.\n5. The data that we want to store for the given user.\n6. You can access the store via `config.store` from anywhere in your nodes, tools and prompts. It contains the store that was passed to the agent when it was created.\n7. The `get` method is used to retrieve data from the store. The first argument is the namespace, and the second argument is the key. This will return a `StoreValue` object, which contains the value and metadata about the value.\n8. The `store` is passed to the agent. This enables the agent to access the store when running tools.\n\n### Writing\n\n```ts title=\"Example of a tool that updates user information\"\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { InMemoryStore } from \"@langchain/langgraph-checkpoint\";\nimport { getStore } from \"@langchain/langgraph\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst store = new InMemoryStore(); // (1)!\n\ninterface UserInfo { // (2)!\n  name: string;\n}\n\n// Save user info tool\nconst saveUserInfo = tool(  // (3)!\n  async (input: UserInfo, config: LangGraphRunnableConfig): Promise<string> => {\n    // Same as that provided to `createReactAgent`\n    // highlight-next-line\n    const store = config.store; // (4)!\n    if (!store) {\n      throw new Error(\"store is required when compiling the graph\");\n    }\n\n    const userId = config.configurable?.userId;\n    if (!userId) {\n      throw new Error(\"userId is required in the config\");\n    }\n\n    await store.put([\"users\"], userId, input); // (5)!\n    return \"Successfully saved user info.\";\n  },\n  {\n    name: \"save_user_info\",\n    description: \"Save user info.\",\n    schema: z.object({\n      name: z.string(),\n    }),\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [saveUserInfo],\n  // highlight-next-line\n  store,\n});\n\n// Run the agent\nawait agent.invoke(\n  { messages: [ { role: \"user\", content: \"My name is John Smith\" } ] },\n  { configurable: { userId: \"user_123\" } } // (6)!\n);\n\n// You can access the store directly to get the value\nconst userInfo = await store.get([\"users\"], \"user_123\")\nuserInfo.value\n```\n\n1. The `InMemoryStore` is a store that stores data in memory. In a production setting, you would typically use a database or other persistent storage. Please review the [store documentation](../reference/stores.md) for more options. If you're deploying with **LangGraph Platform**, the platform will provide a production-ready store for you.\n2. The `UserInfo` class is an interface that defines the structure of the user information. We will specify the same schema below using a zod object, so that the LLM formats the response according to the schema.\n3. The `saveUserInfo` is a tool that allows an agent to update user information. This could be useful for a chat application where the user wants to update their profile information.\n4. You can access the store via `config.store` from anywhere in your nodes, tools and prompts. It contains the store that was passed to the agent when it was created.\n5. The `put` method is used to store data in the store. The first argument is the namespace, and the second argument is the key. This will store the user information in the store.\n6. The `userId` is passed in the config. This is used to identify the user whose information is being updated.\n\n## Additional resources\n\n* [Memory in LangGraph](../concepts/memory.md)","docs/docs/agents/multi-agent.md":"# Multi-agent\n\nA single agent might struggle if it needs to specialize in multiple domains or manage many tools. To tackle this, you can break your agent into smaller, independent agents and composing them into a [multi-agent system](../concepts/multi_agent.md).\n\nIn multi-agent systems, agents need to communicate between each other. They do so via [handoffs](#handoffs) — a primitive that describes which agent to hand control to and the payload to send to that agent.\n\nTwo of the most popular multi-agent architectures are:\n\n- [supervisor](#supervisor) — individual agents are coordinated by a central supervisor agent. The supervisor controls all communication flow and task delegation, making decisions about which agent to invoke based on the current context and task requirements.\n- [swarm](#swarm) — agents dynamically hand off control to one another based on their specializations. The system remembers which agent was last active, ensuring that on subsequent interactions, the conversation resumes with that agent.\n\n## Supervisor\n\n![Supervisor](./assets/supervisor.png)\n\nUse [`langgraph-supervisor`](https://github.com/langchain-ai/langgraphjs/tree/main/libs/langgraph-supervisor) library to create a supervisor multi-agent system:\n\n```bash\nnpm install @langchain/langgraph-supervisor\n```\n\n```ts\nimport { ChatOpenAI } from \"@langchain/openai\";\n// highlight-next-line\nimport { createSupervisor } from \"@langchain/langgraph-supervisor\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst bookHotel = tool(\n  async (input: { hotel_name: string }) => {\n    return `Successfully booked a stay at ${input.hotel_name}.`;\n  },\n  {\n    name: \"book_hotel\",\n    description: \"Book a hotel\",\n    schema: z.object({\n      hotel_name: z.string().describe(\"The name of the hotel to book\"),\n    }),\n  }\n);\n\nconst bookFlight = tool(\n  async (input: { from_airport: string; to_airport: string }) => {\n    return `Successfully booked a flight from ${input.from_airport} to ${input.to_airport}.`;\n  },\n  {\n    name: \"book_flight\",\n    description: \"Book a flight\",\n    schema: z.object({\n      from_airport: z.string().describe(\"The departure airport code\"),\n      to_airport: z.string().describe(\"The arrival airport code\"),\n    }),\n  }\n);\n\nconst llm = new ChatOpenAI({ modelName: \"gpt-4o\" });\n\n// Create specialized agents\nconst flightAssistant = createReactAgent({\n  llm,\n  tools: [bookFlight],\n  prompt: \"You are a flight booking assistant\",\n  // highlight-next-line\n  name: \"flight_assistant\",\n});\n\nconst hotelAssistant = createReactAgent({\n  llm,\n  tools: [bookHotel],\n  prompt: \"You are a hotel booking assistant\",\n  // highlight-next-line\n  name: \"hotel_assistant\",\n});\n\n// highlight-next-line\nconst supervisor = createSupervisor({\n  agents: [flightAssistant, hotelAssistant],\n  llm,\n  prompt: \"You manage a hotel booking assistant and a flight booking assistant. Assign work to them, one at a time.\",\n}).compile();\n\nconst stream = await supervisor.stream({\n  messages: [{\n    role: \"user\",\n    content: \"first book a flight from BOS to JFK and then book a stay at McKittrick Hotel\"\n  }]\n});\n\nfor await (const chunk of stream) {\n  console.log(chunk);\n  console.log(\"\\n\");\n}\n```\n\n## Swarm\n\n![Swarm](./assets/swarm.png)\n\nUse [`langgraph-swarm`](https://github.com/langchain-ai/langgraphjs/tree/main/libs/langgraph-swarm) library to create a swarm multi-agent system:\n\n```bash\nnpm install @langchain/langgraph-swarm\n```\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { ChatAnthropic } from \"@langchain/anthropic\";\n// highlight-next-line\nimport { createSwarm, createHandoffTool } from \"@langchain/langgraph-swarm\";\n\nconst transferToHotelAssistant = createHandoffTool({\n  agentName: \"hotel_assistant\",\n  description: \"Transfer user to the hotel-booking assistant.\",\n});\n\nconst transferToFlightAssistant = createHandoffTool({\n  agentName: \"flight_assistant\",\n  description: \"Transfer user to the flight-booking assistant.\",\n});\n\n\nconst llm = new ChatAnthropic({ modelName: \"claude-3-5-sonnet-latest\" });\n\nconst flightAssistant = createReactAgent({\n  llm,\n  tools: [bookFlight, transferToHotelAssistant],\n  prompt: \"You are a flight booking assistant\",\n  name: \"flight_assistant\",\n});\n\nconst hotelAssistant = createReactAgent({\n  llm,\n  tools: [bookHotel, transferToFlightAssistant],\n  prompt: \"You are a hotel booking assistant\",\n  name: \"hotel_assistant\",\n});\n\n// highlight-next-line\nconst swarm = createSwarm({\n  agents: [flightAssistant, hotelAssistant],\n  defaultActiveAgent: \"flight_assistant\",\n}).compile();\n\nconst stream = await swarm.stream({\n  messages: [{\n    role: \"user\",\n    content: \"first book a flight from BOS to JFK and then book a stay at McKittrick Hotel\"\n  }]\n});\n\nfor await (const chunk of stream) {\n  console.log(chunk);\n  console.log(\"\\n\");\n}\n```\n\n## Handoffs\n\nA common pattern in multi-agent interactions is **handoffs**, where one agent *hands off* control to another. Handoffs allow you to specify:\n\n- **destination**: target agent to navigate to\n- **payload**: information to pass to that agent\n\nThis is used both by `langgraph-supervisor` (supervisor hands off to individual agents) and `langgraph-swarm` (an individual agent can hand off to other agents).\n\nTo implement handoffs with `createReactAgent`, you need to:\n\n1. Create a special tool that can transfer control to a different agent\n\n    ```ts\n    const transferToBob = tool(\n      async (_) => {\n        return new Command({\n          // name of the agent (node) to go to\n          // highlight-next-line\n          goto: \"bob\",\n          // data to send to the agent\n          // highlight-next-line\n          update: { messages: ... },\n          // indicate to LangGraph that we need to navigate to\n          // agent node in a parent graph\n          // highlight-next-line\n          graph: Command.PARENT,\n        });\n      },\n      {\n        name: ...,\n        schema: ...,\n        description: ...\n      }\n    );\n    ```\n\n1. Create individual agents that have access to handoff tools:\n\n    ```ts\n    const flightAssistant = createReactAgent(\n      ..., tools: [bookFlight, transferToHotelAssistant]\n    )\n    const hotelAssistant = createReactAgent(\n      ..., tools=[bookHotel, transferToFlightAssistant]\n    )\n    ```\n\n1. Define a parent graph that contains individual agents as nodes:\n\n    ```ts\n    import { StateGraph, MessagesAnnotation } from \"@langchain/langgraph\";\n\n    const multiAgentGraph = new StateGraph(MessagesAnnotation)\n      .addNode(\"flight_assistant\", flightAssistant)\n      .addNode(\"hotel_assistant\", hotelAssistant)\n      ...\n    ```\n\nPutting this together, here is how you can implement a simple multi-agent system with two agents — a flight booking assistant and a hotel booking assistant:\n\n```ts\nimport { ChatAnthropic } from \"@langchain/anthropic\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { StateGraph, MessagesAnnotation, Command, START, END } from \"@langchain/langgraph\";\nimport { tool, type ToolRuntime } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ToolMessage } from \"@langchain/core/messages\";\n\ninterface CreateHandoffToolParams {\n  agentName: string;\n  description?: string;\n}\n\nconst createHandoffTool = ({\n  agentName,\n  description,\n}: CreateHandoffToolParams) => {\n  const toolName = `transfer_to_${agentName}`;\n  const toolDescription = description || `Ask agent '${agentName}' for help`;\n\n  const handoffTool = tool(\n    async (_, runtime: ToolRuntime<typeof MessagesAnnotation.State>) => {\n      const toolMessage = new ToolMessage({\n        content: `Successfully transferred to ${agentName}`,\n        name: toolName,\n        tool_call_id: runtime.toolCallId,\n      });\n\n      // inject the current agent state\n      // highlight-next-line\n      const state = runtime.state;  // (1)!\n      return new Command({  // (2)!\n        // highlight-next-line\n        goto: agentName,  // (3)!\n        // highlight-next-line\n        update: { messages: state.messages.concat(toolMessage) },  // (4)!\n        // highlight-next-line\n        graph: Command.PARENT,  // (5)!\n      });\n    },\n    {\n      name: toolName,\n      schema: z.object({}),\n      description: toolDescription,\n    }\n  );\n\n  return handoffTool;\n};\n\nconst bookHotel = tool(\n  async (input: { hotel_name: string }) => {\n    return `Successfully booked a stay at ${input.hotel_name}.`;\n  },\n  {\n    name: \"book_hotel\",\n    description: \"Book a hotel\",\n    schema: z.object({\n      hotel_name: z.string().describe(\"The name of the hotel to book\"),\n    }),\n  }\n);\n\nconst bookFlight = tool(\n  async (input: { from_airport: string; to_airport: string }) => {\n    return `Successfully booked a flight from ${input.from_airport} to ${input.to_airport}.`;\n  },\n  {\n    name: \"book_flight\",\n    description: \"Book a flight\",\n    schema: z.object({\n      from_airport: z.string().describe(\"The departure airport code\"),\n      to_airport: z.string().describe(\"The arrival airport code\"),\n    }),\n  }\n);\n\nconst transferToHotelAssistant = createHandoffTool({\n  agentName: \"hotel_assistant\",\n  description: \"Transfer user to the hotel-booking assistant.\",\n});\n\nconst transferToFlightAssistant = createHandoffTool({\n  agentName: \"flight_assistant\",\n  description: \"Transfer user to the flight-booking assistant.\",\n});\n\nconst llm = new ChatAnthropic({ modelName: \"claude-3-5-sonnet-latest\" });\n\nconst flightAssistant = createReactAgent({\n  llm,\n  // highlight-next-line\n  tools: [bookFlight, transferToHotelAssistant],\n  prompt: \"You are a flight booking assistant\",\n  // highlight-next-line\n  name: \"flight_assistant\",\n});\n\nconst hotelAssistant = createReactAgent({\n  llm,\n  // highlight-next-line\n  tools: [bookHotel, transferToFlightAssistant],\n  prompt: \"You are a hotel booking assistant\",\n  // highlight-next-line\n  name: \"hotel_assistant\",\n});\n\nconst multiAgentGraph = new StateGraph(MessagesAnnotation)\n  .addNode(\"flight_assistant\", flightAssistant, { ends: [\"hotel_assistant\", END] })\n  .addNode(\"hotel_assistant\", hotelAssistant, { ends: [\"flight_assistant\", END] })\n  .addEdge(START, \"flight_assistant\")\n  .compile();\n\nconst stream = await multiAgentGraph.stream({\n  messages: [{\n    role: \"user\",\n    content: \"book a flight from BOS to JFK and a stay at McKittrick Hotel\"\n  }]\n});\n\nfor await (const chunk of stream) {\n  console.log(chunk);\n  console.log(\"\\n\");\n}\n```\n\n1. Access agent's state\n2. The `Command` primitive allows specifying a state update and a node transition as a single operation, making it useful for implementing handoffs.\n3. Name of the agent or node to hand off to.\n4. Take the agent's messages and **add** them to the parent's **state** as part of the handoff. The next agent will see the parent state.\n5. Indicate to LangGraph that we need to navigate to agent node in a **parent** multi-agent graph.\n\n!!! Note\n    This handoff implementation assumes that:\n\n    - each agent receives overall message history (across all agents) in the multi-agent system as its input\n    - each agent outputs its internal messages history to the overall message history of the multi-agent system\n\n    Check out LangGraph [supervisor](https://github.com/langchain-ai/langgraph-supervisor-py#customizing-handoff-tools) and [swarm](https://github.com/langchain-ai/langgraph-swarm-py#customizing-handoff-tools) documentation to learn how to customize handoffs.","docs/docs/agents/overview.md":"---\ntitle: Overview\n---\n\n# Agent development with LangGraph\n\n**LangGraph** provides both low-level primitives and high-level prebuilt components for building agent-based applications. This section focuses on the **prebuilt**, **reusable** components designed to help you construct agentic systems quickly and reliably—without the need to implement orchestration, memory, or human feedback handling from scratch.\n\n## What is an agent?\n\nAn _agent_ consists of three components: a **large language model (LLM)**, a set of **tools** it can use, and a **prompt** that provides instructions.\n\nThe LLM operates in a loop. In each iteration, it selects a tool to invoke, provides input, receives the result (an observation), and uses that observation to inform the next action. The loop continues until a stopping condition is met — typically when the agent has gathered enough information to respond to the user.\n\n<figure markdown=\"1\">\n![image](./assets/agent.png){: style=\"max-height:400px\"}\n<figcaption>Agent loop: the LLM selects tools and uses their outputs to fulfill a user request.</figcaption>\n</figure>\n\n## Key features\n\nLangGraph includes several capabilities essential for building robust, production-ready agentic systems:\n\n- [**Memory integration**](./memory.md): Native support for _short-term_ (session-based) and _long-term_ (persistent across sessions) memory, enabling stateful behaviors in chatbots and assistants.\n- [**Human-in-the-loop control**](./human-in-the-loop.md): Execution can pause _indefinitely_ to await human feedback—unlike websocket-based solutions limited to real-time interaction. This enables asynchronous approval, correction, or intervention at any point in the workflow.\n- [**Streaming support**](./streaming.md): Real-time streaming of agent state, model tokens, tool outputs, or combined streams.\n- [**Deployment tooling**](./deployment.md): Includes infrastructure-free deployment tools. [**LangGraph Platform**](https://langchain-ai.github.io/langgraph/concepts/langgraph_platform/) supports testing, debugging, and deployment.\n  - **[Studio](https://langchain-ai.github.io/langgraph/concepts/langgraph_studio/)**: A visual IDE for inspecting and debugging workflows.\n  - Supports multiple [**deployment options**](https://langchain-ai.github.io/langgraph/tutorials/deployment/) for production.\n\n## High-level building blocks\n\nLangGraph comes with a set of prebuilt components that implement common agent behaviors and workflows. These abstractions are built on top of the LangGraph framework, offering a faster path to production while remaining flexible for advanced customization.\n\nUsing LangGraph for agent development allows you to focus on your application's logic and behavior, instead of building and maintaining the supporting infrastructure for state, memory, and human feedback.\n\n## Package ecosystem\n\nThe high-level components are organized into several packages, each with a specific focus.\n\n| Package                  | Description                                                                 | Installation                                       |\n| ------------------------ | --------------------------------------------------------------------------- | -------------------------------------------------- |\n| `langgraph`              | Prebuilt components to [**create agents**](./agents.md)                     | `npm install @langchain/langgraph @langchain/core` |\n| `langgraph-supervisor`   | Tools for building [**supervisor**](./multi-agent.md#supervisor) agents     | `npm install @langchain/langgraph-supervisor`      |\n| `langgraph-swarm`        | Tools for building a [**swarm**](./multi-agent.md#swarm) multi-agent system | `npm install @langchain/langgraph-swarm`           |\n| `langchain-mcp-adapters` | Interfaces to [**MCP servers**](./mcp.md) for tool and resource integration | `npm install @langchain/mcp-adapters`              |\n| `agentevals`             | Utilities to [**evaluate agent performance**](./evals.md)                   | `npm install agentevals`                           |\n\n## Visualize an agent graph\n\nUse the following tool to visualize the graph generated by [`createReactAgent`](/langgraphjs/reference/functions/langgraph_prebuilt.createReactAgent.html) and to view an outline of the corresponding code. It allows you to explore the infrastructure of the agent as defined by the presence of:\n\n- [`tools`](./tools.md): A list of tools (functions, APIs, or other callable objects) that the agent can use to perform tasks.\n- `preModelHook`: A function that is called before the model is invoked. It can be used to condense messages or perform other preprocessing tasks.\n- `postModelHook`: A function that is called after the model is invoked. It can be used to implement guardrails, human-in-the-loop flows, or other postprocessing tasks.\n- [`responseFormat`](./agents.md#structured-output): A data structure used to constrain the type of the final output (via Zod schemas).\n\n<div class=\"agent-layout\">\n  <div class=\"agent-graph-features-container\">\n    <div class=\"agent-graph-features\">\n      <h3 class=\"agent-section-title\">Features</h3>\n      <label><input type=\"checkbox\" id=\"tools\" checked> <code>tools</code></label>\n      <label><input type=\"checkbox\" id=\"preModelHook\"> <code>preModelHook</code></label>\n      <label><input type=\"checkbox\" id=\"postModelHook\"> <code>postModelHook</code></label>\n      <label><input type=\"checkbox\" id=\"responseFormat\"> <code>responseFormat</code></label>\n    </div>\n  </div>\n\n  <div class=\"agent-graph-container\">\n    <h3 class=\"agent-section-title\">Graph</h3>\n    <img id=\"agent-graph-img\" src=\"../assets/react_agent_graphs/0001.svg\" alt=\"graph image\" style=\"max-width: 100%;\"/>\n  </div>\n</div>\n\nThe following code snippet shows how to create the above agent (and underlying graph) with [`createReactAgent`](/langgraphjs/reference/functions/langgraph_prebuilt.createReactAgent.html):\n\n<div class=\"language-typescript\">\n  <pre><code id=\"agent-code\" class=\"language-typescript\"></code></pre>\n</div>\n\n<script>\nfunction getCheckedValue(id) {\n  return document.getElementById(id).checked ? \"1\" : \"0\";\n}\n\nfunction getKey() {\n  return [\n    getCheckedValue(\"responseFormat\"),\n    getCheckedValue(\"postModelHook\"),\n    getCheckedValue(\"preModelHook\"),\n    getCheckedValue(\"tools\")\n  ].join(\"\");\n}\n\nfunction dedent(strings, ...values) {\n  const str = String.raw({ raw: strings }, ...values)\n  const [space] = str.split(\"\\n\").filter(Boolean).at(0).match(/^(\\s*)/)\n  const spaceLen = space.length\n  return str.split(\"\\n\").map(line => line.slice(spaceLen)).join(\"\\n\").trim()\n}\n\nObject.assign(dedent, {\n  offset: (size) => (strings, ...values) => {\n    return dedent(strings, ...values).split(\"\\n\").map(line => \" \".repeat(size) + line).join(\"\\n\")\n  }\n})\n\n\n\n\nfunction generateCodeSnippet({ tools, pre, post, response }) {\n  const lines = []\n\n  lines.push(dedent`\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { ChatOpenAI } from \"@langchain/openai\";\n  `)\n\n  if (tools) lines.push(`import { tool } from \"@langchain/core/tools\";`);  \n  if (response || tools) lines.push(`import { z } from \"zod\";`);\n\n  lines.push(\"\", dedent`\n    const agent = createReactAgent({\n      llm: new ChatOpenAI({ model: \"o4-mini\" }),\n  `)\n\n  if (tools) {\n    lines.push(dedent.offset(2)`\n      tools: [\n        tool(() => \"Sample tool output\", {\n          name: \"sampleTool\",\n          schema: z.object({}),\n        }),\n      ],\n    `)\n  }\n\n  if (pre) {\n    lines.push(dedent.offset(2)`\n      preModelHook: (state) => ({ llmInputMessages: state.messages }),\n    `)\n  }\n\n  if (post) {\n    lines.push(dedent.offset(2)`\n      postModelHook: (state) => state,\n    `)\n  }\n\n  if (response) {\n    lines.push(dedent.offset(2)`\n      responseFormat: z.object({ result: z.string() }),\n    `)\n  }\n\n  lines.push(`});`);\n\n  return lines.join(\"\\n\");\n}\n\nfunction render() {\n  const key = getKey();\n  document.getElementById(\"agent-graph-img\").src = `../assets/react_agent_graphs/${key}.svg`;\n\n  const state = {\n    tools: document.getElementById(\"tools\").checked,\n    pre: document.getElementById(\"preModelHook\").checked,\n    post: document.getElementById(\"postModelHook\").checked,\n    response: document.getElementById(\"responseFormat\").checked\n  };\n\n  document.getElementById(\"agent-code\").textContent = generateCodeSnippet(state);\n}\n\nfunction initializeWidget() {\n  render(); // no need for `await` here\n  document.querySelectorAll(\".agent-graph-features input\").forEach((input) => {\n    input.addEventListener(\"change\", render);\n  });\n}\n\n// Init for both full reload and SPA nav (used by MkDocs Material)\nwindow.addEventListener(\"DOMContentLoaded\", initializeWidget);\ndocument$.subscribe(initializeWidget);\n</script>\n","docs/docs/agents/run_agents.md":"# Subagent: run_agents\n\nPath: `docs/docs/agents/run_agents.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/run_agents.md)","docs/docs/agents/streaming.md":"# Subagent: streaming\n\nPath: `docs/docs/agents/streaming.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/streaming.md)","docs/docs/agents/tools.md":"# Subagent: tools\n\nPath: `docs/docs/agents/tools.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/tools.md)","docs/docs/agents/ui.md":"# Subagent: ui\n\nPath: `docs/docs/agents/ui.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/ui.md)"},"files":{"docs/docs/agents/agents.md":"# LangGraph quickstart\n\nThis guide shows you how to set up and use LangGraph's **prebuilt**, **reusable** components, which are designed to help you construct agentic systems quickly and reliably.\n\n## Prerequisites\n\nBefore you start this tutorial, ensure you have the following:\n\n- An [Anthropic](https://console.anthropic.com/settings/keys) API key\n\n## 1. Install dependencies\n\nIf you haven't already, install LangGraph and LangChain:\n\n```\nnpm install langchain @langchain/langgraph @langchain/anthropic\n```\n\n## 2. Create an agent\n\nUse [`createReactAgent`](/langgraphjs/reference/functions/langgraph_prebuilt.createReactAgent.html) to instantiate an agent:\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst getWeather = tool( // (1)!\n  async (input: { city: string }) => {\n    return `It's always sunny in ${input.city}!`;\n  },\n  {\n    name: \"getWeather\",\n    schema: z.object({\n      city: z.string().describe(\"The city to get the weather for\"),\n    }),\n    description: \"Get weather for a given city.\",\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\"); // (2)!\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather], // (3)!\n  prompt: \"You are a helpful assistant\", // (4)!\n});\n\n// Run the agent\nawait agent.invoke({\n  messages: [{ role: \"user\", content: \"what is the weather in sf\" }],\n});\n```\n\n1. Define a tool for the agent to use. For more advanced tool usage and customization, check the [tools](./tools.md) page.\n2. Provide a language model for the agent to use. To learn more about configuring language models for the agents, check the [models](./models.md) page.\n3. Provide a list of tools for the model to use.\n4. Provide a system prompt (instructions) to the language model used by the agent.\n\n## 3. Configure an LLM\n\nUse [`initChatModel`](https://api.js.langchain.com/functions/langchain.chat_models_universal.initChatModel.html) to configure an LLM with specific parameters, such as temperature:\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\n// highlight-next-line\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\", {\n  // highlight-next-line\n  temperature: 0,\n});\n\nconst agent = createReactAgent({\n  // highlight-next-line\n  llm,\n  tools: [getWeather],\n});\n```\n\nSee the [models](./models.md) page for more information on how to configure LLMs.\n\n## 4. Add a custom prompt\n\nPrompts instruct the LLM how to behave. They can be:\n\n- **Static**: A string is interpreted as a **system message**\n- **Dynamic**: a list of messages generated at **runtime** based on input or configuration\n\n=== \"Static prompt\"\n\n    Define a fixed prompt string or list of messages.\n\n    ```ts\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // A static prompt that never changes\n      // highlight-next-line\n      prompt: \"Never answer questions about the weather.\",\n    });\n\n    await agent.invoke({\n      messages: \"what is the weather in sf\",\n    });\n    ```\n\n=== \"Dynamic prompt\"\n\n    Define a function that returns a message list based on the agent's state and configuration:\n\n    ```ts\n    import { BaseMessageLike } from \"@langchain/core/messages\";\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { MessagesAnnotation } from \"@langchain/langgraph\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n    const prompt = (\n      state: typeof MessagesAnnotation.State,\n      config: RunnableConfig\n    ): BaseMessageLike[] => { // (1)!\n      const userName = config.configurable?.userName;\n      const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;\n      return [{ role: \"system\", content: systemMsg }, ...state.messages];\n    };\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // highlight-next-line\n      prompt,\n    });\n\n    await agent.invoke(\n      { messages: [{ role: \"user\", content: \"what is the weather in sf\" }] },\n      // highlight-next-line\n      { configurable: { userName: \"John Smith\" } }\n    );\n    ```\n\n    1. Dynamic prompts allow including non-message [context](./context.md) when constructing an input to the LLM, such as:\n\n      - Information passed at runtime, like a `userId` or API credentials (using `config`).\n      - Internal agent state updated during a multi-step reasoning process (using `state`).\n\n      Dynamic prompts can be defined as functions that take `state` and `config` and return a list of messages to send to the LLM.\n\nFor more information, see [Context](./context.md).\n\n## 5. Add memory\n\nTo allow multi-turn conversations with an agent, you need to enable [persistence](../concepts/persistence.md) by providing a `checkpointer` when creating an agent. At runtime you need to provide a config containing `thread_id` — a unique identifier for the conversation (session):\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { MemorySaver } from \"@langchain/langgraph-checkpoint\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\n// highlight-next-line\nconst checkpointer = new MemorySaver();\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather],\n  // highlight-next-line\n  checkpointer, // (1)!\n});\n\n// Run the agent\n// highlight-next-line\nconst config = { configurable: { thread_id: \"1\" } };\nconst sfResponse = await agent.invoke(\n  { messages: [{ role: \"user\", content: \"what is the weather in sf\" }] },\n  config // (2)!\n);\nconst nyResponse = await agent.invoke(\n  { messages: [{ role: \"user\", content: \"what about new york?\" }] },\n  config\n);\n```\n\n1. `checkpointer` allows the agent to store its state at every step in the tool calling loop. This enables [short-term memory](./memory.md#short-term-memory) and [human-in-the-loop](./human-in-the-loop.md) capabilities.\n2. Pass configuration with `thread_id` to be able to resume the same conversation on future agent invocations.\n\nWhen you enable the checkpointer, it stores agent state at every step in the provided checkpointer database (or in memory, if using `InMemorySaver`).\n\nNote that in the above example, when the agent is invoked the second time with the same `thread_id`, the original message history from the first conversation is automatically included, together with the new user input.\n\nFor more information, see [Memory](./memory.md).\n\n## 6. Configure structured output\n\nTo produce structured responses conforming to a schema, use the `responseFormat` parameter. The schema can be defined with a `zod` schema. The result will be accessible via the `structuredResponse` field.\n\n```ts\nimport { z } from \"zod\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\nconst WeatherResponse = z.object({\n  conditions: z.string(),\n});\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather],\n  // highlight-next-line\n  responseFormat: WeatherResponse, // (1)!\n});\n\nconst response = await agent.invoke({\n  messages: [{ role: \"user\", content: \"what is the weather in sf\" }],\n});\n// highlight-next-line\nresponse.structuredResponse;\n```\n\n1. When `responseFormat` is provided, a separate step is added at the end of the agent loop: agent message history is passed to an LLM with structured output to generate a structured response.\n\n   To provide a system prompt to this LLM, use an object `{ prompt, schema }`, e.g., `responseFormat: { prompt, schema: WeatherResponse }`.\n\n!!! Note \"LLM post-processing\"\n\n    Structured output requires an additional call to the LLM to format the response according to the schema.\n\n## Next steps\n\n- [Deploy your agent locally](../tutorials/langgraph-platform/local-server.md)\n- [Learn more about prebuilt agents](../agents/overview.md)\n- [LangGraph Platform quickstart](../cloud/quick_start.md)\n","docs/docs/agents/evals.md":"# Evals\n\nTo evaluate your agent's performance you can use `LangSmith` [evaluations](https://docs.smith.langchain.com/evaluation). You would need to first define an evaluator function to judge the results from an agent, such as final outputs or trajectory. Depending on your evaluation technique, this may or may not involve a reference output:\n\n```ts\nconst evaluator = async (params: {\n  inputs: Record<string, unknown>;\n  outputs: Record<string, unknown>;\n  referenceOutputs?: Record<string, unknown>;\n}) => {\n  // compare agent outputs against reference outputs\n  const outputMessages = params.outputs.messages;\n  const referenceMessages = params.referenceOutputs.messages;\n  const score = compareMessages(outputMessages, referenceMessages);\n  return { key: \"evaluator_score\", score: score };\n};\n```\n\nTo get started, you can use prebuilt evaluators from `AgentEvals` package:\n\n```bash\nnpm install agentevals @langchain/core\n```\n\n## Create evaluator\n\nA common way to evaluate agent performance is by comparing its trajectory (the order in which it calls its tools) against a reference trajectory:\n\n```ts\n// highlight-next-line\nimport { createTrajectoryMatchEvaluator } from \"agentevals\";\n\nconst outputs = [\n  {\n    role: \"assistant\",\n    tool_calls: [\n      {\n        function: {\n          name: \"get_weather\",\n          arguments: JSON.stringify({ city: \"san francisco\" }),\n        },\n      },\n      {\n        function: {\n          name: \"get_directions\",\n          arguments: JSON.stringify({ destination: \"presidio\" }),\n        },\n      },\n    ],\n  },\n];\n\nconst referenceOutputs = [\n  {\n    role: \"assistant\",\n    tool_calls: [\n      {\n        function: {\n          name: \"get_weather\",\n          arguments: JSON.stringify({ city: \"san francisco\" }),\n        },\n      },\n    ],\n  },\n];\n\n// Create the evaluator\nconst evaluator = createTrajectoryMatchEvaluator({\n  // highlight-next-line\n  trajectoryMatchMode: \"superset\",  // (1)!\n})\n\n// Run the evaluator\nconst result = await evaluator({\n  outputs,\n  referenceOutputs,\n});\n```\n\n1. Specify how the trajectories will be compared. `superset` will accept output trajectory as valid if it's a superset of the reference one. Other options include: [strict](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#strict-match), [unordered](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#unordered-match) and [subset](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#subset-and-superset-match)\n\n\nAs a next step, learn more about how to [customize trajectory match evaluator](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#agent-trajectory-match).\n\n### LLM-as-a-judge\n\nYou can use LLM-as-a-judge evaluator that uses an LLM to compare the trajectory against the reference outputs and output a score:\n\n```ts\nimport {\n  // highlight-next-line\n  createTrajectoryLLMAsJudge,\n  TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE\n} from \"agentevals\";\n\nconst evaluator = createTrajectoryLLMAsJudge({\n  prompt: TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE,\n  model: \"openai:o3-mini\",\n});\n```\n\n## Run evaluator\n\nTo run an evaluator, you will first need to create a [LangSmith dataset](https://docs.smith.langchain.com/evaluation/concepts#datasets). To use the prebuilt AgentEvals evaluators, you will need a dataset with the following schema:\n\n- **input**: `{ messages: [...] }` input messages to call the agent with.\n- **output**: `{ messages\": [...] }` expected message history in the agent output. For trajectory evaluation, you can choose to keep only assistant messages.\n\n```ts\nimport { evaluate } from \"langsmith/evaluation\";\nimport { createTrajectoryMatchEvaluator } from \"agentevals\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\nconst agent = createReactAgent({ ... })\nconst evaluator = createTrajectoryMatchEvaluator({ ... })\nawait evaluate(\n  async (inputs) => await agent.invoke(inputs),\n  {\n    // replace with your dataset name\n    data: \"<Name of your dataset>\",\n    evaluators: [evaluator],\n  }\n);\n```","docs/docs/agents/deployment.md":"# Deployment\n\nTo deploy your LangGraph agent, create and configure a LangGraph app. This setup supports both local development and production deployments.\n\nFeatures: \n\n* 🖥️ Local server for development\n* 🧩 Studio Web UI for visual debugging\n* ☁️ Cloud and 🔧 self-hosted deployment options\n* 📊 LangSmith integration for tracing and observability\n\n!!! info \"Requirements\" \n\n    - ✅ You **must** have a [LangSmith account](https://www.langchain.com/langsmith). You can sign up for **free** and get started with the free tier.\n\n## Create a LangGraph app\n\n```bash\nnpm install -g create-langgraph\ncreate-langgraph path/to/your/app\n```\n\nFollow the prompts and select `New LangGraph Project`. This will create an empty LangGraph project. You can modify it by replacing the code in `src/agent/graph.ts` with your agent code. For example:\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst getWeather = tool(\n  async (input: { city: string }) => {\n    return `It's always sunny in ${input.city}!`;\n  },\n  {\n    name: \"getWeather\",\n    schema: z.object({\n      city: z.string().describe(\"The city to get the weather for\"),\n    }),\n    description: \"Get weather for a given city.\",\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n// make sure to export the graph that will be used in the LangGraph API server\n// highlight-next-line\nexport const graph = createReactAgent({\n  llm,\n  tools: [getWeather],\n  prompt: \"You are a helpful assistant\"\n})\n```\n\n### Install dependencies\n\nIn the root of your new LangGraph app, install the dependencies:\n\n```shell\nyarn\n# install these to use initChatModel with Anthropic\nyarn add langchain\nyarn add @langchain/anthropic\n```\n\n### Create an `.env` file\n\nYou will find a `.env.example` in the root of your new LangGraph app. Create\na `.env` file in the root of your new LangGraph app and copy the contents of the `.env.example` file into it, filling in the necessary API keys:\n\n```bash\nLANGSMITH_API_KEY=lsv2...\nANTHROPIC_API_KEY=sk-\n```\n\n## Launch LangGraph server locally\n\n```shell\nnpx @langchain/langgraph-cli dev\n```\n\nThis will start up the LangGraph API server locally. If this runs successfully, you should see something like:\n\n>    Welcome to LangGraph.js!\n> \n>    - 🚀 API: http://localhost:2024\n>     \n>    - 🎨 Studio UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024\n\n## LangGraph Studio Web UI\n\nLangGraph Studio Web is a specialized UI that you can connect to LangGraph API server to enable visualization, interaction, and debugging of your application locally. Test your graph in the LangGraph Studio Web UI by visiting the URL provided in the output of the `npx @langchain/langgraph-cli dev` command.\n\n>    - LangGraph Studio Web UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024\n\n## Deployment\n\nOnce your LangGraph app is running locally, you can deploy it using LangSmith Deployment or self-hosted options. Refer to the [deployment options guide](https://langchain-ai.github.io/langgraph/tutorials/deployment/) for detailed instructions on all supported deployment models.\n","docs/docs/agents/mcp.md":"# MCP Integration\n\n[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open protocol that standardizes how applications provide tools and context to language models. LangGraph agents can use tools defined on MCP servers through the `@langchain/mcp-adapters` library.\n\n![MCP](./assets/mcp.png)\n\nInstall the `@langchain/mcp-adapters` library to use MCP tools in LangGraph:\n\n```bash\nnpm install @langchain/mcp-adapters\n```\n\n## Use MCP tools\n\nThe `@langchain/mcp-adapters` package enables agents to use tools defined across one or more MCP servers.\n\n```ts\n// highlight-next-line\nimport { MultiServerMCPClient } from \"@langchain/mcp-adapters\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n// highlight-next-line\nconst client = new MultiServerMCPClient({\n  mcpServers: {\n    \"math\": {\n      command: \"python\",\n      // Replace with absolute path to your math_server.py file\n      args: [\"/path/to/math_server.py\"],\n      transport: \"stdio\",\n    },\n    \"weather\": {\n      // Ensure your start your weather server on port 8000\n      url: \"http://localhost:8000/sse\",\n      transport: \"sse\",\n    }\n  }\n})\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  // highlight-next-line\n  tools: await client.getTools()\n});\n \nconst mathResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what's (3 + 5) x 12?\" } ] }\n);\nconst weatherResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what is the weather in nyc?\" } ] }\n);\nawait client.close();\n```\n\n## Custom MCP servers\n\nTo create your own MCP servers, you can use the `mcp` library in Python (or `@modelcontextprotocol/sdk` in TypeScript). These libraries provide a simple way to define tools and run them as servers.\n\nInstall the MCP library:\n\n```bash\npip install mcp\n```\nUse the following reference implementations to test your agent with MCP tool servers.\n\n```python title=\"Example Math Server (stdio transport)\"\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"Math\")\n\n@mcp.tool()\ndef add(a: int, b: int) -> int:\n    \"\"\"Add two numbers\"\"\"\n    return a + b\n\n@mcp.tool()\ndef multiply(a: int, b: int) -> int:\n    \"\"\"Multiply two numbers\"\"\"\n    return a * b\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"stdio\")\n```\n\n```python title=\"Example Weather Server (SSE transport)\"\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"Weather\")\n\n@mcp.tool()\nasync def get_weather(location: str) -> str:\n    \"\"\"Get weather for location.\"\"\"\n    return \"It's always sunny in New York\"\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"sse\")\n```\n\n## Additional resources\n\n- [MCP documentation](https://modelcontextprotocol.io/introduction)\n- [MCP Transport documentation](https://modelcontextprotocol.io/docs/concepts/transports)","docs/docs/agents/human-in-the-loop.md":"# Human-in-the-loop\n\nTo review, edit and approve tool calls in an agent you can use LangGraph's built-in [human-in-the-loop](../concepts/human_in_the_loop.md) features, specifically the [`interrupt()`](/langgraphjs/reference/functions/langgraph.interrupt-1.html) primitive.\n\nLangGraph allows you to pause execution **indefinitely** — for minutes, hours, or even days—until human input is received.\n\nThis is possible because the agent state is **checkpointed into a database**, which allows the system to persist execution context and later resume the workflow, continuing from where it left off.\n\nFor a deeper dive into the **human-in-the-loop** concept, see the [concept guide](../concepts/human_in_the_loop.md).\n\n<figure markdown=\"1\">\n![image](../concepts/img/human_in_the_loop/tool-call-review.png){: style=\"max-height:400px\"}\n<figcaption>\nA human can review and edit the output from the agent before proceeding. This is particularly critical in applications where the tool calls requested may be sensitive or require human oversight.\n</figcaption>\n</figure>\n\n\n## Review tool calls\n\nTo add a human approval step to a tool:\n\n1. Use `interrupt()` in the tool to pause execution.\n2. Resume with a `Command({ resume: ... })` to continue based on human input.\n\n```ts\nimport { MemorySaver } from \"@langchain/langgraph-checkpoint\";\nimport { interrupt } from \"@langchain/langgraph\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\n// An example of a sensitive tool that requires human review / approval\nconst bookHotel = tool(\n  async (input: { hotelName: string; }) => {\n    let hotelName = input.hotelName;\n    // highlight-next-line\n    const response = interrupt(  // (1)!\n      `Trying to call \\`book_hotel\\` with args {'hotel_name': ${hotelName}}. ` +\n      `Please approve or suggest edits.`\n    )\n    if (response.type === \"accept\") {\n      // proceed to execute the tool logic\n    } else if (response.type === \"edit\") {\n        hotelName = response.args[\"hotel_name\"]\n    } else {\n        throw new Error(`Unknown response type: ${response.type}`)\n    }\n    return `Successfully booked a stay at ${hotelName}.`;\n  },\n  {\n    name: \"bookHotel\",\n    schema: z.object({\n      hotelName: z.string().describe(\"Hotel to book\"),\n    }),\n    description: \"Book a hotel.\",\n  }\n);\n\n// highlight-next-line\nconst checkpointer = new MemorySaver();  // (2)!\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [bookHotel],\n  // highlight-next-line\n  checkpointer  // (3)!\n});\n```\n\n1. The [`interrupt` function](/langgraphjs/reference/functions/langgraph.interrupt-1.html) pauses the agent graph at a specific node. In this case, we call `interrupt()` at the beginning of the tool function, which pauses the graph at the node that executes the tool. The information inside `interrupt()` (e.g., tool calls) can be presented to a human, and the graph can be resumed with the user input (tool call approval, edit or feedback).\n2. The `InMemorySaver` is used to store the agent state at every step in the tool calling loop. This enables [short-term memory](./memory.md#short-term-memory) and [human-in-the-loop](./human-in-the-loop.md) capabilities. In this example, we use `InMemorySaver` to store the agent state in memory. In a production application, the agent state will be stored in a database.\n3. Initialize the agent with the `checkpointer`.\n\nRun the agent with the `stream()` method, passing the `config` object to specify the thread ID. This allows the agent to resume the same conversation on future invocations.\n\n```ts\nconst config = {\n   configurable: {\n      // highlight-next-line\n      \"thread_id\": \"1\"\n   }\n}\n\nfor await (const chunk of await agent.stream(\n  { messages: \"book a stay at McKittrick hotel\" },\n  // highlight-next-line\n  config\n)) {\n  console.log(chunk);\n  console.log(\"\\n\");\n};\n```\n\n> You should see that the agent runs until it reaches the `interrupt()` call, at which point it pauses and waits for human input.\n\nResume the agent with a `Command({ resume: ... })` to continue based on human input.\n\n```ts\nimport { Command } from \"@langchain/langgraph\";\n\nfor await (const chunk of await agent.stream(\n  new Command({ resume: { type: \"accept\" } }),  // (1)!\n  // new Command({ resume: { type: \"edit\", args: { \"hotel_name\": \"McKittrick Hotel\" } } }),\n  // highlight-next-line\n  config\n)) {\n  console.log(chunk);\n  console.log(\"\\n\");\n};\n```\n\n1. The [`interrupt` function](/langgraphjs/reference/functions/langgraph.interrupt-1.html) is used in conjunction with the [`Command`](/langgraphjs/reference/classes/langgraph.Command.html) object to resume the graph with a value provided by the human.\n\n## Additional resources\n\n* [Human-in-the-loop in LangGraph](../concepts/human_in_the_loop.md)","docs/docs/agents/context.md":"# Context\n\nAgents often require more than a list of messages to function effectively. They need **context**.\n\nContext includes *any* data outside the message list that can shape agent behavior or tool execution. This can be:\n\n- Information passed at runtime, like a `user_id` or API credentials.\n- Internal state updated during a multi-step reasoning process.\n- Persistent memory or facts from previous interactions.\n\nLangGraph provides **three** primary ways to supply context:\n\n| Type                                                                         | Description                                   | Mutable? | Lifetime                |\n|------------------------------------------------------------------------------|-----------------------------------------------|----------|-------------------------|\n| [**Config**](#config-static-context)                                         | data passed at the start of a run             | ❌        | per run                 |\n| [**State**](#state-mutable-context)                                          | dynamic data that can change during execution | ✅        | per run or conversation |\n| [**Long-term Memory (Store)**](#long-term-memory-cross-conversation-context) | data that can be shared between conversations | ✅        | across conversations    |\n\nYou can use context to:\n\n- Adjust the system prompt the model sees\n- Feed tools with necessary inputs\n- Track facts during an ongoing conversation\n\n## Providing Runtime Context\n\nUse this when you need to inject data into an agent at runtime.\n\n### Config (static context)\n\nConfig is for immutable data like user metadata or API keys. Use\nwhen you have values that don't change mid-run.\n\nSpecify configuration using a key called **\"configurable\"** which is reserved\nfor this purpose:\n\n```ts\nawait agent.invoke(\n  { messages: \"hi!\" },\n  // highlight-next-line\n  { configurable: { userId: \"user_123\" } }\n)\n```\n\n### State (mutable context)\n\nState acts as short-term memory during a run. It holds dynamic data that can evolve during execution, such as values derived from tools or LLM outputs.\n\n```ts\nconst CustomState = Annotation.Root({\n  ...MessagesAnnotation.spec,\n  userName: Annotation<string>,\n});\n\nconst agent = createReactAgent({\n  // Other agent parameters...\n  // highlight-next-line\n  stateSchema: CustomState,\n})\n\nawait agent.invoke(\n  // highlight-next-line\n  { messages: \"hi!\", userName: \"Jane\" }\n)\n```\n\n!!! tip \"Turning on memory\"\n\n    Please see the [memory guide](./memory.md) for more details on how to enable memory. This is a powerful feature that allows you to persist the agent's state across multiple invocations.\n    Otherwise, the state is scoped only to a single agent run.\n\n\n\n### Long-Term Memory (cross-conversation context)\n\nFor context that spans *across* conversations or sessions, LangGraph allows access to **long-term memory** via a `store`. This can be used to read or update persistent facts (e.g., user profiles, preferences, prior interactions). For more, see the [Memory guide](./memory.md).\n\n## Customizing Prompts with Context\n\nPrompts define how the agent behaves. To incorporate runtime context, you can dynamically generate prompts based on the agent's state or config.\n\nCommon use cases:\n\n- Personalization\n- Role or goal customization\n- Conditional behavior (e.g., user is admin)\n\n=== \"Using config\"\n\n    ```ts\n    import { BaseMessageLike } from \"@langchain/core/messages\";\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { MessagesAnnotation } from \"@langchain/langgraph\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n    const prompt = (\n      state: typeof MessagesAnnotation.State,\n      // highlight-next-line\n      config: RunnableConfig\n    ): BaseMessageLike[] => {\n      // highlight-next-line\n      const userName = config.configurable?.userName;\n      const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;\n      return [{ role: \"system\", content: systemMsg }, ...state.messages];\n    };\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // highlight-next-line\n      prompt\n    });\n\n    await agent.invoke(\n      { messages: \"hi!\" },\n      // highlight-next-line\n      { configurable: { userName: \"John Smith\" } }\n    );\n    ```\n\n=== \"Using state\"\n\n    ```ts\n    import { BaseMessageLike } from \"@langchain/core/messages\";\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { Annotation, MessagesAnnotation } from \"@langchain/langgraph\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n    const CustomState = Annotation.Root({\n      ...MessagesAnnotation.spec,\n      // highlight-next-line\n      userName: Annotation<string>,\n    });\n\n    const prompt = (\n      // highlight-next-line\n      state: typeof CustomState.State,\n    ): BaseMessageLike[] => {\n      // highlight-next-line\n      const userName = state.userName;\n      const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;\n      return [{ role: \"system\", content: systemMsg }, ...state.messages];\n    };\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // highlight-next-line\n      prompt,\n      // highlight-next-line\n      stateSchema: CustomState,\n    });\n\n    await agent.invoke(\n      // highlight-next-line\n      { messages: \"hi!\", userName: \"John Smith\" },\n    );\n    ```\n\n## Tools\n\nTools can access context through:\n\n* Use `RunnableConfig` for config access\n* Use `runtime.state` (the second argument, typed as `ToolRuntime`) for agent state\n\n!!! tip \"Browser / web environments\"\n\n    When a tool runs inside a `ToolNode` (including in `createReactAgent`), the `ToolNode` forwards its input (the current graph state) to the tool via `runtime.state`. This works in every runtime, including web browsers.\n\n    An older alternative, `getCurrentTaskInput()`, relies on [`AsyncLocalStorage`](https://nodejs.org/api/async_hooks.html), which is available in Node.js, Deno, and Cloudflare Workers, but **not** in web browsers. Prefer `runtime.state` for portability.\n\n=== \"Using config\"\n\n    ```ts\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { tool } from \"@langchain/core/tools\";\n    import { z } from \"zod\";\n\n    const getUserInfo = tool(\n      async (input: Record<string, any>, config: RunnableConfig) => {\n        // highlight-next-line\n        const userId = config.configurable?.userId;\n        return userId === \"user_123\" ? \"User is John Smith\" : \"Unknown user\";\n      },\n      {\n        name: \"get_user_info\",\n        description: \"Look up user info.\",\n        schema: z.object({}),\n      }\n    );\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getUserInfo],\n    });\n\n    await agent.invoke(\n      { messages: \"look up user information\" },\n      // highlight-next-line\n      { configurable: { userId: \"user_123\" } }\n    );\n    ```\n\n=== \"Using state\"\n\n    ```ts\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { Annotation, MessagesAnnotation } from \"@langchain/langgraph\";\n    import { tool, type ToolRuntime } from \"@langchain/core/tools\";\n    import { z } from \"zod\";\n\n    const CustomState = Annotation.Root({\n      ...MessagesAnnotation.spec,\n      // highlight-next-line\n      userId: Annotation<string>(),\n    });\n\n    const getUserInfo = tool(\n      async (\n        input: Record<string, any>,\n        // highlight-next-line\n        runtime: ToolRuntime<typeof CustomState.State>,\n      ) => {\n        // Read the graph state directly from the second argument.\n        // This works in web browsers too (no AsyncLocalStorage required).\n        // highlight-next-line\n        const userId = runtime.state.userId;\n        return userId === \"user_123\" ? \"User is John Smith\" : \"Unknown user\";\n      },\n      {\n        name: \"get_user_info\",\n        description: \"Look up user info.\",\n        schema: z.object({})\n      }\n    );\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getUserInfo],\n      // highlight-next-line\n      stateSchema: CustomState,\n    });\n\n    await agent.invoke(\n      // highlight-next-line\n      { messages: \"look up user information\", userId: \"user_123\" }\n    );\n    ```\n\n\n## Update context from tools\n\nTools can modify the agent's state during execution. This is useful for persisting intermediate results or making information accessible to subsequent tools or prompts.\n\n```ts\nimport { Annotation, MessagesAnnotation, LangGraphRunnableConfig, Command } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\nconst CustomState = Annotation.Root({\n  ...MessagesAnnotation.spec,\n  // highlight-next-line\n  userName: Annotation<string>(), // Will be updated by the tool\n});\n\nconst getUserInfo = tool(\n  async (\n    _input: Record<string, never>,\n    config: LangGraphRunnableConfig\n  ): Promise<Command> => {\n    const userId = config.configurable?.userId;\n    if (!userId) {\n      throw new Error(\"Please provide a user id in config.configurable\");\n    }\n\n    const toolCallId = config.toolCall?.id;\n\n    const name = userId === \"user_123\" ? \"John Smith\" : \"Unknown user\";\n    // Return command to update state\n    return new Command({\n      update: {\n        // highlight-next-line\n        userName: name,\n        // Update the message history\n        // highlight-next-line\n        messages: [\n          new ToolMessage({\n            content: \"Successfully looked up user information\",\n            tool_call_id: toolCallId,\n          }),\n        ],\n      },\n    });\n  },\n  {\n    name: \"get_user_info\",\n    description: \"Look up user information.\",\n    schema: z.object({}),\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getUserInfo],\n  // highlight-next-line\n  stateSchema: CustomState,\n});\n\nawait agent.invoke(\n  { messages: \"look up user information\" },\n  // highlight-next-line\n  { configurable: { userId: \"user_123\" } }\n);\n```\n\nFor more details, see [how to update state from tools](../how-tos/update-state-from-tools.ipynb).","docs/docs/agents/models.md":"# Models\n\nThis page describes how to configure the chat model used by an agent.\n\n## Tool calling support\n\nTo enable tool-calling agents, the underlying LLM must support [tool calling](https://js.langchain.com/docs/concepts/tool_calling/).\n\nCompatible models can be found in the [LangChain integrations directory](https://js.langchain.com/docs/integrations/chat/).\n\n## Using `initChatModel`\n\nThe [`initChatModel`](https://js.langchain.com/docs/how_to/chat_models_universal_init/) utility simplifies model initialization with configurable parameters:\n\n```ts\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\nconst llm = await initChatModel(\n  \"anthropic:claude-3-7-sonnet-latest\",\n  {\n    temperature: 0,\n    maxTokens: 2048\n  }\n);\n```\n\nRefer to the [API reference](https://api.js.langchain.com/functions/langchain.chat_models_universal.initChatModel.html) for advanced options.\n\n## Using provider-specific LLMs \n\nIf a model provider is not available via `initChatModel`, you can instantiate the provider's model class directly. The model must implement the [`BaseChatModel`](https://api.js.langchain.com/classes/_langchain_core.language_models_chat_models.BaseChatModel.html) interface and support tool calling:\n\n```ts\nimport { ChatAnthropic } from \"@langchain/anthropic\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n// highlight-next-line\nconst llm = new ChatAnthropic({\n  modelName: \"claude-3-7-sonnet-latest\",\n  temperature: 0,\n  maxTokens: 2048\n});\n\nconst agent = createReactAgent({\n  // highlight-next-line\n  llm,\n  // other parameters\n});\n```\n\n!!! note \"Illustrative example\" \n\n    The example above uses `ChatAnthropic`, which is already supported by `initChatModel`. This pattern is shown to illustrate how to manually instantiate a model not available through `initChatModel`.\n\n## Additional resources\n\n- [Model integration directory](https://js.langchain.com/docs/integrations/chat/)\n- [Universal initialization with `initChatModel`](https://js.langchain.com/docs/how_to/chat_models_universal_init/)","docs/docs/agents/prebuilt.md":"# Community Agents\n\nTo share your project, simply open a Pull Request adding an entry for your package in our [packages.yml](https://github.com/langchain-ai/langgraph/blob/main/docs/_scripts/third_party_page/packages.yml) file.\n\n[//]: # (This file is stub. Do not edit this file directly!)\n[//]: # (1. Update the `packages.yml` file in the `docs/_scripts/third_party_page` directory.)\n[//]: # (2. From the /docs directory, run `make build-prebuilt` to generate an updated version of this file for testing locally.)\n","docs/docs/agents/memory.md":"# Memory\n\nLangGraph supports two types of memory essential for building conversational agents:\n\n- **[Short-term memory](#short-term-memory)**: Tracks the ongoing conversation by maintaining message history within a session.\n- **[Long-term memory](#long-term-memory)**: Stores user-specific or application-level data across sessions.\n\nThis guide demonstrates how to use both memory types with agents in LangGraph. For a deeper\nunderstanding of memory concepts, refer to the [LangGraph memory documentation](../concepts/memory.md).\n\n<figure markdown=\"1\">\n![image](./assets/memory.png){: style=\"max-height:400px\"}\n<figcaption>Both <strong>short-term</strong> and <strong>long-term</strong> memory require persistent storage to maintain continuity across LLM interactions. In production environments, this data is typically stored in a database.</figcaption>\n</figure>\n\n!!! note \"Terminology\"\n\n    In LangGraph:\n\n    - *Short-term memory* is also referred to as **thread-level memory**.\n    - *Long-term memory* is also called **cross-thread memory**.\n\n    A [thread](../concepts/persistence.md#threads) represents a sequence of related runs\n    grouped by the same `thread_id`.\n\n## Short-term memory\n\nShort-term memory enables agents to track multi-turn conversations. To use it, you must:\n\n1. Provide a `checkpointer` when creating the agent. The `checkpointer` enables [persistence](../concepts/persistence.md) of the agent's state.\n2. Supply a `thread_id` in the config when running the agent. The `thread_id` is a unique identifier for the conversation session.\n\n```ts\n// highlight-next-line\nimport { MemorySaver } from \"@langchain/langgraph-checkpoint\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\n// highlight-next-line\nconst checkpointer = new MemorySaver();  // (1)!\n\nconst getWeather = tool(\n  async (input: { city: string }) => {\n    return `It's always sunny in ${input.city}!`;\n  },\n  {\n    name: \"getWeather\",\n    schema: z.object({\n      city: z.string().describe(\"The city to get the weather for\"),\n    }),\n    description: \"Get weather for a given city.\",\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather],\n  // highlight-next-line\n  checkpointer  // (2)!\n});\n\n// Run the agent\n// highlight-next-line\nconst config = { configurable: { thread_id: \"1\" } };  // (3)!\nconst sfResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what is the weather in sf\" } ] },\n  config  // (4)!\n);\nconst nyResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what about new york?\" } ] },\n  config\n);\n```\n\n1. The `MemorySaver` is a checkpointer that stores the agent's state in memory. In a production setting, you would typically use a database or other persistent storage. Please review the [checkpointer documentation](https://langchain-ai.github.io/langgraphjs/reference/index.html) for more options. If you're deploying with **LangGraph Platform**, the platform will provide a production-ready checkpointer for you.\n2. The `checkpointer` is passed to the agent. This enables the agent to persist its state across invocations. Please note that \n3. A unique `thread_id` is provided in the config. This ID is used to identify the conversation session. The value is controlled by the user and can be any string.\n4. The agent will continue the conversation using the same `thread_id`. This will allow the agent to infer that the user is asking specifically about the **weather** in New York. \n\nWhen the agent is invoked the second time with the same `thread_id`, the original message history from the first conversation is automatically included, allowing the agent to infer that the user is asking specifically about the **weather** in New York.\n\n!!! Note \"LangGraph Platform providers a production-ready checkpointer\"\n\n    If you're using [LangGraph Platform](./deployment.md), during deployment your checkpointer will be automatically configured to use a production-ready database.\n\n## Long-term memory\n\nUse long-term memory to store user-specific or application-specific data across conversations. This is useful for applications like chatbots, where you want to remember user preferences or other information.\n\nTo use long-term memory, you need to:\n\n1. [Configure a store](../how-tos/cross-thread-persistence.ipynb) to persist data across invocations.\n2. Use the `config.store` to access the store from within tools or prompts.\n\n### Reading\n\n```ts title=\"A tool the agent can use to look up user information\"\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n// highlight-next-line\nimport { InMemoryStore } from \"@langchain/langgraph-checkpoint\";\n// highlight-next-line\nimport { getStore } from \"@langchain/langgraph\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst store = new InMemoryStore(); // (1)!\n\nawait store.put(  // (2)!\n  [\"users\"],  // (3)!\n  \"user_123\",  // (4)!\n  {\n    name: \"John Smith\",\n    language: \"English\",\n  } // (5)!\n);\n\n// Look up user info tool\nconst getUserInfo = tool(\n  async (input: Record<string, any>, config: LangGraphRunnableConfig): Promise<string> => {\n    // Same as that provided to `createReactAgent`\n    const store = config.store; // (6)!\n    if (!store) {\n      throw new Error(\"store is required when compiling the graph\");\n    }\n\n    const userId = config.configurable?.userId;\n    if (!userId) {\n      throw new Error(\"userId is required in the config\");\n    }\n\n    const userInfo = await store.get([\"users\"], userId); // (7)!\n    return userInfo ? JSON.stringify(userInfo.value) : \"Unknown user\";\n  },\n  {\n    name: \"get_user_info\",\n    description: \"Look up user info.\",\n    schema: z.object({}),\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getUserInfo],\n  store, // (8)!\n});\n\n// Run the agent\nconst response = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"look up user information\" } ] },\n  { configurable: { userId: \"user_123\" } }\n);\n```\n\n1. The `InMemoryStore` is a store that stores data in memory. In a production setting, you would typically use a database or other persistent storage. Please review the [documentation](https://langchain-ai.github.io/langgraphjs/reference/index.html) for more options. If you're deploying with **LangGraph Platform**, the platform will provide a production-ready store for you.\n2. For this example, we write some sample data to the store using the `put` method. Please see the [BaseStore.put](https://langchain-ai.github.io/langgraphjs/reference/classes/checkpoint.BaseStore.html#put) API reference for more details.\n3. The first argument is the namespace. This is used to group related data together. In this case, we are using the `users` namespace to group user data.\n4. A key within the namespace. This example uses a user ID for the key.\n5. The data that we want to store for the given user.\n6. You can access the store via `config.store` from anywhere in your nodes, tools and prompts. It contains the store that was passed to the agent when it was created.\n7. The `get` method is used to retrieve data from the store. The first argument is the namespace, and the second argument is the key. This will return a `StoreValue` object, which contains the value and metadata about the value.\n8. The `store` is passed to the agent. This enables the agent to access the store when running tools.\n\n### Writing\n\n```ts title=\"Example of a tool that updates user information\"\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { InMemoryStore } from \"@langchain/langgraph-checkpoint\";\nimport { getStore } from \"@langchain/langgraph\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst store = new InMemoryStore(); // (1)!\n\ninterface UserInfo { // (2)!\n  name: string;\n}\n\n// Save user info tool\nconst saveUserInfo = tool(  // (3)!\n  async (input: UserInfo, config: LangGraphRunnableConfig): Promise<string> => {\n    // Same as that provided to `createReactAgent`\n    // highlight-next-line\n    const store = config.store; // (4)!\n    if (!store) {\n      throw new Error(\"store is required when compiling the graph\");\n    }\n\n    const userId = config.configurable?.userId;\n    if (!userId) {\n      throw new Error(\"userId is required in the config\");\n    }\n\n    await store.put([\"users\"], userId, input); // (5)!\n    return \"Successfully saved user info.\";\n  },\n  {\n    name: \"save_user_info\",\n    description: \"Save user info.\",\n    schema: z.object({\n      name: z.string(),\n    }),\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [saveUserInfo],\n  // highlight-next-line\n  store,\n});\n\n// Run the agent\nawait agent.invoke(\n  { messages: [ { role: \"user\", content: \"My name is John Smith\" } ] },\n  { configurable: { userId: \"user_123\" } } // (6)!\n);\n\n// You can access the store directly to get the value\nconst userInfo = await store.get([\"users\"], \"user_123\")\nuserInfo.value\n```\n\n1. The `InMemoryStore` is a store that stores data in memory. In a production setting, you would typically use a database or other persistent storage. Please review the [store documentation](../reference/stores.md) for more options. If you're deploying with **LangGraph Platform**, the platform will provide a production-ready store for you.\n2. The `UserInfo` class is an interface that defines the structure of the user information. We will specify the same schema below using a zod object, so that the LLM formats the response according to the schema.\n3. The `saveUserInfo` is a tool that allows an agent to update user information. This could be useful for a chat application where the user wants to update their profile information.\n4. You can access the store via `config.store` from anywhere in your nodes, tools and prompts. It contains the store that was passed to the agent when it was created.\n5. The `put` method is used to store data in the store. The first argument is the namespace, and the second argument is the key. This will store the user information in the store.\n6. The `userId` is passed in the config. This is used to identify the user whose information is being updated.\n\n## Additional resources\n\n* [Memory in LangGraph](../concepts/memory.md)","docs/docs/agents/multi-agent.md":"# Multi-agent\n\nA single agent might struggle if it needs to specialize in multiple domains or manage many tools. To tackle this, you can break your agent into smaller, independent agents and composing them into a [multi-agent system](../concepts/multi_agent.md).\n\nIn multi-agent systems, agents need to communicate between each other. They do so via [handoffs](#handoffs) — a primitive that describes which agent to hand control to and the payload to send to that agent.\n\nTwo of the most popular multi-agent architectures are:\n\n- [supervisor](#supervisor) — individual agents are coordinated by a central supervisor agent. The supervisor controls all communication flow and task delegation, making decisions about which agent to invoke based on the current context and task requirements.\n- [swarm](#swarm) — agents dynamically hand off control to one another based on their specializations. The system remembers which agent was last active, ensuring that on subsequent interactions, the conversation resumes with that agent.\n\n## Supervisor\n\n![Supervisor](./assets/supervisor.png)\n\nUse [`langgraph-supervisor`](https://github.com/langchain-ai/langgraphjs/tree/main/libs/langgraph-supervisor) library to create a supervisor multi-agent system:\n\n```bash\nnpm install @langchain/langgraph-supervisor\n```\n\n```ts\nimport { ChatOpenAI } from \"@langchain/openai\";\n// highlight-next-line\nimport { createSupervisor } from \"@langchain/langgraph-supervisor\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst bookHotel = tool(\n  async (input: { hotel_name: string }) => {\n    return `Successfully booked a stay at ${input.hotel_name}.`;\n  },\n  {\n    name: \"book_hotel\",\n    description: \"Book a hotel\",\n    schema: z.object({\n      hotel_name: z.string().describe(\"The name of the hotel to book\"),\n    }),\n  }\n);\n\nconst bookFlight = tool(\n  async (input: { from_airport: string; to_airport: string }) => {\n    return `Successfully booked a flight from ${input.from_airport} to ${input.to_airport}.`;\n  },\n  {\n    name: \"book_flight\",\n    description: \"Book a flight\",\n    schema: z.object({\n      from_airport: z.string().describe(\"The departure airport code\"),\n      to_airport: z.string().describe(\"The arrival airport code\"),\n    }),\n  }\n);\n\nconst llm = new ChatOpenAI({ modelName: \"gpt-4o\" });\n\n// Create specialized agents\nconst flightAssistant = createReactAgent({\n  llm,\n  tools: [bookFlight],\n  prompt: \"You are a flight booking assistant\",\n  // highlight-next-line\n  name: \"flight_assistant\",\n});\n\nconst hotelAssistant = createReactAgent({\n  llm,\n  tools: [bookHotel],\n  prompt: \"You are a hotel booking assistant\",\n  // highlight-next-line\n  name: \"hotel_assistant\",\n});\n\n// highlight-next-line\nconst supervisor = createSupervisor({\n  agents: [flightAssistant, hotelAssistant],\n  llm,\n  prompt: \"You manage a hotel booking assistant and a flight booking assistant. Assign work to them, one at a time.\",\n}).compile();\n\nconst stream = await supervisor.stream({\n  messages: [{\n    role: \"user\",\n    content: \"first book a flight from BOS to JFK and then book a stay at McKittrick Hotel\"\n  }]\n});\n\nfor await (const chunk of stream) {\n  console.log(chunk);\n  console.log(\"\\n\");\n}\n```\n\n## Swarm\n\n![Swarm](./assets/swarm.png)\n\nUse [`langgraph-swarm`](https://github.com/langchain-ai/langgraphjs/tree/main/libs/langgraph-swarm) library to create a swarm multi-agent system:\n\n```bash\nnpm install @langchain/langgraph-swarm\n```\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { ChatAnthropic } from \"@langchain/anthropic\";\n// highlight-next-line\nimport { createSwarm, createHandoffTool } from \"@langchain/langgraph-swarm\";\n\nconst transferToHotelAssistant = createHandoffTool({\n  agentName: \"hotel_assistant\",\n  description: \"Transfer user to the hotel-booking assistant.\",\n});\n\nconst transferToFlightAssistant = createHandoffTool({\n  agentName: \"flight_assistant\",\n  description: \"Transfer user to the flight-booking assistant.\",\n});\n\n\nconst llm = new ChatAnthropic({ modelName: \"claude-3-5-sonnet-latest\" });\n\nconst flightAssistant = createReactAgent({\n  llm,\n  tools: [bookFlight, transferToHotelAssistant],\n  prompt: \"You are a flight booking assistant\",\n  name: \"flight_assistant\",\n});\n\nconst hotelAssistant = createReactAgent({\n  llm,\n  tools: [bookHotel, transferToFlightAssistant],\n  prompt: \"You are a hotel booking assistant\",\n  name: \"hotel_assistant\",\n});\n\n// highlight-next-line\nconst swarm = createSwarm({\n  agents: [flightAssistant, hotelAssistant],\n  defaultActiveAgent: \"flight_assistant\",\n}).compile();\n\nconst stream = await swarm.stream({\n  messages: [{\n    role: \"user\",\n    content: \"first book a flight from BOS to JFK and then book a stay at McKittrick Hotel\"\n  }]\n});\n\nfor await (const chunk of stream) {\n  console.log(chunk);\n  console.log(\"\\n\");\n}\n```\n\n## Handoffs\n\nA common pattern in multi-agent interactions is **handoffs**, where one agent *hands off* control to another. Handoffs allow you to specify:\n\n- **destination**: target agent to navigate to\n- **payload**: information to pass to that agent\n\nThis is used both by `langgraph-supervisor` (supervisor hands off to individual agents) and `langgraph-swarm` (an individual agent can hand off to other agents).\n\nTo implement handoffs with `createReactAgent`, you need to:\n\n1. Create a special tool that can transfer control to a different agent\n\n    ```ts\n    const transferToBob = tool(\n      async (_) => {\n        return new Command({\n          // name of the agent (node) to go to\n          // highlight-next-line\n          goto: \"bob\",\n          // data to send to the agent\n          // highlight-next-line\n          update: { messages: ... },\n          // indicate to LangGraph that we need to navigate to\n          // agent node in a parent graph\n          // highlight-next-line\n          graph: Command.PARENT,\n        });\n      },\n      {\n        name: ...,\n        schema: ...,\n        description: ...\n      }\n    );\n    ```\n\n1. Create individual agents that have access to handoff tools:\n\n    ```ts\n    const flightAssistant = createReactAgent(\n      ..., tools: [bookFlight, transferToHotelAssistant]\n    )\n    const hotelAssistant = createReactAgent(\n      ..., tools=[bookHotel, transferToFlightAssistant]\n    )\n    ```\n\n1. Define a parent graph that contains individual agents as nodes:\n\n    ```ts\n    import { StateGraph, MessagesAnnotation } from \"@langchain/langgraph\";\n\n    const multiAgentGraph = new StateGraph(MessagesAnnotation)\n      .addNode(\"flight_assistant\", flightAssistant)\n      .addNode(\"hotel_assistant\", hotelAssistant)\n      ...\n    ```\n\nPutting this together, here is how you can implement a simple multi-agent system with two agents — a flight booking assistant and a hotel booking assistant:\n\n```ts\nimport { ChatAnthropic } from \"@langchain/anthropic\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { StateGraph, MessagesAnnotation, Command, START, END } from \"@langchain/langgraph\";\nimport { tool, type ToolRuntime } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ToolMessage } from \"@langchain/core/messages\";\n\ninterface CreateHandoffToolParams {\n  agentName: string;\n  description?: string;\n}\n\nconst createHandoffTool = ({\n  agentName,\n  description,\n}: CreateHandoffToolParams) => {\n  const toolName = `transfer_to_${agentName}`;\n  const toolDescription = description || `Ask agent '${agentName}' for help`;\n\n  const handoffTool = tool(\n    async (_, runtime: ToolRuntime<typeof MessagesAnnotation.State>) => {\n      const toolMessage = new ToolMessage({\n        content: `Successfully transferred to ${agentName}`,\n        name: toolName,\n        tool_call_id: runtime.toolCallId,\n      });\n\n      // inject the current agent state\n      // highlight-next-line\n      const state = runtime.state;  // (1)!\n      return new Command({  // (2)!\n        // highlight-next-line\n        goto: agentName,  // (3)!\n        // highlight-next-line\n        update: { messages: state.messages.concat(toolMessage) },  // (4)!\n        // highlight-next-line\n        graph: Command.PARENT,  // (5)!\n      });\n    },\n    {\n      name: toolName,\n      schema: z.object({}),\n      description: toolDescription,\n    }\n  );\n\n  return handoffTool;\n};\n\nconst bookHotel = tool(\n  async (input: { hotel_name: string }) => {\n    return `Successfully booked a stay at ${input.hotel_name}.`;\n  },\n  {\n    name: \"book_hotel\",\n    description: \"Book a hotel\",\n    schema: z.object({\n      hotel_name: z.string().describe(\"The name of the hotel to book\"),\n    }),\n  }\n);\n\nconst bookFlight = tool(\n  async (input: { from_airport: string; to_airport: string }) => {\n    return `Successfully booked a flight from ${input.from_airport} to ${input.to_airport}.`;\n  },\n  {\n    name: \"book_flight\",\n    description: \"Book a flight\",\n    schema: z.object({\n      from_airport: z.string().describe(\"The departure airport code\"),\n      to_airport: z.string().describe(\"The arrival airport code\"),\n    }),\n  }\n);\n\nconst transferToHotelAssistant = createHandoffTool({\n  agentName: \"hotel_assistant\",\n  description: \"Transfer user to the hotel-booking assistant.\",\n});\n\nconst transferToFlightAssistant = createHandoffTool({\n  agentName: \"flight_assistant\",\n  description: \"Transfer user to the flight-booking assistant.\",\n});\n\nconst llm = new ChatAnthropic({ modelName: \"claude-3-5-sonnet-latest\" });\n\nconst flightAssistant = createReactAgent({\n  llm,\n  // highlight-next-line\n  tools: [bookFlight, transferToHotelAssistant],\n  prompt: \"You are a flight booking assistant\",\n  // highlight-next-line\n  name: \"flight_assistant\",\n});\n\nconst hotelAssistant = createReactAgent({\n  llm,\n  // highlight-next-line\n  tools: [bookHotel, transferToFlightAssistant],\n  prompt: \"You are a hotel booking assistant\",\n  // highlight-next-line\n  name: \"hotel_assistant\",\n});\n\nconst multiAgentGraph = new StateGraph(MessagesAnnotation)\n  .addNode(\"flight_assistant\", flightAssistant, { ends: [\"hotel_assistant\", END] })\n  .addNode(\"hotel_assistant\", hotelAssistant, { ends: [\"flight_assistant\", END] })\n  .addEdge(START, \"flight_assistant\")\n  .compile();\n\nconst stream = await multiAgentGraph.stream({\n  messages: [{\n    role: \"user\",\n    content: \"book a flight from BOS to JFK and a stay at McKittrick Hotel\"\n  }]\n});\n\nfor await (const chunk of stream) {\n  console.log(chunk);\n  console.log(\"\\n\");\n}\n```\n\n1. Access agent's state\n2. The `Command` primitive allows specifying a state update and a node transition as a single operation, making it useful for implementing handoffs.\n3. Name of the agent or node to hand off to.\n4. Take the agent's messages and **add** them to the parent's **state** as part of the handoff. The next agent will see the parent state.\n5. Indicate to LangGraph that we need to navigate to agent node in a **parent** multi-agent graph.\n\n!!! Note\n    This handoff implementation assumes that:\n\n    - each agent receives overall message history (across all agents) in the multi-agent system as its input\n    - each agent outputs its internal messages history to the overall message history of the multi-agent system\n\n    Check out LangGraph [supervisor](https://github.com/langchain-ai/langgraph-supervisor-py#customizing-handoff-tools) and [swarm](https://github.com/langchain-ai/langgraph-swarm-py#customizing-handoff-tools) documentation to learn how to customize handoffs.","docs/docs/agents/overview.md":"---\ntitle: Overview\n---\n\n# Agent development with LangGraph\n\n**LangGraph** provides both low-level primitives and high-level prebuilt components for building agent-based applications. This section focuses on the **prebuilt**, **reusable** components designed to help you construct agentic systems quickly and reliably—without the need to implement orchestration, memory, or human feedback handling from scratch.\n\n## What is an agent?\n\nAn _agent_ consists of three components: a **large language model (LLM)**, a set of **tools** it can use, and a **prompt** that provides instructions.\n\nThe LLM operates in a loop. In each iteration, it selects a tool to invoke, provides input, receives the result (an observation), and uses that observation to inform the next action. The loop continues until a stopping condition is met — typically when the agent has gathered enough information to respond to the user.\n\n<figure markdown=\"1\">\n![image](./assets/agent.png){: style=\"max-height:400px\"}\n<figcaption>Agent loop: the LLM selects tools and uses their outputs to fulfill a user request.</figcaption>\n</figure>\n\n## Key features\n\nLangGraph includes several capabilities essential for building robust, production-ready agentic systems:\n\n- [**Memory integration**](./memory.md): Native support for _short-term_ (session-based) and _long-term_ (persistent across sessions) memory, enabling stateful behaviors in chatbots and assistants.\n- [**Human-in-the-loop control**](./human-in-the-loop.md): Execution can pause _indefinitely_ to await human feedback—unlike websocket-based solutions limited to real-time interaction. This enables asynchronous approval, correction, or intervention at any point in the workflow.\n- [**Streaming support**](./streaming.md): Real-time streaming of agent state, model tokens, tool outputs, or combined streams.\n- [**Deployment tooling**](./deployment.md): Includes infrastructure-free deployment tools. [**LangGraph Platform**](https://langchain-ai.github.io/langgraph/concepts/langgraph_platform/) supports testing, debugging, and deployment.\n  - **[Studio](https://langchain-ai.github.io/langgraph/concepts/langgraph_studio/)**: A visual IDE for inspecting and debugging workflows.\n  - Supports multiple [**deployment options**](https://langchain-ai.github.io/langgraph/tutorials/deployment/) for production.\n\n## High-level building blocks\n\nLangGraph comes with a set of prebuilt components that implement common agent behaviors and workflows. These abstractions are built on top of the LangGraph framework, offering a faster path to production while remaining flexible for advanced customization.\n\nUsing LangGraph for agent development allows you to focus on your application's logic and behavior, instead of building and maintaining the supporting infrastructure for state, memory, and human feedback.\n\n## Package ecosystem\n\nThe high-level components are organized into several packages, each with a specific focus.\n\n| Package                  | Description                                                                 | Installation                                       |\n| ------------------------ | --------------------------------------------------------------------------- | -------------------------------------------------- |\n| `langgraph`              | Prebuilt components to [**create agents**](./agents.md)                     | `npm install @langchain/langgraph @langchain/core` |\n| `langgraph-supervisor`   | Tools for building [**supervisor**](./multi-agent.md#supervisor) agents     | `npm install @langchain/langgraph-supervisor`      |\n| `langgraph-swarm`        | Tools for building a [**swarm**](./multi-agent.md#swarm) multi-agent system | `npm install @langchain/langgraph-swarm`           |\n| `langchain-mcp-adapters` | Interfaces to [**MCP servers**](./mcp.md) for tool and resource integration | `npm install @langchain/mcp-adapters`              |\n| `agentevals`             | Utilities to [**evaluate agent performance**](./evals.md)                   | `npm install agentevals`                           |\n\n## Visualize an agent graph\n\nUse the following tool to visualize the graph generated by [`createReactAgent`](/langgraphjs/reference/functions/langgraph_prebuilt.createReactAgent.html) and to view an outline of the corresponding code. It allows you to explore the infrastructure of the agent as defined by the presence of:\n\n- [`tools`](./tools.md): A list of tools (functions, APIs, or other callable objects) that the agent can use to perform tasks.\n- `preModelHook`: A function that is called before the model is invoked. It can be used to condense messages or perform other preprocessing tasks.\n- `postModelHook`: A function that is called after the model is invoked. It can be used to implement guardrails, human-in-the-loop flows, or other postprocessing tasks.\n- [`responseFormat`](./agents.md#structured-output): A data structure used to constrain the type of the final output (via Zod schemas).\n\n<div class=\"agent-layout\">\n  <div class=\"agent-graph-features-container\">\n    <div class=\"agent-graph-features\">\n      <h3 class=\"agent-section-title\">Features</h3>\n      <label><input type=\"checkbox\" id=\"tools\" checked> <code>tools</code></label>\n      <label><input type=\"checkbox\" id=\"preModelHook\"> <code>preModelHook</code></label>\n      <label><input type=\"checkbox\" id=\"postModelHook\"> <code>postModelHook</code></label>\n      <label><input type=\"checkbox\" id=\"responseFormat\"> <code>responseFormat</code></label>\n    </div>\n  </div>\n\n  <div class=\"agent-graph-container\">\n    <h3 class=\"agent-section-title\">Graph</h3>\n    <img id=\"agent-graph-img\" src=\"../assets/react_agent_graphs/0001.svg\" alt=\"graph image\" style=\"max-width: 100%;\"/>\n  </div>\n</div>\n\nThe following code snippet shows how to create the above agent (and underlying graph) with [`createReactAgent`](/langgraphjs/reference/functions/langgraph_prebuilt.createReactAgent.html):\n\n<div class=\"language-typescript\">\n  <pre><code id=\"agent-code\" class=\"language-typescript\"></code></pre>\n</div>\n\n<script>\nfunction getCheckedValue(id) {\n  return document.getElementById(id).checked ? \"1\" : \"0\";\n}\n\nfunction getKey() {\n  return [\n    getCheckedValue(\"responseFormat\"),\n    getCheckedValue(\"postModelHook\"),\n    getCheckedValue(\"preModelHook\"),\n    getCheckedValue(\"tools\")\n  ].join(\"\");\n}\n\nfunction dedent(strings, ...values) {\n  const str = String.raw({ raw: strings }, ...values)\n  const [space] = str.split(\"\\n\").filter(Boolean).at(0).match(/^(\\s*)/)\n  const spaceLen = space.length\n  return str.split(\"\\n\").map(line => line.slice(spaceLen)).join(\"\\n\").trim()\n}\n\nObject.assign(dedent, {\n  offset: (size) => (strings, ...values) => {\n    return dedent(strings, ...values).split(\"\\n\").map(line => \" \".repeat(size) + line).join(\"\\n\")\n  }\n})\n\n\n\n\nfunction generateCodeSnippet({ tools, pre, post, response }) {\n  const lines = []\n\n  lines.push(dedent`\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { ChatOpenAI } from \"@langchain/openai\";\n  `)\n\n  if (tools) lines.push(`import { tool } from \"@langchain/core/tools\";`);  \n  if (response || tools) lines.push(`import { z } from \"zod\";`);\n\n  lines.push(\"\", dedent`\n    const agent = createReactAgent({\n      llm: new ChatOpenAI({ model: \"o4-mini\" }),\n  `)\n\n  if (tools) {\n    lines.push(dedent.offset(2)`\n      tools: [\n        tool(() => \"Sample tool output\", {\n          name: \"sampleTool\",\n          schema: z.object({}),\n        }),\n      ],\n    `)\n  }\n\n  if (pre) {\n    lines.push(dedent.offset(2)`\n      preModelHook: (state) => ({ llmInputMessages: state.messages }),\n    `)\n  }\n\n  if (post) {\n    lines.push(dedent.offset(2)`\n      postModelHook: (state) => state,\n    `)\n  }\n\n  if (response) {\n    lines.push(dedent.offset(2)`\n      responseFormat: z.object({ result: z.string() }),\n    `)\n  }\n\n  lines.push(`});`);\n\n  return lines.join(\"\\n\");\n}\n\nfunction render() {\n  const key = getKey();\n  document.getElementById(\"agent-graph-img\").src = `../assets/react_agent_graphs/${key}.svg`;\n\n  const state = {\n    tools: document.getElementById(\"tools\").checked,\n    pre: document.getElementById(\"preModelHook\").checked,\n    post: document.getElementById(\"postModelHook\").checked,\n    response: document.getElementById(\"responseFormat\").checked\n  };\n\n  document.getElementById(\"agent-code\").textContent = generateCodeSnippet(state);\n}\n\nfunction initializeWidget() {\n  render(); // no need for `await` here\n  document.querySelectorAll(\".agent-graph-features input\").forEach((input) => {\n    input.addEventListener(\"change\", render);\n  });\n}\n\n// Init for both full reload and SPA nav (used by MkDocs Material)\nwindow.addEventListener(\"DOMContentLoaded\", initializeWidget);\ndocument$.subscribe(initializeWidget);\n</script>\n","docs/docs/agents/run_agents.md":"# Subagent: run_agents\n\nPath: `docs/docs/agents/run_agents.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/run_agents.md)","docs/docs/agents/streaming.md":"# Subagent: streaming\n\nPath: `docs/docs/agents/streaming.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/streaming.md)","docs/docs/agents/tools.md":"# Subagent: tools\n\nPath: `docs/docs/agents/tools.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/tools.md)","docs/docs/agents/ui.md":"# Subagent: ui\n\nPath: `docs/docs/agents/ui.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/ui.md)"},"items":[{"name":"agents.md","path":"docs/docs/agents/agents.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/agents.md","title":"Subagent: agents","category":"subagent-persona","format":"markdown","content":"# LangGraph quickstart\n\nThis guide shows you how to set up and use LangGraph's **prebuilt**, **reusable** components, which are designed to help you construct agentic systems quickly and reliably.\n\n## Prerequisites\n\nBefore you start this tutorial, ensure you have the following:\n\n- An [Anthropic](https://console.anthropic.com/settings/keys) API key\n\n## 1. Install dependencies\n\nIf you haven't already, install LangGraph and LangChain:\n\n```\nnpm install langchain @langchain/langgraph @langchain/anthropic\n```\n\n## 2. Create an agent\n\nUse [`createReactAgent`](/langgraphjs/reference/functions/langgraph_prebuilt.createReactAgent.html) to instantiate an agent:\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst getWeather = tool( // (1)!\n  async (input: { city: string }) => {\n    return `It's always sunny in ${input.city}!`;\n  },\n  {\n    name: \"getWeather\",\n    schema: z.object({\n      city: z.string().describe(\"The city to get the weather for\"),\n    }),\n    description: \"Get weather for a given city.\",\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\"); // (2)!\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather], // (3)!\n  prompt: \"You are a helpful assistant\", // (4)!\n});\n\n// Run the agent\nawait agent.invoke({\n  messages: [{ role: \"user\", content: \"what is the weather in sf\" }],\n});\n```\n\n1. Define a tool for the agent to use. For more advanced tool usage and customization, check the [tools](./tools.md) page.\n2. Provide a language model for the agent to use. To learn more about configuring language models for the agents, check the [models](./models.md) page.\n3. Provide a list of tools for the model to use.\n4. Provide a system prompt (instructions) to the language model used by the agent.\n\n## 3. Configure an LLM\n\nUse [`initChatModel`](https://api.js.langchain.com/functions/langchain.chat_models_universal.initChatModel.html) to configure an LLM with specific parameters, such as temperature:\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\n// highlight-next-line\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\", {\n  // highlight-next-line\n  temperature: 0,\n});\n\nconst agent = createReactAgent({\n  // highlight-next-line\n  llm,\n  tools: [getWeather],\n});\n```\n\nSee the [models](./models.md) page for more information on how to configure LLMs.\n\n## 4. Add a custom prompt\n\nPrompts instruct the LLM how to behave. They can be:\n\n- **Static**: A string is interpreted as a **system message**\n- **Dynamic**: a list of messages generated at **runtime** based on input or configuration\n\n=== \"Static prompt\"\n\n    Define a fixed prompt string or list of messages.\n\n    ```ts\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // A static prompt that never changes\n      // highlight-next-line\n      prompt: \"Never answer questions about the weather.\",\n    });\n\n    await agent.invoke({\n      messages: \"what is the weather in sf\",\n    });\n    ```\n\n=== \"Dynamic prompt\"\n\n    Define a function that returns a message list based on the agent's state and configuration:\n\n    ```ts\n    import { BaseMessageLike } from \"@langchain/core/messages\";\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { MessagesAnnotation } from \"@langchain/langgraph\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n    const prompt = (\n      state: typeof MessagesAnnotation.State,\n      config: RunnableConfig\n    ): BaseMessageLike[] => { // (1)!\n      const userName = config.configurable?.userName;\n      const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;\n      return [{ role: \"system\", content: systemMsg }, ...state.messages];\n    };\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // highlight-next-line\n      prompt,\n    });\n\n    await agent.invoke(\n      { messages: [{ role: \"user\", content: \"what is the weather in sf\" }] },\n      // highlight-next-line\n      { configurable: { userName: \"John Smith\" } }\n    );\n    ```\n\n    1. Dynamic prompts allow including non-message [context](./context.md) when constructing an input to the LLM, such as:\n\n      - Information passed at runtime, like a `userId` or API credentials (using `config`).\n      - Internal agent state updated during a multi-step reasoning process (using `state`).\n\n      Dynamic prompts can be defined as functions that take `state` and `config` and return a list of messages to send to the LLM.\n\nFor more information, see [Context](./context.md).\n\n## 5. Add memory\n\nTo allow multi-turn conversations with an agent, you need to enable [persistence](../concepts/persistence.md) by providing a `checkpointer` when creating an agent. At runtime you need to provide a config containing `thread_id` — a unique identifier for the conversation (session):\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { MemorySaver } from \"@langchain/langgraph-checkpoint\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\n// highlight-next-line\nconst checkpointer = new MemorySaver();\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather],\n  // highlight-next-line\n  checkpointer, // (1)!\n});\n\n// Run the agent\n// highlight-next-line\nconst config = { configurable: { thread_id: \"1\" } };\nconst sfResponse = await agent.invoke(\n  { messages: [{ role: \"user\", content: \"what is the weather in sf\" }] },\n  config // (2)!\n);\nconst nyResponse = await agent.invoke(\n  { messages: [{ role: \"user\", content: \"what about new york?\" }] },\n  config\n);\n```\n\n1. `checkpointer` allows the agent to store its state at every step in the tool calling loop. This enables [short-term memory](./memory.md#short-term-memory) and [human-in-the-loop](./human-in-the-loop.md) capabilities.\n2. Pass configuration with `thread_id` to be able to resume the same conversation on future agent invocations.\n\nWhen you enable the checkpointer, it stores agent state at every step in the provided checkpointer database (or in memory, if using `InMemorySaver`).\n\nNote that in the above example, when the agent is invoked the second time with the same `thread_id`, the original message history from the first conversation is automatically included, together with the new user input.\n\nFor more information, see [Memory](./memory.md).\n\n## 6. Configure structured output\n\nTo produce structured responses conforming to a schema, use the `responseFormat` parameter. The schema can be defined with a `zod` schema. The result will be accessible via the `structuredResponse` field.\n\n```ts\nimport { z } from \"zod\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\nconst WeatherResponse = z.object({\n  conditions: z.string(),\n});\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather],\n  // highlight-next-line\n  responseFormat: WeatherResponse, // (1)!\n});\n\nconst response = await agent.invoke({\n  messages: [{ role: \"user\", content: \"what is the weather in sf\" }],\n});\n// highlight-next-line\nresponse.structuredResponse;\n```\n\n1. When `responseFormat` is provided, a separate step is added at the end of the agent loop: agent message history is passed to an LLM with structured output to generate a structured response.\n\n   To provide a system prompt to this LLM, use an object `{ prompt, schema }`, e.g., `responseFormat: { prompt, schema: WeatherResponse }`.\n\n!!! Note \"LLM post-processing\"\n\n    Structured output requires an additional call to the LLM to format the response according to the schema.\n\n## Next steps\n\n- [Deploy your agent locally](../tutorials/langgraph-platform/local-server.md)\n- [Learn more about prebuilt agents](../agents/overview.md)\n- [LangGraph Platform quickstart](../cloud/quick_start.md)\n","isInternal":false,"tokens":2061,"sizeBytes":8521},{"name":"context.md","path":"docs/docs/agents/context.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/context.md","title":"Subagent: context","category":"subagent-persona","format":"markdown","content":"# Context\n\nAgents often require more than a list of messages to function effectively. They need **context**.\n\nContext includes *any* data outside the message list that can shape agent behavior or tool execution. This can be:\n\n- Information passed at runtime, like a `user_id` or API credentials.\n- Internal state updated during a multi-step reasoning process.\n- Persistent memory or facts from previous interactions.\n\nLangGraph provides **three** primary ways to supply context:\n\n| Type                                                                         | Description                                   | Mutable? | Lifetime                |\n|------------------------------------------------------------------------------|-----------------------------------------------|----------|-------------------------|\n| [**Config**](#config-static-context)                                         | data passed at the start of a run             | ❌        | per run                 |\n| [**State**](#state-mutable-context)                                          | dynamic data that can change during execution | ✅        | per run or conversation |\n| [**Long-term Memory (Store)**](#long-term-memory-cross-conversation-context) | data that can be shared between conversations | ✅        | across conversations    |\n\nYou can use context to:\n\n- Adjust the system prompt the model sees\n- Feed tools with necessary inputs\n- Track facts during an ongoing conversation\n\n## Providing Runtime Context\n\nUse this when you need to inject data into an agent at runtime.\n\n### Config (static context)\n\nConfig is for immutable data like user metadata or API keys. Use\nwhen you have values that don't change mid-run.\n\nSpecify configuration using a key called **\"configurable\"** which is reserved\nfor this purpose:\n\n```ts\nawait agent.invoke(\n  { messages: \"hi!\" },\n  // highlight-next-line\n  { configurable: { userId: \"user_123\" } }\n)\n```\n\n### State (mutable context)\n\nState acts as short-term memory during a run. It holds dynamic data that can evolve during execution, such as values derived from tools or LLM outputs.\n\n```ts\nconst CustomState = Annotation.Root({\n  ...MessagesAnnotation.spec,\n  userName: Annotation<string>,\n});\n\nconst agent = createReactAgent({\n  // Other agent parameters...\n  // highlight-next-line\n  stateSchema: CustomState,\n})\n\nawait agent.invoke(\n  // highlight-next-line\n  { messages: \"hi!\", userName: \"Jane\" }\n)\n```\n\n!!! tip \"Turning on memory\"\n\n    Please see the [memory guide](./memory.md) for more details on how to enable memory. This is a powerful feature that allows you to persist the agent's state across multiple invocations.\n    Otherwise, the state is scoped only to a single agent run.\n\n\n\n### Long-Term Memory (cross-conversation context)\n\nFor context that spans *across* conversations or sessions, LangGraph allows access to **long-term memory** via a `store`. This can be used to read or update persistent facts (e.g., user profiles, preferences, prior interactions). For more, see the [Memory guide](./memory.md).\n\n## Customizing Prompts with Context\n\nPrompts define how the agent behaves. To incorporate runtime context, you can dynamically generate prompts based on the agent's state or config.\n\nCommon use cases:\n\n- Personalization\n- Role or goal customization\n- Conditional behavior (e.g., user is admin)\n\n=== \"Using config\"\n\n    ```ts\n    import { BaseMessageLike } from \"@langchain/core/messages\";\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { MessagesAnnotation } from \"@langchain/langgraph\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n    const prompt = (\n      state: typeof MessagesAnnotation.State,\n      // highlight-next-line\n      config: RunnableConfig\n    ): BaseMessageLike[] => {\n      // highlight-next-line\n      const userName = config.configurable?.userName;\n      const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;\n      return [{ role: \"system\", content: systemMsg }, ...state.messages];\n    };\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // highlight-next-line\n      prompt\n    });\n\n    await agent.invoke(\n      { messages: \"hi!\" },\n      // highlight-next-line\n      { configurable: { userName: \"John Smith\" } }\n    );\n    ```\n\n=== \"Using state\"\n\n    ```ts\n    import { BaseMessageLike } from \"@langchain/core/messages\";\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { Annotation, MessagesAnnotation } from \"@langchain/langgraph\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n    const CustomState = Annotation.Root({\n      ...MessagesAnnotation.spec,\n      // highlight-next-line\n      userName: Annotation<string>,\n    });\n\n    const prompt = (\n      // highlight-next-line\n      state: typeof CustomState.State,\n    ): BaseMessageLike[] => {\n      // highlight-next-line\n      const userName = state.userName;\n      const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;\n      return [{ role: \"system\", content: systemMsg }, ...state.messages];\n    };\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // highlight-next-line\n      prompt,\n      // highlight-next-line\n      stateSchema: CustomState,\n    });\n\n    await agent.invoke(\n      // highlight-next-line\n      { messages: \"hi!\", userName: \"John Smith\" },\n    );\n    ```\n\n## Tools\n\nTools can access context through:\n\n* Use `RunnableConfig` for config access\n* Use `runtime.state` (the second argument, typed as `ToolRuntime`) for agent state\n\n!!! tip \"Browser / web environments\"\n\n    When a tool runs inside a `ToolNode` (including in `createReactAgent`), the `ToolNode` forwards its input (the current graph state) to the tool via `runtime.state`. This works in every runtime, including web browsers.\n\n    An older alternative, `getCurrentTaskInput()`, relies on [`AsyncLocalStorage`](https://nodejs.org/api/async_hooks.html), which is available in Node.js, Deno, and Cloudflare Workers, but **not** in web browsers. Prefer `runtime.state` for portability.\n\n=== \"Using config\"\n\n    ```ts\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { tool } from \"@langchain/core/tools\";\n    import { z } from \"zod\";\n\n    const getUserInfo = tool(\n      async (input: Record<string, any>, config: RunnableConfig) => {\n        // highlight-next-line\n        const userId = config.configurable?.userId;\n        return userId === \"user_123\" ? \"User is John Smith\" : \"Unknown user\";\n      },\n      {\n        name: \"get_user_info\",\n        description: \"Look up user info.\",\n        schema: z.object({}),\n      }\n    );\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getUserInfo],\n    });\n\n    await agent.invoke(\n      { messages: \"look up user information\" },\n      // highlight-next-line\n      { configurable: { userId: \"user_123\" } }\n    );\n    ```\n\n=== \"Using state\"\n\n    ```ts\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { Annotation, MessagesAnnotation } from \"@langchain/langgraph\";\n    import { tool, type ToolRuntime } from \"@langchain/core/tools\";\n    import { z } from \"zod\";\n\n    const CustomState = Annotation.Root({\n      ...MessagesAnnotation.spec,\n      // highlight-next-line\n      userId: Annotation<string>(),\n    });\n\n    const getUserInfo = tool(\n      async (\n        input: Record<string, any>,\n        // highlight-next-line\n        runtime: ToolRuntime<typeof CustomState.State>,\n      ) => {\n        // Read the graph state directly from the second argument.\n        // This works in web browsers too (no AsyncLocalStorage required).\n        // highlight-next-line\n        const userId = runtime.state.userId;\n        return userId === \"user_123\" ? \"User is John Smith\" : \"Unknown user\";\n      },\n      {\n        name: \"get_user_info\",\n        description: \"Look up user info.\",\n        schema: z.object({})\n      }\n    );\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getUserInfo],\n      // highlight-next-line\n      stateSchema: CustomState,\n    });\n\n    await agent.invoke(\n      // highlight-next-line\n      { messages: \"look up user information\", userId: \"user_123\" }\n    );\n    ```\n\n\n## Update context from tools\n\nTools can modify the agent's state during execution. This is useful for persisting intermediate results or making information accessible to subsequent tools or prompts.\n\n```ts\nimport { Annotation, MessagesAnnotation, LangGraphRunnableConfig, Command } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\nconst CustomState = Annotation.Root({\n  ...MessagesAnnotation.spec,\n  // highlight-next-line\n  userName: Annotation<string>(), // Will be updated by the tool\n});\n\nconst getUserInfo = tool(\n  async (\n    _input: Record<string, never>,\n    config: LangGraphRunnableConfig\n  ): Promise<Command> => {\n    const userId = config.configurable?.userId;\n    if (!userId) {\n      throw new Error(\"Please provide a user id in config.configurable\");\n    }\n\n    const toolCallId = config.toolCall?.id;\n\n    const name = userId === \"user_123\" ? \"John Smith\" : \"Unknown user\";\n    // Return command to update state\n    return new Command({\n      update: {\n        // highlight-next-line\n        userName: name,\n        // Update the message history\n        // highlight-next-line\n        messages: [\n          new ToolMessage({\n            content: \"Successfully looked up user information\",\n            tool_call_id: toolCallId,\n          }),\n        ],\n      },\n    });\n  },\n  {\n    name: \"get_user_info\",\n    description: \"Look up user information.\",\n    schema: z.object({}),\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getUserInfo],\n  // highlight-next-line\n  stateSchema: CustomState,\n});\n\nawait agent.invoke(\n  { messages: \"look up user information\" },\n  // highlight-next-line\n  { configurable: { userId: \"user_123\" } }\n);\n```\n\nFor more details, see [how to update state from tools](../how-tos/update-state-from-tools.ipynb).","isInternal":false,"tokens":2446,"sizeBytes":10977},{"name":"deployment.md","path":"docs/docs/agents/deployment.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/deployment.md","title":"Subagent: deployment","category":"subagent-persona","format":"markdown","content":"# Deployment\n\nTo deploy your LangGraph agent, create and configure a LangGraph app. This setup supports both local development and production deployments.\n\nFeatures: \n\n* 🖥️ Local server for development\n* 🧩 Studio Web UI for visual debugging\n* ☁️ Cloud and 🔧 self-hosted deployment options\n* 📊 LangSmith integration for tracing and observability\n\n!!! info \"Requirements\" \n\n    - ✅ You **must** have a [LangSmith account](https://www.langchain.com/langsmith). You can sign up for **free** and get started with the free tier.\n\n## Create a LangGraph app\n\n```bash\nnpm install -g create-langgraph\ncreate-langgraph path/to/your/app\n```\n\nFollow the prompts and select `New LangGraph Project`. This will create an empty LangGraph project. You can modify it by replacing the code in `src/agent/graph.ts` with your agent code. For example:\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst getWeather = tool(\n  async (input: { city: string }) => {\n    return `It's always sunny in ${input.city}!`;\n  },\n  {\n    name: \"getWeather\",\n    schema: z.object({\n      city: z.string().describe(\"The city to get the weather for\"),\n    }),\n    description: \"Get weather for a given city.\",\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n// make sure to export the graph that will be used in the LangGraph API server\n// highlight-next-line\nexport const graph = createReactAgent({\n  llm,\n  tools: [getWeather],\n  prompt: \"You are a helpful assistant\"\n})\n```\n\n### Install dependencies\n\nIn the root of your new LangGraph app, install the dependencies:\n\n```shell\nyarn\n# install these to use initChatModel with Anthropic\nyarn add langchain\nyarn add @langchain/anthropic\n```\n\n### Create an `.env` file\n\nYou will find a `.env.example` in the root of your new LangGraph app. Create\na `.env` file in the root of your new LangGraph app and copy the contents of the `.env.example` file into it, filling in the necessary API keys:\n\n```bash\nLANGSMITH_API_KEY=lsv2...\nANTHROPIC_API_KEY=sk-\n```\n\n## Launch LangGraph server locally\n\n```shell\nnpx @langchain/langgraph-cli dev\n```\n\nThis will start up the LangGraph API server locally. If this runs successfully, you should see something like:\n\n>    Welcome to LangGraph.js!\n> \n>    - 🚀 API: http://localhost:2024\n>     \n>    - 🎨 Studio UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024\n\n## LangGraph Studio Web UI\n\nLangGraph Studio Web is a specialized UI that you can connect to LangGraph API server to enable visualization, interaction, and debugging of your application locally. Test your graph in the LangGraph Studio Web UI by visiting the URL provided in the output of the `npx @langchain/langgraph-cli dev` command.\n\n>    - LangGraph Studio Web UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024\n\n## Deployment\n\nOnce your LangGraph app is running locally, you can deploy it using LangSmith Deployment or self-hosted options. Refer to the [deployment options guide](https://langchain-ai.github.io/langgraph/tutorials/deployment/) for detailed instructions on all supported deployment models.\n","isInternal":false,"tokens":814,"sizeBytes":3271},{"name":"evals.md","path":"docs/docs/agents/evals.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/evals.md","title":"Subagent: evals","category":"subagent-persona","format":"markdown","content":"# Evals\n\nTo evaluate your agent's performance you can use `LangSmith` [evaluations](https://docs.smith.langchain.com/evaluation). You would need to first define an evaluator function to judge the results from an agent, such as final outputs or trajectory. Depending on your evaluation technique, this may or may not involve a reference output:\n\n```ts\nconst evaluator = async (params: {\n  inputs: Record<string, unknown>;\n  outputs: Record<string, unknown>;\n  referenceOutputs?: Record<string, unknown>;\n}) => {\n  // compare agent outputs against reference outputs\n  const outputMessages = params.outputs.messages;\n  const referenceMessages = params.referenceOutputs.messages;\n  const score = compareMessages(outputMessages, referenceMessages);\n  return { key: \"evaluator_score\", score: score };\n};\n```\n\nTo get started, you can use prebuilt evaluators from `AgentEvals` package:\n\n```bash\nnpm install agentevals @langchain/core\n```\n\n## Create evaluator\n\nA common way to evaluate agent performance is by comparing its trajectory (the order in which it calls its tools) against a reference trajectory:\n\n```ts\n// highlight-next-line\nimport { createTrajectoryMatchEvaluator } from \"agentevals\";\n\nconst outputs = [\n  {\n    role: \"assistant\",\n    tool_calls: [\n      {\n        function: {\n          name: \"get_weather\",\n          arguments: JSON.stringify({ city: \"san francisco\" }),\n        },\n      },\n      {\n        function: {\n          name: \"get_directions\",\n          arguments: JSON.stringify({ destination: \"presidio\" }),\n        },\n      },\n    ],\n  },\n];\n\nconst referenceOutputs = [\n  {\n    role: \"assistant\",\n    tool_calls: [\n      {\n        function: {\n          name: \"get_weather\",\n          arguments: JSON.stringify({ city: \"san francisco\" }),\n        },\n      },\n    ],\n  },\n];\n\n// Create the evaluator\nconst evaluator = createTrajectoryMatchEvaluator({\n  // highlight-next-line\n  trajectoryMatchMode: \"superset\",  // (1)!\n})\n\n// Run the evaluator\nconst result = await evaluator({\n  outputs,\n  referenceOutputs,\n});\n```\n\n1. Specify how the trajectories will be compared. `superset` will accept output trajectory as valid if it's a superset of the reference one. Other options include: [strict](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#strict-match), [unordered](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#unordered-match) and [subset](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#subset-and-superset-match)\n\n\nAs a next step, learn more about how to [customize trajectory match evaluator](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#agent-trajectory-match).\n\n### LLM-as-a-judge\n\nYou can use LLM-as-a-judge evaluator that uses an LLM to compare the trajectory against the reference outputs and output a score:\n\n```ts\nimport {\n  // highlight-next-line\n  createTrajectoryLLMAsJudge,\n  TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE\n} from \"agentevals\";\n\nconst evaluator = createTrajectoryLLMAsJudge({\n  prompt: TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE,\n  model: \"openai:o3-mini\",\n});\n```\n\n## Run evaluator\n\nTo run an evaluator, you will first need to create a [LangSmith dataset](https://docs.smith.langchain.com/evaluation/concepts#datasets). To use the prebuilt AgentEvals evaluators, you will need a dataset with the following schema:\n\n- **input**: `{ messages: [...] }` input messages to call the agent with.\n- **output**: `{ messages\": [...] }` expected message history in the agent output. For trajectory evaluation, you can choose to keep only assistant messages.\n\n```ts\nimport { evaluate } from \"langsmith/evaluation\";\nimport { createTrajectoryMatchEvaluator } from \"agentevals\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\nconst agent = createReactAgent({ ... })\nconst evaluator = createTrajectoryMatchEvaluator({ ... })\nawait evaluate(\n  async (inputs) => await agent.invoke(inputs),\n  {\n    // replace with your dataset name\n    data: \"<Name of your dataset>\",\n    evaluators: [evaluator],\n  }\n);\n```","isInternal":false,"tokens":933,"sizeBytes":4013},{"name":"human-in-the-loop.md","path":"docs/docs/agents/human-in-the-loop.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/human-in-the-loop.md","title":"Subagent: human-in-the-loop","category":"subagent-persona","format":"markdown","content":"# Human-in-the-loop\n\nTo review, edit and approve tool calls in an agent you can use LangGraph's built-in [human-in-the-loop](../concepts/human_in_the_loop.md) features, specifically the [`interrupt()`](/langgraphjs/reference/functions/langgraph.interrupt-1.html) primitive.\n\nLangGraph allows you to pause execution **indefinitely** — for minutes, hours, or even days—until human input is received.\n\nThis is possible because the agent state is **checkpointed into a database**, which allows the system to persist execution context and later resume the workflow, continuing from where it left off.\n\nFor a deeper dive into the **human-in-the-loop** concept, see the [concept guide](../concepts/human_in_the_loop.md).\n\n<figure markdown=\"1\">\n![image](../concepts/img/human_in_the_loop/tool-call-review.png){: style=\"max-height:400px\"}\n<figcaption>\nA human can review and edit the output from the agent before proceeding. This is particularly critical in applications where the tool calls requested may be sensitive or require human oversight.\n</figcaption>\n</figure>\n\n\n## Review tool calls\n\nTo add a human approval step to a tool:\n\n1. Use `interrupt()` in the tool to pause execution.\n2. Resume with a `Command({ resume: ... })` to continue based on human input.\n\n```ts\nimport { MemorySaver } from \"@langchain/langgraph-checkpoint\";\nimport { interrupt } from \"@langchain/langgraph\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\n// An example of a sensitive tool that requires human review / approval\nconst bookHotel = tool(\n  async (input: { hotelName: string; }) => {\n    let hotelName = input.hotelName;\n    // highlight-next-line\n    const response = interrupt(  // (1)!\n      `Trying to call \\`book_hotel\\` with args {'hotel_name': ${hotelName}}. ` +\n      `Please approve or suggest edits.`\n    )\n    if (response.type === \"accept\") {\n      // proceed to execute the tool logic\n    } else if (response.type === \"edit\") {\n        hotelName = response.args[\"hotel_name\"]\n    } else {\n        throw new Error(`Unknown response type: ${response.type}`)\n    }\n    return `Successfully booked a stay at ${hotelName}.`;\n  },\n  {\n    name: \"bookHotel\",\n    schema: z.object({\n      hotelName: z.string().describe(\"Hotel to book\"),\n    }),\n    description: \"Book a hotel.\",\n  }\n);\n\n// highlight-next-line\nconst checkpointer = new MemorySaver();  // (2)!\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [bookHotel],\n  // highlight-next-line\n  checkpointer  // (3)!\n});\n```\n\n1. The [`interrupt` function](/langgraphjs/reference/functions/langgraph.interrupt-1.html) pauses the agent graph at a specific node. In this case, we call `interrupt()` at the beginning of the tool function, which pauses the graph at the node that executes the tool. The information inside `interrupt()` (e.g., tool calls) can be presented to a human, and the graph can be resumed with the user input (tool call approval, edit or feedback).\n2. The `InMemorySaver` is used to store the agent state at every step in the tool calling loop. This enables [short-term memory](./memory.md#short-term-memory) and [human-in-the-loop](./human-in-the-loop.md) capabilities. In this example, we use `InMemorySaver` to store the agent state in memory. In a production application, the agent state will be stored in a database.\n3. Initialize the agent with the `checkpointer`.\n\nRun the agent with the `stream()` method, passing the `config` object to specify the thread ID. This allows the agent to resume the same conversation on future invocations.\n\n```ts\nconst config = {\n   configurable: {\n      // highlight-next-line\n      \"thread_id\": \"1\"\n   }\n}\n\nfor await (const chunk of await agent.stream(\n  { messages: \"book a stay at McKittrick hotel\" },\n  // highlight-next-line\n  config\n)) {\n  console.log(chunk);\n  console.log(\"\\n\");\n};\n```\n\n> You should see that the agent runs until it reaches the `interrupt()` call, at which point it pauses and waits for human input.\n\nResume the agent with a `Command({ resume: ... })` to continue based on human input.\n\n```ts\nimport { Command } from \"@langchain/langgraph\";\n\nfor await (const chunk of await agent.stream(\n  new Command({ resume: { type: \"accept\" } }),  // (1)!\n  // new Command({ resume: { type: \"edit\", args: { \"hotel_name\": \"McKittrick Hotel\" } } }),\n  // highlight-next-line\n  config\n)) {\n  console.log(chunk);\n  console.log(\"\\n\");\n};\n```\n\n1. The [`interrupt` function](/langgraphjs/reference/functions/langgraph.interrupt-1.html) is used in conjunction with the [`Command`](/langgraphjs/reference/classes/langgraph.Command.html) object to resume the graph with a value provided by the human.\n\n## Additional resources\n\n* [Human-in-the-loop in LangGraph](../concepts/human_in_the_loop.md)","isInternal":false,"tokens":1192,"sizeBytes":4930},{"name":"mcp.md","path":"docs/docs/agents/mcp.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/mcp.md","title":"Subagent: mcp","category":"subagent-persona","format":"markdown","content":"# MCP Integration\n\n[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open protocol that standardizes how applications provide tools and context to language models. LangGraph agents can use tools defined on MCP servers through the `@langchain/mcp-adapters` library.\n\n![MCP](./assets/mcp.png)\n\nInstall the `@langchain/mcp-adapters` library to use MCP tools in LangGraph:\n\n```bash\nnpm install @langchain/mcp-adapters\n```\n\n## Use MCP tools\n\nThe `@langchain/mcp-adapters` package enables agents to use tools defined across one or more MCP servers.\n\n```ts\n// highlight-next-line\nimport { MultiServerMCPClient } from \"@langchain/mcp-adapters\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n// highlight-next-line\nconst client = new MultiServerMCPClient({\n  mcpServers: {\n    \"math\": {\n      command: \"python\",\n      // Replace with absolute path to your math_server.py file\n      args: [\"/path/to/math_server.py\"],\n      transport: \"stdio\",\n    },\n    \"weather\": {\n      // Ensure your start your weather server on port 8000\n      url: \"http://localhost:8000/sse\",\n      transport: \"sse\",\n    }\n  }\n})\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  // highlight-next-line\n  tools: await client.getTools()\n});\n \nconst mathResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what's (3 + 5) x 12?\" } ] }\n);\nconst weatherResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what is the weather in nyc?\" } ] }\n);\nawait client.close();\n```\n\n## Custom MCP servers\n\nTo create your own MCP servers, you can use the `mcp` library in Python (or `@modelcontextprotocol/sdk` in TypeScript). These libraries provide a simple way to define tools and run them as servers.\n\nInstall the MCP library:\n\n```bash\npip install mcp\n```\nUse the following reference implementations to test your agent with MCP tool servers.\n\n```python title=\"Example Math Server (stdio transport)\"\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"Math\")\n\n@mcp.tool()\ndef add(a: int, b: int) -> int:\n    \"\"\"Add two numbers\"\"\"\n    return a + b\n\n@mcp.tool()\ndef multiply(a: int, b: int) -> int:\n    \"\"\"Multiply two numbers\"\"\"\n    return a * b\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"stdio\")\n```\n\n```python title=\"Example Weather Server (SSE transport)\"\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"Weather\")\n\n@mcp.tool()\nasync def get_weather(location: str) -> str:\n    \"\"\"Get weather for location.\"\"\"\n    return \"It's always sunny in New York\"\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"sse\")\n```\n\n## Additional resources\n\n- [MCP documentation](https://modelcontextprotocol.io/introduction)\n- [MCP Transport documentation](https://modelcontextprotocol.io/docs/concepts/transports)","isInternal":false,"tokens":738,"sizeBytes":2889},{"name":"memory.md","path":"docs/docs/agents/memory.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/memory.md","title":"Subagent: memory","category":"subagent-persona","format":"markdown","content":"# Memory\n\nLangGraph supports two types of memory essential for building conversational agents:\n\n- **[Short-term memory](#short-term-memory)**: Tracks the ongoing conversation by maintaining message history within a session.\n- **[Long-term memory](#long-term-memory)**: Stores user-specific or application-level data across sessions.\n\nThis guide demonstrates how to use both memory types with agents in LangGraph. For a deeper\nunderstanding of memory concepts, refer to the [LangGraph memory documentation](../concepts/memory.md).\n\n<figure markdown=\"1\">\n![image](./assets/memory.png){: style=\"max-height:400px\"}\n<figcaption>Both <strong>short-term</strong> and <strong>long-term</strong> memory require persistent storage to maintain continuity across LLM interactions. In production environments, this data is typically stored in a database.</figcaption>\n</figure>\n\n!!! note \"Terminology\"\n\n    In LangGraph:\n\n    - *Short-term memory* is also referred to as **thread-level memory**.\n    - *Long-term memory* is also called **cross-thread memory**.\n\n    A [thread](../concepts/persistence.md#threads) represents a sequence of related runs\n    grouped by the same `thread_id`.\n\n## Short-term memory\n\nShort-term memory enables agents to track multi-turn conversations. To use it, you must:\n\n1. Provide a `checkpointer` when creating the agent. The `checkpointer` enables [persistence](../concepts/persistence.md) of the agent's state.\n2. Supply a `thread_id` in the config when running the agent. The `thread_id` is a unique identifier for the conversation session.\n\n```ts\n// highlight-next-line\nimport { MemorySaver } from \"@langchain/langgraph-checkpoint\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\n// highlight-next-line\nconst checkpointer = new MemorySaver();  // (1)!\n\nconst getWeather = tool(\n  async (input: { city: string }) => {\n    return `It's always sunny in ${input.city}!`;\n  },\n  {\n    name: \"getWeather\",\n    schema: z.object({\n      city: z.string().describe(\"The city to get the weather for\"),\n    }),\n    description: \"Get weather for a given city.\",\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather],\n  // highlight-next-line\n  checkpointer  // (2)!\n});\n\n// Run the agent\n// highlight-next-line\nconst config = { configurable: { thread_id: \"1\" } };  // (3)!\nconst sfResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what is the weather in sf\" } ] },\n  config  // (4)!\n);\nconst nyResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what about new york?\" } ] },\n  config\n);\n```\n\n1. The `MemorySaver` is a checkpointer that stores the agent's state in memory. In a production setting, you would typically use a database or other persistent storage. Please review the [checkpointer documentation](https://langchain-ai.github.io/langgraphjs/reference/index.html) for more options. If you're deploying with **LangGraph Platform**, the platform will provide a production-ready checkpointer for you.\n2. The `checkpointer` is passed to the agent. This enables the agent to persist its state across invocations. Please note that \n3. A unique `thread_id` is provided in the config. This ID is used to identify the conversation session. The value is controlled by the user and can be any string.\n4. The agent will continue the conversation using the same `thread_id`. This will allow the agent to infer that the user is asking specifically about the **weather** in New York. \n\nWhen the agent is invoked the second time with the same `thread_id`, the original message history from the first conversation is automatically included, allowing the agent to infer that the user is asking specifically about the **weather** in New York.\n\n!!! Note \"LangGraph Platform providers a production-ready checkpointer\"\n\n    If you're using [LangGraph Platform](./deployment.md), during deployment your checkpointer will be automatically configured to use a production-ready database.\n\n## Long-term memory\n\nUse long-term memory to store user-specific or application-specific data across conversations. This is useful for applications like chatbots, where you want to remember user preferences or other information.\n\nTo use long-term memory, you need to:\n\n1. [Configure a store](../how-tos/cross-thread-persistence.ipynb) to persist data across invocations.\n2. Use the `config.store` to access the store from within tools or prompts.\n\n### Reading\n\n```ts title=\"A tool the agent can use to look up user information\"\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n// highlight-next-line\nimport { InMemoryStore } from \"@langchain/langgraph-checkpoint\";\n// highlight-next-line\nimport { getStore } from \"@langchain/langgraph\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst store = new InMemoryStore(); // (1)!\n\nawait store.put(  // (2)!\n  [\"users\"],  // (3)!\n  \"user_123\",  // (4)!\n  {\n    name: \"John Smith\",\n    language: \"English\",\n  } // (5)!\n);\n\n// Look up user info tool\nconst getUserInfo = tool(\n  async (input: Record<string, any>, config: LangGraphRunnableConfig): Promise<string> => {\n    // Same as that provided to `createReactAgent`\n    const store = config.store; // (6)!\n    if (!store) {\n      throw new Error(\"store is required when compiling the graph\");\n    }\n\n    const userId = config.configurable?.userId;\n    if (!userId) {\n      throw new Error(\"userId is required in the config\");\n    }\n\n    const userInfo = await store.get([\"users\"], userId); // (7)!\n    return userInfo ? JSON.stringify(userInfo.value) : \"Unknown user\";\n  },\n  {\n    name: \"get_user_info\",\n    description: \"Look up user info.\",\n    schema: z.object({}),\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getUserInfo],\n  store, // (8)!\n});\n\n// Run the agent\nconst response = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"look up user information\" } ] },\n  { configurable: { userId: \"user_123\" } }\n);\n```\n\n1. The `InMemoryStore` is a store that stores data in memory. In a production setting, you would typically use a database or other persistent storage. Please review the [documentation](https://langchain-ai.github.io/langgraphjs/reference/index.html) for more options. If you're deploying with **LangGraph Platform**, the platform will provide a production-ready store for you.\n2. For this example, we write some sample data to the store using the `put` method. Please see the [BaseStore.put](https://langchain-ai.github.io/langgraphjs/reference/classes/checkpoint.BaseStore.html#put) API reference for more details.\n3. The first argument is the namespace. This is used to group related data together. In this case, we are using the `users` namespace to group user data.\n4. A key within the namespace. This example uses a user ID for the key.\n5. The data that we want to store for the given user.\n6. You can access the store via `config.store` from anywhere in your nodes, tools and prompts. It contains the store that was passed to the agent when it was created.\n7. The `get` method is used to retrieve data from the store. The first argument is the namespace, and the second argument is the key. This will return a `StoreValue` object, which contains the value and metadata about the value.\n8. The `store` is passed to the agent. This enables the agent to access the store when running tools.\n\n### Writing\n\n```ts title=\"Example of a tool that updates user information\"\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { InMemoryStore } from \"@langchain/langgraph-checkpoint\";\nimport { getStore } from \"@langchain/langgraph\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst store = new InMemoryStore(); // (1)!\n\ninterface UserInfo { // (2)!\n  name: string;\n}\n\n// Save user info tool\nconst saveUserInfo = tool(  // (3)!\n  async (input: UserInfo, config: LangGraphRunnableConfig): Promise<string> => {\n    // Same as that provided to `createReactAgent`\n    // highlight-next-line\n    const store = config.store; // (4)!\n    if (!store) {\n      throw new Error(\"store is required when compiling the graph\");\n    }\n\n    const userId = config.configurable?.userId;\n    if (!userId) {\n      throw new Error(\"userId is required in the config\");\n    }\n\n    await store.put([\"users\"], userId, input); // (5)!\n    return \"Successfully saved user info.\";\n  },\n  {\n    name: \"save_user_info\",\n    description: \"Save user info.\",\n    schema: z.object({\n      name: z.string(),\n    }),\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [saveUserInfo],\n  // highlight-next-line\n  store,\n});\n\n// Run the agent\nawait agent.invoke(\n  { messages: [ { role: \"user\", content: \"My name is John Smith\" } ] },\n  { configurable: { userId: \"user_123\" } } // (6)!\n);\n\n// You can access the store directly to get the value\nconst userInfo = await store.get([\"users\"], \"user_123\")\nuserInfo.value\n```\n\n1. The `InMemoryStore` is a store that stores data in memory. In a production setting, you would typically use a database or other persistent storage. Please review the [store documentation](../reference/stores.md) for more options. If you're deploying with **LangGraph Platform**, the platform will provide a production-ready store for you.\n2. The `UserInfo` class is an interface that defines the structure of the user information. We will specify the same schema below using a zod object, so that the LLM formats the response according to the schema.\n3. The `saveUserInfo` is a tool that allows an agent to update user information. This could be useful for a chat application where the user wants to update their profile information.\n4. You can access the store via `config.store` from anywhere in your nodes, tools and prompts. It contains the store that was passed to the agent when it was created.\n5. The `put` method is used to store data in the store. The first argument is the namespace, and the second argument is the key. This will store the user information in the store.\n6. The `userId` is passed in the config. This is used to identify the user whose information is being updated.\n\n## Additional resources\n\n* [Memory in LangGraph](../concepts/memory.md)","isInternal":false,"tokens":2541,"sizeBytes":10751},{"name":"models.md","path":"docs/docs/agents/models.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/models.md","title":"Subagent: models","category":"subagent-persona","format":"markdown","content":"# Models\n\nThis page describes how to configure the chat model used by an agent.\n\n## Tool calling support\n\nTo enable tool-calling agents, the underlying LLM must support [tool calling](https://js.langchain.com/docs/concepts/tool_calling/).\n\nCompatible models can be found in the [LangChain integrations directory](https://js.langchain.com/docs/integrations/chat/).\n\n## Using `initChatModel`\n\nThe [`initChatModel`](https://js.langchain.com/docs/how_to/chat_models_universal_init/) utility simplifies model initialization with configurable parameters:\n\n```ts\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\nconst llm = await initChatModel(\n  \"anthropic:claude-3-7-sonnet-latest\",\n  {\n    temperature: 0,\n    maxTokens: 2048\n  }\n);\n```\n\nRefer to the [API reference](https://api.js.langchain.com/functions/langchain.chat_models_universal.initChatModel.html) for advanced options.\n\n## Using provider-specific LLMs \n\nIf a model provider is not available via `initChatModel`, you can instantiate the provider's model class directly. The model must implement the [`BaseChatModel`](https://api.js.langchain.com/classes/_langchain_core.language_models_chat_models.BaseChatModel.html) interface and support tool calling:\n\n```ts\nimport { ChatAnthropic } from \"@langchain/anthropic\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n// highlight-next-line\nconst llm = new ChatAnthropic({\n  modelName: \"claude-3-7-sonnet-latest\",\n  temperature: 0,\n  maxTokens: 2048\n});\n\nconst agent = createReactAgent({\n  // highlight-next-line\n  llm,\n  // other parameters\n});\n```\n\n!!! note \"Illustrative example\" \n\n    The example above uses `ChatAnthropic`, which is already supported by `initChatModel`. This pattern is shown to illustrate how to manually instantiate a model not available through `initChatModel`.\n\n## Additional resources\n\n- [Model integration directory](https://js.langchain.com/docs/integrations/chat/)\n- [Universal initialization with `initChatModel`](https://js.langchain.com/docs/how_to/chat_models_universal_init/)","isInternal":false,"tokens":477,"sizeBytes":2047},{"name":"multi-agent.md","path":"docs/docs/agents/multi-agent.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/multi-agent.md","title":"Subagent: multi-agent","category":"subagent-persona","format":"markdown","content":"# Multi-agent\n\nA single agent might struggle if it needs to specialize in multiple domains or manage many tools. To tackle this, you can break your agent into smaller, independent agents and composing them into a [multi-agent system](../concepts/multi_agent.md).\n\nIn multi-agent systems, agents need to communicate between each other. They do so via [handoffs](#handoffs) — a primitive that describes which agent to hand control to and the payload to send to that agent.\n\nTwo of the most popular multi-agent architectures are:\n\n- [supervisor](#supervisor) — individual agents are coordinated by a central supervisor agent. The supervisor controls all communication flow and task delegation, making decisions about which agent to invoke based on the current context and task requirements.\n- [swarm](#swarm) — agents dynamically hand off control to one another based on their specializations. The system remembers which agent was last active, ensuring that on subsequent interactions, the conversation resumes with that agent.\n\n## Supervisor\n\n![Supervisor](./assets/supervisor.png)\n\nUse [`langgraph-supervisor`](https://github.com/langchain-ai/langgraphjs/tree/main/libs/langgraph-supervisor) library to create a supervisor multi-agent system:\n\n```bash\nnpm install @langchain/langgraph-supervisor\n```\n\n```ts\nimport { ChatOpenAI } from \"@langchain/openai\";\n// highlight-next-line\nimport { createSupervisor } from \"@langchain/langgraph-supervisor\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst bookHotel = tool(\n  async (input: { hotel_name: string }) => {\n    return `Successfully booked a stay at ${input.hotel_name}.`;\n  },\n  {\n    name: \"book_hotel\",\n    description: \"Book a hotel\",\n    schema: z.object({\n      hotel_name: z.string().describe(\"The name of the hotel to book\"),\n    }),\n  }\n);\n\nconst bookFlight = tool(\n  async (input: { from_airport: string; to_airport: string }) => {\n    return `Successfully booked a flight from ${input.from_airport} to ${input.to_airport}.`;\n  },\n  {\n    name: \"book_flight\",\n    description: \"Book a flight\",\n    schema: z.object({\n      from_airport: z.string().describe(\"The departure airport code\"),\n      to_airport: z.string().describe(\"The arrival airport code\"),\n    }),\n  }\n);\n\nconst llm = new ChatOpenAI({ modelName: \"gpt-4o\" });\n\n// Create specialized agents\nconst flightAssistant = createReactAgent({\n  llm,\n  tools: [bookFlight],\n  prompt: \"You are a flight booking assistant\",\n  // highlight-next-line\n  name: \"flight_assistant\",\n});\n\nconst hotelAssistant = createReactAgent({\n  llm,\n  tools: [bookHotel],\n  prompt: \"You are a hotel booking assistant\",\n  // highlight-next-line\n  name: \"hotel_assistant\",\n});\n\n// highlight-next-line\nconst supervisor = createSupervisor({\n  agents: [flightAssistant, hotelAssistant],\n  llm,\n  prompt: \"You manage a hotel booking assistant and a flight booking assistant. Assign work to them, one at a time.\",\n}).compile();\n\nconst stream = await supervisor.stream({\n  messages: [{\n    role: \"user\",\n    content: \"first book a flight from BOS to JFK and then book a stay at McKittrick Hotel\"\n  }]\n});\n\nfor await (const chunk of stream) {\n  console.log(chunk);\n  console.log(\"\\n\");\n}\n```\n\n## Swarm\n\n![Swarm](./assets/swarm.png)\n\nUse [`langgraph-swarm`](https://github.com/langchain-ai/langgraphjs/tree/main/libs/langgraph-swarm) library to create a swarm multi-agent system:\n\n```bash\nnpm install @langchain/langgraph-swarm\n```\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { ChatAnthropic } from \"@langchain/anthropic\";\n// highlight-next-line\nimport { createSwarm, createHandoffTool } from \"@langchain/langgraph-swarm\";\n\nconst transferToHotelAssistant = createHandoffTool({\n  agentName: \"hotel_assistant\",\n  description: \"Transfer user to the hotel-booking assistant.\",\n});\n\nconst transferToFlightAssistant = createHandoffTool({\n  agentName: \"flight_assistant\",\n  description: \"Transfer user to the flight-booking assistant.\",\n});\n\n\nconst llm = new ChatAnthropic({ modelName: \"claude-3-5-sonnet-latest\" });\n\nconst flightAssistant = createReactAgent({\n  llm,\n  tools: [bookFlight, transferToHotelAssistant],\n  prompt: \"You are a flight booking assistant\",\n  name: \"flight_assistant\",\n});\n\nconst hotelAssistant = createReactAgent({\n  llm,\n  tools: [bookHotel, transferToFlightAssistant],\n  prompt: \"You are a hotel booking assistant\",\n  name: \"hotel_assistant\",\n});\n\n// highlight-next-line\nconst swarm = createSwarm({\n  agents: [flightAssistant, hotelAssistant],\n  defaultActiveAgent: \"flight_assistant\",\n}).compile();\n\nconst stream = await swarm.stream({\n  messages: [{\n    role: \"user\",\n    content: \"first book a flight from BOS to JFK and then book a stay at McKittrick Hotel\"\n  }]\n});\n\nfor await (const chunk of stream) {\n  console.log(chunk);\n  console.log(\"\\n\");\n}\n```\n\n## Handoffs\n\nA common pattern in multi-agent interactions is **handoffs**, where one agent *hands off* control to another. Handoffs allow you to specify:\n\n- **destination**: target agent to navigate to\n- **payload**: information to pass to that agent\n\nThis is used both by `langgraph-supervisor` (supervisor hands off to individual agents) and `langgraph-swarm` (an individual agent can hand off to other agents).\n\nTo implement handoffs with `createReactAgent`, you need to:\n\n1. Create a special tool that can transfer control to a different agent\n\n    ```ts\n    const transferToBob = tool(\n      async (_) => {\n        return new Command({\n          // name of the agent (node) to go to\n          // highlight-next-line\n          goto: \"bob\",\n          // data to send to the agent\n          // highlight-next-line\n          update: { messages: ... },\n          // indicate to LangGraph that we need to navigate to\n          // agent node in a parent graph\n          // highlight-next-line\n          graph: Command.PARENT,\n        });\n      },\n      {\n        name: ...,\n        schema: ...,\n        description: ...\n      }\n    );\n    ```\n\n1. Create individual agents that have access to handoff tools:\n\n    ```ts\n    const flightAssistant = createReactAgent(\n      ..., tools: [bookFlight, transferToHotelAssistant]\n    )\n    const hotelAssistant = createReactAgent(\n      ..., tools=[bookHotel, transferToFlightAssistant]\n    )\n    ```\n\n1. Define a parent graph that contains individual agents as nodes:\n\n    ```ts\n    import { StateGraph, MessagesAnnotation } from \"@langchain/langgraph\";\n\n    const multiAgentGraph = new StateGraph(MessagesAnnotation)\n      .addNode(\"flight_assistant\", flightAssistant)\n      .addNode(\"hotel_assistant\", hotelAssistant)\n      ...\n    ```\n\nPutting this together, here is how you can implement a simple multi-agent system with two agents — a flight booking assistant and a hotel booking assistant:\n\n```ts\nimport { ChatAnthropic } from \"@langchain/anthropic\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { StateGraph, MessagesAnnotation, Command, START, END } from \"@langchain/langgraph\";\nimport { tool, type ToolRuntime } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ToolMessage } from \"@langchain/core/messages\";\n\ninterface CreateHandoffToolParams {\n  agentName: string;\n  description?: string;\n}\n\nconst createHandoffTool = ({\n  agentName,\n  description,\n}: CreateHandoffToolParams) => {\n  const toolName = `transfer_to_${agentName}`;\n  const toolDescription = description || `Ask agent '${agentName}' for help`;\n\n  const handoffTool = tool(\n    async (_, runtime: ToolRuntime<typeof MessagesAnnotation.State>) => {\n      const toolMessage = new ToolMessage({\n        content: `Successfully transferred to ${agentName}`,\n        name: toolName,\n        tool_call_id: runtime.toolCallId,\n      });\n\n      // inject the current agent state\n      // highlight-next-line\n      const state = runtime.state;  // (1)!\n      return new Command({  // (2)!\n        // highlight-next-line\n        goto: agentName,  // (3)!\n        // highlight-next-line\n        update: { messages: state.messages.concat(toolMessage) },  // (4)!\n        // highlight-next-line\n        graph: Command.PARENT,  // (5)!\n      });\n    },\n    {\n      name: toolName,\n      schema: z.object({}),\n      description: toolDescription,\n    }\n  );\n\n  return handoffTool;\n};\n\nconst bookHotel = tool(\n  async (input: { hotel_name: string }) => {\n    return `Successfully booked a stay at ${input.hotel_name}.`;\n  },\n  {\n    name: \"book_hotel\",\n    description: \"Book a hotel\",\n    schema: z.object({\n      hotel_name: z.string().describe(\"The name of the hotel to book\"),\n    }),\n  }\n);\n\nconst bookFlight = tool(\n  async (input: { from_airport: string; to_airport: string }) => {\n    return `Successfully booked a flight from ${input.from_airport} to ${input.to_airport}.`;\n  },\n  {\n    name: \"book_flight\",\n    description: \"Book a flight\",\n    schema: z.object({\n      from_airport: z.string().describe(\"The departure airport code\"),\n      to_airport: z.string().describe(\"The arrival airport code\"),\n    }),\n  }\n);\n\nconst transferToHotelAssistant = createHandoffTool({\n  agentName: \"hotel_assistant\",\n  description: \"Transfer user to the hotel-booking assistant.\",\n});\n\nconst transferToFlightAssistant = createHandoffTool({\n  agentName: \"flight_assistant\",\n  description: \"Transfer user to the flight-booking assistant.\",\n});\n\nconst llm = new ChatAnthropic({ modelName: \"claude-3-5-sonnet-latest\" });\n\nconst flightAssistant = createReactAgent({\n  llm,\n  // highlight-next-line\n  tools: [bookFlight, transferToHotelAssistant],\n  prompt: \"You are a flight booking assistant\",\n  // highlight-next-line\n  name: \"flight_assistant\",\n});\n\nconst hotelAssistant = createReactAgent({\n  llm,\n  // highlight-next-line\n  tools: [bookHotel, transferToFlightAssistant],\n  prompt: \"You are a hotel booking assistant\",\n  // highlight-next-line\n  name: \"hotel_assistant\",\n});\n\nconst multiAgentGraph = new StateGraph(MessagesAnnotation)\n  .addNode(\"flight_assistant\", flightAssistant, { ends: [\"hotel_assistant\", END] })\n  .addNode(\"hotel_assistant\", hotelAssistant, { ends: [\"flight_assistant\", END] })\n  .addEdge(START, \"flight_assistant\")\n  .compile();\n\nconst stream = await multiAgentGraph.stream({\n  messages: [{\n    role: \"user\",\n    content: \"book a flight from BOS to JFK and a stay at McKittrick Hotel\"\n  }]\n});\n\nfor await (const chunk of stream) {\n  console.log(chunk);\n  console.log(\"\\n\");\n}\n```\n\n1. Access agent's state\n2. The `Command` primitive allows specifying a state update and a node transition as a single operation, making it useful for implementing handoffs.\n3. Name of the agent or node to hand off to.\n4. Take the agent's messages and **add** them to the parent's **state** as part of the handoff. The next agent will see the parent state.\n5. Indicate to LangGraph that we need to navigate to agent node in a **parent** multi-agent graph.\n\n!!! Note\n    This handoff implementation assumes that:\n\n    - each agent receives overall message history (across all agents) in the multi-agent system as its input\n    - each agent outputs its internal messages history to the overall message history of the multi-agent system\n\n    Check out LangGraph [supervisor](https://github.com/langchain-ai/langgraph-supervisor-py#customizing-handoff-tools) and [swarm](https://github.com/langchain-ai/langgraph-swarm-py#customizing-handoff-tools) documentation to learn how to customize handoffs.","isInternal":false,"tokens":2704,"sizeBytes":11429},{"name":"overview.md","path":"docs/docs/agents/overview.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/overview.md","title":"Subagent: overview","category":"subagent-persona","format":"markdown","content":"---\ntitle: Overview\n---\n\n# Agent development with LangGraph\n\n**LangGraph** provides both low-level primitives and high-level prebuilt components for building agent-based applications. This section focuses on the **prebuilt**, **reusable** components designed to help you construct agentic systems quickly and reliably—without the need to implement orchestration, memory, or human feedback handling from scratch.\n\n## What is an agent?\n\nAn _agent_ consists of three components: a **large language model (LLM)**, a set of **tools** it can use, and a **prompt** that provides instructions.\n\nThe LLM operates in a loop. In each iteration, it selects a tool to invoke, provides input, receives the result (an observation), and uses that observation to inform the next action. The loop continues until a stopping condition is met — typically when the agent has gathered enough information to respond to the user.\n\n<figure markdown=\"1\">\n![image](./assets/agent.png){: style=\"max-height:400px\"}\n<figcaption>Agent loop: the LLM selects tools and uses their outputs to fulfill a user request.</figcaption>\n</figure>\n\n## Key features\n\nLangGraph includes several capabilities essential for building robust, production-ready agentic systems:\n\n- [**Memory integration**](./memory.md): Native support for _short-term_ (session-based) and _long-term_ (persistent across sessions) memory, enabling stateful behaviors in chatbots and assistants.\n- [**Human-in-the-loop control**](./human-in-the-loop.md): Execution can pause _indefinitely_ to await human feedback—unlike websocket-based solutions limited to real-time interaction. This enables asynchronous approval, correction, or intervention at any point in the workflow.\n- [**Streaming support**](./streaming.md): Real-time streaming of agent state, model tokens, tool outputs, or combined streams.\n- [**Deployment tooling**](./deployment.md): Includes infrastructure-free deployment tools. [**LangGraph Platform**](https://langchain-ai.github.io/langgraph/concepts/langgraph_platform/) supports testing, debugging, and deployment.\n  - **[Studio](https://langchain-ai.github.io/langgraph/concepts/langgraph_studio/)**: A visual IDE for inspecting and debugging workflows.\n  - Supports multiple [**deployment options**](https://langchain-ai.github.io/langgraph/tutorials/deployment/) for production.\n\n## High-level building blocks\n\nLangGraph comes with a set of prebuilt components that implement common agent behaviors and workflows. These abstractions are built on top of the LangGraph framework, offering a faster path to production while remaining flexible for advanced customization.\n\nUsing LangGraph for agent development allows you to focus on your application's logic and behavior, instead of building and maintaining the supporting infrastructure for state, memory, and human feedback.\n\n## Package ecosystem\n\nThe high-level components are organized into several packages, each with a specific focus.\n\n| Package                  | Description                                                                 | Installation                                       |\n| ------------------------ | --------------------------------------------------------------------------- | -------------------------------------------------- |\n| `langgraph`              | Prebuilt components to [**create agents**](./agents.md)                     | `npm install @langchain/langgraph @langchain/core` |\n| `langgraph-supervisor`   | Tools for building [**supervisor**](./multi-agent.md#supervisor) agents     | `npm install @langchain/langgraph-supervisor`      |\n| `langgraph-swarm`        | Tools for building a [**swarm**](./multi-agent.md#swarm) multi-agent system | `npm install @langchain/langgraph-swarm`           |\n| `langchain-mcp-adapters` | Interfaces to [**MCP servers**](./mcp.md) for tool and resource integration | `npm install @langchain/mcp-adapters`              |\n| `agentevals`             | Utilities to [**evaluate agent performance**](./evals.md)                   | `npm install agentevals`                           |\n\n## Visualize an agent graph\n\nUse the following tool to visualize the graph generated by [`createReactAgent`](/langgraphjs/reference/functions/langgraph_prebuilt.createReactAgent.html) and to view an outline of the corresponding code. It allows you to explore the infrastructure of the agent as defined by the presence of:\n\n- [`tools`](./tools.md): A list of tools (functions, APIs, or other callable objects) that the agent can use to perform tasks.\n- `preModelHook`: A function that is called before the model is invoked. It can be used to condense messages or perform other preprocessing tasks.\n- `postModelHook`: A function that is called after the model is invoked. It can be used to implement guardrails, human-in-the-loop flows, or other postprocessing tasks.\n- [`responseFormat`](./agents.md#structured-output): A data structure used to constrain the type of the final output (via Zod schemas).\n\n<div class=\"agent-layout\">\n  <div class=\"agent-graph-features-container\">\n    <div class=\"agent-graph-features\">\n      <h3 class=\"agent-section-title\">Features</h3>\n      <label><input type=\"checkbox\" id=\"tools\" checked> <code>tools</code></label>\n      <label><input type=\"checkbox\" id=\"preModelHook\"> <code>preModelHook</code></label>\n      <label><input type=\"checkbox\" id=\"postModelHook\"> <code>postModelHook</code></label>\n      <label><input type=\"checkbox\" id=\"responseFormat\"> <code>responseFormat</code></label>\n    </div>\n  </div>\n\n  <div class=\"agent-graph-container\">\n    <h3 class=\"agent-section-title\">Graph</h3>\n    <img id=\"agent-graph-img\" src=\"../assets/react_agent_graphs/0001.svg\" alt=\"graph image\" style=\"max-width: 100%;\"/>\n  </div>\n</div>\n\nThe following code snippet shows how to create the above agent (and underlying graph) with [`createReactAgent`](/langgraphjs/reference/functions/langgraph_prebuilt.createReactAgent.html):\n\n<div class=\"language-typescript\">\n  <pre><code id=\"agent-code\" class=\"language-typescript\"></code></pre>\n</div>\n\n<script>\nfunction getCheckedValue(id) {\n  return document.getElementById(id).checked ? \"1\" : \"0\";\n}\n\nfunction getKey() {\n  return [\n    getCheckedValue(\"responseFormat\"),\n    getCheckedValue(\"postModelHook\"),\n    getCheckedValue(\"preModelHook\"),\n    getCheckedValue(\"tools\")\n  ].join(\"\");\n}\n\nfunction dedent(strings, ...values) {\n  const str = String.raw({ raw: strings }, ...values)\n  const [space] = str.split(\"\\n\").filter(Boolean).at(0).match(/^(\\s*)/)\n  const spaceLen = space.length\n  return str.split(\"\\n\").map(line => line.slice(spaceLen)).join(\"\\n\").trim()\n}\n\nObject.assign(dedent, {\n  offset: (size) => (strings, ...values) => {\n    return dedent(strings, ...values).split(\"\\n\").map(line => \" \".repeat(size) + line).join(\"\\n\")\n  }\n})\n\n\n\n\nfunction generateCodeSnippet({ tools, pre, post, response }) {\n  const lines = []\n\n  lines.push(dedent`\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { ChatOpenAI } from \"@langchain/openai\";\n  `)\n\n  if (tools) lines.push(`import { tool } from \"@langchain/core/tools\";`);  \n  if (response || tools) lines.push(`import { z } from \"zod\";`);\n\n  lines.push(\"\", dedent`\n    const agent = createReactAgent({\n      llm: new ChatOpenAI({ model: \"o4-mini\" }),\n  `)\n\n  if (tools) {\n    lines.push(dedent.offset(2)`\n      tools: [\n        tool(() => \"Sample tool output\", {\n          name: \"sampleTool\",\n          schema: z.object({}),\n        }),\n      ],\n    `)\n  }\n\n  if (pre) {\n    lines.push(dedent.offset(2)`\n      preModelHook: (state) => ({ llmInputMessages: state.messages }),\n    `)\n  }\n\n  if (post) {\n    lines.push(dedent.offset(2)`\n      postModelHook: (state) => state,\n    `)\n  }\n\n  if (response) {\n    lines.push(dedent.offset(2)`\n      responseFormat: z.object({ result: z.string() }),\n    `)\n  }\n\n  lines.push(`});`);\n\n  return lines.join(\"\\n\");\n}\n\nfunction render() {\n  const key = getKey();\n  document.getElementById(\"agent-graph-img\").src = `../assets/react_agent_graphs/${key}.svg`;\n\n  const state = {\n    tools: document.getElementById(\"tools\").checked,\n    pre: document.getElementById(\"preModelHook\").checked,\n    post: document.getElementById(\"postModelHook\").checked,\n    response: document.getElementById(\"responseFormat\").checked\n  };\n\n  document.getElementById(\"agent-code\").textContent = generateCodeSnippet(state);\n}\n\nfunction initializeWidget() {\n  render(); // no need for `await` here\n  document.querySelectorAll(\".agent-graph-features input\").forEach((input) => {\n    input.addEventListener(\"change\", render);\n  });\n}\n\n// Init for both full reload and SPA nav (used by MkDocs Material)\nwindow.addEventListener(\"DOMContentLoaded\", initializeWidget);\ndocument$.subscribe(initializeWidget);\n</script>\n","frontmatter":{"title":"Overview"},"isInternal":false,"tokens":1983,"sizeBytes":8743},{"name":"prebuilt.md","path":"docs/docs/agents/prebuilt.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/prebuilt.md","title":"Subagent: prebuilt","category":"subagent-persona","format":"markdown","content":"# Community Agents\n\nTo share your project, simply open a Pull Request adding an entry for your package in our [packages.yml](https://github.com/langchain-ai/langgraph/blob/main/docs/_scripts/third_party_page/packages.yml) file.\n\n[//]: # (This file is stub. Do not edit this file directly!)\n[//]: # (1. Update the `packages.yml` file in the `docs/_scripts/third_party_page` directory.)\n[//]: # (2. From the /docs directory, run `make build-prebuilt` to generate an updated version of this file for testing locally.)\n","isInternal":false,"tokens":126,"sizeBytes":515},{"name":"run_agents.md","path":"docs/docs/agents/run_agents.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/run_agents.md","title":"Subagent: run_agents","category":"subagent-persona","format":"markdown","content":"# Subagent: run_agents\n\nPath: `docs/docs/agents/run_agents.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/run_agents.md)","tokens":300,"sizeBytes":188},{"name":"streaming.md","path":"docs/docs/agents/streaming.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/streaming.md","title":"Subagent: streaming","category":"subagent-persona","format":"markdown","content":"# Subagent: streaming\n\nPath: `docs/docs/agents/streaming.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/streaming.md)","tokens":300,"sizeBytes":185},{"name":"tools.md","path":"docs/docs/agents/tools.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/tools.md","title":"Subagent: tools","category":"subagent-persona","format":"markdown","content":"# Subagent: tools\n\nPath: `docs/docs/agents/tools.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/tools.md)","tokens":300,"sizeBytes":173},{"name":"ui.md","path":"docs/docs/agents/ui.md","rawUrl":"https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/ui.md","title":"Subagent: ui","category":"subagent-persona","format":"markdown","content":"# Subagent: ui\n\nPath: `docs/docs/agents/ui.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/ui.md)","tokens":300,"sizeBytes":164}],"systemPromptSnippet":"<yakaai_skills repo=\"langchain-ai/langgraphjs\">\n<!-- File: docs/docs/agents/agents.md (Tokens: ~2061 | Category: subagent-persona) -->\n# LangGraph quickstart\n\nThis guide shows you how to set up and use LangGraph's **prebuilt**, **reusable** components, which are designed to help you construct agentic systems quickly and reliably.\n\n## Prerequisites\n\nBefore you start this tutorial, ensure you have the following:\n\n- An [Anthropic](https://console.anthropic.com/settings/keys) API key\n\n## 1. Install dependencies\n\nIf you haven't already, install LangGraph and LangChain:\n\n```\nnpm install langchain @langchain/langgraph @langchain/anthropic\n```\n\n## 2. Create an agent\n\nUse [`createReactAgent`](/langgraphjs/reference/functions/langgraph_prebuilt.createReactAgent.html) to instantiate an agent:\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst getWeather = tool( // (1)!\n  async (input: { city: string }) => {\n    return `It's always sunny in ${input.city}!`;\n  },\n  {\n    name: \"getWeather\",\n    schema: z.object({\n      city: z.string().describe(\"The city to get the weather for\"),\n    }),\n    description: \"Get weather for a given city.\",\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\"); // (2)!\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather], // (3)!\n  prompt: \"You are a helpful assistant\", // (4)!\n});\n\n// Run the agent\nawait agent.invoke({\n  messages: [{ role: \"user\", content: \"what is the weather in sf\" }],\n});\n```\n\n1. Define a tool for the agent to use. For more advanced tool usage and customization, check the [tools](./tools.md) page.\n2. Provide a language model for the agent to use. To learn more about configuring language models for the agents, check the [models](./models.md) page.\n3. Provide a list of tools for the model to use.\n4. Provide a system prompt (instructions) to the language model used by the agent.\n\n## 3. Configure an LLM\n\nUse [`initChatModel`](https://api.js.langchain.com/functions/langchain.chat_models_universal.initChatModel.html) to configure an LLM with specific parameters, such as temperature:\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\n// highlight-next-line\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\", {\n  // highlight-next-line\n  temperature: 0,\n});\n\nconst agent = createReactAgent({\n  // highlight-next-line\n  llm,\n  tools: [getWeather],\n});\n```\n\nSee the [models](./models.md) page for more information on how to configure LLMs.\n\n## 4. Add a custom prompt\n\nPrompts instruct the LLM how to behave. They can be:\n\n- **Static**: A string is interpreted as a **system message**\n- **Dynamic**: a list of messages generated at **runtime** based on input or configuration\n\n=== \"Static prompt\"\n\n    Define a fixed prompt string or list of messages.\n\n    ```ts\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // A static prompt that never changes\n      // highlight-next-line\n      prompt: \"Never answer questions about the weather.\",\n    });\n\n    await agent.invoke({\n      messages: \"what is the weather in sf\",\n    });\n    ```\n\n=== \"Dynamic prompt\"\n\n    Define a function that returns a message list based on the agent's state and configuration:\n\n    ```ts\n    import { BaseMessageLike } from \"@langchain/core/messages\";\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { MessagesAnnotation } from \"@langchain/langgraph\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n    const prompt = (\n      state: typeof MessagesAnnotation.State,\n      config: RunnableConfig\n    ): BaseMessageLike[] => { // (1)!\n      const userName = config.configurable?.userName;\n      const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;\n      return [{ role: \"system\", content: systemMsg }, ...state.messages];\n    };\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // highlight-next-line\n      prompt,\n    });\n\n    await agent.invoke(\n      { messages: [{ role: \"user\", content: \"what is the weather in sf\" }] },\n      // highlight-next-line\n      { configurable: { userName: \"John Smith\" } }\n    );\n    ```\n\n    1. Dynamic prompts allow including non-message [context](./context.md) when constructing an input to the LLM, such as:\n\n      - Information passed at runtime, like a `userId` or API credentials (using `config`).\n      - Internal agent state updated during a multi-step reasoning process (using `state`).\n\n      Dynamic prompts can be defined as functions that take `state` and `config` and return a list of messages to send to the LLM.\n\nFor more information, see [Context](./context.md).\n\n## 5. Add memory\n\nTo allow multi-turn conversations with an agent, you need to enable [persistence](../concepts/persistence.md) by providing a `checkpointer` when creating an agent. At runtime you need to provide a config containing `thread_id` — a unique identifier for the conversation (session):\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { MemorySaver } from \"@langchain/langgraph-checkpoint\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\n// highlight-next-line\nconst checkpointer = new MemorySaver();\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather],\n  // highlight-next-line\n  checkpointer, // (1)!\n});\n\n// Run the agent\n// highlight-next-line\nconst config = { configurable: { thread_id: \"1\" } };\nconst sfResponse = await agent.invoke(\n  { messages: [{ role: \"user\", content: \"what is the weather in sf\" }] },\n  config // (2)!\n);\nconst nyResponse = await agent.invoke(\n  { messages: [{ role: \"user\", content: \"what about new york?\" }] },\n  config\n);\n```\n\n1. `checkpointer` allows the agent to store its state at every step in the tool calling loop. This enables [short-term memory](./memory.md#short-term-memory) and [human-in-the-loop](./human-in-the-loop.md) capabilities.\n2. Pass configuration with `thread_id` to be able to resume the same conversation on future agent invocations.\n\nWhen you enable the checkpointer, it stores agent state at every step in the provided checkpointer database (or in memory, if using `InMemorySaver`).\n\nNote that in the above example, when the agent is invoked the second time with the same `thread_id`, the original message history from the first conversation is automatically included, together with the new user input.\n\nFor more information, see [Memory](./memory.md).\n\n## 6. Configure structured output\n\nTo produce structured responses conforming to a schema, use the `responseFormat` parameter. The schema can be defined with a `zod` schema. The result will be accessible via the `structuredResponse` field.\n\n```ts\nimport { z } from \"zod\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\nconst WeatherResponse = z.object({\n  conditions: z.string(),\n});\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather],\n  // highlight-next-line\n  responseFormat: WeatherResponse, // (1)!\n});\n\nconst response = await agent.invoke({\n  messages: [{ role: \"user\", content: \"what is the weather in sf\" }],\n});\n// highlight-next-line\nresponse.structuredResponse;\n```\n\n1. When `responseFormat` is provided, a separate step is added at the end of the agent loop: agent message history is passed to an LLM with structured output to generate a structured response.\n\n   To provide a system prompt to this LLM, use an object `{ prompt, schema }`, e.g., `responseFormat: { prompt, schema: WeatherResponse }`.\n\n!!! Note \"LLM post-processing\"\n\n    Structured output requires an additional call to the LLM to format the response according to the schema.\n\n## Next steps\n\n- [Deploy your agent locally](../tutorials/langgraph-platform/local-server.md)\n- [Learn more about prebuilt agents](../agents/overview.md)\n- [LangGraph Platform quickstart](../cloud/quick_start.md)\n\n<!-- File: docs/docs/agents/context.md (Tokens: ~2446 | Category: subagent-persona) -->\n# Context\n\nAgents often require more than a list of messages to function effectively. They need **context**.\n\nContext includes *any* data outside the message list that can shape agent behavior or tool execution. This can be:\n\n- Information passed at runtime, like a `user_id` or API credentials.\n- Internal state updated during a multi-step reasoning process.\n- Persistent memory or facts from previous interactions.\n\nLangGraph provides **three** primary ways to supply context:\n\n| Type                                                                         | Description                                   | Mutable? | Lifetime                |\n|------------------------------------------------------------------------------|-----------------------------------------------|----------|-------------------------|\n| [**Config**](#config-static-context)                                         | data passed at the start of a run             | ❌        | per run                 |\n| [**State**](#state-mutable-context)                                          | dynamic data that can change during execution | ✅        | per run or conversation |\n| [**Long-term Memory (Store)**](#long-term-memory-cross-conversation-context) | data that can be shared between conversations | ✅        | across conversations    |\n\nYou can use context to:\n\n- Adjust the system prompt the model sees\n- Feed tools with necessary inputs\n- Track facts during an ongoing conversation\n\n## Providing Runtime Context\n\nUse this when you need to inject data into an agent at runtime.\n\n### Config (static context)\n\nConfig is for immutable data like user metadata or API keys. Use\nwhen you have values that don't change mid-run.\n\nSpecify configuration using a key called **\"configurable\"** which is reserved\nfor this purpose:\n\n```ts\nawait agent.invoke(\n  { messages: \"hi!\" },\n  // highlight-next-line\n  { configurable: { userId: \"user_123\" } }\n)\n```\n\n### State (mutable context)\n\nState acts as short-term memory during a run. It holds dynamic data that can evolve during execution, such as values derived from tools or LLM outputs.\n\n```ts\nconst CustomState = Annotation.Root({\n  ...MessagesAnnotation.spec,\n  userName: Annotation<string>,\n});\n\nconst agent = createReactAgent({\n  // Other agent parameters...\n  // highlight-next-line\n  stateSchema: CustomState,\n})\n\nawait agent.invoke(\n  // highlight-next-line\n  { messages: \"hi!\", userName: \"Jane\" }\n)\n```\n\n!!! tip \"Turning on memory\"\n\n    Please see the [memory guide](./memory.md) for more details on how to enable memory. This is a powerful feature that allows you to persist the agent's state across multiple invocations.\n    Otherwise, the state is scoped only to a single agent run.\n\n\n\n### Long-Term Memory (cross-conversation context)\n\nFor context that spans *across* conversations or sessions, LangGraph allows access to **long-term memory** via a `store`. This can be used to read or update persistent facts (e.g., user profiles, preferences, prior interactions). For more, see the [Memory guide](./memory.md).\n\n## Customizing Prompts with Context\n\nPrompts define how the agent behaves. To incorporate runtime context, you can dynamically generate prompts based on the agent's state or config.\n\nCommon use cases:\n\n- Personalization\n- Role or goal customization\n- Conditional behavior (e.g., user is admin)\n\n=== \"Using config\"\n\n    ```ts\n    import { BaseMessageLike } from \"@langchain/core/messages\";\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { MessagesAnnotation } from \"@langchain/langgraph\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n    const prompt = (\n      state: typeof MessagesAnnotation.State,\n      // highlight-next-line\n      config: RunnableConfig\n    ): BaseMessageLike[] => {\n      // highlight-next-line\n      const userName = config.configurable?.userName;\n      const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;\n      return [{ role: \"system\", content: systemMsg }, ...state.messages];\n    };\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // highlight-next-line\n      prompt\n    });\n\n    await agent.invoke(\n      { messages: \"hi!\" },\n      // highlight-next-line\n      { configurable: { userName: \"John Smith\" } }\n    );\n    ```\n\n=== \"Using state\"\n\n    ```ts\n    import { BaseMessageLike } from \"@langchain/core/messages\";\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { Annotation, MessagesAnnotation } from \"@langchain/langgraph\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n    const CustomState = Annotation.Root({\n      ...MessagesAnnotation.spec,\n      // highlight-next-line\n      userName: Annotation<string>,\n    });\n\n    const prompt = (\n      // highlight-next-line\n      state: typeof CustomState.State,\n    ): BaseMessageLike[] => {\n      // highlight-next-line\n      const userName = state.userName;\n      const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;\n      return [{ role: \"system\", content: systemMsg }, ...state.messages];\n    };\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getWeather],\n      // highlight-next-line\n      prompt,\n      // highlight-next-line\n      stateSchema: CustomState,\n    });\n\n    await agent.invoke(\n      // highlight-next-line\n      { messages: \"hi!\", userName: \"John Smith\" },\n    );\n    ```\n\n## Tools\n\nTools can access context through:\n\n* Use `RunnableConfig` for config access\n* Use `runtime.state` (the second argument, typed as `ToolRuntime`) for agent state\n\n!!! tip \"Browser / web environments\"\n\n    When a tool runs inside a `ToolNode` (including in `createReactAgent`), the `ToolNode` forwards its input (the current graph state) to the tool via `runtime.state`. This works in every runtime, including web browsers.\n\n    An older alternative, `getCurrentTaskInput()`, relies on [`AsyncLocalStorage`](https://nodejs.org/api/async_hooks.html), which is available in Node.js, Deno, and Cloudflare Workers, but **not** in web browsers. Prefer `runtime.state` for portability.\n\n=== \"Using config\"\n\n    ```ts\n    import { RunnableConfig } from \"@langchain/core/runnables\";\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { tool } from \"@langchain/core/tools\";\n    import { z } from \"zod\";\n\n    const getUserInfo = tool(\n      async (input: Record<string, any>, config: RunnableConfig) => {\n        // highlight-next-line\n        const userId = config.configurable?.userId;\n        return userId === \"user_123\" ? \"User is John Smith\" : \"Unknown user\";\n      },\n      {\n        name: \"get_user_info\",\n        description: \"Look up user info.\",\n        schema: z.object({}),\n      }\n    );\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getUserInfo],\n    });\n\n    await agent.invoke(\n      { messages: \"look up user information\" },\n      // highlight-next-line\n      { configurable: { userId: \"user_123\" } }\n    );\n    ```\n\n=== \"Using state\"\n\n    ```ts\n    import { initChatModel } from \"langchain/chat_models/universal\";\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { Annotation, MessagesAnnotation } from \"@langchain/langgraph\";\n    import { tool, type ToolRuntime } from \"@langchain/core/tools\";\n    import { z } from \"zod\";\n\n    const CustomState = Annotation.Root({\n      ...MessagesAnnotation.spec,\n      // highlight-next-line\n      userId: Annotation<string>(),\n    });\n\n    const getUserInfo = tool(\n      async (\n        input: Record<string, any>,\n        // highlight-next-line\n        runtime: ToolRuntime<typeof CustomState.State>,\n      ) => {\n        // Read the graph state directly from the second argument.\n        // This works in web browsers too (no AsyncLocalStorage required).\n        // highlight-next-line\n        const userId = runtime.state.userId;\n        return userId === \"user_123\" ? \"User is John Smith\" : \"Unknown user\";\n      },\n      {\n        name: \"get_user_info\",\n        description: \"Look up user info.\",\n        schema: z.object({})\n      }\n    );\n\n    const llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n    const agent = createReactAgent({\n      llm,\n      tools: [getUserInfo],\n      // highlight-next-line\n      stateSchema: CustomState,\n    });\n\n    await agent.invoke(\n      // highlight-next-line\n      { messages: \"look up user information\", userId: \"user_123\" }\n    );\n    ```\n\n\n## Update context from tools\n\nTools can modify the agent's state during execution. This is useful for persisting intermediate results or making information accessible to subsequent tools or prompts.\n\n```ts\nimport { Annotation, MessagesAnnotation, LangGraphRunnableConfig, Command } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\nconst CustomState = Annotation.Root({\n  ...MessagesAnnotation.spec,\n  // highlight-next-line\n  userName: Annotation<string>(), // Will be updated by the tool\n});\n\nconst getUserInfo = tool(\n  async (\n    _input: Record<string, never>,\n    config: LangGraphRunnableConfig\n  ): Promise<Command> => {\n    const userId = config.configurable?.userId;\n    if (!userId) {\n      throw new Error(\"Please provide a user id in config.configurable\");\n    }\n\n    const toolCallId = config.toolCall?.id;\n\n    const name = userId === \"user_123\" ? \"John Smith\" : \"Unknown user\";\n    // Return command to update state\n    return new Command({\n      update: {\n        // highlight-next-line\n        userName: name,\n        // Update the message history\n        // highlight-next-line\n        messages: [\n          new ToolMessage({\n            content: \"Successfully looked up user information\",\n            tool_call_id: toolCallId,\n          }),\n        ],\n      },\n    });\n  },\n  {\n    name: \"get_user_info\",\n    description: \"Look up user information.\",\n    schema: z.object({}),\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getUserInfo],\n  // highlight-next-line\n  stateSchema: CustomState,\n});\n\nawait agent.invoke(\n  { messages: \"look up user information\" },\n  // highlight-next-line\n  { configurable: { userId: \"user_123\" } }\n);\n```\n\nFor more details, see [how to update state from tools](../how-tos/update-state-from-tools.ipynb).\n\n<!-- File: docs/docs/agents/deployment.md (Tokens: ~814 | Category: subagent-persona) -->\n# Deployment\n\nTo deploy your LangGraph agent, create and configure a LangGraph app. This setup supports both local development and production deployments.\n\nFeatures: \n\n* 🖥️ Local server for development\n* 🧩 Studio Web UI for visual debugging\n* ☁️ Cloud and 🔧 self-hosted deployment options\n* 📊 LangSmith integration for tracing and observability\n\n!!! info \"Requirements\" \n\n    - ✅ You **must** have a [LangSmith account](https://www.langchain.com/langsmith). You can sign up for **free** and get started with the free tier.\n\n## Create a LangGraph app\n\n```bash\nnpm install -g create-langgraph\ncreate-langgraph path/to/your/app\n```\n\nFollow the prompts and select `New LangGraph Project`. This will create an empty LangGraph project. You can modify it by replacing the code in `src/agent/graph.ts` with your agent code. For example:\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst getWeather = tool(\n  async (input: { city: string }) => {\n    return `It's always sunny in ${input.city}!`;\n  },\n  {\n    name: \"getWeather\",\n    schema: z.object({\n      city: z.string().describe(\"The city to get the weather for\"),\n    }),\n    description: \"Get weather for a given city.\",\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\n// make sure to export the graph that will be used in the LangGraph API server\n// highlight-next-line\nexport const graph = createReactAgent({\n  llm,\n  tools: [getWeather],\n  prompt: \"You are a helpful assistant\"\n})\n```\n\n### Install dependencies\n\nIn the root of your new LangGraph app, install the dependencies:\n\n```shell\nyarn\n# install these to use initChatModel with Anthropic\nyarn add langchain\nyarn add @langchain/anthropic\n```\n\n### Create an `.env` file\n\nYou will find a `.env.example` in the root of your new LangGraph app. Create\na `.env` file in the root of your new LangGraph app and copy the contents of the `.env.example` file into it, filling in the necessary API keys:\n\n```bash\nLANGSMITH_API_KEY=lsv2...\nANTHROPIC_API_KEY=sk-\n```\n\n## Launch LangGraph server locally\n\n```shell\nnpx @langchain/langgraph-cli dev\n```\n\nThis will start up the LangGraph API server locally. If this runs successfully, you should see something like:\n\n>    Welcome to LangGraph.js!\n> \n>    - 🚀 API: http://localhost:2024\n>     \n>    - 🎨 Studio UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024\n\n## LangGraph Studio Web UI\n\nLangGraph Studio Web is a specialized UI that you can connect to LangGraph API server to enable visualization, interaction, and debugging of your application locally. Test your graph in the LangGraph Studio Web UI by visiting the URL provided in the output of the `npx @langchain/langgraph-cli dev` command.\n\n>    - LangGraph Studio Web UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024\n\n## Deployment\n\nOnce your LangGraph app is running locally, you can deploy it using LangSmith Deployment or self-hosted options. Refer to the [deployment options guide](https://langchain-ai.github.io/langgraph/tutorials/deployment/) for detailed instructions on all supported deployment models.\n\n<!-- File: docs/docs/agents/evals.md (Tokens: ~933 | Category: subagent-persona) -->\n# Evals\n\nTo evaluate your agent's performance you can use `LangSmith` [evaluations](https://docs.smith.langchain.com/evaluation). You would need to first define an evaluator function to judge the results from an agent, such as final outputs or trajectory. Depending on your evaluation technique, this may or may not involve a reference output:\n\n```ts\nconst evaluator = async (params: {\n  inputs: Record<string, unknown>;\n  outputs: Record<string, unknown>;\n  referenceOutputs?: Record<string, unknown>;\n}) => {\n  // compare agent outputs against reference outputs\n  const outputMessages = params.outputs.messages;\n  const referenceMessages = params.referenceOutputs.messages;\n  const score = compareMessages(outputMessages, referenceMessages);\n  return { key: \"evaluator_score\", score: score };\n};\n```\n\nTo get started, you can use prebuilt evaluators from `AgentEvals` package:\n\n```bash\nnpm install agentevals @langchain/core\n```\n\n## Create evaluator\n\nA common way to evaluate agent performance is by comparing its trajectory (the order in which it calls its tools) against a reference trajectory:\n\n```ts\n// highlight-next-line\nimport { createTrajectoryMatchEvaluator } from \"agentevals\";\n\nconst outputs = [\n  {\n    role: \"assistant\",\n    tool_calls: [\n      {\n        function: {\n          name: \"get_weather\",\n          arguments: JSON.stringify({ city: \"san francisco\" }),\n        },\n      },\n      {\n        function: {\n          name: \"get_directions\",\n          arguments: JSON.stringify({ destination: \"presidio\" }),\n        },\n      },\n    ],\n  },\n];\n\nconst referenceOutputs = [\n  {\n    role: \"assistant\",\n    tool_calls: [\n      {\n        function: {\n          name: \"get_weather\",\n          arguments: JSON.stringify({ city: \"san francisco\" }),\n        },\n      },\n    ],\n  },\n];\n\n// Create the evaluator\nconst evaluator = createTrajectoryMatchEvaluator({\n  // highlight-next-line\n  trajectoryMatchMode: \"superset\",  // (1)!\n})\n\n// Run the evaluator\nconst result = await evaluator({\n  outputs,\n  referenceOutputs,\n});\n```\n\n1. Specify how the trajectories will be compared. `superset` will accept output trajectory as valid if it's a superset of the reference one. Other options include: [strict](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#strict-match), [unordered](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#unordered-match) and [subset](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#subset-and-superset-match)\n\n\nAs a next step, learn more about how to [customize trajectory match evaluator](https://github.com/langchain-ai/agentevals?tab=readme-ov-file#agent-trajectory-match).\n\n### LLM-as-a-judge\n\nYou can use LLM-as-a-judge evaluator that uses an LLM to compare the trajectory against the reference outputs and output a score:\n\n```ts\nimport {\n  // highlight-next-line\n  createTrajectoryLLMAsJudge,\n  TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE\n} from \"agentevals\";\n\nconst evaluator = createTrajectoryLLMAsJudge({\n  prompt: TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE,\n  model: \"openai:o3-mini\",\n});\n```\n\n## Run evaluator\n\nTo run an evaluator, you will first need to create a [LangSmith dataset](https://docs.smith.langchain.com/evaluation/concepts#datasets). To use the prebuilt AgentEvals evaluators, you will need a dataset with the following schema:\n\n- **input**: `{ messages: [...] }` input messages to call the agent with.\n- **output**: `{ messages\": [...] }` expected message history in the agent output. For trajectory evaluation, you can choose to keep only assistant messages.\n\n```ts\nimport { evaluate } from \"langsmith/evaluation\";\nimport { createTrajectoryMatchEvaluator } from \"agentevals\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\nconst agent = createReactAgent({ ... })\nconst evaluator = createTrajectoryMatchEvaluator({ ... })\nawait evaluate(\n  async (inputs) => await agent.invoke(inputs),\n  {\n    // replace with your dataset name\n    data: \"<Name of your dataset>\",\n    evaluators: [evaluator],\n  }\n);\n```\n\n<!-- File: docs/docs/agents/human-in-the-loop.md (Tokens: ~1192 | Category: subagent-persona) -->\n# Human-in-the-loop\n\nTo review, edit and approve tool calls in an agent you can use LangGraph's built-in [human-in-the-loop](../concepts/human_in_the_loop.md) features, specifically the [`interrupt()`](/langgraphjs/reference/functions/langgraph.interrupt-1.html) primitive.\n\nLangGraph allows you to pause execution **indefinitely** — for minutes, hours, or even days—until human input is received.\n\nThis is possible because the agent state is **checkpointed into a database**, which allows the system to persist execution context and later resume the workflow, continuing from where it left off.\n\nFor a deeper dive into the **human-in-the-loop** concept, see the [concept guide](../concepts/human_in_the_loop.md).\n\n<figure markdown=\"1\">\n![image](../concepts/img/human_in_the_loop/tool-call-review.png){: style=\"max-height:400px\"}\n<figcaption>\nA human can review and edit the output from the agent before proceeding. This is particularly critical in applications where the tool calls requested may be sensitive or require human oversight.\n</figcaption>\n</figure>\n\n\n## Review tool calls\n\nTo add a human approval step to a tool:\n\n1. Use `interrupt()` in the tool to pause execution.\n2. Resume with a `Command({ resume: ... })` to continue based on human input.\n\n```ts\nimport { MemorySaver } from \"@langchain/langgraph-checkpoint\";\nimport { interrupt } from \"@langchain/langgraph\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\n// An example of a sensitive tool that requires human review / approval\nconst bookHotel = tool(\n  async (input: { hotelName: string; }) => {\n    let hotelName = input.hotelName;\n    // highlight-next-line\n    const response = interrupt(  // (1)!\n      `Trying to call \\`book_hotel\\` with args {'hotel_name': ${hotelName}}. ` +\n      `Please approve or suggest edits.`\n    )\n    if (response.type === \"accept\") {\n      // proceed to execute the tool logic\n    } else if (response.type === \"edit\") {\n        hotelName = response.args[\"hotel_name\"]\n    } else {\n        throw new Error(`Unknown response type: ${response.type}`)\n    }\n    return `Successfully booked a stay at ${hotelName}.`;\n  },\n  {\n    name: \"bookHotel\",\n    schema: z.object({\n      hotelName: z.string().describe(\"Hotel to book\"),\n    }),\n    description: \"Book a hotel.\",\n  }\n);\n\n// highlight-next-line\nconst checkpointer = new MemorySaver();  // (2)!\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [bookHotel],\n  // highlight-next-line\n  checkpointer  // (3)!\n});\n```\n\n1. The [`interrupt` function](/langgraphjs/reference/functions/langgraph.interrupt-1.html) pauses the agent graph at a specific node. In this case, we call `interrupt()` at the beginning of the tool function, which pauses the graph at the node that executes the tool. The information inside `interrupt()` (e.g., tool calls) can be presented to a human, and the graph can be resumed with the user input (tool call approval, edit or feedback).\n2. The `InMemorySaver` is used to store the agent state at every step in the tool calling loop. This enables [short-term memory](./memory.md#short-term-memory) and [human-in-the-loop](./human-in-the-loop.md) capabilities. In this example, we use `InMemorySaver` to store the agent state in memory. In a production application, the agent state will be stored in a database.\n3. Initialize the agent with the `checkpointer`.\n\nRun the agent with the `stream()` method, passing the `config` object to specify the thread ID. This allows the agent to resume the same conversation on future invocations.\n\n```ts\nconst config = {\n   configurable: {\n      // highlight-next-line\n      \"thread_id\": \"1\"\n   }\n}\n\nfor await (const chunk of await agent.stream(\n  { messages: \"book a stay at McKittrick hotel\" },\n  // highlight-next-line\n  config\n)) {\n  console.log(chunk);\n  console.log(\"\\n\");\n};\n```\n\n> You should see that the agent runs until it reaches the `interrupt()` call, at which point it pauses and waits for human input.\n\nResume the agent with a `Command({ resume: ... })` to continue based on human input.\n\n```ts\nimport { Command } from \"@langchain/langgraph\";\n\nfor await (const chunk of await agent.stream(\n  new Command({ resume: { type: \"accept\" } }),  // (1)!\n  // new Command({ resume: { type: \"edit\", args: { \"hotel_name\": \"McKittrick Hotel\" } } }),\n  // highlight-next-line\n  config\n)) {\n  console.log(chunk);\n  console.log(\"\\n\");\n};\n```\n\n1. The [`interrupt` function](/langgraphjs/reference/functions/langgraph.interrupt-1.html) is used in conjunction with the [`Command`](/langgraphjs/reference/classes/langgraph.Command.html) object to resume the graph with a value provided by the human.\n\n## Additional resources\n\n* [Human-in-the-loop in LangGraph](../concepts/human_in_the_loop.md)\n\n<!-- File: docs/docs/agents/mcp.md (Tokens: ~738 | Category: subagent-persona) -->\n# MCP Integration\n\n[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open protocol that standardizes how applications provide tools and context to language models. LangGraph agents can use tools defined on MCP servers through the `@langchain/mcp-adapters` library.\n\n![MCP](./assets/mcp.png)\n\nInstall the `@langchain/mcp-adapters` library to use MCP tools in LangGraph:\n\n```bash\nnpm install @langchain/mcp-adapters\n```\n\n## Use MCP tools\n\nThe `@langchain/mcp-adapters` package enables agents to use tools defined across one or more MCP servers.\n\n```ts\n// highlight-next-line\nimport { MultiServerMCPClient } from \"@langchain/mcp-adapters\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n// highlight-next-line\nconst client = new MultiServerMCPClient({\n  mcpServers: {\n    \"math\": {\n      command: \"python\",\n      // Replace with absolute path to your math_server.py file\n      args: [\"/path/to/math_server.py\"],\n      transport: \"stdio\",\n    },\n    \"weather\": {\n      // Ensure your start your weather server on port 8000\n      url: \"http://localhost:8000/sse\",\n      transport: \"sse\",\n    }\n  }\n})\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  // highlight-next-line\n  tools: await client.getTools()\n});\n \nconst mathResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what's (3 + 5) x 12?\" } ] }\n);\nconst weatherResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what is the weather in nyc?\" } ] }\n);\nawait client.close();\n```\n\n## Custom MCP servers\n\nTo create your own MCP servers, you can use the `mcp` library in Python (or `@modelcontextprotocol/sdk` in TypeScript). These libraries provide a simple way to define tools and run them as servers.\n\nInstall the MCP library:\n\n```bash\npip install mcp\n```\nUse the following reference implementations to test your agent with MCP tool servers.\n\n```python title=\"Example Math Server (stdio transport)\"\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"Math\")\n\n@mcp.tool()\ndef add(a: int, b: int) -> int:\n    \"\"\"Add two numbers\"\"\"\n    return a + b\n\n@mcp.tool()\ndef multiply(a: int, b: int) -> int:\n    \"\"\"Multiply two numbers\"\"\"\n    return a * b\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"stdio\")\n```\n\n```python title=\"Example Weather Server (SSE transport)\"\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"Weather\")\n\n@mcp.tool()\nasync def get_weather(location: str) -> str:\n    \"\"\"Get weather for location.\"\"\"\n    return \"It's always sunny in New York\"\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"sse\")\n```\n\n## Additional resources\n\n- [MCP documentation](https://modelcontextprotocol.io/introduction)\n- [MCP Transport documentation](https://modelcontextprotocol.io/docs/concepts/transports)\n\n<!-- File: docs/docs/agents/memory.md (Tokens: ~2541 | Category: subagent-persona) -->\n# Memory\n\nLangGraph supports two types of memory essential for building conversational agents:\n\n- **[Short-term memory](#short-term-memory)**: Tracks the ongoing conversation by maintaining message history within a session.\n- **[Long-term memory](#long-term-memory)**: Stores user-specific or application-level data across sessions.\n\nThis guide demonstrates how to use both memory types with agents in LangGraph. For a deeper\nunderstanding of memory concepts, refer to the [LangGraph memory documentation](../concepts/memory.md).\n\n<figure markdown=\"1\">\n![image](./assets/memory.png){: style=\"max-height:400px\"}\n<figcaption>Both <strong>short-term</strong> and <strong>long-term</strong> memory require persistent storage to maintain continuity across LLM interactions. In production environments, this data is typically stored in a database.</figcaption>\n</figure>\n\n!!! note \"Terminology\"\n\n    In LangGraph:\n\n    - *Short-term memory* is also referred to as **thread-level memory**.\n    - *Long-term memory* is also called **cross-thread memory**.\n\n    A [thread](../concepts/persistence.md#threads) represents a sequence of related runs\n    grouped by the same `thread_id`.\n\n## Short-term memory\n\nShort-term memory enables agents to track multi-turn conversations. To use it, you must:\n\n1. Provide a `checkpointer` when creating the agent. The `checkpointer` enables [persistence](../concepts/persistence.md) of the agent's state.\n2. Supply a `thread_id` in the config when running the agent. The `thread_id` is a unique identifier for the conversation session.\n\n```ts\n// highlight-next-line\nimport { MemorySaver } from \"@langchain/langgraph-checkpoint\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\n// highlight-next-line\nconst checkpointer = new MemorySaver();  // (1)!\n\nconst getWeather = tool(\n  async (input: { city: string }) => {\n    return `It's always sunny in ${input.city}!`;\n  },\n  {\n    name: \"getWeather\",\n    schema: z.object({\n      city: z.string().describe(\"The city to get the weather for\"),\n    }),\n    description: \"Get weather for a given city.\",\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getWeather],\n  // highlight-next-line\n  checkpointer  // (2)!\n});\n\n// Run the agent\n// highlight-next-line\nconst config = { configurable: { thread_id: \"1\" } };  // (3)!\nconst sfResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what is the weather in sf\" } ] },\n  config  // (4)!\n);\nconst nyResponse = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"what about new york?\" } ] },\n  config\n);\n```\n\n1. The `MemorySaver` is a checkpointer that stores the agent's state in memory. In a production setting, you would typically use a database or other persistent storage. Please review the [checkpointer documentation](https://langchain-ai.github.io/langgraphjs/reference/index.html) for more options. If you're deploying with **LangGraph Platform**, the platform will provide a production-ready checkpointer for you.\n2. The `checkpointer` is passed to the agent. This enables the agent to persist its state across invocations. Please note that \n3. A unique `thread_id` is provided in the config. This ID is used to identify the conversation session. The value is controlled by the user and can be any string.\n4. The agent will continue the conversation using the same `thread_id`. This will allow the agent to infer that the user is asking specifically about the **weather** in New York. \n\nWhen the agent is invoked the second time with the same `thread_id`, the original message history from the first conversation is automatically included, allowing the agent to infer that the user is asking specifically about the **weather** in New York.\n\n!!! Note \"LangGraph Platform providers a production-ready checkpointer\"\n\n    If you're using [LangGraph Platform](./deployment.md), during deployment your checkpointer will be automatically configured to use a production-ready database.\n\n## Long-term memory\n\nUse long-term memory to store user-specific or application-specific data across conversations. This is useful for applications like chatbots, where you want to remember user preferences or other information.\n\nTo use long-term memory, you need to:\n\n1. [Configure a store](../how-tos/cross-thread-persistence.ipynb) to persist data across invocations.\n2. Use the `config.store` to access the store from within tools or prompts.\n\n### Reading\n\n```ts title=\"A tool the agent can use to look up user information\"\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n// highlight-next-line\nimport { InMemoryStore } from \"@langchain/langgraph-checkpoint\";\n// highlight-next-line\nimport { getStore } from \"@langchain/langgraph\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst store = new InMemoryStore(); // (1)!\n\nawait store.put(  // (2)!\n  [\"users\"],  // (3)!\n  \"user_123\",  // (4)!\n  {\n    name: \"John Smith\",\n    language: \"English\",\n  } // (5)!\n);\n\n// Look up user info tool\nconst getUserInfo = tool(\n  async (input: Record<string, any>, config: LangGraphRunnableConfig): Promise<string> => {\n    // Same as that provided to `createReactAgent`\n    const store = config.store; // (6)!\n    if (!store) {\n      throw new Error(\"store is required when compiling the graph\");\n    }\n\n    const userId = config.configurable?.userId;\n    if (!userId) {\n      throw new Error(\"userId is required in the config\");\n    }\n\n    const userInfo = await store.get([\"users\"], userId); // (7)!\n    return userInfo ? JSON.stringify(userInfo.value) : \"Unknown user\";\n  },\n  {\n    name: \"get_user_info\",\n    description: \"Look up user info.\",\n    schema: z.object({}),\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [getUserInfo],\n  store, // (8)!\n});\n\n// Run the agent\nconst response = await agent.invoke(\n  { messages: [ { role: \"user\", content: \"look up user information\" } ] },\n  { configurable: { userId: \"user_123\" } }\n);\n```\n\n1. The `InMemoryStore` is a store that stores data in memory. In a production setting, you would typically use a database or other persistent storage. Please review the [documentation](https://langchain-ai.github.io/langgraphjs/reference/index.html) for more options. If you're deploying with **LangGraph Platform**, the platform will provide a production-ready store for you.\n2. For this example, we write some sample data to the store using the `put` method. Please see the [BaseStore.put](https://langchain-ai.github.io/langgraphjs/reference/classes/checkpoint.BaseStore.html#put) API reference for more details.\n3. The first argument is the namespace. This is used to group related data together. In this case, we are using the `users` namespace to group user data.\n4. A key within the namespace. This example uses a user ID for the key.\n5. The data that we want to store for the given user.\n6. You can access the store via `config.store` from anywhere in your nodes, tools and prompts. It contains the store that was passed to the agent when it was created.\n7. The `get` method is used to retrieve data from the store. The first argument is the namespace, and the second argument is the key. This will return a `StoreValue` object, which contains the value and metadata about the value.\n8. The `store` is passed to the agent. This enables the agent to access the store when running tools.\n\n### Writing\n\n```ts title=\"Example of a tool that updates user information\"\nimport { initChatModel } from \"langchain/chat_models/universal\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { InMemoryStore } from \"@langchain/langgraph-checkpoint\";\nimport { getStore } from \"@langchain/langgraph\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst store = new InMemoryStore(); // (1)!\n\ninterface UserInfo { // (2)!\n  name: string;\n}\n\n// Save user info tool\nconst saveUserInfo = tool(  // (3)!\n  async (input: UserInfo, config: LangGraphRunnableConfig): Promise<string> => {\n    // Same as that provided to `createReactAgent`\n    // highlight-next-line\n    const store = config.store; // (4)!\n    if (!store) {\n      throw new Error(\"store is required when compiling the graph\");\n    }\n\n    const userId = config.configurable?.userId;\n    if (!userId) {\n      throw new Error(\"userId is required in the config\");\n    }\n\n    await store.put([\"users\"], userId, input); // (5)!\n    return \"Successfully saved user info.\";\n  },\n  {\n    name: \"save_user_info\",\n    description: \"Save user info.\",\n    schema: z.object({\n      name: z.string(),\n    }),\n  }\n);\n\nconst llm = await initChatModel(\"anthropic:claude-3-7-sonnet-latest\");\nconst agent = createReactAgent({\n  llm,\n  tools: [saveUserInfo],\n  // highlight-next-line\n  store,\n});\n\n// Run the agent\nawait agent.invoke(\n  { messages: [ { role: \"user\", content: \"My name is John Smith\" } ] },\n  { configurable: { userId: \"user_123\" } } // (6)!\n);\n\n// You can access the store directly to get the value\nconst userInfo = await store.get([\"users\"], \"user_123\")\nuserInfo.value\n```\n\n1. The `InMemoryStore` is a store that stores data in memory. In a production setting, you would typically use a database or other persistent storage. Please review the [store documentation](../reference/stores.md) for more options. If you're deploying with **LangGraph Platform**, the platform will provide a production-ready store for you.\n2. The `UserInfo` class is an interface that defines the structure of the user information. We will specify the same schema below using a zod object, so that the LLM formats the response according to the schema.\n3. The `saveUserInfo` is a tool that allows an agent to update user information. This could be useful for a chat application where the user wants to update their profile information.\n4. You can access the store via `config.store` from anywhere in your nodes, tools and prompts. It contains the store that was passed to the agent when it was created.\n5. The `put` method is used to store data in the store. The first argument is the namespace, and the second argument is the key. This will store the user information in the store.\n6. The `userId` is passed in the config. This is used to identify the user whose information is being updated.\n\n## Additional resources\n\n* [Memory in LangGraph](../concepts/memory.md)\n\n<!-- File: docs/docs/agents/models.md (Tokens: ~477 | Category: subagent-persona) -->\n# Models\n\nThis page describes how to configure the chat model used by an agent.\n\n## Tool calling support\n\nTo enable tool-calling agents, the underlying LLM must support [tool calling](https://js.langchain.com/docs/concepts/tool_calling/).\n\nCompatible models can be found in the [LangChain integrations directory](https://js.langchain.com/docs/integrations/chat/).\n\n## Using `initChatModel`\n\nThe [`initChatModel`](https://js.langchain.com/docs/how_to/chat_models_universal_init/) utility simplifies model initialization with configurable parameters:\n\n```ts\nimport { initChatModel } from \"langchain/chat_models/universal\";\n\nconst llm = await initChatModel(\n  \"anthropic:claude-3-7-sonnet-latest\",\n  {\n    temperature: 0,\n    maxTokens: 2048\n  }\n);\n```\n\nRefer to the [API reference](https://api.js.langchain.com/functions/langchain.chat_models_universal.initChatModel.html) for advanced options.\n\n## Using provider-specific LLMs \n\nIf a model provider is not available via `initChatModel`, you can instantiate the provider's model class directly. The model must implement the [`BaseChatModel`](https://api.js.langchain.com/classes/_langchain_core.language_models_chat_models.BaseChatModel.html) interface and support tool calling:\n\n```ts\nimport { ChatAnthropic } from \"@langchain/anthropic\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n// highlight-next-line\nconst llm = new ChatAnthropic({\n  modelName: \"claude-3-7-sonnet-latest\",\n  temperature: 0,\n  maxTokens: 2048\n});\n\nconst agent = createReactAgent({\n  // highlight-next-line\n  llm,\n  // other parameters\n});\n```\n\n!!! note \"Illustrative example\" \n\n    The example above uses `ChatAnthropic`, which is already supported by `initChatModel`. This pattern is shown to illustrate how to manually instantiate a model not available through `initChatModel`.\n\n## Additional resources\n\n- [Model integration directory](https://js.langchain.com/docs/integrations/chat/)\n- [Universal initialization with `initChatModel`](https://js.langchain.com/docs/how_to/chat_models_universal_init/)\n\n<!-- File: docs/docs/agents/multi-agent.md (Tokens: ~2704 | Category: subagent-persona) -->\n# Multi-agent\n\nA single agent might struggle if it needs to specialize in multiple domains or manage many tools. To tackle this, you can break your agent into smaller, independent agents and composing them into a [multi-agent system](../concepts/multi_agent.md).\n\nIn multi-agent systems, agents need to communicate between each other. They do so via [handoffs](#handoffs) — a primitive that describes which agent to hand control to and the payload to send to that agent.\n\nTwo of the most popular multi-agent architectures are:\n\n- [supervisor](#supervisor) — individual agents are coordinated by a central supervisor agent. The supervisor controls all communication flow and task delegation, making decisions about which agent to invoke based on the current context and task requirements.\n- [swarm](#swarm) — agents dynamically hand off control to one another based on their specializations. The system remembers which agent was last active, ensuring that on subsequent interactions, the conversation resumes with that agent.\n\n## Supervisor\n\n![Supervisor](./assets/supervisor.png)\n\nUse [`langgraph-supervisor`](https://github.com/langchain-ai/langgraphjs/tree/main/libs/langgraph-supervisor) library to create a supervisor multi-agent system:\n\n```bash\nnpm install @langchain/langgraph-supervisor\n```\n\n```ts\nimport { ChatOpenAI } from \"@langchain/openai\";\n// highlight-next-line\nimport { createSupervisor } from \"@langchain/langgraph-supervisor\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nconst bookHotel = tool(\n  async (input: { hotel_name: string }) => {\n    return `Successfully booked a stay at ${input.hotel_name}.`;\n  },\n  {\n    name: \"book_hotel\",\n    description: \"Book a hotel\",\n    schema: z.object({\n      hotel_name: z.string().describe(\"The name of the hotel to book\"),\n    }),\n  }\n);\n\nconst bookFlight = tool(\n  async (input: { from_airport: string; to_airport: string }) => {\n    return `Successfully booked a flight from ${input.from_airport} to ${input.to_airport}.`;\n  },\n  {\n    name: \"book_flight\",\n    description: \"Book a flight\",\n    schema: z.object({\n      from_airport: z.string().describe(\"The departure airport code\"),\n      to_airport: z.string().describe(\"The arrival airport code\"),\n    }),\n  }\n);\n\nconst llm = new ChatOpenAI({ modelName: \"gpt-4o\" });\n\n// Create specialized agents\nconst flightAssistant = createReactAgent({\n  llm,\n  tools: [bookFlight],\n  prompt: \"You are a flight booking assistant\",\n  // highlight-next-line\n  name: \"flight_assistant\",\n});\n\nconst hotelAssistant = createReactAgent({\n  llm,\n  tools: [bookHotel],\n  prompt: \"You are a hotel booking assistant\",\n  // highlight-next-line\n  name: \"hotel_assistant\",\n});\n\n// highlight-next-line\nconst supervisor = createSupervisor({\n  agents: [flightAssistant, hotelAssistant],\n  llm,\n  prompt: \"You manage a hotel booking assistant and a flight booking assistant. Assign work to them, one at a time.\",\n}).compile();\n\nconst stream = await supervisor.stream({\n  messages: [{\n    role: \"user\",\n    content: \"first book a flight from BOS to JFK and then book a stay at McKittrick Hotel\"\n  }]\n});\n\nfor await (const chunk of stream) {\n  console.log(chunk);\n  console.log(\"\\n\");\n}\n```\n\n## Swarm\n\n![Swarm](./assets/swarm.png)\n\nUse [`langgraph-swarm`](https://github.com/langchain-ai/langgraphjs/tree/main/libs/langgraph-swarm) library to create a swarm multi-agent system:\n\n```bash\nnpm install @langchain/langgraph-swarm\n```\n\n```ts\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { ChatAnthropic } from \"@langchain/anthropic\";\n// highlight-next-line\nimport { createSwarm, createHandoffTool } from \"@langchain/langgraph-swarm\";\n\nconst transferToHotelAssistant = createHandoffTool({\n  agentName: \"hotel_assistant\",\n  description: \"Transfer user to the hotel-booking assistant.\",\n});\n\nconst transferToFlightAssistant = createHandoffTool({\n  agentName: \"flight_assistant\",\n  description: \"Transfer user to the flight-booking assistant.\",\n});\n\n\nconst llm = new ChatAnthropic({ modelName: \"claude-3-5-sonnet-latest\" });\n\nconst flightAssistant = createReactAgent({\n  llm,\n  tools: [bookFlight, transferToHotelAssistant],\n  prompt: \"You are a flight booking assistant\",\n  name: \"flight_assistant\",\n});\n\nconst hotelAssistant = createReactAgent({\n  llm,\n  tools: [bookHotel, transferToFlightAssistant],\n  prompt: \"You are a hotel booking assistant\",\n  name: \"hotel_assistant\",\n});\n\n// highlight-next-line\nconst swarm = createSwarm({\n  agents: [flightAssistant, hotelAssistant],\n  defaultActiveAgent: \"flight_assistant\",\n}).compile();\n\nconst stream = await swarm.stream({\n  messages: [{\n    role: \"user\",\n    content: \"first book a flight from BOS to JFK and then book a stay at McKittrick Hotel\"\n  }]\n});\n\nfor await (const chunk of stream) {\n  console.log(chunk);\n  console.log(\"\\n\");\n}\n```\n\n## Handoffs\n\nA common pattern in multi-agent interactions is **handoffs**, where one agent *hands off* control to another. Handoffs allow you to specify:\n\n- **destination**: target agent to navigate to\n- **payload**: information to pass to that agent\n\nThis is used both by `langgraph-supervisor` (supervisor hands off to individual agents) and `langgraph-swarm` (an individual agent can hand off to other agents).\n\nTo implement handoffs with `createReactAgent`, you need to:\n\n1. Create a special tool that can transfer control to a different agent\n\n    ```ts\n    const transferToBob = tool(\n      async (_) => {\n        return new Command({\n          // name of the agent (node) to go to\n          // highlight-next-line\n          goto: \"bob\",\n          // data to send to the agent\n          // highlight-next-line\n          update: { messages: ... },\n          // indicate to LangGraph that we need to navigate to\n          // agent node in a parent graph\n          // highlight-next-line\n          graph: Command.PARENT,\n        });\n      },\n      {\n        name: ...,\n        schema: ...,\n        description: ...\n      }\n    );\n    ```\n\n1. Create individual agents that have access to handoff tools:\n\n    ```ts\n    const flightAssistant = createReactAgent(\n      ..., tools: [bookFlight, transferToHotelAssistant]\n    )\n    const hotelAssistant = createReactAgent(\n      ..., tools=[bookHotel, transferToFlightAssistant]\n    )\n    ```\n\n1. Define a parent graph that contains individual agents as nodes:\n\n    ```ts\n    import { StateGraph, MessagesAnnotation } from \"@langchain/langgraph\";\n\n    const multiAgentGraph = new StateGraph(MessagesAnnotation)\n      .addNode(\"flight_assistant\", flightAssistant)\n      .addNode(\"hotel_assistant\", hotelAssistant)\n      ...\n    ```\n\nPutting this together, here is how you can implement a simple multi-agent system with two agents — a flight booking assistant and a hotel booking assistant:\n\n```ts\nimport { ChatAnthropic } from \"@langchain/anthropic\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { StateGraph, MessagesAnnotation, Command, START, END } from \"@langchain/langgraph\";\nimport { tool, type ToolRuntime } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ToolMessage } from \"@langchain/core/messages\";\n\ninterface CreateHandoffToolParams {\n  agentName: string;\n  description?: string;\n}\n\nconst createHandoffTool = ({\n  agentName,\n  description,\n}: CreateHandoffToolParams) => {\n  const toolName = `transfer_to_${agentName}`;\n  const toolDescription = description || `Ask agent '${agentName}' for help`;\n\n  const handoffTool = tool(\n    async (_, runtime: ToolRuntime<typeof MessagesAnnotation.State>) => {\n      const toolMessage = new ToolMessage({\n        content: `Successfully transferred to ${agentName}`,\n        name: toolName,\n        tool_call_id: runtime.toolCallId,\n      });\n\n      // inject the current agent state\n      // highlight-next-line\n      const state = runtime.state;  // (1)!\n      return new Command({  // (2)!\n        // highlight-next-line\n        goto: agentName,  // (3)!\n        // highlight-next-line\n        update: { messages: state.messages.concat(toolMessage) },  // (4)!\n        // highlight-next-line\n        graph: Command.PARENT,  // (5)!\n      });\n    },\n    {\n      name: toolName,\n      schema: z.object({}),\n      description: toolDescription,\n    }\n  );\n\n  return handoffTool;\n};\n\nconst bookHotel = tool(\n  async (input: { hotel_name: string }) => {\n    return `Successfully booked a stay at ${input.hotel_name}.`;\n  },\n  {\n    name: \"book_hotel\",\n    description: \"Book a hotel\",\n    schema: z.object({\n      hotel_name: z.string().describe(\"The name of the hotel to book\"),\n    }),\n  }\n);\n\nconst bookFlight = tool(\n  async (input: { from_airport: string; to_airport: string }) => {\n    return `Successfully booked a flight from ${input.from_airport} to ${input.to_airport}.`;\n  },\n  {\n    name: \"book_flight\",\n    description: \"Book a flight\",\n    schema: z.object({\n      from_airport: z.string().describe(\"The departure airport code\"),\n      to_airport: z.string().describe(\"The arrival airport code\"),\n    }),\n  }\n);\n\nconst transferToHotelAssistant = createHandoffTool({\n  agentName: \"hotel_assistant\",\n  description: \"Transfer user to the hotel-booking assistant.\",\n});\n\nconst transferToFlightAssistant = createHandoffTool({\n  agentName: \"flight_assistant\",\n  description: \"Transfer user to the flight-booking assistant.\",\n});\n\nconst llm = new ChatAnthropic({ modelName: \"claude-3-5-sonnet-latest\" });\n\nconst flightAssistant = createReactAgent({\n  llm,\n  // highlight-next-line\n  tools: [bookFlight, transferToHotelAssistant],\n  prompt: \"You are a flight booking assistant\",\n  // highlight-next-line\n  name: \"flight_assistant\",\n});\n\nconst hotelAssistant = createReactAgent({\n  llm,\n  // highlight-next-line\n  tools: [bookHotel, transferToFlightAssistant],\n  prompt: \"You are a hotel booking assistant\",\n  // highlight-next-line\n  name: \"hotel_assistant\",\n});\n\nconst multiAgentGraph = new StateGraph(MessagesAnnotation)\n  .addNode(\"flight_assistant\", flightAssistant, { ends: [\"hotel_assistant\", END] })\n  .addNode(\"hotel_assistant\", hotelAssistant, { ends: [\"flight_assistant\", END] })\n  .addEdge(START, \"flight_assistant\")\n  .compile();\n\nconst stream = await multiAgentGraph.stream({\n  messages: [{\n    role: \"user\",\n    content: \"book a flight from BOS to JFK and a stay at McKittrick Hotel\"\n  }]\n});\n\nfor await (const chunk of stream) {\n  console.log(chunk);\n  console.log(\"\\n\");\n}\n```\n\n1. Access agent's state\n2. The `Command` primitive allows specifying a state update and a node transition as a single operation, making it useful for implementing handoffs.\n3. Name of the agent or node to hand off to.\n4. Take the agent's messages and **add** them to the parent's **state** as part of the handoff. The next agent will see the parent state.\n5. Indicate to LangGraph that we need to navigate to agent node in a **parent** multi-agent graph.\n\n!!! Note\n    This handoff implementation assumes that:\n\n    - each agent receives overall message history (across all agents) in the multi-agent system as its input\n    - each agent outputs its internal messages history to the overall message history of the multi-agent system\n\n    Check out LangGraph [supervisor](https://github.com/langchain-ai/langgraph-supervisor-py#customizing-handoff-tools) and [swarm](https://github.com/langchain-ai/langgraph-swarm-py#customizing-handoff-tools) documentation to learn how to customize handoffs.\n\n<!-- File: docs/docs/agents/overview.md (Tokens: ~1983 | Category: subagent-persona) -->\n---\ntitle: Overview\n---\n\n# Agent development with LangGraph\n\n**LangGraph** provides both low-level primitives and high-level prebuilt components for building agent-based applications. This section focuses on the **prebuilt**, **reusable** components designed to help you construct agentic systems quickly and reliably—without the need to implement orchestration, memory, or human feedback handling from scratch.\n\n## What is an agent?\n\nAn _agent_ consists of three components: a **large language model (LLM)**, a set of **tools** it can use, and a **prompt** that provides instructions.\n\nThe LLM operates in a loop. In each iteration, it selects a tool to invoke, provides input, receives the result (an observation), and uses that observation to inform the next action. The loop continues until a stopping condition is met — typically when the agent has gathered enough information to respond to the user.\n\n<figure markdown=\"1\">\n![image](./assets/agent.png){: style=\"max-height:400px\"}\n<figcaption>Agent loop: the LLM selects tools and uses their outputs to fulfill a user request.</figcaption>\n</figure>\n\n## Key features\n\nLangGraph includes several capabilities essential for building robust, production-ready agentic systems:\n\n- [**Memory integration**](./memory.md): Native support for _short-term_ (session-based) and _long-term_ (persistent across sessions) memory, enabling stateful behaviors in chatbots and assistants.\n- [**Human-in-the-loop control**](./human-in-the-loop.md): Execution can pause _indefinitely_ to await human feedback—unlike websocket-based solutions limited to real-time interaction. This enables asynchronous approval, correction, or intervention at any point in the workflow.\n- [**Streaming support**](./streaming.md): Real-time streaming of agent state, model tokens, tool outputs, or combined streams.\n- [**Deployment tooling**](./deployment.md): Includes infrastructure-free deployment tools. [**LangGraph Platform**](https://langchain-ai.github.io/langgraph/concepts/langgraph_platform/) supports testing, debugging, and deployment.\n  - **[Studio](https://langchain-ai.github.io/langgraph/concepts/langgraph_studio/)**: A visual IDE for inspecting and debugging workflows.\n  - Supports multiple [**deployment options**](https://langchain-ai.github.io/langgraph/tutorials/deployment/) for production.\n\n## High-level building blocks\n\nLangGraph comes with a set of prebuilt components that implement common agent behaviors and workflows. These abstractions are built on top of the LangGraph framework, offering a faster path to production while remaining flexible for advanced customization.\n\nUsing LangGraph for agent development allows you to focus on your application's logic and behavior, instead of building and maintaining the supporting infrastructure for state, memory, and human feedback.\n\n## Package ecosystem\n\nThe high-level components are organized into several packages, each with a specific focus.\n\n| Package                  | Description                                                                 | Installation                                       |\n| ------------------------ | --------------------------------------------------------------------------- | -------------------------------------------------- |\n| `langgraph`              | Prebuilt components to [**create agents**](./agents.md)                     | `npm install @langchain/langgraph @langchain/core` |\n| `langgraph-supervisor`   | Tools for building [**supervisor**](./multi-agent.md#supervisor) agents     | `npm install @langchain/langgraph-supervisor`      |\n| `langgraph-swarm`        | Tools for building a [**swarm**](./multi-agent.md#swarm) multi-agent system | `npm install @langchain/langgraph-swarm`           |\n| `langchain-mcp-adapters` | Interfaces to [**MCP servers**](./mcp.md) for tool and resource integration | `npm install @langchain/mcp-adapters`              |\n| `agentevals`             | Utilities to [**evaluate agent performance**](./evals.md)                   | `npm install agentevals`                           |\n\n## Visualize an agent graph\n\nUse the following tool to visualize the graph generated by [`createReactAgent`](/langgraphjs/reference/functions/langgraph_prebuilt.createReactAgent.html) and to view an outline of the corresponding code. It allows you to explore the infrastructure of the agent as defined by the presence of:\n\n- [`tools`](./tools.md): A list of tools (functions, APIs, or other callable objects) that the agent can use to perform tasks.\n- `preModelHook`: A function that is called before the model is invoked. It can be used to condense messages or perform other preprocessing tasks.\n- `postModelHook`: A function that is called after the model is invoked. It can be used to implement guardrails, human-in-the-loop flows, or other postprocessing tasks.\n- [`responseFormat`](./agents.md#structured-output): A data structure used to constrain the type of the final output (via Zod schemas).\n\n<div class=\"agent-layout\">\n  <div class=\"agent-graph-features-container\">\n    <div class=\"agent-graph-features\">\n      <h3 class=\"agent-section-title\">Features</h3>\n      <label><input type=\"checkbox\" id=\"tools\" checked> <code>tools</code></label>\n      <label><input type=\"checkbox\" id=\"preModelHook\"> <code>preModelHook</code></label>\n      <label><input type=\"checkbox\" id=\"postModelHook\"> <code>postModelHook</code></label>\n      <label><input type=\"checkbox\" id=\"responseFormat\"> <code>responseFormat</code></label>\n    </div>\n  </div>\n\n  <div class=\"agent-graph-container\">\n    <h3 class=\"agent-section-title\">Graph</h3>\n    <img id=\"agent-graph-img\" src=\"../assets/react_agent_graphs/0001.svg\" alt=\"graph image\" style=\"max-width: 100%;\"/>\n  </div>\n</div>\n\nThe following code snippet shows how to create the above agent (and underlying graph) with [`createReactAgent`](/langgraphjs/reference/functions/langgraph_prebuilt.createReactAgent.html):\n\n<div class=\"language-typescript\">\n  <pre><code id=\"agent-code\" class=\"language-typescript\"></code></pre>\n</div>\n\n<script>\nfunction getCheckedValue(id) {\n  return document.getElementById(id).checked ? \"1\" : \"0\";\n}\n\nfunction getKey() {\n  return [\n    getCheckedValue(\"responseFormat\"),\n    getCheckedValue(\"postModelHook\"),\n    getCheckedValue(\"preModelHook\"),\n    getCheckedValue(\"tools\")\n  ].join(\"\");\n}\n\nfunction dedent(strings, ...values) {\n  const str = String.raw({ raw: strings }, ...values)\n  const [space] = str.split(\"\\n\").filter(Boolean).at(0).match(/^(\\s*)/)\n  const spaceLen = space.length\n  return str.split(\"\\n\").map(line => line.slice(spaceLen)).join(\"\\n\").trim()\n}\n\nObject.assign(dedent, {\n  offset: (size) => (strings, ...values) => {\n    return dedent(strings, ...values).split(\"\\n\").map(line => \" \".repeat(size) + line).join(\"\\n\")\n  }\n})\n\n\n\n\nfunction generateCodeSnippet({ tools, pre, post, response }) {\n  const lines = []\n\n  lines.push(dedent`\n    import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n    import { ChatOpenAI } from \"@langchain/openai\";\n  `)\n\n  if (tools) lines.push(`import { tool } from \"@langchain/core/tools\";`);  \n  if (response || tools) lines.push(`import { z } from \"zod\";`);\n\n  lines.push(\"\", dedent`\n    const agent = createReactAgent({\n      llm: new ChatOpenAI({ model: \"o4-mini\" }),\n  `)\n\n  if (tools) {\n    lines.push(dedent.offset(2)`\n      tools: [\n        tool(() => \"Sample tool output\", {\n          name: \"sampleTool\",\n          schema: z.object({}),\n        }),\n      ],\n    `)\n  }\n\n  if (pre) {\n    lines.push(dedent.offset(2)`\n      preModelHook: (state) => ({ llmInputMessages: state.messages }),\n    `)\n  }\n\n  if (post) {\n    lines.push(dedent.offset(2)`\n      postModelHook: (state) => state,\n    `)\n  }\n\n  if (response) {\n    lines.push(dedent.offset(2)`\n      responseFormat: z.object({ result: z.string() }),\n    `)\n  }\n\n  lines.push(`});`);\n\n  return lines.join(\"\\n\");\n}\n\nfunction render() {\n  const key = getKey();\n  document.getElementById(\"agent-graph-img\").src = `../assets/react_agent_graphs/${key}.svg`;\n\n  const state = {\n    tools: document.getElementById(\"tools\").checked,\n    pre: document.getElementById(\"preModelHook\").checked,\n    post: document.getElementById(\"postModelHook\").checked,\n    response: document.getElementById(\"responseFormat\").checked\n  };\n\n  document.getElementById(\"agent-code\").textContent = generateCodeSnippet(state);\n}\n\nfunction initializeWidget() {\n  render(); // no need for `await` here\n  document.querySelectorAll(\".agent-graph-features input\").forEach((input) => {\n    input.addEventListener(\"change\", render);\n  });\n}\n\n// Init for both full reload and SPA nav (used by MkDocs Material)\nwindow.addEventListener(\"DOMContentLoaded\", initializeWidget);\ndocument$.subscribe(initializeWidget);\n</script>\n\n<!-- File: docs/docs/agents/prebuilt.md (Tokens: ~126 | Category: subagent-persona) -->\n# Community Agents\n\nTo share your project, simply open a Pull Request adding an entry for your package in our [packages.yml](https://github.com/langchain-ai/langgraph/blob/main/docs/_scripts/third_party_page/packages.yml) file.\n\n[//]: # (This file is stub. Do not edit this file directly!)\n[//]: # (1. Update the `packages.yml` file in the `docs/_scripts/third_party_page` directory.)\n[//]: # (2. From the /docs directory, run `make build-prebuilt` to generate an updated version of this file for testing locally.)\n\n<!-- File: docs/docs/agents/run_agents.md (Tokens: ~300 | Category: subagent-persona) -->\n# Subagent: run_agents\n\nPath: `docs/docs/agents/run_agents.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/run_agents.md)\n\n<!-- File: docs/docs/agents/streaming.md (Tokens: ~300 | Category: subagent-persona) -->\n# Subagent: streaming\n\nPath: `docs/docs/agents/streaming.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/streaming.md)\n\n<!-- File: docs/docs/agents/tools.md (Tokens: ~300 | Category: subagent-persona) -->\n# Subagent: tools\n\nPath: `docs/docs/agents/tools.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/tools.md)\n\n<!-- File: docs/docs/agents/ui.md (Tokens: ~300 | Category: subagent-persona) -->\n# Subagent: ui\n\nPath: `docs/docs/agents/ui.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/langchain-ai/langgraphjs/HEAD/docs/docs/agents/ui.md)\n</yakaai_skills>"}