### Setup Agent with Tools Source: https://docs.langchain.com/oss/javascript/langchain/test/evals Common setup for agent trajectory evaluation examples, including importing necessary modules and defining a sample tool and agent. ```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], }); ``` -------------------------------- ### Install and Test Package Source: https://docs.langchain.com/oss/javascript/contributing/code Install all dependencies and run tests for a specific package to verify the development environment setup. ```bash pnpm install pnpm --filter {package-name} test ``` -------------------------------- ### PostgreSQL Store Setup and Agent with OpenAI Source: https://docs.langchain.com/oss/javascript/langchain/long-term-memory This example demonstrates setting up a PostgreSQL store and creating an agent that uses it to retrieve user information. It configures the agent with an OpenAI model and context schema. ```typescript import * as z from "zod"; import { createAgent, tool, type ToolRuntime } from "langchain"; import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store"; const DB_URI = process.env.POSTGRES_URI ?? "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable"; const store = PostgresStore.fromConnString(DB_URI); await store.setup(); const contextSchema = z.object({ userId: z.string() }); await store.put(["users"], "user_123", { name: "John Smith", language: "English", }); const getUserInfo = tool( async (_, runtime: ToolRuntime>) => { const userId = runtime.context.userId; if (!userId) throw new Error("userId is required"); const userInfo = await runtime.store.get(["users"], userId); return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user"; }, { name: "getUserInfo", description: "Look up user info by userId from the store.", schema: z.object({}), }, ); const agent = createAgent({ model: "openai:gpt-5.5", tools: [getUserInfo], contextSchema, store, }); await agent.invoke( { messages: [{ role: "user", content: "look up user information" }] }, { context: { userId: "user_123" } }, ); ``` -------------------------------- ### Main Function Example Source: https://docs.langchain.com/oss/javascript/deepagents/skills Demonstrates the setup and execution of a DeepAgent, including initializing an in-memory store, seeding skills, creating a sandbox, and configuring the agent with a backend and middleware. ```typescript async function main() { const store = new InMemoryStore(); await seedSkillStore(store); const sandbox = await DaytonaSandbox.create({ language: "python", timeout: 300, }); const backend = new CompositeBackend(sandbox, { "/skills/": new StoreBackend({ store, namespace: () => [...SKILLS_SHARED_NAMESPACE], } as any), }); try { const agent = await createDeepAgent({ model: "fireworks:accounts/fireworks/models/qwen3p5-397b-a17b", backend, skills: ["/skills/"], store, middleware: [createSkillSandboxSyncMiddleware(backend)], }); } finally { await sandbox.close(); } } main().catch((err) => { console.error(err); process.exitCode = 1; }); ``` -------------------------------- ### PostgreSQL Store Setup and Agent with Google Gemini Source: https://docs.langchain.com/oss/javascript/langchain/long-term-memory This example demonstrates setting up a PostgreSQL store and creating an agent that uses it to retrieve user information. It configures the agent with a specific model and context schema. ```typescript import * as z from "zod"; import { createAgent, tool, type ToolRuntime } from "langchain"; import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store"; const DB_URI = process.env.POSTGRES_URI ?? "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable"; const store = PostgresStore.fromConnString(DB_URI); await store.setup(); const contextSchema = z.object({ userId: z.string() }); await store.put(["users"], "user_123", { name: "John Smith", language: "English", }); const getUserInfo = tool( async (_, runtime: ToolRuntime>) => { const userId = runtime.context.userId; if (!userId) throw new Error("userId is required"); const userInfo = await runtime.store.get(["users"], userId); return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user"; }, { name: "getUserInfo", description: "Look up user info by userId from the store.", schema: z.object({}), }, ); const agent = createAgent({ model: "google-genai:gemini-3.5-flash", tools: [getUserInfo], contextSchema, store, }); await agent.invoke( { messages: [{ role: "user", content: "look up user information" }] }, { context: { userId: "user_123" } }, ); ``` -------------------------------- ### Complete Example: Customer Support with Middleware Source: https://docs.langchain.com/oss/javascript/langchain/multi-agent/handoffs This example demonstrates a full customer support agent setup. It defines a state schema, tools that update the state via Commands, and middleware that dynamically configures the agent based on the current step in the state. A MemorySaver is used to persist state across turns. ```typescript import { createAgent, createMiddleware, tool, ToolMessage, type ToolRuntime, } from "langchain"; import { Command, MemorySaver, StateSchema } from "@langchain/langgraph"; import { z } from "zod"; // 1. Define state with current_step tracker const SupportState = new StateSchema({ currentStep: z.string().default("triage"), warrantyStatus: z.string().optional(), }); // 2. Tools update currentStep via Command const recordWarrantyStatus = tool( async ({ status }, config: ToolRuntime) => { return new Command({ update: { messages: [ new ToolMessage({ content: `Warranty status recorded: ${status}`, tool_call_id: config.toolCallId, }), ], warrantyStatus: status, // Transition to next step currentStep: "specialist", }, }); }, { name: "record_warranty_status", description: "Record warranty status and transition", schema: z.object({ status: z.string() }), } ); // 3. Middleware applies dynamic configuration based on currentStep const applyStepConfig = createMiddleware({ name: "applyStepConfig", stateSchema: SupportState, wrapModelCall: async (request, handler) => { const step = request.state.currentStep || "triage"; // Map steps to their configurations const configs = { triage: { prompt: "Collect warranty information...", tools: [recordWarrantyStatus], }, specialist: { prompt: `Provide solutions based on warranty: ${request.state.warrantyStatus}`, tools: [provideSolution, escalate], }, }; const config = configs[step as keyof typeof configs]; return handler({ ...request, systemPrompt: config.prompt, tools: config.tools, }); }, }); // 4. Create agent with middleware const agent = createAgent({ model, tools: [recordWarrantyStatus, provideSolution, escalate], middleware: [applyStepConfig], checkpointer: new MemorySaver(), // Persist state across turns }); ``` -------------------------------- ### Start Falkordb with Docker Source: https://docs.langchain.com/oss/javascript/integrations/tools/falkordb Run Falkordb locally using Docker for easy setup and testing. ```bash docker run -p 6379:6379 -it --rm falkordb/falkordb:latest ``` -------------------------------- ### PostgreSQL Store Setup and Agent with Anthropic Source: https://docs.langchain.com/oss/javascript/langchain/long-term-memory This example demonstrates setting up a PostgreSQL store and creating an agent that uses it to retrieve user information. It configures the agent with an Anthropic model and context schema. ```typescript import * as z from "zod"; import { createAgent, tool, type ToolRuntime } from "langchain"; import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store"; const DB_URI = process.env.POSTGRES_URI ?? "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable"; const store = PostgresStore.fromConnString(DB_URI); await store.setup(); const contextSchema = z.object({ userId: z.string() }); await store.put(["users"], "user_123", { name: "John Smith", language: "English", }); const getUserInfo = tool( ``` -------------------------------- ### Run a setup script after sandbox creation Source: https://docs.langchain.com/oss/javascript/deepagents/code/remote-sandboxes The `--sandbox-setup` flag allows specifying a path to a script that will be executed within the sandbox immediately after its creation. This example uses a `setup.sh` script with the Modal provider. ```bash dcode --sandbox modal --sandbox-setup ./setup.sh ``` -------------------------------- ### Full Example: Postgres Checkpointer with LangGraph Source: https://docs.langchain.com/oss/javascript/langgraph/add-memory Demonstrates a complete LangGraph setup using the Postgres checkpointer, including state definition, model invocation, and streaming. ```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" } }; for await (const chunk of await graph.stream( { messages: [{ role: "user", content: "hi! I'm bob" }] }, { ...config, streamMode: "values" } )) { console.log(chunk.messages.at(-1)?.content); } for await (const chunk of await graph.stream( { messages: [{ role: "user", content: "what's my name?" }] }, { ...config, streamMode: "values" } )) { console.log(chunk.messages.at(-1)?.content); } ``` -------------------------------- ### Running a Setup Script in a Sandbox Source: https://docs.langchain.com/oss/javascript/deepagents/code/remote-sandboxes Use the --sandbox-setup flag with a shell script to run commands inside the sandbox after it's created. This is useful for tasks like cloning repositories or installing dependencies. ```bash #!/bin/bash set -e ``` -------------------------------- ### Complete Example: Sales and Support Agents with Handoffs Source: https://docs.langchain.com/oss/javascript/langchain/multi-agent/handoffs Demonstrates a multi-agent system with distinct sales and support agent nodes. Handoff tools facilitate conversation transfer between these agents. This setup requires careful context engineering for message passing. ```typescript import { StateGraph, START, END, StateSchema, MessagesValue, Command, ConditionalEdgeRouter, GraphNode, } from "@langchain/langgraph"; import { createAgent, AIMessage, ToolMessage } from "langchain"; import { tool, ToolRuntime } from "@langchain/core/tools"; import { z } from "zod/v4"; // 1. Define state with active_agent tracker const MultiAgentState = new StateSchema({ messages: MessagesValue, activeAgent: z.string().optional(), }); // 2. Create handoff tools const transferToSales = tool( async (_, runtime: ToolRuntime) => { const lastAiMessage = [...runtime.state.messages] // [!code highlight] .reverse() // [!code highlight] .find(AIMessage.isInstance); // [!code highlight] const transferMessage = new ToolMessage({ // [!code highlight] content: "Transferred to sales agent from support agent", // [!code highlight] tool_call_id: runtime.toolCallId, // [!code highlight] }); // [!code highlight] return new Command({ goto: "sales_agent", update: { activeAgent: "sales_agent", messages: [lastAiMessage, transferMessage].filter(Boolean), // [!code highlight] }, graph: Command.PARENT, }); }, { name: "transfer_to_sales", description: "Transfer to the sales agent.", schema: z.z.object({}), } ); const transferToSupport = tool( async (_, runtime: ToolRuntime) => { const lastAiMessage = [...runtime.state.messages] // [!code highlight] .reverse() // [!code highlight] .find(AIMessage.isInstance); // [!code highlight] const transferMessage = new ToolMessage({ // [!code highlight] content: "Transferred to support agent from sales agent", // [!code highlight] tool_call_id: runtime.toolCallId, // [!code highlight] }); // [!code highlight] return new Command({ goto: "support_agent", update: { activeAgent: "support_agent", messages: [lastAiMessage, transferMessage].filter(Boolean), // [!code highlight] }, graph: Command.PARENT, }); }, { name: "transfer_to_support", description: "Transfer to the support agent.", schema: z.z.object({}), } ); // 3. Create agents with handoff tools const salesAgent = createAgent({ model: "google_genai:gemini-3.5-flash", tools: [transferToSupport], systemPrompt: "You are a sales agent. Help with sales inquiries. If asked about technical issues or support, transfer to the support agent.", }); const supportAgent = createAgent({ model: "google_genai:gemini-3.5-flash", tools: [transferToSales], systemPrompt: ``` -------------------------------- ### Installation Source: https://docs.langchain.com/oss/javascript/integrations/retrievers/perplexity_search Install the necessary packages for the PerplexitySearchRetriever integration. ```APIDOC ## Installation This retriever lives in the `@langchain/perplexity` package: ```bash npm npm install @langchain/perplexity @langchain/core ``` ```bash yarn yarn add @langchain/perplexity @langchain/core ``` ```bash pnpm pnpm add @langchain/perplexity @langchain/core ``` ``` -------------------------------- ### SQL Agent Setup and Execution Source: https://docs.langchain.com/oss/javascript/langchain/sql-agent Demonstrates how to set up a SQL agent using Langchain, including defining tools, system prompts, and creating the agent instance. This is useful for building conversational interfaces to databases. ```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(); const semis = [...query].filter((c) => c === ";").length; if (semis > 1 || (query.endsWith(";") && query.slice(0, -1).includes(";"))) { throw new Error("multiple statements are not allowed."); } query = query.replace(/;+\s*$/g, "").trim(); if (!query.toLowerCase().startsWith("select")) { throw new Error("Only SELECT statements are allowed"); } if (DENY_RE.test(query)) { throw new Error("DML/DDL detected. Only read-only queries are permitted."); } if (!HAS_LIMIT_TAIL_RE.test(query)) { query += " LIMIT 5"; } return query; } const executeSql = tool( async ({ query }) => { const q = sanitizeSqlQuery(query); try { const result = await runQuery(q); return JSON.stringify(result, null, 2); } catch (e) { const message = e instanceof Error ? e.message : String(e); throw new Error(message); } }, { name: "execute_sql", description: "Execute a READ-ONLY SQLite SELECT query and return results.", schema: z.object({ query: z.string().describe("SQLite SELECT query to execute (read-only)."), }), }, ); const getSystemPrompt = async () => new SystemMessage(`You are a careful SQLite analyst. Authoritative schema (do not invent columns/tables): ${await getSchema()} Rules: - Think step-by-step. - When you need data, call the tool \`execute_sql\` with ONE SELECT query. - Read-only only; no INSERT/UPDATE/DELETE/ALTER/DROP/CREATE/REPLACE/TRUNCATE. - Limit to 5 rows unless user explicitly asks otherwise. - If the tool returns 'Error:', revise the SQL and try again. - Limit the number of attempts to 5. - If you are not successful after 5 attempts, return a note to the user. `); export const agent = createAgent({ model: "fireworks:accounts/fireworks/models/qwen3p5-397b-a17b", tools: [executeSql], systemPrompt: await getSystemPrompt(), }); ``` -------------------------------- ### Create a Simple LangGraph Hello World Example Source: https://docs.langchain.com/oss/javascript/langgraph/overview A basic example demonstrating how to set up a simple stateful graph with a mock LLM node and invoke it. ```typescript import { StateSchema, MessagesValue, type GraphNode, StateGraph, START, END } from "@langchain/langgraph"; const State = new StateSchema({ messages: MessagesValue, }); const mockLlm: GraphNode = (state) => { return { messages: [{ role: "ai", content: "hello world" }] }; }; const graph = new StateGraph(State) .addNode("mock_llm", mockLlm) .addEdge(START, "mock_llm") .addEdge("mock_llm", END) .compile(); await graph.invoke({ messages: [{ role: "user", content: "hi!" }] }); ``` -------------------------------- ### Start ACP Server Programmatically with `startServer` Source: https://docs.langchain.com/oss/javascript/deepagents/acp Use the `startServer` convenience function for a one-call setup and start of an ACP server. Configure agent name and description. ```typescript import { startServer } from "deepagents-acp"; const server = await startServer({ agents: { name: "coding-assistant", description: "AI coding assistant with filesystem access", }, workspaceRoot: process.cwd(), }); ``` -------------------------------- ### Specifying a sandbox setup script Source: https://docs.langchain.com/oss/javascript/deepagents/code Provide a path to a setup script that will run in the sandbox after it has been created. ```bash dcode --sandbox-setup PATH ``` -------------------------------- ### Starting a New Conversation (Angular) Source: https://docs.langchain.com/oss/javascript/langchain/frontend/message-queues An Angular example demonstrating how to start a new conversation by setting the `threadId` to null. This clears the current thread binding, and the next submission will create a new thread. ```ts threadId = signal(null); stream = injectStream({ threadId: this.threadId, onThreadId: (id) => this.threadId.set(id), }); // In template: // ``` -------------------------------- ### Install Baseten and Select Model Source: https://docs.langchain.com/oss/javascript/deepagents/code/providers Install the Baseten extra and select a Baseten model. Requires a BASETEN_API_KEY. ```text /install baseten /model ``` ```bash BASETEN_API_KEY="your-api-key" dcode --model baseten:moonshotai/Kimi-K2.6 ``` -------------------------------- ### Full LangGraph Example with Human Review Interrupt Source: https://docs.langchain.com/oss/javascript/langgraph/interrupts This example demonstrates a complete LangGraph setup that includes a node for human review using `interrupt`. It shows how to define the state, build the graph, invoke it, and resume with edited content. ```typescript import { Command, MemorySaver, START, END, StateGraph, StateSchema, interrupt, } from "@langchain/langgraph"; import * as z from "zod"; const State = new StateSchema({ generatedText: z.string(), }); const builder = new StateGraph(State) .addNode("review", async (state) => { // Ask a reviewer to edit the generated content const updated = interrupt({ instruction: "Review and edit this content", content: state.generatedText, }); return { generatedText: updated }; }) .addEdge(START, "review") .addEdge("review", END); const checkpointer = new MemorySaver(); const graph = builder.compile({ checkpointer }); const config = { configurable: { thread_id: "review-42" } }; const initial = await graph.invoke({ generatedText: "Initial draft" }, config); console.log(initial.__interrupt__); // [{ value: { instruction: ..., content: ... } }] // Resume with the edited text from the reviewer const finalState = await graph.invoke( new Command({ resume: "Improved draft after review" }), config, ); console.log(finalState.generatedText); // -> "Improved draft after review" ``` -------------------------------- ### Full Example: Deleting Messages in LangGraph Source: https://docs.langchain.com/oss/javascript/langgraph/add-memory Demonstrates a complete LangGraph setup that includes a node for deleting messages, a model call node, and message history management. This example shows how to stream events and log the resulting message history. ```typescript import { RemoveMessage } from "@langchain/core/messages"; import { ChatAnthropic } from "@langchain/anthropic"; import { StateGraph, StateSchema, MessagesValue, GraphNode, START, MemorySaver } from "@langchain/langgraph"; const State = new StateSchema({ messages: MessagesValue, }); const model = new ChatAnthropic({ model: "claude-3-5-sonnet-20241022" }); const deleteMessages: GraphNode = (state) => { const messages = state.messages; if (messages.length > 2) { // remove the earliest two messages return { messages: messages.slice(0, 2).map(m => new RemoveMessage({ id: m.id })) }; } return {}; }; const callModel: GraphNode = async (state) => { const response = await model.invoke(state.messages); return { messages: [response] }; }; const builder = new StateGraph(State) .addNode("call_model", callModel) .addNode("delete_messages", deleteMessages) .addEdge(START, "call_model") .addEdge("call_model", "delete_messages"); const checkpointer = new MemorySaver(); const app = builder.compile({ checkpointer }); const config = { configurable: { thread_id: "1" } }; for await (const event of await app.stream( { messages: [{ role: "user", content: "hi! I'm bob" }] }, { ...config, streamMode: "values" } )) { console.log(event.messages.map(message => [message.getType(), message.content])); } for await (const event of await app.stream( { messages: [{ role: "user", content: "what's my name?" }] }, { ...config, streamMode: "values" } )) { console.log(event.messages.map(message => [message.getType(), message.content])); } ``` -------------------------------- ### Start Local Development Server Source: https://docs.langchain.com/oss/javascript/contributing/documentation Start a local development server with hot reload for instant preview of your documentation changes. ```bash make dev ``` -------------------------------- ### Create Agent with Ollama Source: https://docs.langchain.com/oss/javascript/langchain/overview Example of creating an agent using the Ollama model. Ensure you have Ollama installed and the devstral-2 model available. ```typescript // First install: npm install langchain zod import { createAgent, tool } from "langchain"; import * as z from "zod"; const getWeather = tool( (input) => `It's always sunny in ${input.city}!`, { name: "get_weather", description: "Get the weather for a given city", schema: z.object({ city: z.string().describe("The city to get the weather for"), }), } ); const agent = createAgent({ model: "ollama:devstral-2", tools: [getWeather], }); console.log( await agent.invoke({ messages: [{ role: "user", content: "What's the weather in San Francisco?" }], }) ); ``` -------------------------------- ### Invoke Chat Model Source: https://docs.langchain.com/oss/javascript/langchain/models Invoke a chat model with a user message and get a response. This example assumes a model has already been initialized. ```typescript const response = await model.invoke("Why do parrots talk?"); ``` -------------------------------- ### Create Agent with AWS Bedrock Source: https://docs.langchain.com/oss/javascript/langchain/overview Example of creating an agent using AWS Bedrock. Requires installation of @langchain/aws and AWS credentials configuration. ```typescript // First install: npm install langchain zod @langchain/aws import { createAgent, tool } from "langchain"; import * as z from "zod"; const getWeather = tool( (input) => `It's always sunny in ${input.city}!`, { name: "get_weather", description: "Get the weather for a given city", schema: z.object({ city: z.string().describe("The city to get the weather for"), }), } ); const agent = createAgent({ model: "bedrock:gpt-5.5", tools: [getWeather], }); console.log( await agent.invoke({ messages: [{ role: "user", content: "What's the weather in San Francisco?" }], }) ); ``` -------------------------------- ### LangGraph StateSchema with a Cycle Source: https://docs.langchain.com/oss/javascript/langgraph/errors/GRAPH_RECURSION_LIMIT This example demonstrates a LangGraph StateSchema setup that creates a cycle between nodes 'a' and 'b', which can lead to exceeding the recursion limit. ```typescript import { StateGraph, StateSchema } from "@langchain/langgraph"; import { z } from "zod/v4"; const State = new StateSchema({ someKey: z.string(), }); const builder = new StateGraph(State) .addNode("a", ...) .addNode("b", ...) .addEdge("a", "b") .addEdge("b", "a") ... const graph = builder.compile(); ``` -------------------------------- ### Create Agent with Azure OpenAI Source: https://docs.langchain.com/oss/javascript/langchain/overview Example of creating an agent using Azure OpenAI. Requires installation of @langchain/openai and configuration of Azure OpenAI service. ```typescript // First install: npm install langchain zod @langchain/openai import { createAgent, tool } from "langchain"; import * as z from "zod"; const getWeather = tool( (input) => `It's always sunny in ${input.city}!`, { name: "get_weather", description: "Get the weather for a given city", schema: z.object({ city: z.string().describe("The city to get the weather for"), }), } ); const agent = createAgent({ model: "azure_openai:gpt-5.5", tools: [getWeather], }); console.log( await agent.invoke({ messages: [{ role: "user", content: "What's the weather in San Francisco?" }], }) ); ``` -------------------------------- ### Structure Frontend App with CopilotKit Source: https://docs.langchain.com/oss/javascript/langchain/frontend/integrations/copilotkit Wrap your React app in CopilotKit and configure the runtime URL. This example shows basic setup and usage of useAgentContext. ```tsx import { CopilotKit } from "@copilotkit/react-core"; import { CopilotChat, useAgentContext } from "@copilotkit/react-core/v2"; import { s } from "@hashbrownai/core"; import { useChatKit } from "@/components/chat/chat-kit"; import { chatTheme } from "@/lib/chat-theme"; export function App() { return ( ); } function Page() { const chatKit = useChatKit(); useAgentContext({ description: "output_schema", value: s.toJsonSchema(chatKit.schema), }); return ; } ``` -------------------------------- ### Skill File Structure Example Source: https://docs.langchain.com/oss/javascript/deepagents/skills Illustrates a recommended file structure for organizing skills and their supporting reference files, keeping the main SKILL.md concise. ```tree ``` -------------------------------- ### Installing an optional extra Source: https://docs.langchain.com/oss/javascript/deepagents/code Install an optional extra package, such as 'quickjs' or 'daytona', then exit. Use `--package` to specify a custom provider package and `--yes` to skip confirmation. ```bash dcode --install NAME ``` ```bash dcode --install NAME --package ``` ```bash dcode --install NAME --yes ``` -------------------------------- ### Clone and Run Agent Chat UI Repository Source: https://docs.langchain.com/oss/javascript/langchain/ui Clone the Agent Chat UI repository, install dependencies, and start the development server for local customization. ```bash git clone https://github.com/langchain-ai/agent-chat-ui.git cd agent-chat-ui pnpm install pnpm dev ``` -------------------------------- ### Run Local YDB Instance with Docker Source: https://docs.langchain.com/oss/javascript/integrations/vectorstores/ydb Starts a local YDB instance using Docker for development and testing purposes. Ensure Docker is installed and running. ```bash docker run -d -p 2136:2136 --name ydb-langchain -e YDB_USE_IN_MEMORY_PDISKS=true -h localhost ydbplatform/local-ydb:trunk ``` -------------------------------- ### Install @modelcontextprotocol/sdk Source: https://docs.langchain.com/oss/javascript/deepagents/mcp Install the necessary SDK package to begin creating MCP servers. ```bash npm install @modelcontextprotocol/sdk ``` -------------------------------- ### Full Example: MongoDB Checkpointer with LangGraph Source: https://docs.langchain.com/oss/javascript/langgraph/add-memory Demonstrates a complete LangGraph setup using the MongoDB checkpointer, including state definition, model invocation, and streaming. ```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" } }; for await (const chunk of await graph.stream( { messages: [{ role: "user", content: "hi! I'm bob" }] }, { ...config, streamMode: "values" } )) { console.log(chunk.messages.at(-1)?.content); } for await (const chunk of await graph.stream( { messages: [{ role: "user", content: "what's my name?" }] }, { ...config, streamMode: "values" } )) { console.log(chunk.messages.at(-1)?.content); } ``` -------------------------------- ### Non-Interactive Startup Command Example Source: https://docs.langchain.com/oss/javascript/deepagents/code/overview This example shows how to run `dcode` non-interactively, executing a startup command like `git status` before the main task. ```bash # Non-interactive with startup command: show git status before the task runs dcode --startup-cmd "git status" ``` -------------------------------- ### Basic OpenAI Moderation Middleware Setup Source: https://docs.langchain.com/oss/javascript/integrations/providers/openai Sets up an agent with OpenAI moderation for input and output checks. This is a common starting point for ensuring content safety. ```typescript import { createAgent, openAIModerationMiddleware } from "langchain"; const agent = createAgent({ model: "openai:gpt-5.5", tools: [searchTool, databaseTool], middleware: [ openAIModerationMiddleware({ model: "openai:gpt-5.5", moderationModel: "omni-moderation-latest", checkInput: true, checkOutput: true, exitBehavior: "end", }), ], }); ``` -------------------------------- ### Install Assistant UI Packages Source: https://docs.langchain.com/oss/javascript/langchain/frontend/integrations/assistant-ui Install the necessary Assistant UI packages using Bun. This includes the core React components and the Markdown renderer. ```bash bun add @assistant-ui/react @assistant-ui/react-markdown ``` -------------------------------- ### Create and Run Agent Chat UI Project Source: https://docs.langchain.com/oss/javascript/langchain/ui Use npx to create a new Agent Chat UI project, then install dependencies and start the development server. ```bash npx create-agent-chat-app --project-name my-chat-ui cd my-chat-ui pnpm install pnpm dev ``` -------------------------------- ### 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 ``` -------------------------------- ### Assistant-Scoped Sandbox Example Source: https://docs.langchain.com/oss/javascript/deepagents/going-to-production Illustrates an assistant-scoped sandbox where all threads share a single environment. This is useful for maintaining state across conversations, such as cloned repositories or installed dependencies. ```typescript import { Client } from "@langchain/langgraph-sdk"; const client = new Client({ apiUrl: "", apiKey: "" }); // Conversation 1: clone and set up the project const thread1 = await client.threads.create(); for await (const chunk of client.runs.stream( thread1.thread_id, "agent", { input: { messages: [{ role: "human", content: "Clone https://github.com/org/repo and install dependencies" }] } }, )) { console.log(chunk.data); } // Conversation 2: repo and dependencies are still there const thread2 = await client.threads.create(); for await (const chunk of client.runs.stream( thread2.thread_id, "agent", { input: { messages: [{ role: "human", content: "Run the test suite and fix any failures" }] } }, )) { console.log(chunk.data); } ``` -------------------------------- ### SQL Agent Setup with Langchain.js Source: https://docs.langchain.com/oss/javascript/langchain/sql-agent This snippet demonstrates the setup for a SQL agent, including defining tools, fetching the schema, and creating the agent with a specific model and system prompt. It requires Langchain.js and Zod for schema validation. ```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(); const semis = [...query].filter((c) => c === ";").length; if (semis > 1 || (query.endsWith(";") && query.slice(0, -1).includes(";"))) { throw new Error("multiple statements are not allowed."); } query = query.replace(/;+\s*$/g, "").trim(); if (!query.toLowerCase().startsWith("select")) { throw new Error("Only SELECT statements are allowed"); } if (DENY_RE.test(query)) { throw new Error("DML/DDL detected. Only read-only queries are permitted."); } if (!HAS_LIMIT_TAIL_RE.test(query)) { query += " LIMIT 5"; } return query; } const executeSql = tool( async ({ query }) => { const q = sanitizeSqlQuery(query); try { const result = await runQuery(q); return JSON.stringify(result, null, 2); } catch (e) { const message = e instanceof Error ? e.message : String(e); throw new Error(message); } }, { name: "execute_sql", description: "Execute a READ-ONLY SQLite SELECT query and return results.", schema: z.object({ query: z.string().describe("SQLite SELECT query to execute (read-only)."), }), }, ); const getSystemPrompt = async () => new SystemMessage(`You are a careful SQLite analyst. Authoritative schema (do not invent columns/tables): ${await getSchema()} Rules: - Think step-by-step. - When you need data, call the tool - Read-only only; no INSERT/UPDATE/DELETE/ALTER/DROP/CREATE/REPLACE/TRUNCATE. - Limit to 5 rows unless user explicitly asks otherwise. - If the tool returns 'Error:', revise the SQL and try again. - Limit the number of attempts to 5. - If you are not successful after 5 attempts, return a note to the user. - Prefer explicit column lists; avoid SELECT *. `); export const agent = createAgent({ model: "openrouter:anthropic/claude-sonnet-4-6", tools: [executeSql], systemPrompt: await getSystemPrompt(), }); ``` -------------------------------- ### Load Toolbox Tools and Create Agent Source: https://docs.langchain.com/oss/javascript/integrations/tools/mcp_toolbox Load tools from your configured Toolbox server and create an agent. Replace the placeholder URL with your actual Toolbox Server URL. This snippet demonstrates initializing the client, loading a toolset, and setting up an agent with the loaded tools. ```javascript import { ChatGoogle } from "@langchain/google"; import { ToolboxClient } from "@toolbox-sdk/core"; import { tool } from "@langchain/core/tools"; import { createAgent } from "@langchain/classic"; const model = new ChatGoogle("gemini-2.5-flash-lite"); // Replace with your Toolbox Server URL const URL = 'http://127.0.0.1:5000'; let client = ToolboxClient(URL); toolboxTools = await client.loadToolset('toolsetName'); const getTool = (toolboxTool) => tool(toolboxTool, { name: toolboxTool.getName(), description: toolboxTool.getDescription(), schema: toolboxTool.getParamSchema() }); const tools = toolboxTools.map(getTool); const agent = createAgent({ llm: model, tools }); let inputs = { messages: [{ role: "user", content: Some query" }] }; let response = await agent.invoke(inputs); console.log(response); ``` -------------------------------- ### Prompt Caching Example Setup Source: https://docs.langchain.com/oss/javascript/integrations/chat/anthropic Demonstrates how to set up a variable to hold cached text for prompt caching with Anthropic. This is a preliminary step before defining the cache control parameters. ```typescript let CACHED_TEXT = "..."; ``` -------------------------------- ### Run Agent with a Prompt Source: https://docs.langchain.com/oss/javascript/deepagents/content-builder Pass a specific prompt as an argument to the content builder agent to guide content generation. For example, 'Write a blog post about prompt engineering'. ```bash npx tsx content_writer.ts Write a blog post about prompt engineering ``` -------------------------------- ### Navigate to Documentation Directory Source: https://docs.langchain.com/oss/javascript/contributing/documentation Change your current directory to the cloned documentation repository. ```bash cd docs ``` -------------------------------- ### Basic Tool Calling Example Source: https://docs.langchain.com/oss/javascript/langchain/frontend/tool-calling Demonstrates a fundamental example of how to set up and use a tool with LangChain.js for basic tool calling. ```typescript import { ChatOpenAI } from "@langchain/openai"; import { TavilySearchResults } from "@langchain/community/tools/retrieval"; import { formatToOpenAIToolMessages, ChatPromptTemplate, ChatMessageHistory } from "@langchain/core/messages"; import { convertToOpenAIFunction } from "@langchain/core/utils/function_calling"; import { createOpenAIFunctionsAgent, AgentExecutor } from "langchain/agents"; const chat = new ChatOpenAI({}); const tools = [new TavilySearchResults({ count: 1 })]; const prompt = ChatPromptTemplate.fromMessages([ ["system", "You are a helpful assistant"], ["user", "{input}"], new ChatMessageHistory({ memoryKey: "chat_history" }), ]); const agent = await createOpenAIFunctionsAgent({ llm: chat, tools, prompt, }); const agentExecutor = new AgentExecutor({ agent, tools }); const result = await agentExecutor.invoke({ input: "What is the weather in San Francisco?", }); console.log(result); ``` -------------------------------- ### Install Qdrant Vector Store Source: https://docs.langchain.com/oss/javascript/langchain/knowledge-base Install the Qdrant integration package. ```bash npm i @langchain/qdrant ``` ```bash yarn add @langchain/qdrant ``` ```bash pnpm add @langchain/qdrant ``` -------------------------------- ### Multi-turn Interactions in Subgraphs Source: https://docs.langchain.com/oss/javascript/langgraph/use-subgraphs This example illustrates that each invocation of a subgraph with per-invocation persistence starts with a fresh state. The subagent does not retain memory of previous calls, ensuring isolation between turns. ```typescript const config = { configurable: { thread_id: "1" } }; // First call let response = await agent.invoke( { messages: [{ role: "user", content: "Tell me about apples" }] }, config, ); // Subagent message count: 4 // Second call - subagent starts fresh, no memory of apples response = await agent.invoke( ``` -------------------------------- ### Create Project Directory Source: https://docs.langchain.com/oss/javascript/deepagents/deep-research Create a new directory for your project and navigate into it. ```bash mkdir deep-research-agent cd deep-research-agent ```