### Install and Initialize PGVectorStore (Truncated Example) Source: https://docs.langchain.com/oss/python/langchain/knowledge-base Installs langchain-postgres and begins initialization of a PGVector store. Note: The Python code example is incomplete. ```shell pip install -qU langchain-postgres ``` ```python from langchain_postgres import PGVector ``` -------------------------------- ### Python Agent Setup with get_weather Tool Source: https://docs.langchain.com/oss/python/langchain/test/evals This snippet provides a common setup for the examples, initializing a LangChain agent with a `get_weather` tool. It includes necessary imports for agent creation and message types. ```python from langchain.agents import create_agent from langchain.tools import tool from langchain.messages import HumanMessage, AIMessage, ToolMessage from agentevals.trajectory.match import create_trajectory_match_evaluator @tool def get_weather(city: str): """Get weather information for a city.""" return "It's 75 degrees and sunny in {city}." agent = create_agent("claude-sonnet-4-6", tools=[get_weather]) ``` -------------------------------- ### Complete SQL Query Assistant with Skills and Middleware Source: https://docs.langchain.com/oss/python/langchain/multi-agent/skills-sql-assistant This comprehensive example demonstrates the full setup for a LangChain agent that acts as a SQL query assistant, integrating custom skills via `SkillMiddleware` and using a checkpointer for conversation state management. It includes skill loading, middleware definition, model initialization, agent creation, and example invocation. ```python # Find and return the requested skill for skill in SKILLS: if skill["name"] == skill_name: return f"Loaded skill: {skill_name}\n\n{skill['content']}" # Skill not found available = ", ".join(s["name"] for s in SKILLS) return f"Skill '{skill_name}' not found. Available skills: {available}" # Create skill middleware class SkillMiddleware(AgentMiddleware): """Middleware that injects skill descriptions into the system prompt.""" # Register the load_skill tool as a class variable tools = [load_skill] def __init__(self): """Initialize and generate the skills prompt from SKILLS.""" # Build skills prompt from the SKILLS list skills_list = [] for skill in SKILLS: skills_list.append( f"- **{skill['name']}**: {skill['description']}" ) self.skills_prompt = "\n".join(skills_list) def wrap_model_call( self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse], ) -> ModelResponse: """Sync: Inject skill descriptions into system prompt.""" # Build the skills addendum skills_addendum = ( f"\n\n## Available Skills\n\n{self.skills_prompt}\n\n" "Use the load_skill tool when you need detailed information " "about handling a specific type of request." ) # Append to system message content blocks new_content = list(request.system_message.content_blocks) + [ {"type": "text", "text": skills_addendum} ] new_system_message = SystemMessage(content=new_content) modified_request = request.override(system_message=new_system_message) return handler(modified_request) # Initialize your chat model (replace with your model) # Example: from langchain_anthropic import ChatAnthropic # model = ChatAnthropic(model="claude-3-5-sonnet-20241022") from langchain_openai import ChatOpenAI model = ChatOpenAI(model="gpt-4") # Create the agent with skill support agent = create_agent( model, system_prompt=( "You are a SQL query assistant that helps users " "write queries against business databases." ), middleware=[SkillMiddleware()], checkpointer=InMemorySaver(), ) # Example usage if __name__ == "__main__": # Configuration for this conversation thread thread_id = str(uuid7()) config = {"configurable": {"thread_id": thread_id}} # Ask for a SQL query result = agent.invoke( { "messages": [ { "role": "user", "content": ( "Write a SQL query to find all customers " "who made orders over $1000 in the last month" ), } ] }, config ) # Print the conversation for message in result["messages"]: if hasattr(message, 'pretty_print'): message.pretty_print() else: print(f"{message.type}: {message.content}") ``` -------------------------------- ### Install `langchain-mcp-adapters` Source: https://docs.langchain.com/oss/python/langchain/mcp Install the `langchain-mcp-adapters` library to enable LangChain agents to interact with MCP servers. ```bash pip install langchain-mcp-adapters ``` ```bash uv add langchain-mcp-adapters ``` -------------------------------- ### Install Assistant UI React Packages Source: https://docs.langchain.com/oss/python/langchain/frontend/integrations/assistant-ui Install the necessary `@assistant-ui/react` and `@assistant-ui/react-markdown` packages using Bun. ```bash bun add @assistant-ui/react @assistant-ui/react-markdown ``` -------------------------------- ### Install LangChain package Source: https://docs.langchain.com/oss/python/langchain/multi-agent/handoffs-customer-support Install the LangChain library using pip, uv, or conda to get started with building agents. ```bash pip install langchain ``` ```bash uv add langchain ``` ```bash conda install langchain -c conda-forge ``` -------------------------------- ### Install and Initialize PGVector Store Source: https://docs.langchain.com/oss/python/langchain/knowledge-base Installs langchain-postgres and initializes a PGVector store, connecting to a PostgreSQL database. ```shell pip install -qU langchain-postgres ``` ```python from langchain_postgres import PGVector vector_store = PGVector( embeddings=embeddings, collection_name="my_docs", connection="postgresql+psycopg://...", ) ``` -------------------------------- ### Comprehensive Context Editing Middleware Setup (Python) Source: https://docs.langchain.com/oss/python/langchain/middleware/built-in This example provides a more detailed configuration of `ContextEditingMiddleware`, showcasing how to explicitly set parameters like `trigger`, `keep`, `clear_tool_inputs`, `exclude_tools`, and `placeholder` within `ClearToolUsesEdit` to fine-tune context management for an agent. ```python from langchain.agents import create_agent from langchain.agents.middleware import ContextEditingMiddleware, ClearToolUsesEdit agent = create_agent( model="gpt-5.4", tools=[search_tool, your_calculator_tool, database_tool], middleware=[ ContextEditingMiddleware( edits=[ ClearToolUsesEdit( trigger=2000, keep=3, clear_tool_inputs=False, exclude_tools=[], placeholder="[cleared]", ), ], ), ], ) ``` -------------------------------- ### Install LangChain Package Source: https://docs.langchain.com/oss/python/langchain/multi-agent/subagents-personal-assistant Install the `langchain` package using pip or conda to get started with the tutorial. ```bash pip install langchain ``` ```bash conda install langchain -c conda-forge ``` -------------------------------- ### Example project directory structure Source: https://docs.langchain.com/oss/python/langchain/studio This snippet shows the expected project structure after setting up the agent, environment variables, and LangGraph configuration file. ```bash my-app/ ├── src │ └── agent.py ├── .env └── langgraph.json ``` -------------------------------- ### Install LangChain and DeepAgents with uv Source: https://docs.langchain.com/oss/python/langchain/quickstart Use uv to initialize a project, add dependencies, and synchronize the environment. ```bash uv init uv add langchain deepagents uv sync ``` -------------------------------- ### Install AgentEvals Package via pip Source: https://docs.langchain.com/oss/python/langchain/test/evals Run this command to install the `agentevals` package, which provides prebuilt evaluators for agent trajectories. This is the standard way to get the package for use in your projects. ```bash pip install agentevals ``` -------------------------------- ### Full Example of LLMToolEmulator Configuration (Python) Source: https://docs.langchain.com/oss/python/langchain/middleware/built-in Illustrates defining custom tools and configuring an agent with LLMToolEmulator to emulate all tools by default, specific tools only, or using a custom model for emulation. ```python from langchain.agents import create_agent from langchain.agents.middleware import LLMToolEmulator from langchain.tools import tool @tool def get_weather(location: str) -> str: """Get the current weather for a location.""" return f"Weather in {location}" @tool def send_email(to: str, subject: str, body: str) -> str: """Send an email.""" return "Email sent" # Emulate all tools (default behavior) agent = create_agent( model="gpt-5.4", tools=[get_weather, send_email], middleware=[LLMToolEmulator()], ) # Emulate specific tools only agent2 = create_agent( model="gpt-5.4", tools=[get_weather, send_email], middleware=[LLMToolEmulator(tools=["get_weather"])], ) # Use custom model for emulation agent4 = create_agent( model="gpt-5.4", tools=[get_weather, send_email], middleware=[LLMToolEmulator(model="claude-sonnet-4-6")] ) ``` -------------------------------- ### Clone and Run Agent Chat UI from Repository Source: https://docs.langchain.com/oss/python/langchain/ui Clone the official Agent Chat UI repository to set up a local development environment. Install project dependencies and start the application. ```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 ``` -------------------------------- ### Python SQL Agent Setup for Studio Source: https://docs.langchain.com/oss/python/langchain/sql-agent Python code for `sql_agent.py` that initializes the LLM, handles local database download, and imports required LangChain modules for Studio integration. ```python # sql_agent.py for studio import pathlib import sqlite3 import requests from langchain.agents import create_agent from langchain.chat_models import init_chat_model from langchain.tools import tool # Initialize an LLM model = init_chat_model("gpt-5.4") # Get the database, store it locally url = "https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db" local_path = pathlib.Path("Chinook.db") if local_path.exists(): print(f"{local_path} already exists, skipping download.") else: ``` -------------------------------- ### Create and Run Agent Chat UI Project with npx Source: https://docs.langchain.com/oss/python/langchain/ui Use npx to quickly scaffold a new Agent Chat UI project, install its dependencies, and start the development server. This is ideal for new projects. ```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 ``` -------------------------------- ### Create Agent with SubAgentMiddleware using Different Models (Python) Source: https://docs.langchain.com/oss/python/langchain/agents These examples demonstrate creating a LangChain agent configured with a search tool and middleware for filesystem, todo list, and sub-agent delegation, showcasing different LLM providers. ```python from deepagents.backends import StateBackend from deepagents.middleware import FilesystemMiddleware from deepagents.middleware.subagents import SubAgentMiddleware from langchain.agents import create_agent from langchain.agents.middleware import TodoListMiddleware from langchain.tools import tool @tool def search(query: str) -> str: """Search for a query and return a short summary.""" return f"Search results for: {query}" backend = StateBackend() agent = create_agent( model="fireworks:accounts/fireworks/models/qwen3p5-397b-a17b", tools=[search], middleware=[ FilesystemMiddleware(backend=backend), TodoListMiddleware(), SubAgentMiddleware( backend=backend, subagents=[ { "name": "researcher", "description": "Searches and returns a structured summary.", "system_prompt": "Use the search tool to research the question and summarize key points.", "tools": [search], "model": "anthropic:claude-sonnet-4-6", "middleware": [], } ], ), ], ) ``` ```python from deepagents.backends import StateBackend from deepagents.middleware import FilesystemMiddleware from deepagents.middleware.subagents import SubAgentMiddleware from langchain.agents import create_agent from langchain.agents.middleware import TodoListMiddleware from langchain.tools import tool @tool def search(query: str) -> str: """Search for a query and return a short summary.""" return f"Search results for: {query}" backend = StateBackend() agent = create_agent( model="baseten:zai-org/GLM-5", tools=[search], middleware=[ FilesystemMiddleware(backend=backend), TodoListMiddleware(), SubAgentMiddleware( backend=backend, subagents=[ { "name": "researcher", "description": "Searches and returns a structured summary.", "system_prompt": "Use the search tool to research the question and summarize key points.", "tools": [search], "model": "anthropic:claude-sonnet-4-6", "middleware": [], } ], ), ], ) ``` ```python from deepagents.backends import StateBackend from deepagents.middleware import FilesystemMiddleware from deepagents.middleware.subagents import SubAgentMiddleware from langchain.agents import create_agent from langchain.agents.middleware import TodoListMiddleware from langchain.tools import tool @tool def search(query: str) -> str: """Search for a query and return a short summary.""" return f"Search results for: {query}" backend = StateBackend() agent = create_agent( model="ollama:devstral-2", tools=[search], middleware=[ FilesystemMiddleware(backend=backend), TodoListMiddleware(), SubAgentMiddleware( backend=backend, subagents=[ { "name": "researcher", "description": "Searches and returns a structured summary.", "system_prompt": "Use the search tool to research the question and summarize key points.", "tools": [search], "model": "anthropic:claude-sonnet-4-6", "middleware": [], } ], ), ], ) ``` -------------------------------- ### Get Structured Output with Raw AIMessage (Pydantic) Source: https://docs.langchain.com/oss/python/langchain/models Configure the model to return both the parsed structured output and the raw `AIMessage` object, useful for accessing response metadata like token counts. This example uses a Pydantic `BaseModel`. ```python from pydantic import BaseModel, Field class Movie(BaseModel): """A movie with details.""" title: str = Field(description="The title of the movie") year: int = Field(description="The year the movie was released") director: str = Field(description="The director of the movie") rating: float = Field(description="The movie's rating out of 10") model_with_structure = model.with_structured_output(Movie, include_raw=True) # [!code highlight] response = model_with_structure.invoke("Provide details about the movie Inception") response # { # "raw": AIMessage(...), # "parsed": Movie(title=..., year=..., ...), # "parsing_error": None, # } ``` -------------------------------- ### Initialize Chroma Vector Store Source: https://docs.langchain.com/oss/python/langchain/rag Install the LangChain Chroma integration and set up a Chroma vector store, optionally specifying a persistence directory. ```shell pip install -qU langchain-chroma ``` ```python from langchain_chroma import Chroma vector_store = Chroma( collection_name="example_collection", embedding_function=embeddings, persist_directory="./chroma_langchain_db", # Where to save data locally, remove if not necessary ) ``` -------------------------------- ### Install and Initialize Chroma Vector Store Source: https://docs.langchain.com/oss/python/langchain/knowledge-base Installs langchain-chroma and initializes a Chroma vector store, with an option to persist data locally. ```shell pip install -qU langchain-chroma ``` ```python from langchain_chroma import Chroma vector_store = Chroma( collection_name="example_collection", embedding_function=embeddings, persist_directory="./chroma_langchain_db", # Where to save data locally, remove if not necessary ) ``` -------------------------------- ### Initialize QdrantVectorStore with In-Memory Client Source: https://docs.langchain.com/oss/python/langchain/rag This snippet demonstrates how to set up an in-memory Qdrant client, create a collection if it doesn't exist, and initialize a `QdrantVectorStore` for use with LangChain embeddings. ```python from qdrant_client.models import Distance, VectorParams from langchain_qdrant import QdrantVectorStore from qdrant_client import QdrantClient client = QdrantClient(":memory:") vector_size = len(embeddings.embed_query("sample text")) if not client.collection_exists("test"): client.create_collection( collection_name="test", vectors_config=VectorParams(size=vector_size, distance=Distance.COSINE) ) vector_store = QdrantVectorStore( client=client, collection_name="test", embedding=embeddings, ) ``` -------------------------------- ### React Component for Embedding Examples Source: https://docs.langchain.com/oss/python/langchain/frontend/integrations/copilotkit This React component dynamically embeds examples from a specified source, handling theme detection, iframe resizing, and position synchronization. It manages iframe caching and communication for interactive examples. ```javascript export const ExampleEmbed = ({example, theme, minHeight = 500, maxHeight = 700}) => { var PROD_BASE = "https://ui-patterns.langchain.com"; var iframeCache = (() => { const g = globalThis; if (!g.__lcExampleIframeCache) { g.__lcExampleIframeCache = new Map(); } return g.__lcExampleIframeCache; })(); function detectPageTheme() { if (typeof document === "undefined") return "light"; const root = document.documentElement; if (root.classList.contains("dark") || root.getAttribute("data-theme") === "dark" || root.style.colorScheme === "dark") { return "dark"; } return "light"; } var LOCAL_BASE = "http://localhost"; var LOCAL_PORTS = { "ai-elements": 4600, "assistant-ui": 4500 }; function isLocalhost() { return typeof location !== "undefined" && (location.hostname === "localhost" || location.hostname === "127.0.0.1"); } var EMBED_CSS = "\n[data-lc-ee] .lc-border{border-color:#B8DFFF}\n[data-lc-ee].dark .lc-border{border-color:#1A2740}\n[data-lc-ee] .lc-bg-surface{background-color:white}\n[data-lc-ee].dark .lc-bg-surface{background-color:#0B1120}\n[data-lc-ee] .lc-bg-wash{background-color:#F2FAFF}\n[data-lc-ee].dark .lc-bg-wash{background-color:#030710}\n[data-lc-ee] .lc-spinner{border-color:#B8DFFF;border-top-color:#7FC8FF}\n[data-lc-ee].dark .lc-spinner{border-color:#1A2740;border-top-color:#7FC8FF}\n"; const slotRef = useRef(null); const [ready, setReady] = useState(() => Boolean(iframeCache.get(example)?.iframe)); const [iframeHeight, setIframeHeight] = useState(minHeight); const [pageTheme, setPageTheme] = useState(detectPageTheme); const effectiveTheme = theme ?? pageTheme; const effectiveThemeRef = useRef(effectiveTheme); effectiveThemeRef.current = effectiveTheme; useEffect(() => { if (document.getElementById("lc-ee-css")) return; const style = document.createElement("style"); style.id = "lc-ee-css"; style.textContent = EMBED_CSS; document.head.appendChild(style); }, []); useEffect(() => { setPageTheme(detectPageTheme()); const observer = new MutationObserver(() => setPageTheme(detectPageTheme())); observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "data-theme", "style"] }); return () => observer.disconnect(); }, []); useEffect(() => { const useLocal = isLocalhost(); const localPort = LOCAL_PORTS[example]; const src = useLocal && localPort ? `${LOCAL_BASE}:${localPort}/` : `${PROD_BASE}/${example}/`; let cached = iframeCache.get(example); if (cached?.hideTimer) { clearTimeout(cached.hideTimer); cached.hideTimer = void 0; } if (!cached) { const iframe = document.createElement("iframe"); iframe.src = src; iframe.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms"); iframe.setAttribute("allow", "clipboard-write"); iframe.title = `${example} example`; Object.assign(iframe.style, { position: "fixed", border: "none", visibility: "hidden", pointerEvents: "auto", zIndex: "1", borderRadius: "15px" }); document.body.appendChild(iframe); cached = { iframe }; iframeCache.set(example, cached); window.addEventListener("message", e => { if (e.data?.type === "RESIZE" && iframeCache.get(example)?.iframe === iframe) { const h = Math.min(maxHeight, Math.max(minHeight, e.data.height)); setIframeHeight(h); } }); iframe.addEventListener("load", () => { iframe.style.visibility = "visible"; setReady(true); try { iframe.contentWindow?.postMessage({ type: "CHAT_LC_SET_THEME", theme: effectiveThemeRef.current }, "*"); } catch {} }); } else { cached.iframe.style.visibility = "visible"; setReady(true); } function syncPosition() { const slot = slotRef.current; if (!slot) return; const rect = slot.getBoundingClientRect(); const {style} = cached.iframe; style.top = `${rect.top}px`; style.left = `${rect.left}px`; style.width = `${rect.width}px`; style.setProperty("height", `${rect.height}px`, "important"); } syncPosition(); const ro = new ResizeObserver(syncPosition); if (slotRef.current) ro.observe(slotRef.current); document.addEventListener("scroll", syncPosition, { passive: true, capture: true }); window.addEventListener("resize", syncPosition, { passive: true }); let frameCount = 0; let rafId = 0; function initialSync() { syncPosition(); if (++frameCount < 5) rafId = requestAnimationFrame(initialSync); } }); return (
{!ready && (
)}
); }; ``` -------------------------------- ### Install LangChain and DeepAgents with pip Source: https://docs.langchain.com/oss/python/langchain/quickstart Use pip to install or upgrade LangChain and DeepAgents packages. ```bash pip install -U langchain deepagents ``` -------------------------------- ### Install and Initialize Milvus Vector Store Source: https://docs.langchain.com/oss/python/langchain/knowledge-base Installs langchain-milvus and initializes a Milvus vector store, specifying connection arguments and index parameters. ```shell pip install -qU langchain-milvus ``` ```python from langchain_milvus import Milvus URI = "./milvus_example.db" vector_store = Milvus( embedding_function=embeddings, connection_args={"uri": URI}, index_params={"index_type": "FLAT", "metric_type": "L2"}, ) ``` -------------------------------- ### Install Isaacus LangChain Integration Source: https://docs.langchain.com/oss/python/langchain/rag Installs the necessary Python package for integrating Isaacus embeddings with LangChain. ```shell pip install -qU langchain-isaacus ``` -------------------------------- ### Full Agent Example Imports (Partial) Source: https://docs.langchain.com/oss/python/langchain/quickstart Initial imports for a comprehensive agent example, including urllib for network operations and agent creation functions. ```python import urllib.error import urllib.request from langchain.agents import create_agent from deepagents import create_deep_agent ``` -------------------------------- ### Install LangChain Core for Fake Embeddings Source: https://docs.langchain.com/oss/python/langchain/rag Installs the core LangChain package, which includes the DeterministicFakeEmbedding class. ```shell pip install -qU langchain-core ``` -------------------------------- ### Install NVIDIA LangChain Integration Source: https://docs.langchain.com/oss/python/langchain/rag Installs the necessary Python package for integrating NVIDIA embeddings with LangChain. ```shell pip install -qU langchain-nvidia-ai-endpoints ``` -------------------------------- ### Full FilesystemFileSearchMiddleware Example with Agent Invocation Source: https://docs.langchain.com/oss/python/langchain/middleware/built-in Demonstrates an agent configured with `FilesystemFileSearchMiddleware` to perform glob and grep searches, showing how to invoke the agent to find specific files and content. ```python from langchain.agents import create_agent from langchain.agents.middleware import FilesystemFileSearchMiddleware from langchain.messages import HumanMessage agent = create_agent( model="gpt-5.4", tools=[], middleware=[ FilesystemFileSearchMiddleware( root_path="/workspace", use_ripgrep=True, max_file_size_mb=10, ), ], ) # Agent can now use glob_search and grep_search tools result = agent.invoke({ "messages": [HumanMessage("Find all Python files containing 'async def'")] }) # The agent will use: # 1. glob_search(pattern="**/*.py") to find Python files # 2. grep_search(pattern="async def", include="*.py") to find async functions ``` -------------------------------- ### Install Nomic LangChain Integration Source: https://docs.langchain.com/oss/python/langchain/rag Installs the necessary Python package for integrating Nomic embeddings with LangChain. ```shell pip install -qU langchain-nomic ``` -------------------------------- ### Complete Customer Support State Machine Example Source: https://docs.langchain.com/oss/python/langchain/multi-agent/handoffs-customer-support This script demonstrates a customer support workflow using a state machine pattern, where a single agent dynamically changes its behavior based on the current step to collect information sequentially. ```python """ Customer Support State Machine Example This example demonstrates the state machine pattern. A single agent dynamically changes its behavior based on the current_step state, creating a state machine for sequential information collection. """ from langchain_core.utils.uuid import uuid7 from langgraph.checkpoint.memory import InMemorySaver from langgraph.types import Command from typing import Callable, Literal from typing_extensions import NotRequired from langchain.agents import AgentState, create_agent from langchain.agents.middleware import wrap_model_call, ModelRequest, ModelResponse, SummarizationMiddleware from langchain.chat_models import init_chat_model from langchain.messages import HumanMessage, ToolMessage from langchain.tools import tool, ToolRuntime model = init_chat_model("google_genai:gemini-3.5-flash") # Define the possible workflow steps SupportStep = Literal["warranty_collector", "issue_classifier", "resolution_specialist"] class SupportState(AgentState): """State for customer support workflow.""" current_step: NotRequired[SupportStep] warranty_status: NotRequired[Literal["in_warranty", "out_of_warranty"]] issue_type: NotRequired[Literal["hardware", "software"]] @tool def record_warranty_status( status: Literal["in_warranty", "out_of_warranty"], runtime: ToolRuntime[None, SupportState], ) -> Command: """Record the customer's warranty status and transition to issue classification.""" return Command( update={ "messages": [ ToolMessage( content=f"Warranty status recorded as: {status}", tool_call_id=runtime.tool_call_id, ) ], "warranty_status": status, "current_step": "issue_classifier", } ) @tool def record_issue_type( issue_type: Literal["hardware", "software"], runtime: ToolRuntime[None, SupportState], ) -> Command: """Record the type of issue and transition to resolution specialist.""" return Command( update={ "messages": [ ToolMessage( content=f"Issue type recorded as: {issue_type}", tool_call_id=runtime.tool_call_id, ) ], "issue_type": issue_type, "current_step": "resolution_specialist", } ) @tool def escalate_to_human(reason: str) -> str: """Escalate the case to a human support specialist.""" # In a real system, this would create a ticket, notify staff, etc. return f"Escalating to human support. Reason: {reason}" @tool def provide_solution(solution: str) -> str: """Provide a solution to the customer's issue.""" return f"Solution provided: {solution}" # Define prompts as constants WARRANTY_COLLECTOR_PROMPT = """You are a customer support agent helping with device issues. CURRENT STEP: Warranty verification At this step, you need to: 1. Greet the customer warmly 2. Ask if their device is under warranty 3. Use record_warranty_status to record their response and move to the next step Be conversational and friendly. Don't ask multiple questions at once.""" ISSUE_CLASSIFIER_PROMPT = """You are a customer support agent helping with device issues. CURRENT STEP: Issue classification CUSTOMER INFO: Warranty status is {warranty_status} At this step, you need to: 1. Ask the customer to describe their issue 2. Determine if it's a hardware issue (physical damage, broken parts) or software issue (app crashes, performance) 3. Use record_issue_type to record the classification and move to the next step If unclear, ask clarifying questions before classifying.""" RESOLUTION_SPECIALIST_PROMPT = """You are a customer support agent helping with device issues. CURRENT STEP: Resolution CUSTOMER INFO: Warranty status is {warranty_status}, issue type is {issue_type} At this step, you need to: 1. For SOFTWARE issues: provide troubleshooting steps using provide_solution 2. For HARDWARE issues: - If IN WARRANTY: explain warranty repair process using provide_solution - If OUT OF WARRANTY: escalate_to_human for paid repair options Be specific and helpful in your solutions.""" # Step configuration: maps step name to (prompt, tools, required_state) STEP_CONFIG = { "warranty_collector": { "prompt": WARRANTY_COLLECTOR_PROMPT, "tools": [record_warranty_status], "requires": [], }, "issue_classifier": { "prompt": ISSUE_CLASSIFIER_PROMPT, "tools": [record_issue_type], ``` -------------------------------- ### Install MistralAI LangChain Integration Source: https://docs.langchain.com/oss/python/langchain/rag Installs the necessary Python package for integrating MistralAI embeddings with LangChain. ```shell pip install -qU langchain-mistralai ``` -------------------------------- ### Example of the openui-lang Program Format Source: https://docs.langchain.com/oss/python/langchain/frontend/integrations/openui This snippet illustrates the `openui-lang` format, where UI components are defined through assignments, with `root` serving as the main entry point. It demonstrates how hoisting allows the `root` structure to appear immediately, with sections filling in later. ```openui-lang root = Stack([header, execSummary, kpis, marketSection]) header = CardHeader("State of AI in 2025", "Comprehensive Analysis") execSummary = MarkDownRenderer("## Executive Summary\n\nThe AI market reached...") kpi1 = Card([CardHeader("$826B", "Global Market"), TextContent("42% YoY", "small")], "sunk") kpi2 = Card([CardHeader("78%", "Adoption"), TextContent("Fortune 500", "small")], "sunk") kpis = Stack([kpi1, kpi2], "row", "m", "stretch", "start", true) col1 = Col("Segment", "string") col2 = Col("Revenue ($B)", "number") tbl = Table([col1, col2], [["Generative AI", 286], ["ML Infra", 198]]) s1 = Series("Revenue", [286, 198, 147]) ch1 = BarChart(["Gen AI", "ML Infra", "Vision"], [s1]) marketSection = Card([CardHeader("Market Breakdown"), tbl, ch1]) ``` -------------------------------- ### Install Cohere LangChain Integration Source: https://docs.langchain.com/oss/python/langchain/rag Installs the necessary Python package for integrating Cohere embeddings with LangChain. ```shell pip install -qU langchain-cohere ``` -------------------------------- ### Install Ollama LangChain Integration Source: https://docs.langchain.com/oss/python/langchain/rag Installs the necessary Python package for integrating Ollama embeddings with LangChain. ```shell pip install -qU langchain-ollama ``` -------------------------------- ### Install and Initialize In-memory Vector Store Source: https://docs.langchain.com/oss/python/langchain/knowledge-base Installs the core LangChain library and initializes an in-memory vector store for lightweight, local workloads. ```shell pip install -U "langchain-core" ``` ```python from langchain_core.vectorstores import InMemoryVectorStore vector_store = InMemoryVectorStore(embeddings) ``` -------------------------------- ### Configure Agent with Postgres Checkpointer Source: https://docs.langchain.com/oss/python/langchain/short-term-memory Demonstrates how to initialize an agent with a `PostgresSaver` for persistent short-term memory, automatically creating necessary tables in PostgreSQL. ```python from langchain.agents import create_agent from langgraph.checkpoint.postgres import PostgresSaver def get_user_info() -> str: """Look up information about the current user.""" return "No user profile on file." DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable" with PostgresSaver.from_conn_string(DB_URI) as checkpointer: checkpointer.setup() # auto create tables in PostgreSQL agent = create_agent( "gpt-5.5", tools=[get_user_info], checkpointer=checkpointer, ) ``` -------------------------------- ### Install LangChain AWS Embeddings Integration Source: https://docs.langchain.com/oss/python/langchain/rag Install the necessary package for integrating AWS models with LangChain. ```shell pip install -qU langchain-aws ``` -------------------------------- ### Example Output from Streaming Agent Updates (Shell) Source: https://docs.langchain.com/oss/python/langchain/streaming Illustrates the typical output format when streaming agent progress, showing distinct steps like 'model' and 'tools' with their respective content blocks. ```shell step: model content: [{'type': 'tool_call', 'name': 'get_weather', 'args': {'city': 'San Francisco'}, 'id': 'call_9lBtsDbmmobzyA8xc4I4Ctne'}] step: tools content: [{'type': 'text', 'text': "It's always sunny in San Francisco!"}] step: model content: [{'type': 'text', 'text': "San Francisco weather: It's always sunny in San Francisco!\n\nIf you’d like the exact current conditions (temperature, humidity, wind) and a short forecast, I can fetch that next. Would you like me to pull live details for San Francisco?"}] ``` -------------------------------- ### Install LangChain OpenAI Embeddings Integration Source: https://docs.langchain.com/oss/python/langchain/rag Install the necessary package for integrating OpenAI models with LangChain. ```shell pip install -U "langchain-openai" ``` -------------------------------- ### Install LangChain OpenRouter Integration Source: https://docs.langchain.com/oss/python/langchain/multi-agent/handoffs-customer-support Installs the necessary LangChain integration package for OpenRouter chat models. ```shell pip install -U "langchain-openrouter" ``` -------------------------------- ### Complete Personal Assistant Supervisor Example Source: https://docs.langchain.com/oss/python/langchain/multi-agent/subagents-personal-assistant This runnable script demonstrates the full multi-agent system, including defining low-level API tools, creating specialized sub-agents, wrapping sub-agents as tools for the supervisor, and initializing the supervisor agent. ```python """ Personal Assistant Supervisor Example This example demonstrates the tool calling pattern for multi-agent systems. A supervisor agent coordinates specialized sub-agents (calendar and email) that are wrapped as tools. """ from langchain.tools import tool from langchain.agents import create_agent from langchain.chat_models import init_chat_model # ============================================================================ # Step 1: Define low-level API tools (stubbed) # ============================================================================ @tool def create_calendar_event( title: str, start_time: str, # ISO format: "2024-01-15T14:00:00" end_time: str, # ISO format: "2024-01-15T15:00:00" attendees: list[str], # email addresses location: str = "" ) -> str: """Create a calendar event. Requires exact ISO datetime format.""" return f"Event created: {title} from {start_time} to {end_time} with {len(attendees)} attendees" @tool def send_email( to: list[str], # email addresses subject: str, body: str, cc: list[str] = [] ) -> str: """Send an email via email API. Requires properly formatted addresses.""" return f"Email sent to {', '.join(to)} - Subject: {subject}" @tool def get_available_time_slots( attendees: list[str], date: str, # ISO format: "2024-01-15" duration_minutes: int ) -> list[str]: """Check calendar availability for given attendees on a specific date.""" return ["09:00", "14:00", "16:00"] # ============================================================================ # Step 2: Create specialized sub-agents # ============================================================================ model = init_chat_model("gpt-5.4") # for example calendar_agent = create_agent( model, tools=[create_calendar_event, get_available_time_slots], system_prompt=( "You are a calendar scheduling assistant. " "Parse natural language scheduling requests (e.g., 'next Tuesday at 2pm') " "into proper ISO datetime formats. " "Use get_available_time_slots to check availability when needed. " "If there is no suitable time slot, stop and confirm unavailability in your response. " "Use create_calendar_event to schedule events. " "Always confirm what was scheduled in your final response." ) ) email_agent = create_agent( model, tools=[send_email], system_prompt=( "You are an email assistant. " "Compose professional emails based on natural language requests. " "Extract recipient information and craft appropriate subject lines and body text. " "Use send_email to send the message. " "Always confirm what was sent in your final response." ) ) # ============================================================================ # Step 3: Wrap sub-agents as tools for the supervisor # ============================================================================ @tool def schedule_event(request: str) -> str: """Schedule calendar events using natural language. Use this when the user wants to create, modify, or check calendar appointments. Handles date/time parsing, availability checking, and event creation. Input: Natural language scheduling request (e.g., 'meeting with design team next Tuesday at 2pm') """ result = calendar_agent.invoke({ "messages": [{"role": "user", "content": request}] }) return result["messages"][-1].text @tool def manage_email(request: str) -> str: """Send emails using natural language. Use this when the user wants to send notifications, reminders, or any email communication. Handles recipient extraction, subject generation, and email composition. Input: Natural language email request (e.g., 'send them a reminder about the meeting') """ result = email_agent.invoke({ "messages": [{"role": "user", "content": request}] }) return result["messages"][-1].text # ============================================================================ # Step 4: Create the supervisor agent # ============================================================================ supervisor_agent = create_agent( model, tools=[schedule_event, manage_email], system_prompt=( "You are a helpful personal assistant. " "You can schedule calendar events and send emails. " "Break down user requests into appropriate tool calls and coordinate the results. " ``` -------------------------------- ### Install LangChain HuggingFace Integration Source: https://docs.langchain.com/oss/python/langchain/multi-agent/handoffs-customer-support Installs the necessary LangChain integration package for HuggingFace chat models. ```shell pip install -U "langchain[huggingface]" ``` -------------------------------- ### Python: Complete Multi-Agent Handoff Example Source: https://docs.langchain.com/oss/python/langchain/multi-agent/handoffs This comprehensive example illustrates setting up a multi-agent system where sales and support agents can transfer conversations using custom handoff tools. It defines a shared state, agent creation, and node functions for graph integration. ```python from typing import Literal from langchain.agents import AgentState, create_agent from langchain.messages import AIMessage, ToolMessage from langchain.tools import tool, ToolRuntime from langgraph.graph import StateGraph, START, END from langgraph.types import Command from typing_extensions import NotRequired # 1. Define state with active_agent tracker class MultiAgentState(AgentState): active_agent: NotRequired[str] # 2. Create handoff tools @tool def transfer_to_sales( runtime: ToolRuntime, ) -> Command: """Transfer to the sales agent.""" last_ai_message = next( # [!code highlight] msg for msg in reversed(runtime.state["messages"]) if isinstance(msg, AIMessage) # [!code highlight] ) # [!code highlight] transfer_message = ToolMessage( # [!code highlight] content="Transferred to sales agent from support agent", # [!code highlight] tool_call_id=runtime.tool_call_id, # [!code highlight] ) # [!code highlight] return Command( goto="sales_agent", update={ "active_agent": "sales_agent", "messages": [last_ai_message, transfer_message], # [!code highlight] }, graph=Command.PARENT, ) @tool def transfer_to_support( runtime: ToolRuntime, ) -> Command: """Transfer to the support agent.""" last_ai_message = next( # [!code highlight] msg for msg in reversed(runtime.state["messages"]) if isinstance(msg, AIMessage) # [!code highlight] ) # [!code highlight] transfer_message = ToolMessage( # [!code highlight] content="Transferred to support agent from sales agent", # [!code highlight] tool_call_id=runtime.tool_call_id, # [!code highlight] ) # [!code highlight] return Command( goto="support_agent", update={ "active_agent": "support_agent", "messages": [last_ai_message, transfer_message], # [!code highlight] }, graph=Command.PARENT, ) # 3. Create agents with handoff tools sales_agent = create_agent( model="google_genai:gemini-3.5-flash", tools=[transfer_to_support], system_prompt="You are a sales agent. Help with sales inquiries. If asked about technical issues or support, transfer to the support agent.", ) support_agent = create_agent( model="google_genai:gemini-3.5-flash", tools=[transfer_to_sales], system_prompt="You are a support agent. Help with technical issues. If asked about pricing or purchasing, transfer to the sales agent.", ) # 4. Create agent nodes that invoke the agents def call_sales_agent(state: MultiAgentState) -> Command: """Node that calls the sales agent.""" response = sales_agent.invoke(state) return response def call_support_agent(state: MultiAgentState) -> Command: """Node that calls the support agent.""" response = support_agent.invoke(state) return response ``` -------------------------------- ### Accessing PostgreSQL Store with Agent Tools Source: https://docs.langchain.com/oss/python/langchain/long-term-memory This example illustrates configuring an agent with a `PostgresStore` for persistent long-term memory. It covers setting up the PostgreSQL connection, initializing the store, and defining a tool to retrieve user data from the database. ```python from dataclasses import dataclass from langchain.agents import create_agent from langchain.tools import ToolRuntime, tool from langchain_core.runnables import Runnable from langgraph.store.postgres import PostgresStore # type: ignore[import-not-found] @dataclass class Context: user_id: str DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable" with PostgresStore.from_conn_string(DB_URI) as store: store.setup() store.put(("users",), "user_123", {"name": "John Smith", "language": "English"}) @tool def get_user_info(runtime: ToolRuntime[Context]) -> str: """Look up user info.""" assert runtime.store is not None user_info = runtime.store.get(("users",), runtime.context.user_id) return str(user_info.value) if user_info else "Unknown user" agent: Runnable = create_agent( "claude-sonnet-4-6", tools=[get_user_info], store=store, context_schema=Context, ) result = agent.invoke( {"messages": [{"role": "user", "content": "look up user information"}]}, context=Context(user_id="user_123"), ) ```