> For the complete documentation index, see [llms.txt](https://docs.bluerock.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.bluerock.io/agent-frameworks-integration/langchain.md).

# LangChain

The BlueRock runtime provides native, out-of-the-box telemetry tracing for the LangChain ecosystem. By embedding the `bluerock` sensor directly into the execution space, BlueRock automatically hooks into LangChain's internal orchestration engines without requiring architectural changes to the codebase or manual analytics callbacks.

#### Core Architecture

<figure><img src="/files/Ejl2eq752vKKzuO3YJAv" alt=""><figcaption></figcaption></figure>

#### Environment Setup

1. **Provision the Isolated Project Environment**\
   Initialize the local configuration layout with `uv` to ensure strict, repeatable dependency management across testing environments:<br>

   ```shellscript
   # Initialize clean project workspace
   $ uv init --python python3.13 sample_agent
   $ cd sample_agent

   # Activate virtual runtime environment
   $ source .venv/bin/activate

   # (Optional) Append required core modules
   $ uv add <module-names>
   ```
2. **Inject and Register BlueRock Sensors**\
   Deploy the custom BlueRock telemetry sensor library directly within the activated workspace context:<br>

   ```shellscript
   # Perform localized wheel installation
   $ uv pip install /opt/bluerock/python-dist/bluerock-0.0.1*.whl

   # Activate runtime sensor hooks
   $ python -m bluerock --install
   ```
3. **Establish the Associated Tool Layer (MCP Sandbox)**\
   Launch the isolated Model Context Protocol tool container, ensuring the container bridges telemetry hooks securely using a shared socket mount configuration:<br>

   ```bash
   $ docker run --name mcp_fileserver \
     --rm \
     -d \
     -v /run/bluerock:/run/bluerock \
     -p 8001:8001 \
     mcp_fileserver:latest
   ```

#### Agent Execution Block

Create the localized controller file as `file_agent.py` to initiate runtime actions. Ensure appropriate authorization environment variables (`OPENAI_API_KEY`) are bound to the parent terminal session:

```shellscript
# Execute target LangChain workspace script
$ uv run sample_agent.py  
```

#### Captured OpenTelemetry (OTEL) Lifecycle Events

During validation phases, the active `bluepython` sensor writes structured payloads tracking the progression of agent execution states.

**Phase 1: Chain Initialization (`chain_start`)**

Triggers at the point of boundary entry, registering raw intent values before prompt parsing steps.

```json
{
    "body": {
        "chain_type": "unknown",
        "context": { "process": { "pid": 000000 } },
        "entity_id": "xxxxxxxx-0000-0xxx-xxxx-000000xxxxxx",
        "event": "chain_start",
        "inputs": {
            "messages": "[('human', \"What files do I have, and can you add a 'README.md' to the list?. Also remove any tmp file present?\")]"
        },
        "run_id": "00000xx0-00xx-0xxx-0000-0xxx00xxxx00"
    },
    "severity_number": 0,
    "severity_text": "INFO",
    "attributes": {
        "domain": "gyro",
        "event_name": "python_langchain_event",
        "origin": "bluepython",
        "sensor_id": 0000,
        "type": "event"
    },
    "scope": { "name": "bluerockd" },
    "resource": { "service.name": "bluerock" }
}
```

**Phase 2: System & Context Compilation (`llm_start`)**

Logs model requests immediately after prompt construction, revealing state tracking injected by MCP adapters (`TextResourceContents` derived from the file server mount).

```json
{
    "body": {
        "context": { "process": { "pid": 000000 } },
        "entity_id": "xxxxxxxx-0000-0xxx-xxxx-000000xxxxxx",
        "event": "llm_start",
        "model": "ChatOpenAI",
        "prompts": [
            "System: You are a file manager. Current files: [TextResourceContents(uri=AnyUrl('folder://explorer'), mimeType='text/plain', text='sample.txt\\ntestfile.tmp')]\nHuman: What files do I have, and can you add a 'README.md' to the list?. Also remove any tmp file present?"
        ],
        "run_id": "00000xx0-00xx-0000-000b-00f0xxxx0000"
    },
    "severity_number": 0,
    "severity_text": "INFO",
    "attributes": {
        "domain": "gyro",
        "event_name": "python_langchain_event",
        "origin": "bluepython",
        "sensor_id": 0000
    }
}
```

**Phase 3: Structural Action Interception (`tool_start` / `tool_end`)**

Captures downstream execution tasks, auditing intent values and programmatic outputs before mutation phases proceed.

Invocation Trace (`tool_start`):

```json
{
    "body": {
        "context": { "process": { "pid": 000000 } },
        "entity_id": "xxxxxxxx-0000-0xxx-xxxx-000000xxxxxx",
        "event": "tool_start",
        "run_id": "00000xx0-0xxx-0xx0-0c00-00b00000xx0d",
        "tool_input": "{'filename': 'README.md', 'content': '# Project Documentation\\n\\nThis is the README file for the project.'}",
        "tool_name": "write_file"
    },
    "severity_number": 0,
    "severity_text": "INFO",
    "attributes": {
        "event_name": "python_langchain_event",
        "origin": "bluepython"
    }
}
```

* Resolution Trace (`tool_end`):

```json
{
    "body": {
        "context": { "process": { "pid": 000000 } },
        "entity_id": "xxxxxxxx-0000-0xxx-xxxx-000000xxxxxx",
        "event": "tool_end",
        "run_id": "00000xx0-0xxx-0xx0-0c00-00b00000xx0d",
        "tool_output": "content=[{'type': 'text', 'text': \"File 'README.md' written successfully.\"}] name='write_file' artifact={'structured_content': {'result': \"File 'README.md' written successfully.\"}}"
    },
    "severity_number": 0,
    "severity_text": "INFO",
    "attributes": {
        "event_name": "python_langchain_event",
        "origin": "bluepython"
    }
}
```

**Phase 4: Resolution Convergence (`chain_end`)**

Marks terminal parsing completion steps, mapping execution-wide performance metadata (including provider footprints, resource token counts, and internal fingerprint registers).

```json
{
    "body": {
        "context": { "process": { "pid": 000000 } },
        "entity_id": "xxxxxxxx-0000-0xxx-xxxx-000000xxxxxx",
        "event": "chain_end",
        "outputs": {
            "messages": "[... Tool Response Convergence Output ...]",
            "response_metadata": {
                "token_usage": { "completion_tokens": 00, "prompt_tokens": 000, "total_tokens": 000 },
                "model_provider": "openai",
                "model_name": "gpt-4o",
                "finish_reason": "tool_calls"
            }
        },
        "run_id": "00000xx0-00xx-0xxx-0000-0xxx00xxxx00"
    },
    "severity_number": 0,
    "severity_text": "INFO",
    "attributes": {
        "domain": "gyro",
        "event_name": "python_langchain_event",
        "origin": "bluepython"
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.bluerock.io/agent-frameworks-integration/langchain.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
