LangChain NVIDIA

repository·main·Indexed 42 days ago

https://github.com/langchain-ai/langchain-nvidia

A collection of integration packages to optimize LangChain applications using NVIDIA's AI ecosystem. Features include the ChatNVIDIA interface for hosted models like Nemotron, NVIDIAEmbeddings, NVIDIARerank, and NVIDIARetriever. It also provides specialized optimizations for LangGraph via StateGraph and OptimizationConfig, as well as OpenShellSandbox integration for secure agentic tool execution.

Tokens
42.8K
Snippets
144
Records
169
Agent score
54%

What's inside LangChain NVIDIA

  1. Overview of LangChain NVIDIA packages

    main

    The langchain-nvidia repository provides several specialized integration packages for NVIDIA hardware and software ecosystems within the LangChain framework:

    • langchain-nvidia-ai-endpoints: Integrates NVIDIA AI Foundation Models and Endpoints, including the Nemotron open model family designed for agentic AI.
    • langchain-nvidia-trt: Provides integrations for NVIDIA TensorRT models.
    • langchain-nvidia-langgraph: Offers NVIDIA-optimized execution for LangGraph, utilizing parallel and speculative execution strategies.
    • langchain-nvidia-openshell: Connects NVIDIA OpenShell sandboxes to LangChain Deep Agents.
    • langchain-nvidia-switchyard: Uses NVIDIA Switchyard's libsy algorithms to route model calls for LangChain and Deep Agents.
  2. How OpenShellSandbox works with LangChain Deep Agents

    main

    The OpenShellSandbox implements the LangChain BaseSandbox interface. It follows the sandbox-as-tool pattern: the agent (running on the host via ChatNVIDIA) remains outside the sandbox, while tools for shell commands, file uploads, and downloads are dispatched into a hardened, policy-enforced runtime. This prevents the agent itself from being exposed to the sandbox environment.

                      ┌──────────────────────────────┐
                      │   Host (your agent)          │
                      │                              │
                      │   ChatNVIDIA(...)            │
                      │       │                      │
                      │       ▼                      │
                      │   create_deep_agent(         │
                      │     model=...,               │
                      │     backend=OpenShellSandbox │
                      │   )                          │
                      └──────────────┬───────────────┘
                                     │  gRPC (mTLS)
                                     ▼
                      ┌──────────────────────────────┐
                      │   OpenShell Gateway          │
                      └──────────────┬───────────────┘
                                     │  ExecSandbox stream
                                     ▼
                      ┌──────────────────────────────┐
                      │   Sandbox compute driver     │
                      │   Docker/Podman/K8s/MicroVM  │
                      │   policy-enforced execution   │
                      └──────────────────────────────┘
  3. OpenShell Security Model and Policy Layers

    main

    OpenShell enforces security through three primary layers. Filesystem (RO/RW mounts) and Process (syscall filters/user privileges) are locked once the sandbox is running and cannot be hot-reloaded. Network (outbound hosts/ports) is enforced via an in-sandbox HTTP proxy and can be hot-reloaded using openshell policy set.

    | Layer | What it controls | Enforced by | Set at create | Hot-reloadable |
    |---|---|---|---|---|
    | **Filesystem** | RO/RW mounts inside the sandbox | Linux Landlock LSM | ✅ | ❌ locked once running |
    | **Network** | Outbound hosts, ports, HTTP methods/paths | In-sandbox HTTP CONNECT proxy + OPA/Rego | ✅ | ✅ via `openshell policy set` |
    | **Process** | Run-as user/group, syscall filter | seccomp BPF + dropped privileges | ✅ | ❌ locked once running |
  4. How Switchyard routing middleware works with Deep Agents

    main

    Switchyard acts as a routing middleware for LangChain Deep Agents. It allows a Deep Agent to route individual model calls through a Switchyard libsy algorithm to select the most appropriate model target (e.g., an 'efficient' model for simple tasks or a 'capable' model for complex ones).

    The Mental Model:

    1. The Deep Agent maintains control over the agent loop, tools, state, and middleware composition.
    2. The SwitchyardRoutingMiddleware intercepts model turns and uses a configured libsy Algorithm to make a routing decision.
    3. The Algorithm selects a LangChainLlmClient target.
    4. The LangChainLlmClient adapts the selected LangChain BaseChatModel to the interface required by Switchyard.
    5. The Target Model processes the request and returns an AIMessage containing Switchyard decision metadata.

    Because the middleware uses LangChain's dynamic-model pattern (request.override(model=...)), existing tool bindings, callbacks, and LangChain tracing continue to function normally.

  5. Use multimodal models with images

    main

    Models such as nvidia/neva-22b support multimodal inputs (text and images).

    Important: Local file paths are no longer accepted directly. You must explicitly read local files and pass them as base64 encoded URIs in the format data:image/...;base64,....

    NVIDIA APIs also uniquely support images provided as base64 strings within HTML <img> tags.

    import requests
    import base64
    from langchain_nvidia_ai_endpoints import ChatNVIDIA
    from langchain_core.messages import HumanMessage
    
    # 1. Using standard image_url format (URL or Base64 URI)
    image_url = "https://picsum.photos/seed/kitten/300/200"
    llm = ChatNVIDIA(model="nvidia/neva-22b")
    llm.invoke(
        [
            HumanMessage(content=[
                {"type": "text", "text": "Describe this image:"},
                {"type": "image_url", "image_url": {"url": image_url}},
            ])
        ])
    
    # 2. Using Base64 encoded string
    image_content = requests.get(image_url).content
    b64_string = base64.b64encode(image_content).decode('utf-8')
    llm.invoke(
        [
            HumanMessage(content=[
                {"type": "text", "text": "Describe this image:"},
                {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64_string}"}},
            ])
        ])
    
    # 3. Using HTML img tag (NVIDIA unique support)
    base64_with_mime_type = f"data:image/png;base64,{b64_string}"
    llm.invoke(
        f"What's in this image?\n<img src=\"{base64_with_mime_type}\" />"
    )
  6. Explore NVIDIA LangChain usage via Cookbooks

    main

    You can find practical implementation examples in the cookbook directory. These notebooks demonstrate how to use ChatNVIDIA and NVIDIAEmbeddings in conjunction with LangGraph to build:

    • Agentic RAG (Retrieval-Augmented Generation) workflows.
    • Tool-calling agents.
  7. Configure OpenRouter for Switchyard examples

    main

    To run the provided end-to-end examples using OpenRouter, you must set up your environment variables. The example reads from a .env file located in the langchain-nvidia repository root.

    1. Create the .env file:

      cp libs/switchyard/.env.example .env
    2. Configure keys and models in .env:

      OPENROUTER_API_KEY=sk-or-v1-your-key
      OPENROUTER_EFFICIENT_MODEL=nvidia/nemotron-3-ultra-550b-a55b
      OPENROUTER_CAPABLE_MODEL=anthropic/claude-sonnet-4.6

    Note: Existing process environment variables take precedence over the .env file.

    cp libs/switchyard/.env.example .env
  8. Install langchain-nvidia-switchyard from source

    main

    Switchyard's libsy Python bindings must be built from the Switchyard source tree before installing this integration. Follow these steps:

    1. Build libsy bindings:

      git clone https://github.com/NVIDIA-NeMo/Switchyard.git
      python -m pip install -e ./Switchyard
    2. Install the integration: Clone the langchain-nvidia repository and install the desired extra:

      • Generic (adapter only): python -m pip install -e "./langchain-nvidia/libs/switchyard"
      • With Deep Agents: python -m pip install -e "./langchain-nvidia/libs/switchyard[deepagents]"
      • With Deep Agents & OpenRouter: python -m pip install -e "./langchain-nvidia/libs/switchyard[openrouter]"
    git clone https://github.com/NVIDIA-NeMo/Switchyard.git
    python -m pip install -e ./Switchyard
    
    git clone https://github.com/langchain-ai/langchain-nvidia.git
    python -m pip install -e "./langchain-nvidia/libs/switchyard[openrouter]"
  9. Install langchain-nvidia-openshell and OpenShell CLI

    main

    To use the OpenShell sandbox integration, you must install both the Python package and the OpenShell CLI/gateway. Ensure the OpenShell version matches the SDK requirements (tested against 0.0.72+).

    # Install the Python package
    pip install langchain-nvidia-openshell
    
    # Install the OpenShell CLI/gateway (pinned to v0.0.72)
    curl -LsSf https://raw.githubusercontent.com/NVIDIA/OpenShell/main/install.sh \
      | OPENSHELL_VERSION=v0.0.72 sh
    
    # Verify installation
    openshell --version
  10. Configure LangGraph Optimization Modes

    main

    You can compile your graph in three distinct modes to balance performance and safety:

    1. Baseline: No optimization; executes nodes sequentially (standard LangGraph behavior).
    2. Parallel: Parallelizes independent stages (fan-out/fan-in) via compile-time graph rewriting. Set enable_parallel=True.
    3. Speculative: Combines parallel execution with speculative branch execution (runtime speculation). Set both enable_parallel=True and enable_speculation=True.

    Warning: Speculative execution has significant limitations regarding state persistence and streaming (see Limitations record).

    # Baseline — no optimization
    baseline_compiled = graph.compile()
    
    # Parallel — independent stages parallelized
    optimized_parallel = graph.compile(optimization=OptimizationConfig(enable_parallel=True))
    
    # Speculative — parallel + speculative branch execution
    optimized_speculative = graph.compile(
        optimization=OptimizationConfig(enable_parallel=True, enable_speculation=True),
    )
  11. Configure the NVIDIA_API_KEY environment variable

    main

    To access the NVIDIA API Catalog, you must provide an API key.

    1. Create an account at the NVIDIA API Catalog.
    2. Generate an API key in your profile settings.
    3. Save the key as the NVIDIA_API_KEY environment variable. All valid keys start with the prefix nvapi-.

    You can use the following snippet to securely set the environment variable in a notebook environment:

    import getpass
    import os
    
    if not os.environ.get("NVIDIA_API_KEY", "").startswith("nvapi-"):
        nvidia_api_key = getpass.getpass("Enter your NVIDIA API key: ")
        assert nvidia_api_key.startswith("nvapi-"), f"{nvidia_api_key[:5]}... is not a valid key"
        os.environ["NVIDIA_API_KEY"] = nvidia_api_key
  12. Self-host with NVIDIA NIM Microservices

    main

    When deploying locally using NVIDIA NIM Microservices, you can point the LangChain classes to your local endpoints by specifying the base_url parameter.

    from langchain_nvidia_ai_endpoints import ChatNVIDIA, NVIDIAEmbeddings, NVIDIARerank
    
    # Chat NIM
    llm = ChatNVIDIA(base_url="http://localhost:8000/v1", model="nvidia/nemotron-3-super-120b-a12b")
    
    # Embedding NIM
    embedder = NVIDIAEmbeddings(base_url="http://localhost:8080/v1")
    
    # Reranking NIM
    ranker = NVIDIARerank(base_url="http://localhost:2016/v1")