### Run the frontend locally Source: https://github.com/langchain-ai/chat-langchain/blob/master/README.md Install dependencies and start the development server for the Next.js frontend. ```bash cd frontend npm ci npm run dev:local ``` -------------------------------- ### Setup Python Environment Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/10-deployment-and-env.md Commands for checking Python versions, managing virtual environments, and installing dependencies. ```bash # Requires Python 3.11 - 3.14 python --version # Check current version pyenv install 3.11 # If using pyenv ``` ```bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate ``` ```bash # Using uv (recommended) uv sync # Or using pip pip install -e . pip install -r requirements-dev.txt # For mypy, ruff ``` -------------------------------- ### search_support_articles Usage Examples Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md Examples demonstrating how to search all collections, a specific collection, or multiple collections. ```python # Search all collections result = search_support_articles() # Search specific collection result = search_support_articles(collections="LangSmith Deployment") # Search multiple collections result = search_support_articles( collections="LangSmith Deployment,LangSmith Observability" ) ``` -------------------------------- ### Initialize Environment File Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/10-deployment-and-env.md Command to create the local .env file from the provided example. ```bash cp .env.example .env # Edit .env with your actual API keys ``` -------------------------------- ### Support Articles JSON example Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/05-types-and-schemas.md Example of a populated JSON response for support articles. ```json { "collections": "LangSmith Deployment", "total": 1, "articles": [ { "id": "123e4567-e89b-12d3-a456-426614174000", "title": "How to Deploy a Graph", "url": "https://support.langchain.com/articles/123e4567-deploy-graph", "collection": "LangSmith Deployment" } ], "note": "All articles listed are public and have content. Use IDs to fetch full content." } ``` -------------------------------- ### Example usage of fetch_langchain_pricing Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md Demonstrates calling the asynchronous pricing tool. ```python pricing = await fetch_langchain_pricing() # Contains: plan names, pricing per seat, trace limits, fleet run quotas, etc. ``` -------------------------------- ### Install Chat LangChain dependencies Source: https://github.com/langchain-ai/chat-langchain/blob/master/README.md Clone the repository and install dependencies using uv or pip. ```bash # Clone the repository git clone https://github.com/langchain-ai/chat-langchain.git cd chat-langchain # Install dependencies with uv uv sync # Or with pip pip install -e . ``` -------------------------------- ### Run Deployment Commands Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/10-deployment-and-env.md Commands for starting a local development server or deploying to production. ```bash mda dev . ``` ```bash mda deploy . ``` -------------------------------- ### Initialize LinkCheckResult Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/05-types-and-schemas.md Example of creating an instance of LinkCheckResult. ```python from src.tools.link_check_tools import LinkCheckResult result = LinkCheckResult( url="https://docs.langchain.com/page", valid=True, status_code=200, error=None, final_url=None ) ``` -------------------------------- ### Example usage of get_support_article_content Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md Demonstrates searching for articles and fetching content by ID. ```python # First search for articles articles = search_support_articles(collections="LangSmith Deployment") # Extract an article ID, then fetch content content = get_support_article_content(article_id="123") ``` -------------------------------- ### Run the backend locally Source: https://github.com/langchain-ai/chat-langchain/blob/master/README.md Start the Managed Deep Agent development environment. ```bash # Build the Managed Deep Agent bundle uv run mda dev . # Or with pip mda dev . ``` -------------------------------- ### Check Links Usage Example Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md Example of invoking the check_links tool with a list of URLs. ```python urls = [ "https://docs.langchain.com/python/langchain/agents", "https://docs.langchain.com/nonexistent", "https://support.langchain.com/articles/123-something" ] result = await check_links(urls, timeout=15.0) ``` -------------------------------- ### Configure CustomSummarizationMiddleware in agent.py Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/03-middleware-reference.md Example instantiation of the middleware with specific token triggers and model configurations. ```python CustomSummarizationMiddleware( model=DEFAULT_MODEL.id, summary_model=summarization_model, trigger=("tokens", 130_000), # Summarize when > 130k tokens keep=("tokens", 30_000), # Keep last 30k tokens summary_prompt=context_summary_prompt, trim_tokens_to_summarize=None, ) ``` -------------------------------- ### Initialize GuardrailsDecision Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/05-types-and-schemas.md Example of creating a decision object returned by the guardrails middleware. ```python from src.middleware.guardrails_middleware import GuardrailsDecision # Returned from GuardrailsMiddleware._classify_query() decision: GuardrailsDecision = { "decision": "ALLOWED", "explanation": "Query is about LangChain streaming features." } ``` -------------------------------- ### Initialize Retry Fallback Model Usage Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/02-configuration.md Example of initializing a model and invoking it using the retry fallback configuration. ```python from src.agent.config import init_retry_fallback_model model = init_retry_fallback_model("google_genai:gemini-3.5-flash-lite") response = model.invoke("What is LangChain?") ``` -------------------------------- ### Example check_links output Source: https://github.com/langchain-ai/chat-langchain/blob/master/instructions.md The function returns a summary of valid and invalid links, including error details for failed connections. ```text Link Check Results: 2/3 valid Invalid links: - https://bad-link.com: Connection failed: ... Valid links: - https://docs.langchain.com ``` -------------------------------- ### Initialize GuardrailsState Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/05-types-and-schemas.md Example of initializing the GuardrailsState dictionary within a middleware hook. ```python # In middleware hook state: GuardrailsState = { "messages": [...], "off_topic_query": False } ``` -------------------------------- ### Optimize Search Queries Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/07-prompts-and-instructions.md Examples of how to extract core nouns from user questions to maximize cache efficiency. ```markdown | User Question | Extract | |----------------|---------| | "How do I add middleware?" | `query="middleware"` | | "What is middleware in LangChain?" | `query="middleware"` | | "How to stream from subagents?" | `query="streaming"` + `query="subgraphs"` | | "Deploy with authentication?" | `query="deployment"` + `query="authentication"` | ``` -------------------------------- ### Example Tool Error Response Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md The structured JSON format returned to the model when a tool fails after all retry attempts. ```json { "error": "Tool unavailable", "message": "search_support_articles failed after 3 attempts.", "tool": "search_support_articles", "suggestion": "Try a narrower or related query, use another available source, or answer from already retrieved context.", "details": "Connection error: timeout" } ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/INDEX.md Minimal configuration required for project initialization. Replace placeholders with actual API keys and service credentials. ```bash GOOGLE_API_KEY=... # (or OPENAI_API_KEY or ANTHROPIC_API_KEY) PYLON_API_KEY=... PYLON_KB_ID=... SUPABASE_URL=... SUPABASE_ANON_KEY=... ``` -------------------------------- ### Configure Support KB Tools Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/10-deployment-and-env.md Authentication keys for Pylon knowledge base integration. ```bash PYLON_API_KEY=pk_live_... # Pylon API authentication PYLON_KB_ID=kb_... # Knowledge base identifier ``` -------------------------------- ### Configure environment variables Source: https://github.com/langchain-ai/chat-langchain/blob/master/README.md Initialize the environment configuration file from the provided template. ```bash # Copy environment template cp .env.example .env # Edit .env with your API keys ``` -------------------------------- ### Backend Build and Deployment Commands Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/08-project-structure.md Commands for managing backend dependencies and running the local development server. ```bash uv sync # Install dependencies mda dev . # Local development server (port 2024) mda deploy . # Deploy as Managed Deep Agent ``` -------------------------------- ### Frontend Build and Deployment Commands Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/08-project-structure.md Commands for managing frontend dependencies and running the development or production environment. ```bash cd frontend npm ci # Install dependencies npm run dev:local # Local dev against MDA backend npm run build && npm run start # Production build ``` -------------------------------- ### Optional Environment Variables Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/02-configuration.md List of optional keys for Pylon integration and local prompt configuration. ```text PYLON_API_KEY # Pylon KB authentication PYLON_KB_ID # Pylon knowledge base identifier USE_LOCAL_PROMPTS # Set to "true"/"1"/"yes" to use local guardrails prompt instead of LangSmith Hub ``` -------------------------------- ### Import search_support_articles Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md Import the tool from the pylon_tools module. ```python from src.tools.pylon_tools import search_support_articles ``` -------------------------------- ### Tool Selection Strategies Source: https://github.com/langchain-ai/chat-langchain/blob/master/instructions.md Outlines the three primary approaches for managing tool selection in LangChain. ```python # Option 1: Better descriptions with constraints in the docstring # Option 2: tool_choice parameter to force a specific tool # Option 3: Conditional binding based on user permissions ``` -------------------------------- ### Configure Guest Provider Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/06-identity-and-auth.md Sets up authentication for anonymous users with a 24-hour token TTL. ```python providers.guest(ttl="24h", actor_prefix="guest:") ``` -------------------------------- ### Query Official Documentation Filesystem Source: https://github.com/langchain-ai/chat-langchain/blob/master/instructions.md Use these commands to read and navigate official documentation files. Always perform a search before using these commands to identify relevant file paths. ```python query_docs_filesystem_docs_by_lang_chain( command="head -120 /oss/python/langgraph/streaming.mdx" ) ``` ```python query_docs_filesystem_docs_by_lang_chain( command='rg -C 4 "stream subgraph" /oss/python/langgraph/streaming.mdx' ) ``` ```python query_docs_filesystem_docs_by_lang_chain( command="head -80 /oss/python/langgraph/streaming.mdx /oss/python/langgraph/subgraphs.mdx" ) ``` -------------------------------- ### Configure Optional Settings Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/10-deployment-and-env.md Optional environment variables for local prompts, LangSmith tracing, and deployment tracking. ```bash USE_LOCAL_PROMPTS=true ``` ```bash LANGSMITH_API_KEY=lsv2_... # Enable tracing if set LANGSMITH_PROJECT=chat-langchain # Trace project name ``` ```bash LANGCHAIN_REVISION_ID=abc123def... # Agent version identifier LANGSMITH_HOST_REVISION_ID=abc123def... # Fallback version identifier ``` -------------------------------- ### Import fetch_langchain_pricing Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md Import statement for the pricing information tool. ```python from src.tools.pricing_tools import fetch_langchain_pricing ``` -------------------------------- ### Configure Next.js Frontend Environment Variables Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/10-deployment-and-env.md Set the API URL for the frontend in a local development environment. ```bash # .env.local (development only) NEXT_PUBLIC_LANGGRAPH_API_URL=http://127.0.0.1:2024 # Production: set NEXT_PUBLIC_LANGGRAPH_API_URL to deployed MDA URL ``` -------------------------------- ### Supabase KB Configuration Variables Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/02-configuration.md Environment variables for configuring Supabase knowledge base connections across different regions. ```text SUPABASE_URL # US region Supabase project URL SUPABASE_ANON_KEY # US region anon key SUPABASE_EU_URL # EU region Supabase project URL SUPABASE_EU_ANON_KEY # EU region anon key SUPABASE_APAC_URL # APAC region Supabase project URL SUPABASE_APAC_ANON_KEY # APAC region anon key SUPABASE_AWS_URL # AWS region Supabase project URL SUPABASE_AWS_ANON_KEY # AWS region anon key ``` -------------------------------- ### Configure LLM API Keys Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/10-deployment-and-env.md Required environment variables for LLM provider authentication. ```bash ANTHROPIC_API_KEY=sk-ant-... # For claude-haiku-4-5 ``` ```bash OPENAI_API_KEY=sk-proj-... # For gpt-5.4-nano ``` ```bash GOOGLE_API_KEY=AIzaSy... # For gemini-3.5-flash-lite (default) ``` -------------------------------- ### Execute Documentation Search Source: https://github.com/langchain-ai/chat-langchain/blob/master/instructions.md Use the search_docs_by_lang_chain function with a simplified query string to retrieve documentation titles and paths. ```python search_docs_by_lang_chain( query="streaming", # Simple page title ) ``` -------------------------------- ### Optional Environment Variables Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/06-identity-and-auth.md Additional configuration for LangSmith tracing and agent version tracking. ```text LANGSMITH_API_KEY # For LangSmith trace operations LANGSMITH_HOST_REVISION_ID # For agent version tracking ``` -------------------------------- ### Access ModelConfig Registry Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/05-types-and-schemas.md Demonstrates retrieving a model configuration from the registry. ```python from src.agent.config import ModelConfig, MODELS # Access via registry model_config = MODELS["gemini-3.5-flash-lite"] print(model_config.id) # "google_genai:gemini-3.5-flash-lite" print(model_config.name) # "Gemini 3.5 Flash Lite" ``` -------------------------------- ### Configure Multi-Region Supabase Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/10-deployment-and-env.md Environment variables for Supabase identity services across different regions. ```bash SUPABASE_URL=https://xxxx.supabase.co SUPABASE_ANON_KEY=eyJhbGc... ``` ```bash SUPABASE_EU_URL=https://yyyy.supabase.co SUPABASE_EU_ANON_KEY=eyJhbGc... ``` ```bash SUPABASE_APAC_URL=https://zzzz.supabase.co SUPABASE_APAC_ANON_KEY=eyJhbGc... ``` ```bash SUPABASE_AWS_URL=https://wwww.supabase.co SUPABASE_AWS_ANON_KEY=eyJhbGc... ``` -------------------------------- ### Configure Identity Providers Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/06-identity-and-auth.md Dynamically builds identity provider configurations using Supabase URL and key environment variables. ```python provider = providers.supabase(url=base.rstrip("/"), introspect=True) provider["id"] = f"supabase-{region}" provider["introspect"]["headers"] = {"apikey": "${" + key_env + "}"} ``` -------------------------------- ### Import get_support_article_content Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md Import statement for the support article retrieval tool. ```python from src.tools.pylon_tools import get_support_article_content ``` -------------------------------- ### Import GuardrailsMiddleware Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/03-middleware-reference.md Import the GuardrailsMiddleware class from the middleware module. ```python from src.middleware.guardrails_middleware import GuardrailsMiddleware ``` -------------------------------- ### Import IngressGuardsMiddleware Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/03-middleware-reference.md Import the middleware class and the character limit constant. ```python from src.middleware.ingress_guards_middleware import IngressGuardsMiddleware, MAX_MESSAGE_CHARS ``` -------------------------------- ### Import the agent instance Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/01-agent-entry-point.md Import the primary agent instance from the agent module. ```python from agent import agent ``` -------------------------------- ### Import ToolRetryMiddleware Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/03-middleware-reference.md Import the middleware class from the source module. ```python from src.middleware.tool_retry_middleware import ToolRetryMiddleware ``` -------------------------------- ### Required Environment Variables Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/02-configuration.md List of mandatory API keys required for service access. ```text OPENAI_API_KEY # OpenAI access ANTHROPIC_API_KEY # Anthropic/Claude access GOOGLE_API_KEY # Google GenAI access ``` -------------------------------- ### Bind Tools to an LLM Source: https://github.com/langchain-ai/chat-langchain/blob/master/instructions.md Use bind_tools() to allow the LLM to select and invoke tools based on their descriptions. ```python @tool def search_database(query: str) -> str: """Search products. Use ONLY for discovery questions.""" return db.search(query) llm_with_tools = llm.bind_tools([search_database, check_inventory]) ``` -------------------------------- ### search_support_articles() Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/INDEX.md Searches the Pylon knowledge base for support articles. ```APIDOC ## search_support_articles() ### Description Searches the Pylon knowledge base for relevant support articles based on a query. ``` -------------------------------- ### Deploy Managed Deep Agent Source: https://github.com/langchain-ai/chat-langchain/blob/master/README.md Command to deploy the project using the MDA CLI. ```bash mda deploy . ``` -------------------------------- ### Generate rejection messages with rejection_system_prompt Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/07-prompts-and-instructions.md Uses the rejection system prompt to generate a polite, scoped response when a user query is blocked. ```python from src.prompts.guardrails_prompts import rejection_system_prompt prompt = [ SystemMessage(content=rejection_system_prompt), HumanMessage(content=f"The user asked: {user_query}"), ] rejection_message = rejection_llm.ainvoke(prompt) ``` -------------------------------- ### Environment Variable Template Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/10-deployment-and-env.md Template for required and optional environment variables including LLM providers, Pylon support, and Supabase authentication. ```bash # LLM Providers (at least one required) ANTHROPIC_API_KEY=sk-ant-... OPENAI_API_KEY=sk-proj-... GOOGLE_API_KEY=AIzaSy... # Support KB (Pylon) PYLON_API_KEY=pk_live_... PYLON_KB_ID=kb_... # Supabase Multi-Region Authentication SUPABASE_URL=https://xxxx.supabase.co SUPABASE_ANON_KEY=eyJhbGc... SUPABASE_EU_URL=https://yyyy.supabase.co SUPABASE_EU_ANON_KEY=eyJhbGc... SUPABASE_APAC_URL=https://zzzz.supabase.co SUPABASE_APAC_ANON_KEY=eyJhbGc... SUPABASE_AWS_URL=https://wwww.supabase.co SUPABASE_AWS_ANON_KEY=eyJhbGc... # Optional USE_LOCAL_PROMPTS=false LANGSMITH_API_KEY=lsv2_... LANGSMITH_PROJECT=chat-langchain ``` -------------------------------- ### Project Directory Structure Source: https://github.com/langchain-ai/chat-langchain/blob/master/README.md Visual representation of the project file organization. ```txt ├── agent.py # Managed Deep Agent entrypoint ├── identity.py # MDA identity contract (Supabase + guest) ├── instructions.md # Managed Deep Agent system prompt ├── connectors/ │ ├── langsmith.py # LangSmith feedback + trace connector │ └── mcp.py # Managed MCP docs connector ├── src/ │ ├── agent/ │ │ └── config.py # Model configuration │ ├── tools/ │ │ ├── pylon_tools.py # Support KB tools │ │ ├── pricing_tools.py # Pricing fetch │ │ └── link_check_tools.py # URL validation │ ├── prompts/ │ │ ├── docs_agent_prompt.py # Hub push / eval mirror of instructions.md │ │ ├── guardrails_prompts.py │ │ └── context_summary_prompt.py │ └── middleware/ │ ├── guardrails_middleware.py │ ├── ingress_guards_middleware.py │ └── retry_middleware.py ├── frontend/ # Next.js public chat UI └── pyproject.toml # Python project config ``` -------------------------------- ### Documenting a function reference Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/README.md Standard format for documenting module functions, including signature, return values, and caching policies. ```markdown ## fetch_langchain_pricing **Module:** `src.tools.pricing_tools` **Signature:** ```python async def fetch_langchain_pricing() -> str: """...""" ``` **Returns:** Plain text with pricing data **Caching:** 1-hour TTL per process ``` -------------------------------- ### Backend Module Hierarchy Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/08-project-structure.md Displays the directory and module structure for the Python backend, including agents, tools, middleware, and configuration. ```text agent.py ├── agent definition (define_deep_agent) ├── tools imported from src.tools ├── middleware imported from src.middleware └── config imported from src.agent.config src.agent.config ├── ModelConfig dataclass ├── MODELS registry ├── model initialization functions └── middleware factories src.middleware.* ├── GuardrailsMiddleware (query classification) ├── IngressGuardsMiddleware (input caps) ├── ModelRetryMiddleware (retry model calls) ├── ToolRetryMiddleware (retry tool calls) └── CustomSummarizationMiddleware (compress history) src.tools ├── pylon_tools (search KB, fetch articles) ├── pricing_tools (fetch pricing page) └── link_check_tools (validate URLs) src.prompts ├── guardrails_prompts (classification + rejection) ├── docs_agent_prompt (Hub push) └── context_summary_prompt (summarization) src.utils ├── trace_root_metadata (LangSmith metadata) └── prompt_provenance (prompt source tracking) connectors/ ├── langsmith.py (feedback + trace proxy) └── mcp.py (docs MCP server) identity.py (MDA identity contract) ``` -------------------------------- ### Apply Metadata to Agent Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/07-prompts-and-instructions.md Integrating the generated metadata into the agent definition. ```python from src.utils.trace_root_metadata import build_docs_agent_trace_metadata metadata = build_docs_agent_trace_metadata() agent = define_deep_agent( name="docs_agent", model="...", tools=[...], metadata=metadata, ) ``` -------------------------------- ### Supabase Environment Variables Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/06-identity-and-auth.md Required environment variables for connecting to Supabase projects in various regions. At least one region pair must be configured. ```text SUPABASE_URL # US region Supabase project URL SUPABASE_ANON_KEY # US region anon key SUPABASE_EU_URL # EU region Supabase project URL SUPABASE_EU_ANON_KEY # EU region anon key SUPABASE_APAC_URL # APAC region Supabase project URL SUPABASE_APAC_ANON_KEY # APAC region anon key SUPABASE_AWS_URL # AWS region Supabase project URL SUPABASE_AWS_ANON_KEY # AWS region anon key ``` -------------------------------- ### Configure MCP Servers in Python Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/06-identity-and-auth.md Defines MCP server connections using the define_mcp_servers function. Ensure the transport and URL are correctly specified for the target MCP endpoint. ```python connector = define_mcp_servers( prefix_tool_name_with_server_name=False, mcp_servers={ "langchain-docs": { "transport": "http", "url": "https://docs.langchain.com/mcp", }, }, ) ``` -------------------------------- ### Signature of fetch_langchain_pricing Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md Asynchronous function signature for retrieving live LangChain pricing data. ```python @tool async def fetch_langchain_pricing() -> str: """ALWAYS use this tool for ANY question about LangChain pricing, plans, or trace limits. Returns live pricing data directly from https://www.langchain.com/pricing. """ ``` -------------------------------- ### Classify user queries with guardrails_system_prompt Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/07-prompts-and-instructions.md Uses the guardrails system prompt within a GuardrailsMiddleware to classify incoming queries as allowed or blocked. ```python from src.prompts.guardrails_prompts import guardrails_system_prompt # Used by GuardrailsMiddleware for structured classification prompt = [ SystemMessage(content=guardrails_system_prompt), HumanMessage(content=user_query), ] decision = classifier_llm.with_structured_output(GuardrailsDecision).invoke(prompt) ``` -------------------------------- ### Signature of get_support_article_content Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md Function signature for fetching Pylon support article content. ```python @tool def get_support_article_content(article_id: str) -> str: """Fetch the full HTML content of a specific Pylon support article. Uses cached articles from search_support_articles to avoid redundant API calls. This only accepts article IDs returned by search_support_articles; do not pass docs.langchain.com URLs or paths. """ ``` -------------------------------- ### Import ModelRetryMiddleware Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/03-middleware-reference.md Import the retry middleware class and the associated error exception. ```python from src.middleware.retry_middleware import ModelRetryMiddleware, MalformedResponseError ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/10-deployment-and-env.md Configure the Python logging module to output debug-level information. ```python import logging logging.basicConfig(level=logging.DEBUG) ``` -------------------------------- ### Trace Metadata Structure Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/09-data-flow.md Visual representation of the LangSmith root run and nested span hierarchy for agent execution. ```text [Agent Execution] │ └─→ LangSmith Root Run ├─ source_type: "Chat-LangChain" ├─ prompt_source: "hub:production" or "local:file" ├─ prompt_hub_commit: "{hash}" (if from Hub) ├─ LANGSMITH_AGENT_VERSION: "{revision}" │ └─→ Nested Spans ├─ before_agent (GuardrailsMiddleware) │ ├─ guardrails_result: "ALLOWED"|"BLOCKED" │ └─ guardrails_explanation: str │ ├─ Model invocation │ ├─ Model: "gemini-3.5-flash-lite" │ ├─ Tokens: prompt_tokens, completion_tokens │ └─ Cost: prompt_cost, completion_cost │ └─ Tool invocations ├─ Tool name: search_support_articles, fetch_langchain_pricing, etc. ├─ Inputs: tool arguments └─ Outputs: tool result JSON ``` -------------------------------- ### Import ModelConfig Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/02-configuration.md Import the ModelConfig dataclass from the configuration module. ```python from src.agent.config import ModelConfig ``` -------------------------------- ### Build Trace Metadata Structure Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/07-prompts-and-instructions.md The structure of the metadata dictionary returned by build_docs_agent_trace_metadata. ```python { "source_type": "Chat-LangChain", **get_prompt_provenance(graph_id), # Includes prompt source + commit "LANGSMITH_AGENT_VERSION": revision, # If LANGCHAIN_REVISION_ID or LANGSMITH_HOST_REVISION_ID set } ``` -------------------------------- ### Access Model Registry Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/02-configuration.md Retrieve specific model configurations from the MODELS dictionary. ```python from src.agent.config import MODELS # Get a specific model model_config = MODELS["gemini-3.5-flash-lite"] print(model_config.id) # "google_genai:gemini-3.5-flash-lite" ``` -------------------------------- ### Guardrails Configuration Constants Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/03-middleware-reference.md Configuration settings for evaluation datasets and retry logic. ```python GUARDRAILS_DATASET_NAME = "Chat-LangChain-Guardrails-Samples" ALLOWED_SAMPLE_RATE = 0.01 # 1% of allowed queries GUARDRAILS_MAX_RETRIES = 2 GUARDRAILS_TIMEOUT_SECONDS = 10 ``` -------------------------------- ### init_retry_fallback_model(model: str) -> Runnable Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/02-configuration.md Initializes a LangChain Runnable for a specified model, incorporating shared retry logic and fallback policies. This function handles exponential backoff and switches to fallback models upon final failure. ```APIDOC ## init_retry_fallback_model(model: str) -> Runnable ### Description Initializes a model runnable with shared retry and fallback policies. The returned object automatically handles retries for retryable errors and falls back to secondary models if necessary. ### Parameters - **model** (str) - Required - Model identifier from the MODELS registry (e.g., "google_genai:gemini-3.5-flash-lite"). ### Returns - **Runnable** - A configured LangChain Runnable object. ### Example ```python from src.agent.config import init_retry_fallback_model model = init_retry_fallback_model("google_genai:gemini-3.5-flash-lite") response = model.invoke("What is LangChain?") ``` ``` -------------------------------- ### fetch_langchain_pricing Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/README.md Fetches current pricing data for LangChain services. ```APIDOC ## fetch_langchain_pricing ### Description Fetches pricing data for LangChain services. This function is located in `src.tools.pricing_tools`. ### Signature `async def fetch_langchain_pricing() -> str` ### Returns - **str** - Plain text containing the pricing data. ### Caching - 1-hour TTL per process ``` -------------------------------- ### ToolRetryMiddleware Execution Logic Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/09-data-flow.md Implements exponential backoff and retry logic for tool calls, including handling of specific error types. ```text [ToolRetryMiddleware.awrap_tool_call] │ ├─ Attempt 1: │ ├─ Call tool (search_support_articles, fetch_langchain_pricing, etc.) │ ├─ On success: Return ToolMessage │ ├─ On "no results": Return normalized "No results found." │ └─ On retryable error: → Attempt 2 │ ├─ Attempt 2 (if attempt 1 failed): │ ├─ Sleep: 0.5s │ ├─ Retry same tool │ └─ On failure: → Attempt 3 │ ├─ Attempt 3 (if attempt 2 failed): │ ├─ Sleep: 1s (exponential backoff) │ ├─ Retry same tool │ └─ On failure: → Final error │ └─ Final error: ├─ Format as JSON: {"error": "...", "message": "...", "suggestion": "..."} ├─ Return as ToolMessage └─→ Model reads error and adapts strategy ``` -------------------------------- ### Configure LangSmith Trace Viewer Capability Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/06-identity-and-auth.md Enables the retrieval of run traces and the generation of public share links within a conversation thread. ```python langsmith.runs( id="langsmith:trace-viewer", expose_to=["browser"], actions=["read", "share"], scope="thread", include=[ "id", "status", "start_time", "end_time", "url", "metadata", "prompt_tokens", "completion_tokens", "total_tokens", "prompt_cost", "completion_cost", "total_cost", ], ) ``` -------------------------------- ### Define Identity Configuration Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/06-identity-and-auth.md Configures ingress authentication and thread scoping for the managed deployment. ```python identity = define_identity( ingress={"http": {"mode": "validated_token", "providers": _providers()}}, tenancy="single", scoping={"threads": "actor", "memory": "none", "credentials": "agent"}, ) ``` -------------------------------- ### Public API Exports in src.agent.config Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/02-configuration.md Lists the available models, runnables, middleware, and configuration constants exported by the module. ```python __all__ = [ # Models "MODELS", "DEFAULT_MODEL", "GUARDRAILS_MODEL", "FALLBACK_MODELS", "ModelConfig", # Runnables "default_model", "init_retry_fallback_model", "summarization_model", # Middleware "model_retry_middleware", "tool_retry_middleware", "model_fallback_middleware", # Config "MAX_RETRIES", "logger", ] ``` -------------------------------- ### MDA to Managed Deep Agent Invocation Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/09-data-flow.md Shows the compilation of the agent with identity scoping, connectors, and tools before invoking the LangGraph runtime. ```text [MDA] │ ├─ Compile agent with: │ ├─ Identity scoping (actor) │ ├─ Connectors (LangSmith proxy, MCP docs) │ ├─ Tools (Pylon, pricing, link checker) │ └─ Middleware stack │ └─→ [Agent Runtime] └─ Receives LangGraph invocation with: ├─ messages: [HumanMessage] ├─ actor: authenticated user └─ thread_id: conversation identifier ``` -------------------------------- ### Agent Core Routing Logic Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/09-data-flow.md Describes the model inference loop and the decision process for tool usage versus final response. ```text [Agent Routing] │ ├─ messages → Model inference │ ├─ Model (Gemini 3.5 Flash Lite) │ ├─ Reads: messages, tool definitions │ ├─ Decides: Next action (tool call or done) │ └─ Outputs: AIMessage with tool_calls or text │ ├─ Tool use? │ └─ Yes: Route to ToolRetryMiddleware │ └─ No: Return response │ └─→ [Response handling] ``` -------------------------------- ### Import CustomSummarizationMiddleware Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/03-middleware-reference.md Required import statement for accessing the middleware class. ```python from src.middleware.summarization_middleware import CustomSummarizationMiddleware ``` -------------------------------- ### Define Guardrails Dataset Fields Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/07-prompts-and-instructions.md Structure for inputs and outputs when logging guardrails evaluation samples. ```python inputs={"query": safe_query_text} outputs={ "expected_result": "ALLOWED" or "BLOCKED", "explanation": explanation_text, } ``` -------------------------------- ### Retrieve Prompt Provenance Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/07-prompts-and-instructions.md Usage of the get_prompt_provenance utility to include prompt metadata in LangSmith traces. ```python from src.utils.trace_root_metadata import build_docs_agent_trace_metadata metadata = build_docs_agent_trace_metadata() # Includes prompt provenance in metadata for LangSmith root run ``` -------------------------------- ### search_support_articles Signature Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md The function signature for the search_support_articles tool. ```python @tool def search_support_articles(collections: str = "all") -> str: """Get LangChain support article titles from Pylon KB, filtered by collection(s). Returns article titles in structured JSON format so the LLM can decide which ones to fetch. """ ``` -------------------------------- ### get_support_article_content() Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/INDEX.md Fetches the full content of a specific support article from the knowledge base. ```APIDOC ## get_support_article_content() ### Description Retrieves the full text content of a support article from the Pylon knowledge base. ``` -------------------------------- ### Define agent tools Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/01-agent-entry-point.md The docs_agent_tools list contains the specific tools available to the agent for search, content retrieval, and validation. ```python docs_agent_tools = [ search_support_articles, # Search Pylon KB by collection get_support_article_content, # Fetch full article HTML fetch_langchain_pricing, # Fetch live pricing page check_links, # Validate URLs for accessibility ] ``` -------------------------------- ### Frontend Module Hierarchy Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/08-project-structure.md Displays the directory and module structure for the TypeScript/React frontend, including UI components, API routes, and authentication. ```text frontend/app/page.tsx ├── Chat interface component ├── LangGraph API client ├── Supabase auth integration └── LangSmith feedback frontend/components/chat/ ├── chat-interface (main UI) ├── chat-input (message input) ├── message-list (conversation rendering) └── features/ (time-travel, voice input, etc.) frontend/components/auth/ └── AuthModal (Supabase login) frontend/components/layout/ ├── header ├── sidebar └── keyboard shortcuts frontend/app/api/ ├── auth/guest/route.ts (guest token issuance) └── auth/callback/route.ts (OAuth callback) ``` -------------------------------- ### Implement fallback_rejection_message usage Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/07-prompts-and-instructions.md Returns the fallback message as an AIMessage when the primary rejection generation process times out. ```python from src.prompts.guardrails_prompts import fallback_rejection_message # Used if _generate_rejection_message() times out return AIMessage(content=fallback_rejection_message) ``` -------------------------------- ### get_support_article_content(article_id: str) -> str Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md Fetches the full HTML content of a specific Pylon support article using a cached ID. ```APIDOC ## get_support_article_content ### Description Fetches the full HTML content of a specific Pylon support article. This tool uses cached articles from search_support_articles to avoid redundant API calls. ### Parameters - **article_id** (str) - Required - Article ID returned by search_support_articles. ### Returns - **string** - Formatted string containing article metadata (ID, Title, URL, Collection) and the first 5000 characters of HTML content. ``` -------------------------------- ### Environment Variables for Revision Tracking Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/07-prompts-and-instructions.md Environment variables used for tracking agent revisions. ```text LANGCHAIN_REVISION_ID # Preferred for revision tracking LANGSMITH_HOST_REVISION_ID # Fallback revision tracking ``` -------------------------------- ### Initialize MAX_RETRIES Constant Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/02-configuration.md Retrieves the maximum retry count from environment variables with a default of 2. ```python MAX_RETRIES = int(os.getenv("MODEL_MAX_RETRIES", "2")) ``` -------------------------------- ### Define CustomSummarizationMiddleware Class Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/03-middleware-reference.md Class signature showing inheritance from SummarizationMiddleware and the required summary_model parameter. ```python class CustomSummarizationMiddleware(SummarizationMiddleware): def __init__( self, *args: Any, summary_model: Runnable, **kwargs: Any ): ``` -------------------------------- ### ModelRetryMiddleware class definition Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/03-middleware-reference.md Constructor signature for configuring retry behavior. ```python class ModelRetryMiddleware(AgentMiddleware): def __init__( self, max_retries: int = 2, initial_delay: float = 0.5, backoff_factor: float = 2.0, ): ``` -------------------------------- ### Signature of before_agent hook Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/03-middleware-reference.md Method signature for the before_agent hook in IngressGuardsMiddleware. ```python def before_agent( self, state: AgentState, runtime: Runtime ) -> dict[str, Any] | None: ``` -------------------------------- ### Configure Checkpointer TTL Source: https://github.com/langchain-ai/chat-langchain/blob/master/instructions.md Sets the default TTL and sweep interval for checkpoint data in langgraph.json. ```json { "checkpointer": { "ttl": { "default_ttl": 43200, // 30 days "sweep_interval_minutes": 10 // Check every 10 min } } } ``` -------------------------------- ### Support Articles JSON schema Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/05-types-and-schemas.md Defines the expected JSON structure for support article responses. ```json { "collections": "string (requested collection filter)", "total": "number (count of articles returned)", "articles": [ { "id": "string (article UUID)", "title": "string", "url": "string (https://support.langchain.com/articles/...)", "collection": "string (collection name)" } ], "note": "string" } ``` -------------------------------- ### Configure Store Item TTL Source: https://github.com/langchain-ai/chat-langchain/blob/master/instructions.md Sets the TTL for memory or store items with an optional refresh-on-read behavior. ```json { "store": { "ttl": { "default_ttl": 10080, // 7 days "refresh_on_read": true } } } ``` -------------------------------- ### Import Link Checking Tools Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md Required imports for using the link checking functionality. ```python from src.tools.link_check_tools import check_links, LinkCheckResult ``` -------------------------------- ### check_links() Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/INDEX.md Validates URLs for accessibility and correctness. ```APIDOC ## check_links() ### Description Validates a set of URLs to ensure they are reachable and valid. ``` -------------------------------- ### search_support_articles JSON Structure Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/04-tools-reference.md The expected JSON output structure returned by the tool. ```json { "collections": "all|collection_name", "total": 5, "articles": [ { "id": "article_id_123", "title": "How to Configure XYZ", "url": "https://support.langchain.com/articles/article_id_123-how-to-configure-xyz", "collection": "LangSmith Deployment" } ], "note": "All articles listed are public and have content. Use IDs to fetch full content." } ``` -------------------------------- ### Browser to MDA Ingress Request Flow Source: https://github.com/langchain-ai/chat-langchain/blob/master/_autodocs/09-data-flow.md Visual representation of the initial HTTP request from the browser to the MDA Ingress. ```text [Browser] │ ├─ HTTP Request │ ├─ Headers: Authorization (Supabase token or guest token) │ ├─ Body: User message text or multimodal content │ └─ X-Supabase-Region: Region hint (us/eu/apac/aws) │ └─→ [MDA Ingress] ```