> ## 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.

# Google Gemini

> Learn how to integrate Maxim observability with the Google Gemini 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/aaFPm9KEfFs?si=TDe3e7vuHpV7jtgy" />

## Requirements

```
"google-genai"
"maxim-py"
```

## Env Variables

```
MAXIM_API_KEY=
MAXIM_LOG_REPO_ID=
GEMINI_API_KEY=
```

## Initialize Logger

```
python
```

```
from maxim import Maxim

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

## Initialize MaximGeminiClient

```python {4-7} theme={null}
from google import genai
from maxim.logger.gemini import MaximGeminiClient

client = MaximGeminiClient(
    client=genai.Client(api_key=GEMINI_API_KEY), 
    logger=logger
)
```

## Make LLM Calls Using MaximGeminiClient

```python theme={null}
from google import genai
from maxim.logger.gemini import MaximGeminiClient

client = MaximGeminiClient(
    client=genai.Client(api_key=GEMINI_API_KEY), 
    logger=logger
)

# Create a generation request
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Write a haiku about recursion in programming.",
    config={
        "temperature": 0.8,
        "system_instruction": "You are a helpful assistant."
    }
)

# Extract response text
response_text = response.text
print(response_text)
```

## Maxim-specific Headers

The Gemini instrumentation supports additional headers via the `http_options.headers` parameter within the `config` dictionary 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 HTTP Headers

```python theme={null}
import json
from uuid import uuid4
from google import genai
from maxim.logger.gemini import MaximGeminiClient

client = MaximGeminiClient(
    client=genai.Client(api_key=GEMINI_API_KEY), 
    logger=logger
)

trace_id = str(uuid4())

response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Explain how AI works",
    config={
        "system_instruction": "You are a helpful assistant",
        "temperature": 0.8,
        "http_options": {
            "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-Cases

### Function Calling Support

```python theme={null}
import os
import dotenv
from google import genai
from maxim import Maxim
from maxim.logger.gemini import MaximGeminiClient

# Load environment variables
dotenv.load_dotenv()
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")

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

# Initialize MaximGeminiClient
client = MaximGeminiClient(
    client=genai.Client(api_key=GEMINI_API_KEY), 
    logger=logger
)
```

### **Define function tools**

```python theme={null}
def get_current_weather(location: str) -> str:
    """Get the current weather in a given location.
    Args:
        location: required, The city and state, e.g. San Francisco, CA
    """
    print(f"Called with: {location=}")
    return "23°C, sunny"
```

### **Make calls with function tools**

```python theme={null}
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="What's the weather like in San Francisco?",
    config={
        "tools": [get_current_weather],
        "system_instruction": "You are a helpful assistant",
        "temperature": 0.8,
    }
)

print(response.text)
```

## Capture Multiple LLM Calls in One Trace

**Initialize Maxim SDK and Gemini Client**

```python theme={null}
from google import genai
from maxim import Maxim
from maxim.logger.gemini import MaximGeminiClient

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

# Initialize MaximGeminiClient
client = MaximGeminiClient(
    client=genai.Client(api_key=GEMINI_API_KEY), 
    logger=logger
)
```

**Create a new trace externally**

```python theme={null}
from uuid import uuid4
from maxim.logger import TraceConfig

trace_id = str(uuid4())

trace = logger.trace(TraceConfig(
    id=trace_id,
    name="Trace name"
))
```

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

```python theme={null}
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="What was the capital of France in 1800s?",
    config={
        "temperature": 0.8,
        "system_instruction": "You are a helpful assistant"
    },
    trace_id=trace_id
)

# Extract response text
response_text = response.text
print(response_text)

# End the trace when done
trace.end()
```

**Keep adding LLM calls** All LLM calls with the same `trace_id` parameter will be added to the declared trace.

## Capture Multi-Turn Conversations

**Initialize Maxim SDK and Gemini Client**

```python theme={null}
from google import genai
from maxim import Maxim
from maxim.logger.gemini import MaximGeminiClient

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

# Initialize MaximGeminiClient
client = MaximGeminiClient(
    client=genai.Client(api_key=GEMINI_API_KEY), 
    logger=logger
)
```

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

```python theme={null}
from uuid import uuid4
from maxim.logger import TraceConfig

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

trace = logger.trace(TraceConfig(
    id=trace_id,
    name="Trace name",
    session_id=session_id
))
```

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

```python theme={null}
# First message in the conversation
response1 = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Hello, can you help me with Python programming?",
    config={
        "temperature": 0.8,
        "system_instruction": "You are a helpful Python programming assistant"
    },
    trace_id=trace_id
)

response_text1 = response1.text
print("Assistant:", response_text1)

# Continue the conversation with follow-up question
response2 = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Can you write a simple Python function to calculate fibonacci numbers?",
    config={
        "temperature": 0.8,
        "system_instruction": "You are a helpful Python programming assistant"
    },
    trace_id=trace_id
)

response_text2 = response2.text
print("Assistant:", response_text2)

# End the trace when conversation is complete
trace.end()
```

**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(TraceConfig(
    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.models.generate_content(
    model="gemini-2.0-flash",
    contents="Tell me about machine learning basics",
    config={
        "temperature": 0.8,
        "system_instruction": "You are a helpful ML tutor"
    },
    trace_id=trace_id_2
)

print("Assistant:", response3.text)
trace2.end()
```

<img src="https://mintcdn.com/maximai/fHnWe0mnvuD5228y/images/gemini_traces.gif?s=cecb5edcdb6d9c2c7045f0a9c7ddcde9" alt="Gif" width="1280" height="720" data-path="images/gemini_traces.gif" />

## Resources

<CardGroup cols={2}>
  <Card title="Google Gemini integration Notebook (Colab)" icon="google" href="https://colab.research.google.com/drive/1qtjxlIIlOInQcRhXRP5eJvrWenXmJfSS?usp=sharing" />
</CardGroup>
