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

# Python Integrations

> Trace Python AI applications with MutagenT

# Python Integrations

MutagenT provides first-class Python support for tracing AI applications. The Python ecosystem consists of a **core tracing SDK** and **framework-specific adapters** that automatically instrument your LLM calls.

## Architecture

<Mermaid>
  flowchart TD
  App\["Your Python App"] --> Adapter\["Framework Adapter"]
  Adapter --> Core\["mutagent-sdk (mutagent.tracing)"]
  Core -->|Batch async| MT\["MutagenT Platform"]

  subgraph Adapters
  ANT\["mutagent-anthropic"]
  OAI\["mutagent-openai"]
  LC\["mutagent-langchain"]
  LG\["mutagent-langgraph"]
  end

  ANT --> Core
  OAI --> Core
  LC --> Core
  LG --> Core
</Mermaid>

## Requirements

* Python >= 3.10
* A MutagenT API key ([get one here](/quickstart/api-keys))

## Package Status

| Package              | Version | Status            | Description                                               |
| -------------------- | ------- | ----------------- | --------------------------------------------------------- |
| `mutagent-sdk`       | `0.1.1` | Available on PyPI | Full Python SDK — prompts, datasets, evaluations, tracing |
| `mutagent-anthropic` | `0.1.0` | Coming soon       | Automatic tracing for the Anthropic Python SDK            |
| `mutagent-openai`    | `0.1.0` | Coming soon       | Automatic tracing for the OpenAI Python SDK               |
| `mutagent-langchain` | `0.1.0` | Coming soon       | Callback handler for LangChain                            |
| `mutagent-langgraph` | `0.1.0` | Coming soon       | Callback handler for LangGraph workflows                  |

## Quick Setup

<Steps>
  <Step title="Install the SDK">
    ```bash theme={null}
    pip install mutagent-sdk
    ```

    The `mutagent-sdk` package includes the core tracing module (`mutagent.tracing`).
  </Step>

  <Step title="Install a framework adapter">
    <Warning>
      The framework adapter packages are coming soon to PyPI. The install commands below will work once published.
    </Warning>

    ```bash theme={null}
    pip install mutagent-anthropic
    pip install mutagent-openai
    pip install mutagent-langchain
    pip install mutagent-langgraph
    ```

    Each adapter auto-installs its framework dependency and tracing transport.
  </Step>

  <Step title="Initialize tracing">
    ```python theme={null}
    from mutagent.tracing import init_tracing

    init_tracing(api_key="mt_xxxxxxxxxxxx")
    ```

    Or set `MUTAGENT_API_KEY` in your environment and omit the argument.
  </Step>
</Steps>

## Environment Variables

| Variable              | Description                                           | Default                 |
| --------------------- | ----------------------------------------------------- | ----------------------- |
| `MUTAGENT_API_KEY`    | Your MutagenT API key                                 | Required                |
| `MUTAGENT_SERVER_URL` | MutagenT API client endpoint (Python SDK client only) | `http://localhost:3003` |

<Note>
  The `init_tracing` function uses its own `endpoint` kwarg (defaulting to `https://api.mutagent.io`) and does not read `MUTAGENT_SERVER_URL`. Set `endpoint` explicitly when calling `init_tracing` for production.
</Note>

```python theme={null}
import os
from mutagent.tracing import init_tracing

init_tracing(
    api_key=os.environ["MUTAGENT_API_KEY"],
    endpoint="https://api.mutagent.io",
)
```

## Configuration Options

The `init_tracing` function accepts the following parameters:

| Parameter           | Type          | Default                   | Description                                      |
| ------------------- | ------------- | ------------------------- | ------------------------------------------------ |
| `api_key`           | `str`         | Required                  | MutagenT API key                                 |
| `endpoint`          | `str`         | `https://api.mutagent.io` | API endpoint URL                                 |
| `environment`       | `str \| None` | `None`                    | Environment name (e.g., `production`, `staging`) |
| `batch_size`        | `int`         | `10`                      | Number of spans to buffer before flushing        |
| `batch_interval_ms` | `int`         | `5000`                    | Flush interval in milliseconds                   |
| `debug`             | `bool`        | `False`                   | Enable debug logging                             |

## Core SDK: Manual Spans

The `mutagent.tracing` module also exposes a low-level API for creating custom spans when you need fine-grained control:

```python theme={null}
from mutagent.tracing import (
    init_tracing,
    start_span,
    end_span,
    SpanOptions,
    SpanEndOptions,
    SpanKind,
    SpanStatus,
    SpanIO,
    SpanMetrics,
)

init_tracing(api_key="mt_xxxxxxxxxxxx")

# Start a span
span = start_span(SpanOptions(
    kind="chain",
    name="my-pipeline",
    input=SpanIO(text="input data"),
))

# Do work...

# End the span
if span:
    end_span(span, SpanEndOptions(
        status="ok",
        output=SpanIO(text="output result"),
        metrics=SpanMetrics(
            model="gpt-4",
            provider="openai",
            input_tokens=150,
            output_tokens=50,
            total_tokens=200,
        ),
    ))
```

### Available Span Kinds

| Kind             | Value            | Use Case             |
| ---------------- | ---------------- | -------------------- |
| `LLM_CHAT`       | `llm.chat`       | Chat completions     |
| `LLM_COMPLETION` | `llm.completion` | Text completions     |
| `LLM_EMBEDDING`  | `llm.embedding`  | Embedding generation |
| `CHAIN`          | `chain`          | Sequential pipelines |
| `AGENT`          | `agent`          | Agent execution      |
| `GRAPH`          | `graph`          | Graph workflows      |
| `NODE`           | `node`           | Graph nodes          |
| `EDGE`           | `edge`           | Graph edges          |
| `WORKFLOW`       | `workflow`       | Multi-step workflows |
| `MIDDLEWARE`     | `middleware`     | Middleware layers    |
| `TOOL`           | `tool`           | Tool invocations     |
| `RETRIEVAL`      | `retrieval`      | RAG retrieval        |
| `RERANK`         | `rerank`         | Reranking operations |
| `GUARDRAIL`      | `guardrail`      | Safety checks        |
| `CUSTOM`         | `custom`         | Custom operations    |

## Shutdown

Always call `shutdown_tracing()` before your application exits to flush remaining spans:

```python theme={null}
import asyncio
from mutagent.tracing import shutdown_tracing

# At application shutdown (shutdown_tracing is async)
asyncio.run(shutdown_tracing())
```

<Note>
  The SDK registers an `atexit` handler that flushes remaining spans automatically. Calling `shutdown_tracing()` explicitly is recommended for long-running applications or serverless functions.
</Note>

## Framework Guides

<CardGroup cols={2}>
  <Card title="Anthropic" icon="robot" href="/integrations/python/anthropic">
    `wrap_anthropic(client)` — zero-change tracing for Claude
  </Card>

  <Card title="OpenAI" icon="bolt" href="/integrations/python/openai">
    `MutagentOpenAI` — drop-in OpenAI client replacement
  </Card>

  <Card title="LangChain" icon="link" href="/integrations/python/langchain">
    Callback handler for LangChain chains and agents
  </Card>

  <Card title="LangGraph" icon="diagram-project" href="/integrations/python/langgraph">
    Callback handler for LangGraph workflows
  </Card>
</CardGroup>

## TypeScript Equivalents

If you are using TypeScript/Node.js, see the [TypeScript integration guides](/integrations/overview) for the equivalent packages:

| Python Package           | TypeScript Equivalent |
| ------------------------ | --------------------- |
| `mutagent-sdk` (tracing) | `@mutagent/sdk`       |
| `mutagent-openai`        | `@mutagent/openai`    |
| `mutagent-langchain`     | `@mutagent/langchain` |
| `mutagent-langgraph`     | `@mutagent/langgraph` |
