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

# Anthropic SDK

> Learn how to integrate Maxim observability with the Anthropic SDK in just one line of code.

export const MaximPlayer = ({url}) => {
  return <iframe className="border-background-highlight-secondary h-full w-full rounded-md border-2 aspect-video" src={url} allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowFullScreen></iframe>;
};

<MaximPlayer url="https://www.youtube.com/embed/LMthXxhUTbQ?si=Zwn29woY7WUq-NF0" />

## Requirements

```
"anthropic"
"maxim-py"
```

## Env Variables

```
MAXIM_API_KEY=
MAXIM_LOG_REPO_ID=
ANTHROPIC_API_KEY=
```

## Initialize Logger

```python theme={null}
from maxim import Maxim

logger = Maxim().logger()
```

## Initialize MaximAnthropicClient

```python {4,5} theme={null}
from anthropic import Anthropic
from maxim.logger.anthropic import MaximAnthropicClient

client = MaximAnthropicClient(client=Anthropic(api_key=ANTHROPIC_API_KEY), logger=logger)
```

## Make LLM Calls Using MaximAnthropicClient

```python theme={null}
from anthropic import Anthropic
from maxim.logger.anthropic import MaximAnthropicClient

client = MaximAnthropicClient(client=Anthropic(api_key=ANTHROPIC_API_KEY), logger=logger)

# Create a message request
response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Write a haiku about recursion in programming."}
    ]
)

# Extract response text
response_text = response.content[0].text
print(response_text)
```

## Maxim-specific Headers

The Anthropic instrumentation supports additional headers via the `extra_headers` parameter to enhance trace metadata and organization. You can use the following headers:

* **`x-maxim-trace-id`**: Associate LLM calls with a specific trace ID (UUID string). All calls with the same trace ID will be grouped together in a single trace.
* **`x-maxim-trace-tags`**: Add custom tags to traces as a JSON string containing key-value pairs. Useful for filtering and organizing traces.
* **`x-maxim-generation-name`**: Assign a custom name to a specific generation/LLM call within a trace (string).
* **`x-maxim-session-id`**: Associate traces with a specific session ID (string).

### Example: Using Extra Headers

```python theme={null}
import json
from uuid import uuid4
from anthropic import Anthropic
from maxim.logger.anthropic import MaximAnthropicClient

client = MaximAnthropicClient(client=Anthropic(api_key=ANTHROPIC_API_KEY), logger=logger)

trace_id = str(uuid4())

response = client.messages.create(
    messages=[{"role": "user", "content": "Explain how AI works"}],
    model="claude-opus-4-5-20251101",
    max_tokens=1000,
    extra_headers={
        "x-maxim-trace-tags": json.dumps({
            "environment": "production",
            "feature": "ai-explanation",
            "version": "1.0"
        }),
        "x-maxim-trace-id": trace_id,
        "x-maxim-generation-name": "ai-explanation-generation"
    }
)
```

## Advanced Use Case: Streaming Support

### Initialize Maxim SDK and Anthropic Client

```python theme={null}
import os
import dotenv
from uuid import uuid4
from anthropic import Anthropic
from maxim import Maxim
from maxim.logger.anthropic import MaximAnthropicClient

# Load environment variables
dotenv.load_dotenv()
MODEL_NAME = "claude-3-5-sonnet-20241022"
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")

# Initialize Maxim logger
logger = Maxim().logger()

# Initialize MaximAnthropicClient
client = MaximAnthropicClient(Anthropic(api_key=ANTHROPIC_API_KEY), logger)
```

### Make Streaming Calls

```python theme={null}
user_input = "What was the capital of France in 1800s?"
final_response = ""
response_chunks = []

with client.messages.stream(
    max_tokens=1024,
    messages=[{"role": "user", "content": user_input}],
    model=MODEL_NAME,
) as stream:
    for text_chunk in stream.text_stream:
        # Collect streamed chunks
        response_chunks.append(text_chunk)
        
        # Print the streamed text chunk
        print(text_chunk, end="", flush=True)    
    
    final_response = "".join(response_chunks)
```

## Capture Multiple LLM Calls in One Trace

**Initialize Maxim SDK and Anthropic Client**

```python theme={null}
from anthropic import Anthropic
from maxim import Maxim
from maxim.logger.anthropic import MaximAnthropicClient

# Make sure MAXIM_API_KEY and MAXIM_LOG_REPO_ID are set in env variables
logger = Maxim().logger()

# Initialize MaximAnthropicClient
client = MaximAnthropicClient(client=Anthropic(api_key=ANTHROPIC_API_KEY), logger=logger)
```

**Create a new trace externally**

```python theme={null}
from uuid import uuid4

trace_id = str(uuid4())

trace = logger.trace({
    "id": trace_id,
    "name": "Trace name"
})
```

**Make LLM calls and use this trace id**

```python theme={null}
response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "What was the capital of France in 1800s?"}
    ],
    extra_headers={"x-maxim-trace-id": trace_id}
)

# Extract response text
response_text = response.content[0].text
print(response_text)
```

**Keep adding LLM calls** All LLM calls with extra header `x-maxim-trace-id: trace_id` will add it to the declared trace.

## Capture Multi-Turn Conversations

**Initialize Maxim SDK and Anthropic Client**

```python theme={null}
from anthropic import Anthropic
from maxim import Maxim
from maxim.logger.anthropic import MaximAnthropicClient

# Make sure MAXIM_API_KEY and MAXIM_LOG_REPO_ID are set in env variables
logger = Maxim().logger()

# Initialize MaximAnthropicClient
client = MaximAnthropicClient(client=Anthropic(api_key=ANTHROPIC_API_KEY), logger=logger)
```

**Create a new trace externally and add it to a session**

```python theme={null}
from uuid import uuid4

# use this session id to add multiple traces in one session
session_id = str(uuid4())
trace_id = str(uuid4())

trace = logger.trace({
    "id": trace_id,
    "name": "Trace name",
    "session_id": session_id
})
```

**Make LLM calls and use this trace id**

```python theme={null}
messages = [
    {"role": "user", "content": "Hello, can you help me with Python programming?"}
]

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=messages,
    extra_headers={"x-maxim-trace-id": trace_id}
)

# Extract response text
response_text = response.content[0].text
print(response_text)

# Continue the conversation - add assistant's response to messages
messages.append({"role": "assistant", "content": response_text})
messages.append({"role": "user", "content": "Can you write a simple Python function?"})

# Make another call with the same trace_id to continue the conversation
response2 = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=messages,
    extra_headers={"x-maxim-trace-id": trace_id}
)

response_text2 = response2.content[0].text
print(response_text2)
```

**Create additional traces in the same session** To add more conversations to the same session, create new traces with the same `session_id`:

```python theme={null}
# Create another trace in the same session
trace_id_2 = str(uuid4())

trace2 = logger.trace({
    "id": trace_id_2,
    "name": "Second conversation",
    "session_id": session_id  # Same session_id to group conversations
})

# Make calls with the new trace_id
response3 = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Tell me about machine learning"}],
    extra_headers={"x-maxim-trace-id": trace_id_2}
)
```

<img src="https://mintcdn.com/maximai/ieTtaXix416w-43r/images/anthropic.gif?s=ebfdec137c4dbf5fda37601080f1af69" alt="" width="1280" height="720" data-path="images/anthropic.gif" />

## Resources

<CardGroup cols={2}>
  <Card title="Anthropic integration cookbook (GitHub)" icon="github" href="https://github.com/maximhq/maxim-cookbooks/blob/main/python/observability-online-eval/anthropic/basic.ipynb" />

  <Card title="Anthropic + Maxim integration Notebook (Colab)" icon="google" href="https://colab.research.google.com/drive/1Urk3XvEA6-K4yZyKC9oUb94KQUGcvAYM?usp=sharing" />
</CardGroup>
