### Install Deno Integration Source: https://docs.langchain.com/oss/javascript/integrations/providers/deno Install the `@langchain/deno` package using npm, yarn, or pnpm to get started with Deno sandboxes. ```bash npm install @langchain/deno ``` ```bash yarn add @langchain/deno ``` ```bash pnpm add @langchain/deno ``` -------------------------------- ### Development Environment Setup Source: https://docs.langchain.com/oss/javascript/contributing/code Commands to install dependencies and verify tests pass before starting development in LangChain JS/TS projects using pnpm. ```bash pnpm install pnpm --filter {package-name} test # Verify tests pass before starting development ``` -------------------------------- ### Full LangGraph Example with Postgres Checkpointer Source: https://docs.langchain.com/oss/javascript/langgraph/add-memory This example demonstrates a complete LangGraph setup using `PostgresSaver` for state persistence, including node definition, graph compilation, and streaming events with a configurable thread ID. ```typescript import { ChatAnthropic } from "@langchain/anthropic"; import { StateGraph, StateSchema, MessagesValue, GraphNode, START } from "@langchain/langgraph"; import { PostgresSaver } from "@langchain/langgraph-checkpoint-postgres"; const State = new StateSchema({ messages: MessagesValue, }); const model = new ChatAnthropic({ model: "claude-haiku-4-5-20251001" }); const DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable"; const checkpointer = PostgresSaver.fromConnString(DB_URI); // await checkpointer.setup(); const callModel: GraphNode = async (state) => { const response = await model.invoke(state.messages); return { messages: [response] }; }; const builder = new StateGraph(State) .addNode("call_model", callModel) .addEdge(START, "call_model"); const graph = builder.compile({ checkpointer }); const config = { configurable: { thread_id: "1" } }; const stream1 = await graph.streamEvents( { messages: [{ role: "user", content: "hi! I'm bob" }] }, { ...config, version: "v3" } ); for await (const snapshot of stream1.values) { console.log(snapshot); } const stream2 = await graph.streamEvents( { messages: [{ role: "user", content: "what's my name?" }] }, { ...config, version: "v3" } ); for await (const snapshot of stream2.values) { console.log(snapshot); } ``` -------------------------------- ### Install @langchain/classic with bun Source: https://docs.langchain.com/oss/javascript/releases/langchain-v1 Install the legacy functionality package using bun. ```bash bun add @langchain/classic ``` -------------------------------- ### Install documentation dependencies Source: https://docs.langchain.com/oss/javascript/contributing/documentation Install the necessary project dependencies using Make. ```bash make install ``` -------------------------------- ### Install ExaRetriever Package Source: https://docs.langchain.com/oss/javascript/integrations/retrievers/exa Install the necessary packages to use the ExaRetriever. ```bash npm install @langchain/exa @langchain/core ``` ```bash yarn add @langchain/exa @langchain/core ``` ```bash pnpm add @langchain/exa @langchain/core ``` -------------------------------- ### Install dependencies Source: https://docs.langchain.com/oss/javascript/langchain/sql-agent Install the required LangChain packages and SQLite driver. ```bash npm i langchain @langchain/core sqlite3 zod ``` ```bash yarn add langchain @langchain/core sqlite3 zod ``` ```bash pnpm add langchain @langchain/core sqlite3 zod ``` -------------------------------- ### Initialize Filesystem Backend Source: https://docs.langchain.com/oss/javascript/deepagents/customization Setup for using the FilesystemBackend with a MemorySaver checkpointer. ```typescript import { createDeepAgent, FilesystemBackend } from "deepagents"; import { MemorySaver } from "@langchain/langgraph"; // Checkpointer is REQUIRED for human-in-the-loop const checkpointer = new MemorySaver(); ``` -------------------------------- ### Install Qdrant dependencies Source: https://docs.langchain.com/oss/javascript/integrations/vectorstores Installation commands for Qdrant vector store integration. ```bash npm install @langchain/qdrant @langchain/core ``` ```bash yarn add @langchain/qdrant @langchain/core ``` ```bash pnpm add @langchain/qdrant @langchain/core ``` -------------------------------- ### Install @langchain/classic with yarn Source: https://docs.langchain.com/oss/javascript/releases/langchain-v1 Install the legacy functionality package using yarn. ```bash yarn add @langchain/classic ``` -------------------------------- ### Install @langchain/classic with pnpm Source: https://docs.langchain.com/oss/javascript/releases/langchain-v1 Install the legacy functionality package using pnpm. ```bash pnpm install @langchain/classic ``` -------------------------------- ### Install Azure Dependencies Source: https://docs.langchain.com/oss/javascript/deepagents/customization Install the required packages for Azure integration. ```bash npm install @langchain/azure deepagents ``` ```bash pnpm install @langchain/azure deepagents ``` -------------------------------- ### Install project dependencies Source: https://docs.langchain.com/oss/javascript/deepagents/rag Install the required DeepAgents, LangChain, and utility packages. ```bash npm install deepagents langchain @langchain/core @langchain/openai @langchain/anthropic @langchain/google-genai @langchain/textsplitters @langchain/classic dotenv zod tsx ``` -------------------------------- ### Configure Deep Agent with Skills Source: https://docs.langchain.com/oss/javascript/deepagents/customization Examples demonstrating how to initialize a deep agent with skills using various backend storage options. ```ts import { createDeepAgent, StateBackend, type FileData } from "deepagents"; import { MemorySaver } from "@langchain/langgraph"; const checkpointer = new MemorySaver(); const backend = new StateBackend(); function createFileData(content: string): FileData { const now = new Date().toISOString(); return { content: content.split("\n"), created_at: now, modified_at: now, }; } const skillsFiles: Record = {}; const skillUrl = "https://raw.githubusercontent.com/langchain-ai/deepagentsjs/refs/heads/main/examples/skills/langgraph-docs/SKILL.md"; const response = await fetch(skillUrl); const skillContent = await response.text(); skillsFiles["/skills/langgraph-docs/SKILL.md"] = createFileData(skillContent); const agent = await createDeepAgent({ model: "google-genai:gemini-3.1-pro-preview", backend, checkpointer, // Required ! // IMPORTANT: deepagents skill source paths are virtual (POSIX) paths relative to the backend root. skills: ["/skills/"], }); const config = { configurable: { thread_id: `thread-${Date.now()}` } }; const result = await agent.invoke( { messages: [{ role: "user", content: "what is langraph?" }], files: skillsFiles, }, config, ); ``` ```ts import { createDeepAgent, StoreBackend, type FileData } from "deepagents"; import { InMemoryStore, MemorySaver } from "@langchain/langgraph"; const checkpointer = new MemorySaver(); const store = new InMemoryStore(); const backend = new StoreBackend({ namespace: () => ["filesystem"], }); function createFileData(content: string): FileData { const now = new Date().toISOString(); return { content: content.split("\n"), created_at: now, modified_at: now, }; } const skillUrl = "https://raw.githubusercontent.com/langchain-ai/deepagentsjs/refs/heads/main/examples/skills/langgraph-docs/SKILL.md"; const response = await fetch(skillUrl); const skillContent = await response.text(); const fileData = createFileData(skillContent); await store.put(["filesystem"], "/skills/langgraph-docs/SKILL.md", fileData); const agent = await createDeepAgent({ model: "google-genai:gemini-3.1-pro-preview", backend, store, checkpointer, // IMPORTANT: deepagents skill source paths are virtual (POSIX) paths relative to the backend root. skills: ["/skills/"], }); const config = { recursionLimit: 50, configurable: { thread_id: `thread-${Date.now()}` }, }; const result = await agent.invoke( { messages: [{ role: "user", content: "what is langraph?" }] }, config, ); ``` ```ts import { createDeepAgent, FilesystemBackend } from "deepagents"; import { MemorySaver } from "@langchain/langgraph"; const checkpointer = new MemorySaver(); const backend = new FilesystemBackend({ rootDir: process.cwd() }); const agent = await createDeepAgent({ model: "google-genai:gemini-3.1-pro-preview", backend, skills: ["./examples/skills/"], interruptOn: { read_file: true, write_file: true, delete_file: true, }, checkpointer, // Required! }); const config = { configurable: { thread_id: `thread-${Date.now()}` } }; const result = await agent.invoke( { messages: [{ role: "user", content: "what is langraph?" }] }, config, ); ``` -------------------------------- ### Configure DeepAgents with Model Backends Source: https://docs.langchain.com/oss/javascript/deepagents/customization Examples of initializing a DeepAgent with different model providers using CompositeBackend and StoreBackend. ```typescript const agent = createDeepAgent({ model: "fireworks:accounts/fireworks/models/glm-5p2", backend: new CompositeBackend(new StateBackend(), { "/memories/": new StoreBackend({ namespace: () => ["memories"], }), }), store, }); ``` ```typescript import { createDeepAgent, CompositeBackend, StateBackend, StoreBackend, } from "deepagents"; import { InMemoryStore } from "@langchain/langgraph"; const store = new InMemoryStore(); const agent = createDeepAgent({ model: "baseten:zai-org/GLM-5.2", backend: new CompositeBackend(new StateBackend(), { "/memories/": new StoreBackend({ namespace: () => ["memories"], }), }), store, }); ``` ```typescript import { createDeepAgent, CompositeBackend, StateBackend, StoreBackend, } from "deepagents"; import { InMemoryStore } from "@langchain/langgraph"; const store = new InMemoryStore(); const agent = createDeepAgent({ model: "ollama:north-mini-code-1.0", backend: new CompositeBackend(new StateBackend(), { "/memories/": new StoreBackend({ namespace: () => ["memories"], }), }), store, }); ``` -------------------------------- ### Fireworks Model Setup Source: https://docs.langchain.com/oss/javascript/deepagents/customization Initial setup code for the Fireworks provider integration. ```typescript import { createDeepAgent, StoreBackend, type FileData } from "deepagents"; import { InMemoryStore, MemorySaver } from "@langchain/langgraph"; const AGENTS_MD_URL = "https://raw.githubusercontent.com/langchain-ai/deepagents/refs/heads/main/examples/text-to-sql-agent/AGENTS.md"; async function fetchText(url: string): Promise { const res = await fetch(url); if (!res.ok) { throw new Error(`Failed to fetch ${url}: ${res.status} ${res.statusText}`); } return await res.text(); } const agentsMd = await fetchText(AGENTS_MD_URL); ``` -------------------------------- ### Configure DeepAgent with Memory Store Source: https://docs.langchain.com/oss/javascript/deepagents/customization Examples demonstrating agent initialization with different model providers using an InMemoryStore for file-based memory. ```typescript function createFileData(content: string): FileData { const now = new Date().toISOString(); return { content, mimeType: "text/plain", created_at: now, modified_at: now, }; } const store = new InMemoryStore(); const fileData = createFileData(agentsMd); await store.put(["filesystem"], "/AGENTS.md", fileData); const checkpointer = new MemorySaver(); const agent = await createDeepAgent({ model: "fireworks:accounts/fireworks/models/glm-5p2", backend: new StoreBackend({ namespace: () => ["filesystem"], }), store: store, checkpointer: checkpointer, memory: ["/AGENTS.md"], }); const result = await agent.invoke( { messages: [ { role: "user", content: "Please tell me what's in your memory files.", }, ], }, { configurable: { thread_id: "12345" } }, ); ``` ```typescript import { createDeepAgent, StoreBackend, type FileData } from "deepagents"; import { InMemoryStore, MemorySaver } from "@langchain/langgraph"; const AGENTS_MD_URL = "https://raw.githubusercontent.com/langchain-ai/deepagents/refs/heads/main/examples/text-to-sql-agent/AGENTS.md"; async function fetchText(url: string): Promise { const res = await fetch(url); if (!res.ok) { throw new Error(`Failed to fetch ${url}: ${res.status} ${res.statusText}`); } return await res.text(); } const agentsMd = await fetchText(AGENTS_MD_URL); function createFileData(content: string): FileData { const now = new Date().toISOString(); return { content, mimeType: "text/plain", created_at: now, modified_at: now, }; } const store = new InMemoryStore(); const fileData = createFileData(agentsMd); await store.put(["filesystem"], "/AGENTS.md", fileData); const checkpointer = new MemorySaver(); const agent = await createDeepAgent({ model: "baseten:zai-org/GLM-5.2", backend: new StoreBackend({ namespace: () => ["filesystem"], }), store: store, checkpointer: checkpointer, memory: ["/AGENTS.md"], }); const result = await agent.invoke( { messages: [ { role: "user", content: "Please tell me what's in your memory files.", }, ], }, { configurable: { thread_id: "12345" } }, ); ``` ```typescript import { createDeepAgent, StoreBackend, type FileData } from "deepagents"; import { InMemoryStore, MemorySaver } from "@langchain/langgraph"; const AGENTS_MD_URL = "https://raw.githubusercontent.com/langchain-ai/deepagents/refs/heads/main/examples/text-to-sql-agent/AGENTS.md"; async function fetchText(url: string): Promise { const res = await fetch(url); if (!res.ok) { throw new Error(`Failed to fetch ${url}: ${res.status} ${res.statusText}`); } return await res.text(); } const agentsMd = await fetchText(AGENTS_MD_URL); function createFileData(content: string): FileData { const now = new Date().toISOString(); return { content, mimeType: "text/plain", created_at: now, modified_at: now, }; } const store = new InMemoryStore(); const fileData = createFileData(agentsMd); await store.put(["filesystem"], "/AGENTS.md", fileData); const checkpointer = new MemorySaver(); const agent = await createDeepAgent({ model: "ollama:north-mini-code-1.0", backend: new StoreBackend({ namespace: () => ["filesystem"], }), store: store, checkpointer: checkpointer, memory: ["/AGENTS.md"], }); const result = await agent.invoke( { messages: [ { role: "user", content: "Please tell me what's in your memory files.", }, ], }, { configurable: { thread_id: "12345" } }, ); ``` -------------------------------- ### Install AWS Bedrock Dependencies Source: https://docs.langchain.com/oss/javascript/deepagents/customization Commands to install the required packages for AWS Bedrock integration. ```bash npm install @langchain/aws deepagents ``` ```bash pnpm install @langchain/aws deepagents ``` ```bash yarn add @langchain/aws deepagents ``` ```bash bun add @langchain/aws deepagents ``` -------------------------------- ### Configure CompositeBackend with various providers Source: https://docs.langchain.com/oss/javascript/deepagents/customization Examples of using CompositeBackend to route specific filesystem paths to a StoreBackend while using a StateBackend for general state. ```typescript import { createDeepAgent, CompositeBackend, StateBackend, StoreBackend, } from "deepagents"; import { InMemoryStore } from "@langchain/langgraph"; const store = new InMemoryStore(); const agent = createDeepAgent({ model: "google-genai:gemini-3.6-flash", backend: new CompositeBackend(new StateBackend(), { "/memories/": new StoreBackend({ namespace: () => ["memories"], }), }), store, }); ``` ```typescript import { createDeepAgent, CompositeBackend, StateBackend, StoreBackend, } from "deepagents"; import { InMemoryStore } from "@langchain/langgraph"; const store = new InMemoryStore(); const agent = createDeepAgent({ model: "openai:gpt-5.5", backend: new CompositeBackend(new StateBackend(), { "/memories/": new StoreBackend({ namespace: () => ["memories"], }), }), store, }); ``` ```typescript import { createDeepAgent, CompositeBackend, StateBackend, StoreBackend, } from "deepagents"; import { InMemoryStore } from "@langchain/langgraph"; const store = new InMemoryStore(); const agent = createDeepAgent({ model: "anthropic:claude-sonnet-4-6", backend: new CompositeBackend(new StateBackend(), { "/memories/": new StoreBackend({ namespace: () => ["memories"], }), }), store, }); ``` ```typescript import { createDeepAgent, CompositeBackend, StateBackend, StoreBackend, } from "deepagents"; import { InMemoryStore } from "@langchain/langgraph"; const store = new InMemoryStore(); const agent = createDeepAgent({ model: "openrouter:openrouter:z-ai/glm-5.2", backend: new CompositeBackend(new StateBackend(), { "/memories/": new StoreBackend({ namespace: () => ["memories"], }), }), store, }); ``` ```typescript import { createDeepAgent, CompositeBackend, StateBackend, StoreBackend, } from "deepagents"; import { InMemoryStore } from "@langchain/langgraph"; const store = new InMemoryStore(); ``` -------------------------------- ### Initialize DeepAgent with Memory Source: https://docs.langchain.com/oss/javascript/deepagents/customization Basic setup for an agent using an InMemoryStore and MemorySaver to access filesystem data. ```typescript const store = new InMemoryStore(); const fileData = createFileData(agentsMd); await store.put(["filesystem"], "/AGENTS.md", fileData); const checkpointer = new MemorySaver(); const agent = await createDeepAgent({ model: "openai:gpt-5.5", backend: new StoreBackend({ namespace: () => ["filesystem"], }), store: store, checkpointer: checkpointer, memory: ["/AGENTS.md"], }); const result = await agent.invoke( { messages: [ { role: "user", content: "Please tell me what's in your memory files.", }, ], }, { configurable: { thread_id: "12345" } }, ); ``` -------------------------------- ### Initialize project directory Source: https://docs.langchain.com/oss/javascript/deepagents/content-builder Create and enter the project directory. ```bash mkdir content-builder-agent cd content-builder-agent ``` -------------------------------- ### Initialize project directory Source: https://docs.langchain.com/oss/javascript/deepagents/deep-research Create and enter the project directory. ```bash mkdir deep-research-agent cd deep-research-agent ``` -------------------------------- ### Example output of split text Source: https://docs.langchain.com/oss/javascript/integrations/splitters/split_by_token An example of the text content after being split by the `TokenTextSplitter`. ```text Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. Last year COVID-19 kept us apart. This year we are finally together again. Tonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. With a duty to one another to the American people to the Constitution. ``` -------------------------------- ### Install @langchain/textsplitters Source: https://docs.langchain.com/oss/javascript/integrations/splitters/split_by_token Commands to install the `@langchain/textsplitters` package using different package managers. ```bash npm install @langchain/textsplitters ``` ```bash pnpm install @langchain/textsplitters ``` ```bash yarn add @langchain/textsplitters ``` ```bash bun add @langchain/textsplitters ``` -------------------------------- ### Project Structure Example Source: https://docs.langchain.com/oss/javascript/langgraph/studio An example of the expected project structure after setting up the LangGraph agent and configuration files. ```bash my-app/ ├── src │ └── agent.ts ├── .env ├── package.json └── langgraph.json ``` -------------------------------- ### Define and Integrate Custom Tools Source: https://docs.langchain.com/oss/javascript/deepagents/customization Create a custom internet search tool using Tavily and register it with a DeepAgent. The examples show configuration for Google, OpenAI, and Anthropic models. ```ts import { tool } from "langchain"; import { TavilySearch } from "@langchain/tavily"; import { createDeepAgent } from "deepagents"; import { z } from "zod"; const internetSearch = tool( async ({ query, maxResults = 5, topic = "general", includeRawContent = false, }: { query: string; maxResults?: number; topic?: "general" | "news" | "finance"; includeRawContent?: boolean; }) => { const tavilySearch = new TavilySearch({ maxResults, tavilyApiKey: process.env.TAVILY_API_KEY, includeRawContent, topic, }); return await tavilySearch._call({ query }); }, { name: "internet_search", description: "Run a web search", schema: z.object({ query: z.string().describe("The search query"), maxResults: z.number().optional().default(5), topic: z .enum(["general", "news", "finance"]) .optional() .default("general"), includeRawContent: z.boolean().optional().default(false), }), }, ); const agent = createDeepAgent({ model: "google-genai:gemini-3.6-flash", tools: [internetSearch], }); ``` ```ts import { tool } from "langchain"; import { TavilySearch } from "@langchain/tavily"; import { createDeepAgent } from "deepagents"; import { z } from "zod"; const internetSearch = tool( async ({ query, maxResults = 5, topic = "general", includeRawContent = false, }: { query: string; maxResults?: number; topic?: "general" | "news" | "finance"; includeRawContent?: boolean; }) => { const tavilySearch = new TavilySearch({ maxResults, tavilyApiKey: process.env.TAVILY_API_KEY, includeRawContent, topic, }); return await tavilySearch._call({ query }); }, { name: "internet_search", description: "Run a web search", schema: z.object({ query: z.string().describe("The search query"), maxResults: z.number().optional().default(5), topic: z .enum(["general", "news", "finance"]) .optional() .default("general"), includeRawContent: z.boolean().optional().default(false), }), }, ); const agent = createDeepAgent({ model: "openai:gpt-5.5", tools: [internetSearch], }); ``` ```ts import { tool } from "langchain"; import { TavilySearch } from "@langchain/tavily"; import { createDeepAgent } from "deepagents"; import { z } from "zod"; const internetSearch = tool( async ({ query, maxResults = 5, topic = "general", includeRawContent = false, }: { query: string; maxResults?: number; topic?: "general" | "news" | "finance"; includeRawContent?: boolean; }) => { const tavilySearch = new TavilySearch({ maxResults, tavilyApiKey: process.env.TAVILY_API_KEY, includeRawContent, topic, }); return await tavilySearch._call({ query }); }, { name: "internet_section", description: "Run a web search", schema: z.object({ query: z.string().describe("The search query"), maxResults: z.number().optional().default(5), topic: z .enum(["general", "news", "finance"]) .optional() .default("general"), includeRawContent: z.boolean().optional().default(false), }), }, ); const agent = createDeepAgent({ model: "anthropic:claude-sonnet-4-6", tools: [internetSearch], }); ``` -------------------------------- ### Install Composio LangChain with yarn or pnpm Source: https://docs.langchain.com/oss/javascript/integrations/tools/composio Installs the `@composio/langchain` and `@composio/core` packages using yarn or pnpm, providing alternative package managers for setup. ```bash yarn add @composio/langchain @composio/core ``` ```bash pnpm add @composio/langchain @composio/core ``` -------------------------------- ### Initialize Daytona Backend Source: https://docs.langchain.com/oss/javascript/deepagents/data-analysis Create a Daytona sandbox and initialize the backend. ```python from daytona import Daytona from langchain_daytona import DaytonaSandbox sandbox = Daytona().create() backend = DaytonaSandbox(sandbox=sandbox) ``` -------------------------------- ### Implement and Apply Custom Middleware Source: https://docs.langchain.com/oss/javascript/deepagents/customization Create a middleware function to intercept tool calls and register it with a DeepAgent instance. The examples show configuration for different model providers. ```typescript import { tool, createMiddleware } from "langchain"; import { createDeepAgent } from "deepagents"; import * as z from "zod"; const getWeather = tool( ({ city }: { city: string }) => { return `The weather in ${city} is sunny.`; }, { name: "get_weather", description: "Get the weather in a city.", schema: z.object({ city: z.string(), }), }, ); let callCount = 0; const logToolCallsMiddleware = createMiddleware({ name: "LogToolCallsMiddleware", wrapToolCall: async (request, handler) => { // Intercept and log every tool call - demonstrates cross-cutting concern callCount += 1; const toolName = request.toolCall.name; console.log(`[Middleware] Tool call #${callCount}: ${toolName}`); console.log( `[Middleware] Arguments: ${JSON.stringify(request.toolCall.args)}`, ); // Execute the tool call const result = await handler(request); // Log the result console.log(`[Middleware] Tool call #${callCount} completed`); return result; }, }); const agent = await createDeepAgent({ model: "anthropic:claude-sonnet-4-6", tools: [getWeather] as any, middleware: [logToolCallsMiddleware] as any, }); ``` ```typescript import { tool, createMiddleware } from "langchain"; import { createDeepAgent } from "deepagents"; import * as z from "zod"; const getWeather = tool( ({ city }: { city: string }) => { return `The weather in ${city} is sunny.`; }, { name: "get_weather", description: "Get the weather in a city.", schema: z.object({ city: z.string(), }), }, ); let callCount = 0; const logToolCallsMiddleware = createMiddleware({ name: "LogToolCallsMiddleware", wrapToolCall: async (request, handler) => { // Intercept and log every tool call - demonstrates cross-cutting concern callCount += 1; const toolName = request.toolCall.name; console.log(`[Middleware] Tool call #${callCount}: ${toolName}`); console.log( `[Middleware] Arguments: ${JSON.stringify(request.toolCall.args)}`, ); // Execute the tool call const result = await handler(request); // Log the result console.log(`[Middleware] Tool call #${callCount} completed`); return result; }, }); const agent = await createDeepAgent({ model: "openrouter:openrouter:z-ai/glm-5.2", tools: [getWeather] as any, middleware: [logToolCallsMiddleware] as any, }); ``` ```typescript import { tool, createMiddleware } from "langchain"; import { createDeepAgent } from "deepagents"; import * as z from "zod"; const getWeather = tool( ({ city }: { city: string }) => { return `The weather in ${city} is sunny.`; }, { name: "get_weather", description: "Get the weather in a city.", schema: z.object({ city: z.string(), }), }, ); let callCount = 0; const logToolCallsMiddleware = createMiddleware({ name: "LogToolCallsMiddleware", wrapToolCall: async (request, handler) => { // Intercept and log every tool call - demonstrates cross-cutting concern callCount += 1; const toolName = request.toolCall.name; console.log(`[Middleware] Tool call #${callCount}: ${toolName}`); console.log( `[Middleware] Arguments: ${JSON.stringify(request.toolCall.args)}`, ); // Execute the tool call const result = await handler(request); // Log the result console.log(`[Middleware] Tool call #${callCount} completed`); return result; }, }); const agent = await createDeepAgent({ model: "fireworks:accounts/fireworks/models/glm-5p2", tools: [getWeather] as any, middleware: [logToolCallsMiddleware] as any, }); ``` -------------------------------- ### Full LangGraph Example with MongoDB Checkpointer Source: https://docs.langchain.com/oss/javascript/langgraph/add-memory This example demonstrates a complete LangGraph setup using `MongoDBSaver` for state persistence, including node definition, graph compilation, and streaming events with a configurable thread ID. ```typescript import { ChatAnthropic } from "@langchain/anthropic"; import { StateGraph, StateSchema, MessagesValue, GraphNode, START } from "@langchain/langgraph"; import { MongoDBSaver } from "@langchain/langgraph-checkpoint-mongodb"; import { MongoClient } from "mongodb"; const State = new StateSchema({ messages: MessagesValue, }); const model = new ChatAnthropic({ model: "claude-haiku-4-5-20251001" }); const client = new MongoClient("mongodb://user:password@localhost:27017"); const checkpointer = new MongoDBSaver({ client, dbName: "langgraph" }); const callModel: GraphNode = async (state) => { const response = await model.invoke(state.messages); return { messages: [response] }; }; const builder = new StateGraph(State) .addNode("call_model", callModel) .addEdge(START, "call_model"); const graph = builder.compile({ checkpointer }); const config = { configurable: { thread_id: "1" } }; const stream1 = await graph.streamEvents( { messages: [{ role: "user", content: "hi! I'm bob" }] }, { ...config, version: "v3" } ); for await (const snapshot of stream1.values) { console.log(snapshot); } const stream2 = await graph.streamEvents( { messages: [{ role: "user", content: "what's my name?" }] }, { ...config, version: "v3" } ); for await (const snapshot of stream2.values) { console.log(snapshot); } ``` -------------------------------- ### Install Assistant-UI React Packages Source: https://docs.langchain.com/oss/javascript/langchain/frontend/integrations/assistant-ui Installs the necessary `@assistant-ui/react` and `@assistant-ui/react-markdown` packages using Bun. ```bash bun add @assistant-ui/react @assistant-ui/react-markdown ``` -------------------------------- ### Start the development server Source: https://docs.langchain.com/oss/javascript/contributing/documentation Launch the local development server with hot reload enabled. ```bash make dev ``` -------------------------------- ### Full LangGraph example for collecting and validating age Source: https://docs.langchain.com/oss/javascript/langgraph/interrupts This example demonstrates a complete LangGraph setup for collecting and validating user age. It includes state definition, node definition, conditional edges for looping, and execution with different inputs. ```typescript import { Command, MemorySaver, START, END, StateGraph, StateSchema, interrupt, } from "@langchain/langgraph"; import * as z from "zod"; const State = new StateSchema({ age: z.number().nullable(), pendingQuestion: z.string().nullable(), }); const builder = new StateGraph(State) .addNode("collectAge", (state) => { const question = state.pendingQuestion ?? "What is your age?"; const answer = interrupt(question); // called exactly once per invocation if (typeof answer === "number" && answer > 0) { return { age: answer, pendingQuestion: null }; } return { pendingQuestion: `'${answer}' is not a valid age. Please enter a positive number.` }; }) .addEdge(START, "collectAge") .addConditionalEdges("collectAge", (state) => state.age !== null ? END : "collectAge" ); const checkpointer = new MemorySaver(); const graph = builder.compile({ checkpointer }); const config = { configurable: { thread_id: "form-1" } }; const first = await graph.invoke({ age: null, pendingQuestion: null }, config); console.log(first.__interrupt__); // -> [{ value: "What is your age?", ... }] // Provide invalid data; the node re-prompts via the conditional edge const retry = await graph.invoke(new Command({ resume: "thirty" }), config); console.log(retry.__interrupt__); // -> [{ value: "'thirty' is not a valid age...", ... }] // Provide valid data; route returns END and the graph finishes const final = await graph.invoke(new Command({ resume: 30 }), config); console.log(final.age); // -> 30 ``` -------------------------------- ### Initialize Modal Backend Source: https://docs.langchain.com/oss/javascript/deepagents/data-analysis Lookup a Modal app and initialize the backend with a sandbox. ```python import modal from langchain_modal import ModalSandbox app = modal.App.lookup("your-app") modal_sandbox = modal.Sandbox.create(app=app) backend = ModalSandbox(sandbox=modal_sandbox) ``` -------------------------------- ### Full Graph Setup with MessagesValue Source: https://docs.langchain.com/oss/javascript/langgraph/use-graph-api Complete example showing state definition, node logic, and graph compilation using MessagesValue. ```typescript import { StateSchema, StateGraph, MessagesValue, GraphNode, START } from "@langchain/langgraph"; import * as z from "zod"; const State = new StateSchema({ // [!code highlight] messages: MessagesValue, extraField: z.number(), }); const node: GraphNode = (state) => { const newMessage = new AIMessage("Hello!"); return { messages: [newMessage], extraField: 10 }; }; const graph = new StateGraph(State) .addNode("node", node) .addEdge(START, "node") .compile(); ``` -------------------------------- ### Full code example: Tools and State Source: https://docs.langchain.com/oss/javascript/langgraph/quickstart Complete setup for defining tools, binding them to a model, and importing necessary graph components. ```typescript // Step 1: Define tools and model import { ChatAnthropic } from "@langchain/anthropic"; import { tool } from "@langchain/core/tools"; import * as z from "zod"; const model = new ChatAnthropic({ model: "claude-sonnet-4-6", temperature: 0, }); // Define tools const add = tool(({ a, b }) => a + b, { name: "add", description: "Add two numbers", schema: z.object({ a: z.number().describe("First number"), b: z.number().describe("Second number"), }), }); const multiply = tool(({ a, b }) => a * b, { name: "multiply", description: "Multiply two numbers", schema: z.object({ a: z.number().describe("First number"), b: z.number().describe("Second number"), }), }); const divide = tool(({ a, b }) => a / b, { name: "divide", description: "Divide two numbers", schema: z.object({ a: z.number().describe("First number"), b: z.number().describe("Second number"), }), }); // Augment the LLM with tools const toolsByName = { [add.name]: add, [multiply.name]: multiply, [divide.name]: divide, }; const tools = Object.values(toolsByName); const modelWithTools = model.bindTools(tools); ``` ```typescript // Step 2: Define state import { StateGraph, StateSchema, MessagesValue, ReducedValue, GraphNode, ConditionalEdgeRouter, START, END, } from "@langchain/langgraph"; import * as z from "zod"; ``` -------------------------------- ### Navigate to the documentation directory Source: https://docs.langchain.com/oss/javascript/contributing/documentation Change the working directory to the cloned repository folder. ```bash cd docs ``` -------------------------------- ### Setup Database and Environment Source: https://docs.langchain.com/oss/javascript/langchain/sql-agent Boilerplate for downloading the Chinook database and setting up the SQLite connection. ```typescript import fs from "node:fs/promises"; import path from "node:path"; import sqlite3 from "sqlite3"; import { SystemMessage, createAgent, tool } from "langchain"; import * as z from "zod"; const url = "https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db"; const localPath = path.resolve("Chinook.db"); async function resolveDbPath() { try { await fs.access(localPath); return localPath; } catch { // Chinook.db not present locally; download it. } const resp = await fetch(url); if (!resp.ok) throw new Error(`Failed to download DB. Status code: ${resp.status}`); const buf = Buffer.from(await resp.arrayBuffer()); await fs.writeFile(localPath, buf); return localPath; } // Below are minimal tools for demonstration purposes. async function runQuery(query: string): Promise[]> { const dbPath = await resolveDbPath(); const db = new sqlite3.Database(dbPath); return new Promise((resolve, reject) => { db.all(query, [], (err, rows) => { db.close(); if (err) reject(err); else resolve(rows as Record[]); }); }); } async function getSchema() { const tables = await runQuery( "SELECT sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';", ); return tables.map((row) => String(row.sql)).join("\n\n"); } const DENY_RE = /\b(INSERT|UPDATE|DELETE|ALTER|DROP|CREATE|REPLACE|TRUNCATE)\b/i; const HAS_LIMIT_TAIL_RE = /\blimit\b\s+\d+(\s*,\s*\d+)?\s*;?\s*$/i; function sanitizeSqlQuery(q: string) { let query = String(q ?? "").trim(); ``` -------------------------------- ### Define SQL Assistant Skills in TypeScript Source: https://docs.langchain.com/oss/javascript/langchain/multi-agent/skills-sql-assistant Define structured skills containing database schemas, business logic, and example queries to guide the SQL assistant. ```typescript import { context } from "langchain"; const SKILLS: Skill[] = [ { name: "sales_analytics", description: "Database schema and business logic for sales data analysis including customers, orders, and revenue.", content: context` # Sales Analytics Schema ## Tables ### customers - customer_id (PRIMARY KEY) - name - email - signup_date - status (active/inactive) - customer_tier (bronze/silver/gold/platinum) ### orders - order_id (PRIMARY KEY) - customer_id (FOREIGN KEY -> customers) - order_date - status (pending/completed/cancelled/refunded) - total_amount - sales_region (north/south/east/west) ### order_items - item_id (PRIMARY KEY) - order_id (FOREIGN KEY -> orders) - product_id - quantity - unit_price - discount_percent ## Business Logic **Active customers**: status = 'active' AND signup_date <= CURRENT_DATE - INTERVAL '90 days' **Revenue calculation**: Only count orders with status = 'completed'. Use total_amount from orders table, which already accounts for discounts. **Customer lifetime value (CLV)**: Sum of all completed order amounts for a customer. **High-value orders**: Orders with total_amount > 1000 ## Example Query -- Get top 10 customers by revenue in the last quarter SELECT c.customer_id, c.name, c.customer_tier, SUM(o.total_amount) as total_revenue FROM customers c JOIN orders o ON c.customer_id = o.customer_id WHERE o.status = 'completed' AND o.order_date >= CURRENT_DATE - INTERVAL '3 months' GROUP BY c.customer_id, c.name, c.customer_tier ORDER BY total_revenue DESC LIMIT 10;`, }, { name: "inventory_management", description: "Database schema and business logic for inventory tracking including products, warehouses, and stock levels.", content: context` # Inventory Management Schema ## Tables ### products - product_id (PRIMARY KEY) - product_name - sku - category - unit_cost - reorder_point (minimum stock level before reordering) - discontinued (boolean) ### warehouses - warehouse_id (PRIMARY KEY) - warehouse_name - location - capacity ### inventory - inventory_id (PRIMARY KEY) - product_id (FOREIGN KEY -> products) - warehouse_id (FOREIGN KEY -> warehouses) - quantity_on_hand - last_updated ### stock_movements - movement_id (PRIMARY KEY) - product_id (FOREIGN KEY -> products) - warehouse_id (FOREIGN KEY -> warehouses) - movement_type (inbound/outbound/transfer/adjustment) - quantity (positive for inbound, negative for outbound) - movement_date - reference_number ## Business Logic **Available stock**: quantity_on_hand from inventory table where quantity_on_hand > 0 **Products needing reorder**: Products where total quantity_on_hand across all warehouses is less than or equal to the product's reorder_point **Active products only**: Exclude products where discontinued = true unless specifically analyzing discontinued items **Stock valuation**: quantity_on_hand * unit_cost for each product ## Example Query -- Find products below reorder point across all warehouses SELECT p.product_id, p.product_name, p.reorder_point, SUM(i.quantity_on_hand) as total_stock, p.unit_cost, (p.reorder_point - SUM(i.quantity_on_hand)) as units_to_reorder FROM products p JOIN inventory i ON p.product_id = i.product_id WHERE p.discontinued = false GROUP BY p.product_id, p.product_name, p.reorder_point, p.unit_cost HAVING SUM(i.quantity_on_hand) <= p.reorder_point ORDER BY units_to_reorder DESC;`, }, ]; ``` -------------------------------- ### Set up agent with get_weather tool Source: https://docs.langchain.com/oss/javascript/langchain/test/evals Common setup for trajectory evaluator examples. Creates an agent with a single get_weather tool that returns weather information for a given city. ```typescript import { createAgent } from "langchain"; import { tool } from "@langchain/core/tools"; import { HumanMessage, AIMessage, ToolMessage } from "@langchain/core/messages"; import { createTrajectoryMatchEvaluator } from "agentevals"; import * as z from "zod"; const getWeather = tool( async ({ city }) => { return `It's 75 degrees and sunny in ${city}.`; }, { name: "get_weather", description: "Get weather information for a city.", schema: z.object({ city: z.string() }), } ); const agent = createAgent({ model: "claude-sonnet-4-6", tools: [getWeather], }); ``` -------------------------------- ### Example .env file for API keys Source: https://docs.langchain.com/oss/javascript/langchain/test/integration-testing Shows how to define an API key in a .env file, which should be excluded from version control. ```bash OPENAI_API_KEY=sk-... ``` -------------------------------- ### sandbox.start() Source: https://docs.langchain.com/oss/javascript/integrations/providers/daytona Starts a stopped Daytona sandbox. ```APIDOC ## sandbox.start() ### Description Starts a previously stopped Daytona sandbox, making it ready for command execution. ### Method `async start(): Promise` ### Parameters None. ### Request Example ```typescript await reconnected.start(); ``` ### Response #### Success Response Returns a `Promise` that resolves when the sandbox has successfully started. ```typescript // Sandbox is now running ``` ``` -------------------------------- ### List metadata keys in TypeScript Source: https://docs.langchain.com/oss/javascript/integrations/document_loaders/web_loaders/langsmith Get an array of all top-level keys present in a document's metadata object. The example output shows the typical keys found. ```typescript console.log(Object.keys(docs[0].metadata)) ``` ```python [ 'id', 'created_at', 'modified_at', 'name', 'dataset_id', 'source_run_id', 'metadata', 'inputs', 'outputs' ] ```