### Install Core LangChain.js Source: https://docs.langchain.com/oss/javascript/langchain/install Installs the main LangChain.js package and the core utilities. This is the primary package needed to start using LangChain.js. ```bash npm install langchain @langchain/core ``` ```bash pnpm add langchain @langchain/core ``` ```bash yarn add langchain @langchain/core ``` ```bash bun add langchain @langchain/core ``` -------------------------------- ### Create and Run Agent (TypeScript) Source: https://docs.langchain.com/oss/javascript/langchain/quickstart Assembles the agent by combining the configured model, system prompt, and other components. This snippet shows the initial setup for agent creation. ```typescript import { createAgent } from "langchain"; const agent = createAgent({ model: "claude-sonnet-4-5-20250929", systemPrompt: systemPrompt, ``` -------------------------------- ### Start Agent Server using Langgraph Dev Source: https://docs.langchain.com/oss/javascript/langchain/studio This command starts the Langchain Agent server for development. It allows you to view your agent in the Studio UI. Note that Safari may block localhost connections, requiring the use of the `--tunnel` flag for a secure connection. ```shell langgraph dev ``` ```shell langgraph dev --tunnel ``` -------------------------------- ### Install LangGraph CLI with In-Memory Support Source: https://docs.langchain.com/oss/javascript/langchain/studio Installs the LangGraph CLI with in-memory support, which is necessary for setting up a local agent server. Python version 3.11 or higher is required for this installation. This command is executed in a shell environment. ```shell pip install --upgrade "langgraph-cli[inmem]" ``` -------------------------------- ### LangGraph Configuration File for Agent Setup Source: https://docs.langchain.com/oss/javascript/langchain/studio Defines the configuration for a LangGraph application in a `langgraph.json` file. This JSON specifies project dependencies, lists the available graphs (linking the agent definition from `src/agent.py`), and points to the environment file (`.env`) for configuration settings. This file is used by the LangGraph CLI to set up and run the agent. ```json { "dependencies": ["ப்பான."], "graphs": { "agent": "./src/agent.py:agent" }, "env": ".env" } ``` -------------------------------- ### Create and Run Agent Chat UI Locally (Bash) Source: https://docs.langchain.com/oss/javascript/langchain/ui This snippet demonstrates how to create a new Agent Chat UI project using npx, navigate into the project directory, install dependencies, and start the development server. It's a quick way to set up a local instance for customization or testing. ```bash # Create a new Agent Chat UI project npx create-agent-chat-app --project-name my-chat-ui cd my-chat-ui # Install dependencies and start pnpm install pnpm dev ``` -------------------------------- ### Example: Using JSON Schema for Tool Input (TypeScript) Source: https://docs.langchain.com/oss/javascript/langchain/quickstart An alternative way to define tool input schemas using JSON schema objects. Note that JSON schemas are not validated at runtime. ```typescript const getWeather = tool( ({ city }) => `It's always sunny in ${city}!`, { name: "get_weather_for_location", description: "Get the weather for a given city", schema: { type: "object", properties: { city: { type: "string", description: "The city to get the weather for" } }, required: ["city"] }, } ); ``` -------------------------------- ### Install LangChain.js and dependencies for SQL agent Source: https://docs.langchain.com/oss/javascript/langchain/sql-agent Installs the necessary LangChain.js packages, TypeORM, SQLite3, and Zod for building the SQL agent. This setup is crucial for database interaction and data validation. ```bash npm i langchain @langchain/core typeorm sqlite3 zod ``` ```bash yarn add langchain @langchain/core typeorm sqlite3 zod ``` ```bash pnpm add langchain @langchain/core typeorm sqlite3 zod ``` -------------------------------- ### Install Project Dependencies using Pip Source: https://docs.langchain.com/oss/javascript/langchain/studio Installs the project's Python dependencies using pip. The `-e` flag installs the package in editable mode, meaning changes to the source code will be reflected immediately without needing to reinstall. This command is typically run from the root of the LangGraph application directory. ```shell pip install -e . ``` -------------------------------- ### LangChain.js AI Agent with Tools and Memory Source: https://docs.langchain.com/oss/javascript/langchain/quickstart This TypeScript code sets up an AI agent using LangChain.js. It defines tools for getting weather and user location, configures a chat model, and specifies a structured response format. The agent is initialized with a system prompt, tools, response format, and a memory checkpointer. It then demonstrates invoking the agent for a weather query and a follow-up 'thank you' message, showcasing conversation context and tool usage. ```typescript import { createAgent, tool, initChatModel } from "langchain"; import { MemorySaver, type Runtime } from "@langchain/langgraph"; import * as z from "zod"; // Define system prompt const systemPrompt = `You are an expert weather forecaster, who speaks in puns. You have access to two tools: - get_weather_for_location: use this to get the weather for a specific location - get_user_location: use this to get the user's location If a user asks you for the weather, make sure you know the location. If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location.`; // Define tools const getWeather = tool( ({ city }) => `It's always sunny in ${city}!`, { name: "get_weather_for_location", description: "Get the weather for a given city", schema: z.object({ city: z.string(), }), } ); const getUserLocation = tool( (_, config: Runtime<{ user_id: string}>) => { const { user_id } = config.context; return user_id === "1" ? "Florida" : "SF"; }, { name: "get_user_location", description: "Retrieve user information based on user ID", schema: z.object({}), } ); // Configure model const model = await initChatModel( "claude-sonnet-4-5-20250929", { temperature: 0 } ); // Define response format const responseFormat = z.object({ punny_response: z.string(), weather_conditions: z.string().optional(), }); // Set up memory const checkpointer = new MemorySaver(); // Create agent const agent = createAgent({ model: "claude-sonnet-4-5-20250929", systemPrompt: systemPrompt, tools: [getUserLocation, getWeather], responseFormat, checkpointer, }); // Run agent // `thread_id` is a unique identifier for a given conversation. const config = { configurable: { thread_id: "1" }, context: { user_id: "1" }, }; const response = await agent.invoke( { messages: [{ role: "user", content: "what is the weather outside?" }] }, config ); console.log(response.structuredResponse); // { // punny_response: "Florida is still having a 'sun-derful' day! The sunshine is playing 'ray-dio' hits all day long! I'd say it's the perfect weather for some 'solar-bration'! If you were hoping for rain, I'm afraid that idea is all 'washed up' - the forecast remains 'clear-ly' brilliant!", // weather_conditions: "It's always sunny in Florida!" // } // Note that we can continue the conversation using the same `thread_id`. const thankYouResponse = await agent.invoke( { messages: [{ role: "user", content: "thank you!" }] }, config ); console.log(thankYouResponse.structuredResponse); // { // punny_response: "You're 'thund-erfully' welcome! It's always a 'breeze' to help you stay 'current' with the weather. I'm just 'cloud'-ing around waiting to 'shower' you with more forecasts whenever you need them. Have a 'sun-sational' day in the Florida sunshine!", // weather_conditions: undefined // } ``` -------------------------------- ### Install Langchain.js Package Source: https://docs.langchain.com/oss/javascript/langchain/supervisor Installs the necessary 'langchain' package for building Langchain.js applications. Supports installation via npm, yarn, or pnpm. ```bash npm install langchain ``` ```bash yarn add langchain ``` ```bash pnpm add langchain ``` -------------------------------- ### Extended Agentic RAG Example for LangGraph Docs (TypeScript) Source: https://docs.langchain.com/oss/javascript/langchain/retrieval This extended example shows a more complex Agentic RAG setup for querying LangGraph documentation. It includes a custom `fetchDocumentation` tool with domain restrictions and a detailed system prompt to guide the agent. The example fetches content from `llms.txt` and then invokes the agent with a user's question. ```typescript import { tool, createAgent, HumanMessage } from "langchain"; import * as z from "zod"; const ALLOWED_DOMAINS = ["https://langchain-ai.github.io/"]; const LLMS_TXT = "https://langchain-ai.github.io/langgraph/llms.txt"; const fetchDocumentation = tool( async (input) => { if (!ALLOWED_DOMAINS.some((domain) => input.url.startsWith(domain))) { return `Error: URL not allowed. Must start with one of: ${ALLOWED_DOMAINS.join(", ")}`; } const response = await fetch(input.url); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.text(); }, { name: "fetch_documentation", description: "Fetch and convert documentation from a URL", schema: z.object({ url: z.string().describe("The URL of the documentation to fetch"), }), } ); const llmsTxtResponse = await fetch(LLMS_TXT); const llmsTxtContent = await llmsTxtResponse.text(); const systemPrompt = ` You are an expert TypeScript developer and technical assistant. Your primary role is to help users with questions about LangGraph and related tools. Instructions: 1. If a user asks a question you're unsure about — or one that likely involves API usage, behavior, or configuration — you MUST use the `fetch_documentation` tool to consult the relevant docs. 2. When citing documentation, summarize clearly and include relevant context from the content. 3. Do not use any URLs outside of the allowed domain. 4. If a documentation fetch fails, tell the user and proceed with your best expert understanding. You can access official documentation from the following approved sources: ${llmsTxtContent} You MUST consult the documentation to get up to date documentation before answering a user's question about LangGraph. Your answers should be clear, concise, and technically accurate. `; const tools = [fetchDocumentation]; const agent = createAgent({ model: "claude-sonnet-4-0", tools, systemPrompt, name: "Agentic RAG", }); const response = await agent.invoke({ messages: [ new HumanMessage( "Write a short example of a langgraph agent using the " + "prebuilt create react agent. the agent should be able " + "to look up stock pricing information." ), ], }); console.log(response.messages.at(-1)?.content); ``` -------------------------------- ### Synchronize Project Dependencies using Uv Source: https://docs.langchain.com/oss/javascript/langchain/studio Synchronizes project dependencies using the `uv` tool. This command ensures that the installed packages match the project's requirements, potentially offering faster dependency management than pip. It is executed from the root of the LangGraph application directory. ```shell uv sync ``` -------------------------------- ### Clone and Run Agent Chat UI Locally (Bash) Source: https://docs.langchain.com/oss/javascript/langchain/ui This snippet shows how to clone the Agent Chat UI repository from GitHub, navigate into the cloned directory, install project dependencies using pnpm, and then start the development server. This method is useful for developers who want to work directly with the source code. ```bash # Clone the repository git clone https://github.com/langchain-ai/agent-chat-ui.git cd agent-chat-ui # Install dependencies and start pnpm install pnpm dev ``` -------------------------------- ### Install @modelcontextprotocol/sdk Source: https://docs.langchain.com/oss/javascript/langchain/mcp Install the @modelcontextprotocol/sdk library using your preferred package manager (npm, pnpm, yarn, or bun). This is the foundational step for building MCP servers. ```bash npm install @modelcontextprotocol/sdk ``` ```bash pnpm add @modelcontextprotocol/sdk ``` ```bash yarn add @modelcontextprotocol/sdk ``` ```bash bun add @modelcontextprotocol/sdk ``` -------------------------------- ### Tool Execution Loop with Model and Tools Source: https://docs.langchain.com/oss/javascript/langchain/models This example illustrates the manual tool execution loop. It shows how to get tool calls from a model, execute the requested tool, and then pass the tool's results back to the model to generate a final response. This pattern is crucial when not using an agent. ```typescript // Bind (potentially multiple) tools to the model const modelWithTools = model.bindTools([get_weather]) // Step 1: Model generates tool calls const messages = [{"role": "user", "content": "What's the weather in Boston?"}] const ai_msg = await modelWithTools.invoke(messages) messages.push(ai_msg) // Step 2: Execute tools and collect results for (const tool_call of ai_msg.tool_calls) { // Execute the tool with the generated arguments const tool_result = await get_weather.invoke(tool_call) messages.push(tool_result) } // Step 3: Pass results back to model for final response const final_response = await modelWithTools.invoke(messages) console.log(final_response.text) // "The current weather in Boston is 72°F and sunny." ``` -------------------------------- ### Install Pinecone Vector Store (JavaScript) Source: https://docs.langchain.com/oss/javascript/langchain/knowledge-base Installs the `@langchain/pinecone` package for integrating with Pinecone, a managed vector database service. Also requires the `@pinecone-database/pinecone` client library. ```bash npm i @langchain/pinecone ``` ```bash yarn add @langchain/pinecone ``` ```bash pnpm add @langchain/pinecone ``` -------------------------------- ### Install Chroma Vector Store (JavaScript) Source: https://docs.langchain.com/oss/javascript/langchain/knowledge-base Installs the `@langchain/community` package for integrating with the Chroma vector store. Chroma is a popular open-source vector database. ```bash npm i @langchain/community ``` ```bash yarn add @langchain/community ``` ```bash pnpm add @langchain/community ``` -------------------------------- ### Install Memory Vector Store (JavaScript) Source: https://docs.langchain.com/oss/javascript/langchain/knowledge-base Installs the `@langchain/classic` package required for the MemoryVectorStore. This is a lightweight, in-memory solution suitable for testing or small workloads. ```bash npm i @langchain/classic ``` ```bash yarn add @langchain/classic ``` ```bash pnpm add @langchain/classic ``` -------------------------------- ### Install Qdrant Vector Store (JavaScript) Source: https://docs.langchain.com/oss/javascript/langchain/knowledge-base Installs the `@langchain/qdrant` package for Qdrant vector store integration. Qdrant is a popular open-source vector similarity search engine. ```bash npm i @langchain/qdrant ``` ```bash yarn add @langchain/qdrant ``` ```bash pnpm add @langchain/qdrant ``` -------------------------------- ### Install @langchain/mcp-adapters Source: https://docs.langchain.com/oss/javascript/langchain/mcp Installs the @langchain/mcp-adapters library using various package managers (npm, pnpm, yarn, bun). This library is necessary for integrating MCP tools with LangChain agents. ```bash npm install @langchain/mcp-adapters ``` ```bash pnpm add @langchain/mcp-adapters ``` ```bash yarn add @langchain/mcp-adapters ``` ```bash bun add @langchain/mcp-adapters ``` -------------------------------- ### Install and Configure VertexAI Embeddings Source: https://docs.langchain.com/oss/javascript/langchain/rag Installs the `@langchain/google-vertexai` package and sets the `GOOGLE_APPLICATION_CREDENTIALS` environment variable for VertexAI embeddings. ```bash npm i @langchain/google-vertexai yarn add @langchain/google-vertexai pnpm add @langchain/google-vertexai ``` ```bash GOOGLE_APPLICATION_CREDENTIALS=credentials.json ``` -------------------------------- ### Install Azure Package for Langchain.js Source: https://docs.langchain.com/oss/javascript/langchain/sql-agent Installs the Azure package for Langchain.js, supporting integration with Azure OpenAI services. Available for npm, pnpm, yarn, and bun. ```bash npm install @langchain/azure ``` ```bash pnpm install @langchain/azure ``` ```bash yarn add @langchain/azure ``` ```bash bun add @langchain/azure ``` -------------------------------- ### Install and Use Chroma Vector Store Source: https://docs.langchain.com/oss/javascript/langchain/rag Installs the `@langchain/community` package and initializes a Chroma vector store. Chroma is a popular vector database that can be run locally or in a client-server mode. ```bash npm i @langchain/community yarn add @langchain/community pnpm add @langchain/community ``` ```typescript import { Chroma } from "@langchain/community/vectorstores/chroma"; const vectorStore = new Chroma(embeddings, { ``` -------------------------------- ### Install LangChain Community and PDF Parsing Packages Source: https://docs.langchain.com/oss/javascript/langchain/knowledge-base Installs the necessary LangChain community package and the pdf-parse library for handling PDF documents. Supports npm, yarn, and pnpm package managers. ```bash npm i @langchain/community pdf-parse ``` ```bash yarn add @langchain/community pdf-parse ``` ```bash pnpm add @langchain/community pdf-parse ``` -------------------------------- ### ReAct Loop Example: Tool Use in Agent Source: https://docs.langchain.com/oss/javascript/langchain/agents Illustrates the ReAct (Reasoning + Acting) pattern where an agent alternates between reasoning and tool calls to fulfill a user request. This example shows how an agent identifies popular headphones, checks inventory, and provides a final answer. ```text ================================ Human Message ================================= Find the most popular wireless headphones right now and check if they're in stock ================================== Ai Message ================================== Tool Calls: search_products (call_abc123) Call ID: call_abc123 Args: query: wireless headphones ================================= Tool Message ================================= Found 5 products matching "wireless headphones". Top 5 results: WH-1000XM5, ... ================================== Ai Message ================================== Tool Calls: check_inventory (call_def456) Call ID: call_def456 Args: product_id: WH-1000XM5 ================================= Tool Message ================================= Product WH-1000XM5: 10 units in stock ================================== Ai Message ================================== I found wireless headphones (model WH-1000XM5) with 10 units in stock... ``` -------------------------------- ### Install Google GenAI Package for Langchain.js Source: https://docs.langchain.com/oss/javascript/langchain/sql-agent Installs the Google Generative AI package for Langchain.js using npm, pnpm, yarn, or bun. This enables integration with Google's Gemini models. ```bash npm install @langchain/google-genai ``` ```bash pnpm install @langchain/google-genai ``` ```bash yarn add @langchain/google-genai ``` ```bash bun add @langchain/google-genai ``` -------------------------------- ### Install Anthropic Package for Langchain.js Source: https://docs.langchain.com/oss/javascript/langchain/sql-agent Installs the Anthropic package for Langchain.js using common package managers (npm, pnpm, yarn, bun). This enables integration with Anthropic's chat models. ```bash npm install @langchain/anthropic ``` ```bash pnpm install @langchain/anthropic ``` ```bash yarn add @langchain/anthropic ``` ```bash pnpm add @langchain/anthropic ``` -------------------------------- ### Create Tools for Weather Agent (TypeScript) Source: https://docs.langchain.com/oss/javascript/langchain/quickstart Implements tools for retrieving weather information and user location. It utilizes Zod for input schema validation and demonstrates runtime configuration for dynamic behavior. ```typescript import { type Runtime } from "@langchain/langgraph"; import { tool } from "langchain"; import * as z from "zod"; const getWeather = tool( (input) => `It's always sunny in ${input.city}!`, { name: "get_weather_for_location", description: "Get the weather for a given city", schema: z.object({ city: z.string().describe("The city to get the weather for"), }), } ); type AgentRuntime = Runtime<{ user_id: string }>; const getUserLocation = tool( (_, config: AgentRuntime) => { const { user_id } = config.context; return user_id === "1" ? "Florida" : "SF"; }, { name: "get_user_location", description: "Retrieve user information based on user ID", } ); ``` -------------------------------- ### Configure Language Model for Agent (TypeScript) Source: https://docs.langchain.com/oss/javascript/langchain/quickstart Initializes a chat model with specific parameters like temperature, timeout, and max tokens for consistent and controlled responses. ```typescript import { initChatModel } from "langchain"; const model = await initChatModel( "claude-sonnet-4-5-20250929", { temperature: 0.5, timeout: 10, maxTokens: 1000 } ); ``` -------------------------------- ### Quick Start: LangChain Agent with Automatic LangSmith Tracing Source: https://docs.langchain.com/oss/javascript/langchain/observability This TypeScript example demonstrates creating a LangChain agent with 'create_agent' and running an invocation. All steps, including tool calls and model interactions, are automatically traced to LangSmith without additional code. ```typescript import { createAgent } from "@langchain/agents"; function sendEmail(to: string, subject: string, body: string): string { // ... email sending logic return `Email sent to ${to}`; } function searchWeb(query: string): string { // ... web search logic return `Search results for: ${query}`; } const agent = createAgent({ model: "gpt-4o", tools: [sendEmail, searchWeb], systemPrompt: "You are a helpful assistant that can send emails and search the web." }); // Run the agent - all steps will be traced automatically const response = await agent.invoke({ messages: [{ role: "user", content: "Search for the latest AI news and email a summary to john@example.com" }] }); ``` -------------------------------- ### Run the SQL Agent (TypeScript) Source: https://docs.langchain.com/oss/javascript/langchain/sql-agent Executes a sample query using the created agent. It demonstrates how to stream the agent's responses, logging each step (human input, tool calls, and AI output) to the console. This allows observation of the agent's reasoning and execution process. ```typescript const question = "Which genre, on average, has the longest tracks?"; const stream = await agent.stream( { messages: [{ role: "user", content: question }] }, { streamMode: "values" } ); for await (const step of stream) { const message = step.messages.at(-1); console.log(`${message.role}: ${JSON.stringify(message.content, null, 2)}`); } ``` -------------------------------- ### Streaming Semantic Events with Langchain Source: https://docs.langchain.com/oss/javascript/langchain/models Demonstrates using `streamEvents()` to stream semantic events from Langchain chat models. This method simplifies filtering by event type and aggregates the full message. The example logs the start input, individual text tokens as they are streamed, and the final complete message output. ```typescript const stream = await model.streamEvents("Hello"); for await (const event of stream) { if (event.event === "on_chat_model_start") { console.log(`Input: ${event.data.input}`); } if (event.event === "on_chat_model_stream") { console.log(`Token: ${event.data.chunk.text}`); } if (event.event === "on_chat_model_end") { console.log(`Full message: ${event.data.output.text}`); } } ``` -------------------------------- ### Install LangChain.js Integrations Source: https://docs.langchain.com/oss/javascript/langchain/install Installs specific provider integration packages for LangChain.js, such as OpenAI or Anthropic. These packages extend LangChain's capabilities by connecting to different LLM providers and tools. ```bash # Installing the OpenAI integration npm install @langchain/openai # Installing the Anthropic integration npm install @langchain/anthropic ``` ```bash # Installing the OpenAI integration pnpm install @langchain/openai # Installing the Anthropic integration pnpm install @langchain/anthropic ``` ```bash # Installing the OpenAI integration yarn add @langchain/openai # Installing the Anthropic integration yarn add @langchain/anthropic ``` ```bash # Installing the OpenAI integration bun add @langchain/openai # Installing the Anthropic integration bun add @langchain/anthropic ``` -------------------------------- ### Define System Prompt for Weather Agent (TypeScript) Source: https://docs.langchain.com/oss/javascript/langchain/quickstart Defines the agent's role and behavior as an expert weather forecaster who speaks in puns. It specifies the available tools and how to handle location information. ```typescript const systemPrompt = `You are an expert weather forecaster, who speaks in puns.\n\nYou have access to two tools:\n\n- get_weather_for_location: use this to get the weather for a specific location\n- get_user_location: use this to get the user's location\n\nIf a user asks you for the weather, make sure you know the location. If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location.`; ``` -------------------------------- ### Inject User Writing Style Middleware for Langchain JS Source: https://docs.langchain.com/oss/javascript/langchain/context-engineering This middleware injects a user's email writing style from a store into the LLM's prompt. It requires a `userId` from the runtime context and reads writing style preferences (tone, greeting, sign-off, example email) from a store. The retrieved style is formatted into a user message to guide the LLM's response generation, particularly for drafting emails. Dependencies include 'langchain' and 'zod'. ```typescript import * as z from "zod"; import { createMiddleware } from "langchain"; const contextSchema = z.object({ userId: z.string(), }); const injectWritingStyle = createMiddleware({ name: "InjectWritingStyle", contextSchema, wrapModelCall: async (request, handler) => { const userId = request.runtime.context.userId; // [!code highlight] // Read from Store: get user's writing style examples const store = request.runtime.store; // [!code highlight] const writingStyle = await store.get(["writing_style"], userId); // [!code highlight] if (writingStyle) { const style = writingStyle.value; // Build style guide from stored examples const styleContext = `Your writing style: - Tone: ${style.tone || 'professional'} - Typical greeting: "${style.greeting || 'Hi'}" - Typical sign-off: "${style.signOff || 'Best'}" - Example email you've written: ${style.exampleEmail || ''}`; // Append at end - models pay more attention to final messages const messages = [ ...request.messages, { role: "user", content: styleContext } ]; request = request.override({ messages }); // [!code highlight] } return handler(request); }, }); ``` -------------------------------- ### Initialize Qdrant Vector Store (TypeScript) Source: https://docs.langchain.com/oss/javascript/langchain/knowledge-base Initializes the QdrantVectorStore from an existing collection. Requires the Qdrant service URL and the name of the collection to connect to. ```typescript import { QdrantVectorStore } from "@langchain/qdrant"; const vectorStore = await QdrantVectorStore.fromExistingCollection(embeddings, { url: process.env.QDRANT_URL, collectionName: "langchainjs-testing", ``` -------------------------------- ### Install and Configure Cohere Embeddings Source: https://docs.langchain.com/oss/javascript/langchain/rag Installs the `@langchain/cohere` package and sets the `COHERE_API_KEY` environment variable for Cohere embeddings. ```bash npm i @langchain/cohere yarn add @langchain/cohere pnpm add @langchain/cohere ``` ```bash COHERE_API_KEY=your-api-key ``` -------------------------------- ### Install and Configure MistralAI Embeddings Source: https://docs.langchain.com/oss/javascript/langchain/rag Installs the `@langchain/mistralai` package and sets the `MISTRAL_API_KEY` environment variable for MistralAI embeddings. ```bash npm i @langchain/mistralai yarn add @langchain/mistralai pnpm add @langchain/mistralai ``` ```bash MISTRAL_API_KEY=your-api-key ``` -------------------------------- ### Install and Configure AWS Bedrock Embeddings Source: https://docs.langchain.com/oss/javascript/langchain/rag Installs the `@langchain/aws` package and sets the `BEDROCK_AWS_REGION` environment variable for AWS Bedrock embeddings. ```bash npm i @langchain/aws yarn add @langchain/aws pnpm add @langchain/aws ``` ```bash BEDROCK_AWS_REGION=your-region ``` -------------------------------- ### Install Langgraph CLI Source: https://docs.langchain.com/oss/javascript/langchain/sql-agent Installs the latest version of the Langgraph command-line interface globally. This is a prerequisite for running agents within the Langgraph environment. ```shell npm i -g langgraph-cli@latest ``` -------------------------------- ### Create Basic Agent with Claude and Weather Tool (TypeScript) Source: https://docs.langchain.com/oss/javascript/langchain/quickstart This snippet demonstrates how to create a basic AI agent using Langchain. It utilizes Claude Sonnet 4.5 as the language model and defines a 'getWeather' tool. The agent is configured to answer user questions by invoking the defined tools. Ensure ANTHROPIC_API_KEY environment variable is set. ```typescript 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: "claude-sonnet-4-5-20250929", tools: [getWeather], }); console.log( await agent.invoke({ messages: [{ role: "user", content: "What's the weather in Tokyo?" }], }) ); ``` -------------------------------- ### Model Invocation with Configuration Source: https://docs.langchain.com/oss/javascript/langchain/models Demonstrates how to invoke a model with various configuration options using the `RunnableConfig` object. ```APIDOC ## POST /models/invoke ### Description Invokes a language model with a given prompt and optional runtime configuration. ### Method POST ### Endpoint `/models/invoke` ### Parameters #### Request Body - **prompt** (string) - Required - The input prompt for the model. - **config** (object) - Optional - Configuration object for the invocation. - **runName** (string) - Optional - A custom name for this specific run. - **tags** (string[]) - Optional - Labels for categorization and filtering. - **metadata** (object) - Optional - Custom key-value pairs for additional context. - **callbacks** (CallbackHandler[]) - Optional - Handlers for monitoring execution events. - **maxConcurrency** (number) - Optional - Maximum parallel calls for batch operations. - **recursion_limit** (number) - Optional - Maximum recursion depth for chains. ### Request Example ```json { "prompt": "Tell me a joke", "config": { "runName": "joke_generation", "tags": ["humor", "demo"], "metadata": {"user_id": "123"}, "callbacks": [my_callback_handler] } } ``` ### Response #### Success Response (200) - **text** (string) - The model's generated response. #### Response Example ```json { "text": "Why don't scientists trust atoms? Because they make up everything!" } ``` ``` -------------------------------- ### Install Cohere Embeddings for Langchain.js Source: https://docs.langchain.com/oss/javascript/langchain/knowledge-base Installs the necessary package for using Cohere embeddings with Langchain.js. Supports npm, yarn, and pnpm package managers. ```bash npm i @langchain/cohere ``` ```bash yarn add @langchain/cohere ``` ```bash pnpm add @langchain/cohere ``` -------------------------------- ### Initialize Google Gemini Chat Model in Langchain.js Source: https://docs.langchain.com/oss/javascript/langchain/sql-agent Demonstrates initializing a Google Gemini chat model using `initChatModel` or `ChatGoogleGenerativeAI`. Requires the Google API key and specifies the model (e.g., 'google-genai:gemini-2.5-flash-lite'). ```typescript import { initChatModel } from "langchain"; process.env.GOOGLE_API_KEY = "your-api-key"; const model = await initChatModel("google-genai:gemini-2.5-flash-lite"); ``` ```typescript import { ChatGoogleGenerativeAI } from "@langchain/google-genai"; const model = new ChatGoogleGenerativeAI({ model: "gemini-2.5-flash-lite", apiKey: "your-api-key" }); ``` -------------------------------- ### Install MistralAI Embeddings for Langchain.js Source: https://docs.langchain.com/oss/javascript/langchain/knowledge-base Installs the necessary package for using MistralAI embeddings with Langchain.js. Supports npm, yarn, and pnpm package managers. ```bash npm i @langchain/mistralai ``` ```bash yarn add @langchain/mistralai ``` ```bash pnpm add @langchain/mistralai ``` -------------------------------- ### Install OpenAI Embeddings for Langchain.js Source: https://docs.langchain.com/oss/javascript/langchain/knowledge-base Installs the necessary package for using OpenAI embeddings with Langchain.js. Supports npm, yarn, and pnpm package managers. ```bash npm i @langchain/openai ``` ```bash yarn add @langchain/openai ``` ```bash pnpm add @langchain/openai ``` -------------------------------- ### Define Fetch URL Tool and Create Agent (TypeScript) Source: https://docs.langchain.com/oss/javascript/langchain/retrieval This snippet demonstrates how to define a simple tool for fetching content from a URL and then create an agent using this tool. The agent is configured with a model, the defined tool, and a system prompt. ```typescript import { tool, createAgent } from "langchain"; const fetchUrl = tool( (url: string) => { return `Fetched content from ${url}`; }, { name: "fetch_url", description: "Fetch text content from a URL" } ); const agent = createAgent({ model: "claude-sonnet-4-0", tools: [fetchUrl], systemPrompt, }); ``` -------------------------------- ### Install and Use Memory Vector Store Source: https://docs.langchain.com/oss/javascript/langchain/rag Installs the `@langchain/classic` package and initializes a `MemoryVectorStore`. This vector store operates in memory and is suitable for smaller datasets or testing. ```bash npm i @langchain/classic yarn add @langchain/classic pnpm add @langchain/classic ``` ```typescript import { MemoryVectorStore } from "@langchain/classic/vectorstores/memory"; const vectorStore = new MemoryVectorStore(embeddings); ``` -------------------------------- ### Implementing Dynamic System Prompts with Middleware Source: https://docs.langchain.com/oss/javascript/langchain/agents Shows how to dynamically adjust the system prompt at runtime using middleware. This example uses Zod for schema validation and a middleware function to tailor the prompt based on the 'userRole' context, providing different instructions for 'expert' and 'beginner' users. ```typescript import * as z from "zod"; import { createAgent, dynamicSystemPromptMiddleware } from "langchain"; const contextSchema = z.object({ userRole: z.enum(["expert", "beginner"]), }); const agent = createAgent({ model: "gpt-4o", tools: [/* ... */], contextSchema, middleware: [ dynamicSystemPromptMiddleware>((state, runtime) => { const userRole = runtime.context.userRole || "user"; const basePrompt = "You are a helpful assistant."; if (userRole === "expert") { return `${basePrompt} Provide detailed technical responses.`; } else if (userRole === "beginner") { return `${basePrompt} Explain concepts simply and avoid jargon.`; } return basePrompt; }), ], }); // The system prompt will be set dynamically based on context const result = await agent.invoke( { messages: [{ role: "user", content: "Explain machine learning" }] }, { context: { userRole: "expert" } } ); ``` -------------------------------- ### Install and Configure Azure OpenAI Embeddings Source: https://docs.langchain.com/oss/javascript/langchain/rag Installs the `@langchain/openai` package and sets up environment variables for Azure OpenAI embeddings. Requires `AZURE_OPENAI_API_INSTANCE_NAME`, `AZURE_OPENAI_API_KEY`, and `AZURE_OPENAI_API_VERSION` to be set. ```bash npm i @langchain/openai yarn add @langchain/openai pnpm add @langchain/openai ``` ```bash AZURE_OPENAI_API_INSTANCE_NAME= AZURE_OPENAI_API_KEY= AZURE_OPENAI_API_VERSION="2024-02-01" ``` -------------------------------- ### Add Memory to Agent (TypeScript) Source: https://docs.langchain.com/oss/javascript/langchain/quickstart Initializes a MemorySaver for managing conversational state. For production environments, a persistent checkpointer that saves to a database is recommended. ```typescript import { MemorySaver } from "@langchain/langgraph"; const checkpointer = new MemorySaver(); ``` -------------------------------- ### Install AgentEvals and LangChain Core Packages Source: https://docs.langchain.com/oss/javascript/langchain/test Installs the AgentEvals package and the LangChain Core library using npm. These are essential dependencies for performing integration tests on agentic applications. ```bash npm install agentevals @langchain/core ```