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

# Google Generative AI

> Trace Gemini text, image generation, embeddings, and Veo video generation in TypeScript and Python — works with both the legacy and new Google Gemini SDKs.

<Note>
  Available for: **Python** and **TypeScript**.
</Note>

Zespan supports both Google Gemini SDK generations, in both languages:

| SDK generation    | TypeScript package      | TypeScript wrapper                | Python package        | Python wrapper                               |
| ----------------- | ----------------------- | --------------------------------- | --------------------- | -------------------------------------------- |
| New (recommended) | `@google/genai`         | `wrapGoogleGenAI()` or auto-patch | `google-genai`        | `patch_google_genai()` — no auto-patch       |
| Legacy            | `@google/generative-ai` | `wrapGoogle()` or auto-patch      | `google-generativeai` | `patch_google()` — included in `autopatch()` |

Both SDKs produce `span_kind: llm` for text, `image_gen` for image generation, `embedding` for embeddings, and `video_gen` for Veo video generation.

***

## New SDK — `@google/genai`

The `@google/genai` package is Google's current SDK (v1+); the Python equivalent is `google-genai`. In TypeScript, use `wrapGoogleGenAI()` for explicit wrapping, or let auto-patch handle it. In Python, call `patch_google_genai()` explicitly before constructing any client — there is no auto-patch for this SDK generation, and no separate function to wrap an already-constructed client.

### Installation

<CodeGroup>
  ```bash TypeScript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  npm install @zespan/sdk @google/genai
  ```

  ```bash Python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  pip install zespan google-genai
  ```
</CodeGroup>

### Auto-patch (recommended)

Auto-patch traces all calls from any `GoogleGenAI` instance with no changes to existing code:

```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { zespan } from "@zespan/sdk";

zespan.init({ apiKey: process.env.ZESPAN_API_KEY! });
zespan.autoPatch(); // detects @google/genai automatically
```

<Note>
  Python has no auto-patch equivalent for this SDK generation. `autopatch()` covers the legacy `google-generativeai` package only (see below) — for `google-genai`, call `patch_google_genai()` explicitly, shown next.
</Note>

### Explicit wrapper

<CodeGroup>
  ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  import { GoogleGenAI } from "@google/genai";
  import { zespan } from "@zespan/sdk";

  zespan.init({ apiKey: process.env.ZESPAN_API_KEY! });

  const ai = zespan.wrapGoogleGenAI(new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY! }));
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  import os
  from google import genai
  import zespan

  zespan.init(api_key=os.environ["ZESPAN_API_KEY"])
  zespan.patch_google_genai()

  client = genai.Client(api_key=os.environ["GOOGLE_API_KEY"])
  ```
</CodeGroup>

<Note>
  Python has no `wrapGoogleGenAI()`-style function for wrapping an existing client instance. `patch_google_genai()` patches `Client.__init__` — call it before constructing `genai.Client()`, and every client created afterward is traced automatically.
</Note>

### Text generation

<CodeGroup>
  ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  const response = await ai.models.generateContent({
    model: "gemini-2.5-flash",
    contents: "Explain transformer attention in two sentences.",
  });
  console.log(response.text);
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  response = client.models.generate_content(
      model="gemini-2.5-flash",
      contents="Explain transformer attention in two sentences.",
  )
  print(response.text)
  ```
</CodeGroup>

### Image generation

Models ending in `-image` (e.g. `gemini-3.1-flash-image`, `gemini-2.5-flash-image`) return `inline_data` parts. Zespan detects this automatically and emits `span_kind: image_gen`, in both languages.

<CodeGroup>
  ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  const response = await ai.models.generateContent({
    model: "gemini-3.1-flash-image",
    contents: "Generate a photorealistic sunset over the ocean.",
  });

  // Image bytes available in parts
  const imagePart = response.candidates?.[0]?.content?.parts?.find(
    (p: any) => p.inlineData
  );
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  response = client.models.generate_content(
      model="gemini-3.1-flash-image",
      contents="Generate a photorealistic sunset over the ocean.",
  )

  # Image bytes available in parts
  image_part = next(
      (p for p in response.candidates[0].content.parts if getattr(p, "inline_data", None)),
      None,
  )
  ```
</CodeGroup>

### Embeddings

<CodeGroup>
  ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  const response = await ai.models.embedContent({
    model: "gemini-embedding-2",
    contents: "The quick brown fox jumps over the lazy dog.",
  });
  // Emits span_kind: embedding
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  response = client.models.embed_content(
      model="gemini-embedding-2",
      contents="The quick brown fox jumps over the lazy dog.",
  )
  # Emits span_kind: embedding
  ```
</CodeGroup>

### Video generation (Veo)

Video generation is a long-running operation. Zespan traces the initiation call with `span_kind: video_gen`, in both languages.

<CodeGroup>
  ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  const operation = await ai.models.generateVideos({
    model: "veo-3.1-generate-preview",
    prompt: "A slow-motion close-up of rain hitting a still lake.",
  });
  // Poll operation.name to check completion
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  operation = client.models.generate_videos(
      model="veo-3.1-generate-preview",
      prompt="A slow-motion close-up of rain hitting a still lake.",
  )
  # Poll operation.name to check completion
  ```
</CodeGroup>

***

## Legacy SDK — `@google/generative-ai`

In Python, the equivalent legacy package is `google-generativeai`, patched with `patch_google()`.

### Installation

<CodeGroup>
  ```bash TypeScript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  npm install @zespan/sdk @google/generative-ai
  ```

  ```bash Python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  pip install zespan google-generativeai
  ```
</CodeGroup>

### Setup

<CodeGroup>
  ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  import { GoogleGenerativeAI } from "@google/generative-ai";
  import { zespan } from "@zespan/sdk";

  zespan.init({ apiKey: process.env.ZESPAN_API_KEY! });

  const genAI = zespan.wrapGoogle(new GoogleGenerativeAI(process.env.GOOGLE_API_KEY!));
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  import os
  import google.generativeai as genai
  import zespan

  zespan.init(api_key=os.environ["ZESPAN_API_KEY"])
  zespan.patch_google()

  genai.configure(api_key=os.environ["GOOGLE_API_KEY"])
  ```
</CodeGroup>

<Note>
  Unlike the new `google-genai` SDK, `patch_google()` is included in Python's `autopatch()` — calling `zespan.autopatch()` instead of `zespan.patch_google()` also traces this SDK, alongside OpenAI, Anthropic, Bedrock, Mistral, Groq, and LiteLLM.
</Note>

### Example

<CodeGroup>
  ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });

  const result = await model.generateContent("Explain token pricing in two sentences.");
  console.log(result.response.text());
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  model = genai.GenerativeModel("gemini-2.5-flash")

  result = model.generate_content("Explain token pricing in two sentences.")
  print(result.text)
  ```
</CodeGroup>

Also patches `genai.embed_content()` (Python) / `embedContent()` (TypeScript) automatically — embedding calls emit `span_kind: embedding`. Image generation models are detected from the response and emit `span_kind: image_gen`, in both languages.

### Chat sessions

<CodeGroup>
  ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });
  const chat = model.startChat();

  const result = await chat.sendMessage("What is Zespan?");
  console.log(result.response.text());
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
  model = genai.GenerativeModel("gemini-2.5-flash")
  chat = model.start_chat()

  result = chat.send_message("What is Zespan?")
  print(result.text)
  ```
</CodeGroup>

Each `sendMessage`/`send_message` call is traced as a separate span in the session. In Python, `patch_google()` patches `GenerativeModel.generate_content` at the class level, and `ChatSession.send_message()` calls that same method internally — so chat sessions are traced automatically with no extra step.

***

## What gets captured

| Field           | Details                                                                  |
| --------------- | ------------------------------------------------------------------------ |
| `span_kind`     | `llm` (text), `image_gen` (image models), `embedding`, `video_gen` (Veo) |
| `model`         | Model name as passed, e.g. `gemini-2.5-flash`                            |
| `input_tokens`  | From `usageMetadata.promptTokenCount`                                    |
| `output_tokens` | From `usageMetadata.candidatesTokenCount`                                |
| `cached_tokens` | From `usageMetadata.cachedContentTokenCount`                             |
| `cost_usd`      | Calculated from token counts and Google list pricing                     |
| `latency_ms`    | Total request duration                                                   |
| `finish_reason` | `STOP`, `MAX_TOKENS`, `SAFETY`, etc.                                     |

***

## Supported models

See [Models & pricing](/reference/models) for the full Gemini pricing table, including image gen, TTS, Veo, and embedding models.

## Next steps

* [Google ADK](/sdk/integrations/google-adk) — trace full ADK agents built with Gemini
* [Agent tracing](/sdk/agent-tracing) — wrap multi-agent workflows
* [Span kinds](/reference/span-kinds) — understand `image_gen`, `video_gen`, `embedding`
