> ## Documentation Index
> Fetch the complete documentation index at: https://docs.arcbeam.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# LangChain Integration

> Send traces from LangChain applications to Arcbeam

Arcbeam integrates seamlessly with <Tooltip tip="LangChain is a framework for developing applications powered by language models">LangChain</Tooltip> applications using OpenTelemetry instrumentation. Capture every chain execution, LLM call, and retrieval automatically.

## What Gets Captured

<AccordionGroup>
  <Accordion title="Chain Executions" icon="link">
    Every chain run from start to finish, including nested chains and their relationships
  </Accordion>

  <Accordion title="LLM Calls" icon="robot">
    All model invocations with prompts, responses, <Tooltip tip="Tokens are the basic units that LLMs process - roughly 4 characters per token">tokens</Tooltip>, and costs
  </Accordion>

  <Accordion title="Retrievals" icon="database">
    Documents fetched from vector stores with similarity scores and metadata
  </Accordion>

  <Accordion title="Tool Calls" icon="wrench">
    External API calls and function executions with inputs and outputs
  </Accordion>

  <Accordion title="Agent Steps" icon="brain">
    Multi-step reasoning and decisions showing the agent's thought process
  </Accordion>

  <Accordion title="Timing Data" icon="clock">
    Latency for each operation to identify performance bottlenecks
  </Accordion>

  <Accordion title="Errors" icon="triangle-exclamation">
    Stack traces and error messages with full context
  </Accordion>
</AccordionGroup>

## Installation

<Steps>
  <Step title="Check Prerequisites">
    Ensure you have:

    * Python 3.8 or higher
    * LangChain installed (`pip install langchain`)
    * Arcbeam account and API key
  </Step>

  <Step title="Install Arcbeam SDK">
    ```bash theme={null}
    pip install arcbeam-connector
    ```

    <Check>
      Installation complete! You're ready to instrument your LangChain application.
    </Check>
  </Step>
</Steps>

## Quick Start

### 1. Initialize Arcbeam

Add these lines at the start of your application:

```python theme={null}
from arcbeam_connector.langchain.connector import ArcbeamLangConnector

connector = ArcbeamLangConnector(
    base_url="http://platform.arcbeam.ai",  # Or your self-hosted URL
    api_key="your-api-key-here",  # Your Arcbeam API key
    project_id="your-project-id-here",  # Your project ID
)
connector.init()
```

### 2. Run Your LangChain Code

That's it! Your existing LangChain code will now send traces to Arcbeam:

```python theme={null}
from langchain.chains import RetrievalQA
from langchain.llms import OpenAI
from langchain.vectorstores import FAISS

# Your normal LangChain code - no changes needed
llm = OpenAI(temperature=0)
vectorstore = FAISS.load_local("index")
qa = RetrievalQA.from_chain_type(
    llm=llm,
    retriever=vectorstore.as_retriever()
)

# This execution is automatically traced
result = qa.run("What is the refund policy?")
```

## Configuration

<Tabs>
  <Tab title="Python" icon="tag">
    Add environment tag to organize traces:

    ```python theme={null}
    from arcbeam_connector.langchain.connector import ArcbeamLangConnector

    connector = ArcbeamLangConnector(
        base_url="http://platform.arcbeam.ai",
        api_key="your_api_key",
        project_id="your_project_id",
        environment="production",  # Tag traces by environment
    )
    connector.init()
    ```

    The environment tag appears on every trace and can be used for filtering.

    | Environment   | Use Case                      |
    | ------------- | ----------------------------- |
    | `development` | Local testing and development |
    | `staging`     | Pre-production testing        |
    | `production`  | Live applications             |
  </Tab>

  <Tab title="Environment Variables" icon="key">
    Instead of hardcoding credentials, use environment variables:

    ```bash theme={null}
    export ARCBEAM_API_KEY="your_api_key"
    export ARCBEAM_PROJECT_ID="your_project_id"
    export ARCBEAM_BASE_URL="http://platform.arcbeam.ai"
    ```

    Then Arcbeam reads the envrionment variables at runtime:

    ```python theme={null}
    import os
    from arcbeam_connector.langchain.connector import ArcbeamLangConnector

    connector = ArcbeamLangConnector()
    connector.init()
    ```

    <Tip>
      Use a secrets manager like AWS Secrets Manager or HashiCorp Vault for production deployments.
    </Tip>
  </Tab>
</Tabs>

## Example: RAG Application

Full example with LangChain and Arcbeam:

```python theme={null}
import os
from arcbeam_connector.langchain.connector import ArcbeamLangConnector
from langchain.chains import RetrievalQA
from langchain.llms import OpenAI
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import PGVector

# Initialize Arcbeam
connector = ArcbeamLangConnector(
    base_url=os.getenv("ARCBEAM_BASE_URL", "http://platform.arcbeam.ai"),
    api_key=os.getenv("ARCBEAM_API_KEY"),
    project_id=os.getenv("ARCBEAM_PROJECT_ID"),
    environment="production",
)
connector.init()

# Set up LangChain components
embeddings = OpenAIEmbeddings()
vectorstore = PGVector(
    connection_string=os.getenv("DATABASE_URL"),
    embedding_function=embeddings,
    collection_name="support_docs"
)

llm = OpenAI(temperature=0, model="gpt-4")
qa = RetrievalQA.from_chain_type(
    llm=llm,
    chain_type="stuff",
    retriever=vectorstore.as_retriever(search_kwargs={"k": 3})
)

# Handle user request
def handle_query(user_id, query):
    # Run the chain (automatically traced)
    response = qa.run(query)

    return response

# Example usage
response = handle_query("user_123", "What's the return policy?")
print(response)
```

## Debugging LangChain Applications

### View Chain Execution

In the Arcbeam dashboard:

1. Go to **Traces** page
2. Find your trace
3. View the span tree showing:
   * Chain execution span
   * Retrieval span (with documents)
   * LLM call span (with prompt and response)
   * Timing for each step

### Find Slow Chains

Filter traces by duration:

1. Set duration filter: `> 5 seconds`
2. Review which chains are slow
3. Check if retrieval or LLM is the bottleneck
4. Optimize accordingly

### Track Costs

Monitor LangChain application costs:

1. View cost breakdown by model
2. Identify expensive chains
3. Find opportunities to reduce token usage
4. Compare costs across different chain configurations

## Best Practices

### Initialize Early

Call `connector.init()` at application startup, before any LangChain code:

```python theme={null}
# Good: Initialize first
from arcbeam_connector.langchain.connector import ArcbeamLangConnector

connector = ArcbeamLangConnector(
    base_url="http://platform.arcbeam.ai",
    api_key="your-api-key-here",
    project_id="your-project-id-here",
)
connector.init()

from langchain.chains import RetrievalQA
# ... rest of your code
```

### Use Environment Tags

Tag traces by environment for better organization:

```python theme={null}
connector = ArcbeamLangConnector(
    base_url="http://platform.arcbeam.ai",
    api_key="your-api-key-here",
    project_id="your-project-id-here",
    environment="production",  # or "dev", "staging"
)
connector.init()
```

## Troubleshooting

### Traces Not Appearing

**Check API Key**: Verify your API key is correct:

```python theme={null}
import os
print(os.getenv("ARCBEAM_API_KEY"))
```

**Check Project ID**: Ensure project ID is valid:

```python theme={null}
print(os.getenv("ARCBEAM_PROJECT_ID"))
```

**Check Initialization**: Make sure `init()` is called before LangChain code.

**Check Network**: Ensure your application can reach `https://api.arcbeam.ai`.

### Missing Retrieved Documents

**Connect Dataset**: Make sure you've added your vector store as a dataset in Arcbeam.

**Verify Schema Mapping**: Check that document ID columns are mapped correctly.

**Sync Dataset**: Trigger a manual sync to ensure metadata is current.

## Next Steps

<CardGroup cols={2}>
  <Card title="LangGraph Integration" icon="diagram-project" href="/v0/integrations/ai-frameworks/langgraph">
    Instrument LangGraph applications
  </Card>

  <Card title="Add Data Sources" icon="database" href="/v0/setup/add-data-sources">
    Connect vector stores for data lineage
  </Card>

  <Card title="Find Problematic Traces" icon="magnifying-glass" href="/v0/debugging/find-problematic-traces">
    Debug LangChain applications
  </Card>

  <Card title="Core Concepts" icon="book" href="/v0/core-concepts/observability">
    Understand traces, spans, and lineage
  </Card>
</CardGroup>
