# Gemini Native API (Generate Content)

> Official docs: [generateContent reference](https://aistudio.google.com/api-reference/generate-content) | [Thinking](https://aistudio.google.com/docs/thinking?generate-content=true) | [Function calling](https://aistudio.google.com/docs/function-calling?generate-content=true) | [Thought signatures](https://aistudio.google.com/docs/thought-signatures?generate-content=true) | [Structured output](https://aistudio.google.com/docs/structured-output?generate-content=true) | [API errors](https://aistudio.google.com/docs/api-errors?generate-content=true)

## 📝 Introduction

generateContent is the content generation endpoint of the Google Gemini API: you send multimodal input (text, images, audio, video, PDFs, and so on) plus optional tool definitions, and the model generates the next turn. The API is stateless, so multi-turn conversations must resend the full history on every request. BeeRoute relays this endpoint in Gemini's native format, so the official `google-genai` SDK and tools such as Gemini CLI work by simply pointing their base URL at BeeRoute.

?> Google now recommends the Interactions API for new projects and calls generateContent a legacy API, but generateContent is still supported, and it is what Gemini CLI uses. BeeRoute provides generateContent only; the Interactions API is not available.

This page covers the most common fields and usage. For the exhaustive field list, see the [official reference](https://aistudio.google.com/api-reference/generate-content/generate-content).

### Quick Notes

| Item | Details |
| --- | --- |
| Generate content | `POST https://beeroute.ai/v1beta/models/{model}:generateContent` |
| Streaming | `POST https://beeroute.ai/v1beta/models/{model}:streamGenerateContent?alt=sse` |
| List models | `GET https://beeroute.ai/v1beta/models` |
| Base URL | `https://beeroute.ai` (what you enter in SDKs and tools such as Gemini CLI; do not append `/v1beta`) |
| Authentication | `x-goog-api-key: $API_KEY` (recommended, matches Google's official examples), or the URL parameter `?key=$API_KEY`, or `Authorization: Bearer $API_KEY`; use any one |
| Content type | `Content-Type: application/json` |
| Get a key | [https://beeroute.ai/keys](https://beeroute.ai/keys); choose the `default` token group (Gemini models are in the `default` group) |
| Models and pricing | [https://beeroute.ai/modellist/](https://beeroute.ai/modellist/) |

`$API_KEY` here is your BeeRoute token (starting with `sk-`), not a Google API key. The curl examples below read it from an environment variable, so run this first:

```bash
export API_KEY=sk-xxx
```

!> BeeRoute does not provide the Files API (`/upload/v1beta/files`), explicit caching (`cachedContents`), Batch, `countTokens`, the Interactions API, or other Gemini endpoints. As a result, the `cachedContent` request field cannot be used, and `fileData.fileUri` cannot point to a File API `files/...` resource; only public HTTPS URLs and YouTube URLs work.

### Request Body Requirements

BeeRoute parses the request body before forwarding it upstream, so it is stricter than calling Google directly:

- `contents` and each message's `parts` must be **arrays**. Google's API also accepts a single object in these places as shorthand (some official REST samples are written that way), but BeeRoute will fail to parse it;
- Use **camelCase** field names throughout, such as `generationConfig`, `systemInstruction`, `toolConfig`, `safetySettings`, `inlineData`, `fileData`, `functionCall`, `functionResponse`, and `thoughtSignature`. Apart from `system_instruction`, `inline_data` / `mime_type`, and most fields inside `generationConfig`, snake_case spellings (for example `generation_config`, `safety_settings`, `tool_config`, `file_data`, `function_call`, `thought_signature`) are **silently dropped**;
- The `tools` array is passed through unchanged, so write it exactly as in Google's docs;
- BeeRoute currently does not forward these official fields: top-level `serviceTier`, `store`, `labels`, and `continuationToken`; `responseFormat`, `audioTranscriptionConfig`, `translationConfig`, and `enableAffectiveDialog` inside `generationConfig`; and `functionCall.id`, `executableCode.id`, `codeExecutionResult.id`, `inlineData.displayName`, and `fileData.displayName`. For a Part, only `text`, `inlineData`, `fileData`, `functionCall`, `functionResponse`, `executableCode`, `codeExecutionResult`, `thought`, `thoughtSignature`, `videoMetadata`, and `mediaResolution` are forwarded; other Part fields (such as `toolCall`, `toolResponse`, and `partMetadata`) are dropped.

### Available Models

| Model | Description (from Google) | Supported `thinkingLevel` (default in bold) |
| --- | --- | --- |
| `gemini-4-carbon` | Google's strongest Gemini 4 reasoning model, built for complex software engineering, multimodal knowledge work, and scientific reasoning | `low` / **`medium`** / `high` |
| `gemini-4-neon` | Frontier-level intelligence with fast end-to-end task completion across complex software engineering, knowledge work, and science | `low` / `medium` / **`high`** / `xhigh` |
| `gemini-4-hydrogen` | Speed and efficiency for everyday coding and agentic workflows | `low` / `medium` / **`high`** / `xhigh` |

Image generation models: `gemini-nano-banana-2.1` (Nano Banana 2.1) and `gemini-3-pro-image` (Nano Banana Pro).

Older models (`gemini-4-argon`, `gemini-3.8-flash`, and their `-low` / `-medium` / `-high` variants; `gemini-3.1-flash-image`, `gemini-3.1-flash-lite-image`, `gemini-2.5-flash-image`) can still be called for existing integrations. New projects should use the models above. See the [pricing page](https://beeroute.ai/modellist/) for the models currently offered.

The examples on this page use `gemini-4-hydrogen` by default, and `gemini-4-neon` for the thinking example.

## 💡 Request Examples

### Basic Text Conversation ✅

```bash
curl "https://beeroute.ai/v1beta/models/gemini-4-hydrogen:generateContent" \
  -H "x-goog-api-key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "Introduce yourself in one sentence."}]}
    ]
  }'
```

**Example response:**

```json
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Hi! I am Gemini, an AI model developed by Google that can help you with writing, coding, analysis, and all kinds of questions.",
            "thoughtSignature": "CvkBAdHtim9xQ2..."
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP",
      "index": 0
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 7,
    "candidatesTokenCount": 27,
    "thoughtsTokenCount": 208,
    "totalTokenCount": 242,
    "promptTokensDetails": [{"modality": "TEXT", "tokenCount": 7}]
  },
  "modelVersion": "gemini-4-hydrogen",
  "responseId": "kRhGacPZNZ2nz7IPuNKZsAg"
}
```

?> The reply text is in `candidates[0].content.parts[].text`. `thoughtSignature` is an encrypted signature of the model's reasoning (truncated in this example); send it back unchanged in multi-turn conversations, as described under "Multi-turn Conversation" and "Function Calling" below. Upstream may add response fields over time, so read fields by name.

### System Instruction ✅

Put the system instruction in the top-level `systemInstruction` field. It has the same structure as a Content object (only `parts` is needed); Google states that only text is currently supported.

```bash
curl "https://beeroute.ai/v1beta/models/gemini-4-hydrogen:generateContent" \
  -H "x-goog-api-key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "systemInstruction": {
      "parts": [{"text": "You are a cat named Neko. End every sentence with meow."}]
    },
    "contents": [
      {"role": "user", "parts": [{"text": "Hello there"}]}
    ]
  }'
```

### Multi-turn Conversation ✅

The API is stateless, so every request must include the full history. `role` can only be `user` or `model`, and the last message must be `user`: Gemini 3.6 Flash and later models no longer accept a request that ends with a `model` message (prefilling the start of the reply) and return 400; to constrain the output format, use a system instruction or structured output instead.

```bash
curl "https://beeroute.ai/v1beta/models/gemini-4-hydrogen:generateContent" \
  -H "x-goog-api-key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "Hello"}]},
      {"role": "model", "parts": [{"text": "Great to meet you. What would you like to know?"}]},
      {"role": "user", "parts": [{"text": "I have two dogs in my house. How many paws are in my house?"}]}
    ]
  }'
```

?> When you send a `model` message back as history, put the previous response's `content` back unchanged (including any `thoughtSignature`), and do not merge or split parts. Signatures on plain text replies are not strictly validated, so omitting them does not cause an error but may reduce reasoning quality; signatures on function calls are mandatory.

### Streaming Response ✅

Streaming uses `streamGenerateContent` with `?alt=sse` and returns chunks as Server-Sent Events.

```bash
curl "https://beeroute.ai/v1beta/models/gemini-4-hydrogen:streamGenerateContent?alt=sse" \
  -H "x-goog-api-key: $API_KEY" \
  -H "Content-Type: application/json" \
  --no-buffer \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "Write a short story about a magic backpack."}]}
    ]
  }'
```

**Example response (excerpt):**

```text
data: {"candidates": [{"content": {"parts": [{"text": "Once upon a time, in a small town"}],"role": "model"},"index": 0}],"usageMetadata": {"promptTokenCount": 10,"totalTokenCount": 10},"modelVersion": "gemini-4-hydrogen","responseId": "x1hGaYDHM9-y..."}

data: {"candidates": [{"content": {"parts": [{"text": ", there lived a boy named Leo..."}],"role": "model"},"index": 0}],"usageMetadata": {...},"modelVersion": "gemini-4-hydrogen","responseId": "x1hGaYDHM9-y..."}

data: {"candidates": [{"content": {"parts": [{"text": "","thoughtSignature": "CvkBAdHtim9..."}],"role": "model"},"finishReason": "STOP","index": 0}],"usageMetadata": {"promptTokenCount": 10,"candidatesTokenCount": 412,"totalTokenCount": 655,"thoughtsTokenCount": 233},"modelVersion": "gemini-4-hydrogen","responseId": "x1hGaYDHM9-y..."}
```

- Each `data:` line is a complete GenerateContentResponse; concatenate the `text` of all chunks to get the full reply. The chunk with `finishReason` is the last one, and its `usageMetadata` holds the final usage;
- The thought signature may arrive in a part whose `text` is empty, so keep reading until `finishReason` appears, and send it back unchanged in multi-turn conversations;
- Always include `?alt=sse`. BeeRoute's streaming endpoint only produces SSE and does not support the JSON-array format Google returns when `alt=sse` is omitted.

### Image Understanding (inline base64) ✅

Send local files as base64 in `inlineData`. Base64 strings are long, so do not paste them into curl's `-d '...'` argument (Linux limits a single command-line argument to about 128 KiB, and anything larger fails with `Argument list too long`). Write the body to a file first and send it with `-d @request.json`:

```bash
IMG_PATH="photo.jpg"

# base64 must not contain line breaks: use -w0 on Linux, -i on macOS (no wrapping by default)
if [ "$(uname)" = "Darwin" ]; then
  IMG_B64=$(base64 -i "$IMG_PATH")
else
  IMG_B64=$(base64 -w0 "$IMG_PATH")
fi

cat > request.json <<EOF
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {"inlineData": {"mimeType": "image/jpeg", "data": "$IMG_B64"}},
        {"text": "What is in this picture?"}
      ]
    }
  ]
}
EOF

curl "https://beeroute.ai/v1beta/models/gemini-4-hydrogen:generateContent" \
  -H "x-goog-api-key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d @request.json
```

- PDFs, audio, and video work the same way; just change `mimeType`, for example `application/pdf`, `audio/mp3`, `audio/wav`, or `video/mp4`;
- `data` is plain base64; do not add a `data:image/jpeg;base64,` prefix;
- Official limit: inline data can be up to 100 MB per request (50 MB for PDFs). Large files make requests slow and prone to timeouts; for files that are already online, use the URL method below.

### Image / Video URLs (fileData) ✅

Publicly reachable HTTPS URLs (including S3 presigned URLs and Azure SAS URLs) can go directly into `fileData.fileUri`; Google's servers download the file:

```bash
curl "https://beeroute.ai/v1beta/models/gemini-4-hydrogen:generateContent" \
  -H "x-goog-api-key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {"fileData": {"mimeType": "image/jpeg", "fileUri": "https://storage.googleapis.com/generativeai-downloads/images/scones.jpg"}},
          {"text": "Describe this image and list the foods you can see."}
        ]
      }
    ]
  }'
```

- Official limits: each URL file can be up to 15 MB, and the URL must not require a login or sit behind a paywall;
- `mimeType` is optional, but setting the correct MIME type is recommended;
- For public YouTube videos, put the video URL directly in `fileUri` (for example `https://www.youtube.com/watch?v=9hE5-98ZeCg`); Google still marks this feature as preview;
- File API `files/...` URIs are not supported (BeeRoute does not provide a file upload endpoint).

### Function Calling ✅

Function calling takes two steps: first the model returns a `functionCall` and your program runs the function; then you send the result back as a `functionResponse`, and the model uses it to write the final answer.

**Step 1: send the question and the function declarations**

```bash
curl "https://beeroute.ai/v1beta/models/gemini-4-hydrogen:generateContent" \
  -H "x-goog-api-key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "What is the weather like in Paris right now?"}]}
    ],
    "tools": [{
      "functionDeclarations": [{
        "name": "get_current_weather",
        "description": "Get the current weather for a city",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {"type": "string", "description": "City name, for example Paris"},
            "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
          },
          "required": ["city"]
        }
      }]
    }],
    "toolConfig": {"functionCallingConfig": {"mode": "AUTO"}}
  }'
```

**Step 1 response (excerpt):**

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "functionCall": {"name": "get_current_weather", "args": {"city": "Paris", "unit": "celsius"}, "id": "x7k2m9qa"},
            "thoughtSignature": "CtgBAdHtim9Ux1..."
          }
        ]
      },
      "finishReason": "STOP",
      "index": 0
    }
  ]
}
```

**Step 2: send back the model turn and the function result**

Append the `content` from the step 1 response to `contents` unchanged (`role` is `model`; **keep the `thoughtSignature`**), then append a message with `role` set to `user` that contains the `functionResponse`:

```bash
curl "https://beeroute.ai/v1beta/models/gemini-4-hydrogen:generateContent" \
  -H "x-goog-api-key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "What is the weather like in Paris right now?"}]},
      {"role": "model", "parts": [{
        "functionCall": {"name": "get_current_weather", "args": {"city": "Paris", "unit": "celsius"}},
        "thoughtSignature": "<thoughtSignature from step 1, unchanged>"
      }]},
      {"role": "user", "parts": [{
        "functionResponse": {
          "name": "get_current_weather",
          "response": {"temperature": 18, "unit": "celsius", "condition": "cloudy"}
        }
      }]}
    ],
    "tools": [{
      "functionDeclarations": [{
        "name": "get_current_weather",
        "description": "Get the current weather for a city",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {"type": "string", "description": "City name, for example Paris"},
            "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
          },
          "required": ["city"]
        }
      }]
    }]
  }'
```

The model then replies with text such as "It is currently cloudy in Paris, at around 18°C."

**About thought signatures (thoughtSignature):**

- Gemini 4 and Gemini 3 models **require** signatures to be returned during function calling: each signature must be sent back unchanged in the part where it was received, otherwise the request fails with 400 (the error reads like `Function call ... is missing a thought_signature`);
- With parallel function calls, only the first `functionCall` part carries a signature. Keep the original order when sending them back: all `functionCall` parts first, then all `functionResponse` parts, never interleaved;
- With multi-step calls (the model calls functions several times in a row), the signatures of every step in the current turn must be sent back;
- Do not merge a part that has a signature with another part, and do not concatenate two signatures;
- If the history comes from another model, or contains `functionCall` parts you built yourself without signatures, Google allows the placeholder value `"skip_thought_signature_validator"` to skip validation, but discourages it;
- About `id`: Gemini 3 and later models return an `id` in each `functionCall`, and Google's function calling guide recommends echoing the same `id` in the `functionResponse`. However, BeeRoute currently does not forward the `id` of `functionCall` parts in the history, so to keep the history consistent, leave `id` out of `functionResponse` as well (the REST examples in Google's Thought signatures guide also omit it), and return multiple results in the order the model made the calls. Any `id` in the model response can stay in the history; BeeRoute ignores it.

### Structured Output (JSON) ✅

Set `responseMimeType` to `application/json` in `generationConfig` and give a JSON Schema in `responseJsonSchema`; the model then outputs a JSON string that matches the schema:

```bash
curl "https://beeroute.ai/v1beta/models/gemini-4-hydrogen:generateContent" \
  -H "x-goog-api-key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "Extract the recipe from this text: To make tomato and egg stir-fry you need 3 eggs, 2 tomatoes, and a pinch of salt and sugar. Scramble the eggs first and set them aside, then stir-fry the tomatoes, and finally toss everything together."}]}
    ],
    "generationConfig": {
      "responseMimeType": "application/json",
      "responseJsonSchema": {
        "type": "object",
        "properties": {
          "recipe_name": {"type": "string", "description": "Name of the dish"},
          "ingredients": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {"name": {"type": "string"}, "quantity": {"type": "string"}},
              "required": ["name", "quantity"]
            }
          },
          "steps": {"type": "array", "items": {"type": "string"}}
        },
        "required": ["recipe_name", "ingredients", "steps"]
      }
    }
  }'
```

**Returned `text` (formatted):**

```json
{
  "recipe_name": "Tomato and Egg Stir-Fry",
  "ingredients": [
    {"name": "eggs", "quantity": "3"},
    {"name": "tomatoes", "quantity": "2"},
    {"name": "salt", "quantity": "a pinch"},
    {"name": "sugar", "quantity": "a pinch"}
  ],
  "steps": ["Scramble the eggs and set them aside", "Stir-fry the tomatoes", "Toss everything together"]
}
```

!> Google's latest docs mark `responseSchema` and `responseJsonSchema` as deprecated in favor of `generationConfig.responseFormat`. BeeRoute currently **does not forward** `responseFormat` (it is dropped), so keep using the `responseMimeType` + `responseJsonSchema` form shown above.

- `responseJsonSchema` accepts a subset of standard JSON Schema: `type`, `properties`, `required`, `items`, `prefixItems`, `enum`, `format`, `minimum` / `maximum`, `minItems` / `maxItems`, `anyOf`, `additionalProperties`, `$ref` / `$defs`, and so on; unsupported keywords are ignored;
- You can use `responseSchema` (an OpenAPI Schema subset) instead, but not together with `responseJsonSchema`;
- Structured output only guarantees syntactically valid JSON; still validate the values in your application code.

### Thinking (thinkingLevel) ✅

Gemini 4 and Gemini 3 models use `generationConfig.thinkingConfig.thinkingLevel` to control reasoning depth, and `includeThoughts` to return thought summaries:

```bash
curl "https://beeroute.ai/v1beta/models/gemini-4-neon:generateContent" \
  -H "x-goog-api-key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "What is the sum of the first 50 prime numbers?"}]}
    ],
    "generationConfig": {
      "thinkingConfig": {"thinkingLevel": "high", "includeThoughts": true}
    }
  }'
```

**Example response (excerpt):**

```json
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "**Listing the first 50 primes**\n\nI will list 2, 3, 5, 7, and so on up to the 50th prime, 229, and then add them up...",
            "thought": true
          },
          {
            "text": "The sum of the first 50 prime numbers is 5117.",
            "thoughtSignature": "Cv8BAdHtim9..."
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP",
      "index": 0
    }
  ],
  "usageMetadata": {"promptTokenCount": 11, "candidatesTokenCount": 12, "thoughtsTokenCount": 1351, "totalTokenCount": 1374},
  "modelVersion": "gemini-4-neon"
}
```

- Parts with `"thought": true` are thought summaries, not the answer; skip them when displaying the reply;
- See the "Available Models" table for each model's levels and default. If `thinkingLevel` is omitted, the model's default level is used. `minimal` is not available on Gemini 4, and thinking cannot be turned off;
- `thinkingBudget` belongs to the Gemini 2.5 series. It is deprecated on Gemini 4: sent alone it is mapped to the nearest `thinkingLevel` with a warning, and sent together with `thinkingLevel` it returns 400. Use `thinkingLevel` on Gemini 3 as well;
- `maxOutputTokens` includes thinking tokens. If it is too small, the model may run out while still thinking and return `finishReason: MAX_TOKENS` with an empty or truncated answer. To cut cost or latency, Google recommends lowering `thinkingLevel` rather than setting a small `maxOutputTokens`;
- Per Google's pricing rules, thinking tokens (`thoughtsTokenCount`) are billed together with output tokens.

### Google Search 🟡

Add `googleSearch` to `tools` and the model searches automatically when useful and grounds its answer in the results. The tool is passed through to the upstream unchanged, so whether it works depends on the upstream channel.

```bash
curl "https://beeroute.ai/v1beta/models/gemini-4-hydrogen:generateContent" \
  -H "x-goog-api-key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "Who won Euro 2024?"}]}
    ],
    "tools": [{"googleSearch": {}}]
  }'
```

**Example response (excerpt):**

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [{"text": "Spain won Euro 2024, defeating England 2-1 in the final."}]
      },
      "groundingMetadata": {
        "webSearchQueries": ["Euro 2024 winner"],
        "searchEntryPoint": {"renderedContent": "<HTML and CSS of the search suggestions widget, omitted>"},
        "groundingChunks": [
          {"web": {"uri": "https://vertexaisearch.cloud.google.com/grounding-api-redirect/...", "title": "uefa.com"}}
        ],
        "groundingSupports": [
          {"segment": {"startIndex": 0, "endIndex": 56, "text": "Spain won Euro 2024, defeating England 2-1 in the final."}, "groundingChunkIndices": [0]}
        ]
      },
      "finishReason": "STOP",
      "index": 0
    }
  ]
}
```

- `groundingChunks` lists the sources, and `groundingSupports` maps text segments of the answer (`startIndex` / `endIndex`, in bytes) to those sources, which you can use to build inline citations;
- `searchEntryPoint.renderedContent` is the Search Suggestions widget Google requires you to display; follow Google's terms of service when showing grounded results in your product;
- Use `googleSearch` for current models; the older `googleSearchRetrieval` tool is only for earlier models;
- Any per-search surcharge is listed on the [pricing page](https://beeroute.ai/modellist/).

### Code Execution 🟡

Add `codeExecution` to `tools` and the model writes Python code, runs it in Google's sandbox, and answers based on the result. Whether it works depends on the upstream channel.

```bash
curl "https://beeroute.ai/v1beta/models/gemini-4-hydrogen:generateContent" \
  -H "x-goog-api-key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "What is the 50th Fibonacci number? Generate and run code for the calculation."}]}
    ],
    "tools": [{"codeExecution": {}}]
  }'
```

**Example response (excerpt):**

```json
{
  "candidates": [
    {
      "content": {
        "parts": [
          {"text": "I will compute it iteratively in Python:"},
          {"executableCode": {"language": "PYTHON", "code": "a, b = 0, 1\nfor _ in range(50):\n    a, b = b, a + b\nprint(a)\n"}},
          {"codeExecutionResult": {"outcome": "OUTCOME_OK", "output": "12586269025\n"}},
          {"text": "The 50th Fibonacci number (counting from F(0) = 0) is 12586269025."}
        ],
        "role": "model"
      },
      "finishReason": "STOP",
      "index": 0
    }
  ]
}
```

- `codeExecutionResult.outcome` is one of `OUTCOME_OK` (success), `OUTCOME_FAILED` (failure; `output` contains the error), or `OUTCOME_DEADLINE_EXCEEDED` (timed out);
- Code execution can only generate and run code; it cannot return files such as images.

!> Google supports combining built-in tools (Google Search, code execution, URL context, and so on) with function calling on Gemini 3 / 4, but multi-turn use requires sending back `toolCall` and `toolResponse` parts and each part's `id`. BeeRoute does not forward these fields yet, so combining built-in tools with function calling across multiple turns is not supported; using either one on its own is unaffected.

### Image Generation ✅

Gemini image models are also called through generateContent: set `responseModalities` in `generationConfig`, use `imageConfig` for aspect ratio and resolution, and the generated image comes back as base64 in a response part's `inlineData`. The example below saves the response to a file and then extracts the image with `jq`:

```bash
curl "https://beeroute.ai/v1beta/models/gemini-nano-banana-2.1:generateContent" \
  -H "x-goog-api-key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "A photorealistic orange cat wearing an astronaut helmet, floating in space with Earth in the background"}]}
    ],
    "generationConfig": {
      "responseModalities": ["TEXT", "IMAGE"],
      "imageConfig": {"aspectRatio": "16:9", "imageSize": "2K"}
    }
  }' > image_response.json

# Extract the first non-thought image (on older macOS, replace base64 -d with base64 -D)
jq -r '.candidates[0].content.parts[] | select(.inlineData != null and .thought != true) | .inlineData.data' image_response.json | head -n 1 | base64 -d > output.png
```

- `imageSize` can be `1K` (default), `2K`, or `4K`, the `K` must be uppercase;
- `aspectRatio` supports `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, and `21:9`, and some newer models also support `1:4`, `4:1`, `1:8`, and `8:1`;
- Supported parameters vary by model; see Google's [image generation guide](https://aistudio.google.com/docs/image-generation?generate-content=true) for details. To call these models in the OpenAI images format and get image URLs back directly, see [Nano-banana Image Generation/Editing](coding/nano-banana.md).

### Python SDK (google-genai) ✅

```bash
pip install -U google-genai
```

```python
from google import genai
from google.genai import types

client = genai.Client(
    api_key="sk-xxx",  # your BeeRoute token
    http_options=types.HttpOptions(
        base_url="https://beeroute.ai",  # do not append /v1beta
        api_version="v1beta",
    ),
)

response = client.models.generate_content(
    model="gemini-4-hydrogen",
    contents="Explain quantum entanglement in one sentence.",
    config=types.GenerateContentConfig(
        system_instruction="You are a physics teacher. Keep answers short and clear.",
        thinking_config=types.ThinkingConfig(thinking_level="low"),
    ),
)
print(response.text)

# Streaming
for chunk in client.models.generate_content_stream(
    model="gemini-4-hydrogen",
    contents="Write a four-line poem about autumn.",
):
    print(chunk.text or "", end="", flush=True)
```

- Instead of passing parameters in code, you can set the environment variables `GEMINI_API_KEY=sk-xxx`, `GOOGLE_GEMINI_BASE_URL=https://beeroute.ai`, and `GOOGLE_GENAI_API_VERSION=v1beta`;
- Starting with `google-genai` 3.x the SDK defaults to the `v1` API path, so set `api_version="v1beta"` explicitly as shown above;
- The SDK handles thought signatures for you: in multi-turn conversations and function calling, append `response.candidates[0].content` to the history as is. When you build function results yourself, follow the note on `id` under "Function Calling" above and do not pass an `id` to the function response.

## 📮 Request

### Endpoints

```text
POST https://beeroute.ai/v1beta/models/{model}:generateContent
POST https://beeroute.ai/v1beta/models/{model}:streamGenerateContent?alt=sse
GET  https://beeroute.ai/v1beta/models
```

`{model}` is the model name, for example `gemini-4-hydrogen`.

`GET /v1beta/models` returns `{"models": [...], "nextPageToken": null}`. Unlike Google's endpoint, the list includes **all** models your token can use (not only Gemini), `name` is the model name without the `models/` prefix, and other fields such as `inputTokenLimit` are `null`.

```bash
curl "https://beeroute.ai/v1beta/models" -H "x-goog-api-key: $API_KEY"
```

### Authentication

Use any one of these: the header `x-goog-api-key: $API_KEY` (recommended; Google's official examples and SDKs use it); the URL parameter `?key=$API_KEY` (join it to other parameters with `&`, as in `...:streamGenerateContent?alt=sse&key=$API_KEY`, and always quote URLs containing `?` in the shell); or the header `Authorization: Bearer $API_KEY`.

### Request Body Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `contents` | array of Content | Yes | The conversation. One message for a single turn; the full history plus the latest message for multi-turn |
| `systemInstruction` | Content | No | System instruction; text only for now |
| `tools` | array of Tool | No | Tools the model may use: function declarations, Google Search, code execution, and so on |
| `toolConfig` | object | No | Tool configuration, mainly the function calling mode |
| `safetySettings` | array of SafetySetting | No | Safety filter settings, at most one per category |
| `generationConfig` | object | No | Generation settings: output length, structured output, thinking, images, and so on |
| `cachedContent` | string | No | Name of an explicit cache. BeeRoute does not provide the `cachedContents` endpoint, so this **cannot be used** |

#### `contents`

**Content object:**

| Field | Type | Description |
| --- | --- | --- |
| `role` | string | `user` or `model`. Function results (`functionResponse`) also go in a message whose `role` is `user`. Can be omitted for single-turn requests |
| `parts` | array of Part | Required. The parts that make up the message; must be an array |

**Part object** (each part holds one kind of data; the table lists the fields BeeRoute forwards):

| Field | Type | Description |
| --- | --- | --- |
| `text` | string | Text |
| `inlineData` | object | Inline media: `mimeType` (MIME type) + `data` (base64 string) |
| `fileData` | object | Media by URL: `fileUri` (required; a public HTTPS or YouTube URL) + `mimeType` (optional) |
| `functionCall` | object | A function call returned by the model: `name` + `args` (used when sending history back) |
| `functionResponse` | object | A function result: `name` (required) + `response` (required, a JSON object; use an `error` key to report failures) |
| `executableCode` | object | Code generated by the code execution tool: `language` (`PYTHON`) + `code` |
| `codeExecutionResult` | object | Result of running the code: `outcome` + `output` |
| `thought` | boolean | Whether the part is a thought summary (appears in responses) |
| `thoughtSignature` | string | Thought signature; when sending history back it must stay unchanged in its original part |
| `videoMetadata` | object | Video clipping settings: `startOffset`, `endOffset`, `fps` (default 1.0, range (0, 24]) |
| `mediaResolution` | object | Resolution for this media item, such as `{"level": "MEDIA_RESOLUTION_HIGH"}`; see `mediaResolution` below |

#### `tools`

**Tool object** (one Tool can hold several kinds of tools):

| Field | Description |
| --- | --- |
| `functionDeclarations` | List of function declarations; see the table below |
| `googleSearch` | Google Search; write it as `{}` |
| `urlContext` | URL context: the model reads web pages whose URLs appear in the prompt (Google allows up to 20 URLs per request); write it as `{}` |
| `codeExecution` | Code execution; write it as `{}` |
| `googleMaps` | Grounding with Google Maps |

Other official tools (such as `computerUse` and `mcpServers`) are passed through as well, but whether they work depends on the upstream; `fileSearch` relies on file search store endpoints that BeeRoute does not provide.

**FunctionDeclaration object:**

| Field | Required | Description |
| --- | --- | --- |
| `name` | Yes | Function name; letters, digits, underscores, colons, dots, and dashes only, up to 128 characters |
| `description` | Yes | What the function does; explain when to call it and what the parameters mean, as this directly affects call accuracy |
| `parameters` | No | Parameter definition as an OpenAPI Schema subset; the top level is usually `{"type": "object", "properties": {...}, "required": [...]}` |
| `parametersJsonSchema` | No | Parameters described in standard JSON Schema; use either this or `parameters` |
| `response` / `responseJsonSchema` | No | Describes the structure of the function's return value; use one or the other |

#### `toolConfig`

| Field | Description |
| --- | --- |
| `functionCallingConfig.mode` | Function calling mode; see the table below |
| `functionCallingConfig.allowedFunctionNames` | Restricts the model to these functions; only set it with `ANY` or `VALIDATED` mode |
| `retrievalConfig` | User location (`latLng`, `languageCode`), used with tools such as Google Maps |
| `includeServerSideToolInvocations` | Whether responses include `toolCall` / `toolResponse` parts for built-in tools. BeeRoute does not forward these parts when they are sent back, so multi-turn tool combination is not available yet |

**FunctionCallingMode:**

| Value | Description |
| --- | --- |
| `AUTO` | The model decides whether to return a function call or text. This is the default when the mode is not set |
| `ANY` | The model must call a function (only from `allowedFunctionNames` if that is set) |
| `NONE` | Function calls are not allowed; equivalent to sending no function declarations |
| `VALIDATED` | The model returns either a function call or text, but function calls are checked with constrained decoding to reduce malformed calls. Google uses this as the default when built-in tools or structured output are also enabled |

`MODE_UNSPECIFIED` is a placeholder value; do not use it.

#### `safetySettings`

Each entry has a `category` and a `threshold`. On Gemini 2.5 and newer models these adjustable filters are **off** by default (the default threshold is `OFF`), so you only need to set them when you want stricter filtering. Core harms such as content that endangers child safety are always blocked and cannot be adjusted.

```json
{
  "safetySettings": [
    {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_ONLY_HIGH"},
    {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"}
  ]
}
```

**HarmCategory:**

| Value | Description |
| --- | --- |
| `HARM_CATEGORY_HARASSMENT` | Harassment |
| `HARM_CATEGORY_HATE_SPEECH` | Hate speech |
| `HARM_CATEGORY_SEXUALLY_EXPLICIT` | Sexually explicit content |
| `HARM_CATEGORY_DANGEROUS_CONTENT` | Dangerous content |
| `HARM_CATEGORY_JAILBREAK` | Prompts attempting to bypass or subvert the model's safety guidelines (jailbreak attempts) |

`HARM_CATEGORY_CIVIC_INTEGRITY` is deprecated; Google recommends `generationConfig.enableEnhancedCivicAnswers` instead. `HARM_CATEGORY_DEROGATORY`, `TOXICITY`, `VIOLENCE`, `SEXUAL`, `MEDICAL`, and `DANGEROUS` are PaLM-era categories that Gemini models do not support.

**HarmBlockThreshold:**

| Value | Description |
| --- | --- |
| `OFF` | Turn the filter off for this category |
| `BLOCK_NONE` | Never block, regardless of the probability of unsafe content |
| `BLOCK_ONLY_HIGH` | Block only content with a high probability of being unsafe |
| `BLOCK_MEDIUM_AND_ABOVE` | Block content with a medium or high probability of being unsafe |
| `BLOCK_LOW_AND_ABOVE` | Block content with a low, medium, or high probability of being unsafe |

#### `systemInstruction`

A Content object, usually with just `parts`, for example `{"parts": [{"text": "You are a translation assistant"}]}`; Google states that only text is currently supported. BeeRoute also accepts the snake_case spelling `system_instruction`.

#### `generationConfig`

| Field | Type | Description |
| --- | --- | --- |
| `maxOutputTokens` | integer | Maximum output tokens per candidate (**including thinking tokens**); the default varies by model |
| `stopSequences` | array of string | Up to 5 stop sequences; generation stops at the first match, which is not included in the output |
| `candidateCount` | integer | Number of candidates to return; defaults to 1. Google states it is unsupported on Gemini 3 and later models, so do not set it |
| `responseMimeType` | string | Output MIME type: `text/plain` (default), `application/json`, or `text/x.enum` |
| `responseJsonSchema` | object | JSON Schema for the output, used together with `responseMimeType`; see "Structured Output" above |
| `responseSchema` | object | Output structure as an OpenAPI Schema subset; use either this or `responseJsonSchema` |
| `responseModalities` | array of string | Requested output modalities: `TEXT`, `IMAGE`, `AUDIO`; must match a combination the model supports |
| `thinkingConfig` | object | Thinking settings; see below |
| `imageConfig` | object | Image generation settings: `aspectRatio`, `imageSize`; see "Image Generation" above |
| `speechConfig` | object | Speech generation settings; see below |
| `mediaResolution` | string | Default resolution for all media inputs; see below |
| `seed` | integer | Decoding seed; random if not set |
| `temperature` / `topP` / `topK` | number / number / integer | Sampling parameters. Per Google, these are **no longer supported and are silently ignored** on Gemini 3.6 Flash and newer models (including the Gemini 4 models); Google recommends removing them, as future models will return an error |
| `presencePenalty` / `frequencyPenalty` | number | Presence penalty / frequency penalty |
| `responseLogprobs` / `logprobs` | boolean / integer | Whether to return log probabilities, and how many top candidates to return per step (0 to 20) |
| `enableEnhancedCivicAnswers` | boolean | Enables enhanced answers on civic topics (such as elections and other public-affairs information); not available on all models |

?> Per-request output caps on Gemini 4: 65,536 tokens for streaming requests and for `gemini-4-neon` / `gemini-4-hydrogen`; 32,768 tokens for **non-streaming** calls to `gemini-4-carbon` / `gemini-4-argon`, where setting `maxOutputTokens` above 32,768 returns 400, so use streaming for longer output. Google's Long decode feature (continuing past the per-request cap with a `continuationToken`) relies on `continuationToken`, which BeeRoute does not forward, so do not set `maxOutputTokens` above 65,536. Google also recommends keeping `maxOutputTokens` at 32,768 or more on Gemini 4 (use `thinkingLevel` to control token spend) and setting client timeouts to at least 20 minutes per call.

##### `thinkingConfig`

| Field | Type | Description |
| --- | --- | --- |
| `thinkingLevel` | string | Reasoning depth: `minimal`, `low`, `medium`, `high`, `xhigh` (the official enum names are uppercase, such as `MINIMAL`; Google's examples use lowercase). See the "Available Models" table for each model's levels and default; using it with Gemini 2.5 returns an error |
| `includeThoughts` | boolean | When `true`, the response includes thought summaries (parts with `"thought": true`) |
| `thinkingBudget` | integer | Thinking token budget, for the Gemini 2.5 series only (`0` turns thinking off, `-1` enables dynamic thinking). Deprecated on Gemini 4; sending it together with `thinkingLevel` returns 400 |

##### `speechConfig`

Used by TTS (speech generation) models; BeeRoute does not currently offer TTS models. Main fields: `voiceConfig.prebuiltVoiceConfig.voiceName` (a single prebuilt voice, such as `Kore`); `multiSpeakerVoiceConfig.speakerVoiceConfigs` (multiple speakers, each with a `speaker` name and a `voiceConfig`; use either this or `voiceConfig`); and `languageCode` (a BCP-47 code such as `en-US`; Mandarin Chinese is `cmn-CN`).

##### `mediaResolution`

Controls the maximum number of tokens used for image, video, and PDF input (audio is counted at a fixed rate per second and is not affected). Approximate token counts on Gemini 4 / Gemini 3 models:

| Value | Image | Video (per frame) | PDF |
| --- | --- | --- | --- |
| `MEDIA_RESOLUTION_UNSPECIFIED` (default) | 1120 | 70 | 560 |
| `MEDIA_RESOLUTION_LOW` | 280 | 70 | 280 + native text |
| `MEDIA_RESOLUTION_MEDIUM` | 560 | 70 | 560 + native text |
| `MEDIA_RESOLUTION_HIGH` | 1120 | 280 | 1120 + native text |
| `MEDIA_RESOLUTION_ULTRA_HIGH` (per part only) | 2240 | N/A | N/A |

- Global setting: set `generationConfig.mediaResolution` to a string such as `"MEDIA_RESOLUTION_LOW"`;
- Per-item setting (Gemini 4 / 3; marked experimental by Google): add `"mediaResolution": {"level": "MEDIA_RESOLUTION_HIGH"}` to that part; it overrides the global setting;
- Audio is fixed at about 25 tokens per second on Gemini 4 / 3. Google recommends `HIGH` for images, `MEDIUM` for PDFs, and `LOW` for general video.

## 📥 Response

### GenerateContentResponse

| Field | Description |
| --- | --- |
| `candidates` | List of candidate replies, usually just one |
| `promptFeedback` | Safety feedback on the prompt. When the prompt is blocked, `blockReason` is set and no candidates are returned |
| `usageMetadata` | Token usage |
| `modelVersion` | The model version that generated the reply |
| `responseId` | Response ID |

### Candidate

| Field | Description |
| --- | --- |
| `content` | The generated content (`role` is `model`; `parts` may contain text, function calls, thought summaries, images, and so on) |
| `finishReason` | Why generation stopped; see the table below |
| `finishMessage` | Details on why generation stopped; present only when `finishReason` is set |
| `safetyRatings` | Ratings per safety category (`category`, `probability`, `blocked`) |
| `citationMetadata` | Citation sources (`citationSources`: `startIndex`, `endIndex`, `uri`, `license`) |
| `groundingMetadata` | Source information when grounding tools such as Google Search are used: `webSearchQueries`, `searchEntryPoint`, `groundingChunks`, `groundingSupports`, and more |
| `urlContextMetadata` | Retrieval results for each URL when the URL context tool is used: `urlMetadata[].retrievedUrl` and `urlRetrievalStatus` (`URL_RETRIEVAL_STATUS_SUCCESS`, `_ERROR`, `_PAYWALL`, `_UNSAFE`) |
| `avgLogprobs` / `logprobsResult` | Log probability information, returned only when `responseLogprobs` is requested |
| `tokenCount` / `index` | Token count of this candidate / candidate index |

### `finishReason`

| Value | Description |
| --- | --- |
| `STOP` | Natural stop point or a stop sequence was hit |
| `MAX_TOKENS` | The `maxOutputTokens` limit was reached |
| `SAFETY` | The reply was blocked for safety reasons |
| `RECITATION` | The reply was blocked for possibly reciting copyrighted material |
| `LANGUAGE` | The reply used an unsupported language |
| `BLOCKLIST` / `PROHIBITED_CONTENT` / `SPII` | The reply contains forbidden terms / may contain prohibited content / may contain sensitive personally identifiable information |
| `MALFORMED_FUNCTION_CALL` | The function call generated by the model is invalid |
| `UNEXPECTED_TOOL_CALL` | The model called a tool, but no tools were enabled in the request |
| `TOO_MANY_TOOL_CALLS` | The model called tools too many times in a row, so the system stopped execution |
| `MISSING_THOUGHT_SIGNATURE` | The request is missing a thought signature |
| `IMAGE_SAFETY` / `IMAGE_PROHIBITED_CONTENT` / `IMAGE_RECITATION` / `IMAGE_OTHER` / `NO_IMAGE` | Image generation stopped for safety, prohibited content, recitation, or other reasons, or an image was expected but none was generated |
| `CONTINUATION` | The per-request cap was reached before generation finished (Long decode). BeeRoute does not support continuing; see the `generationConfig` notes above |
| `OTHER` | Other reasons |

The official enum also has rare values such as `MALFORMED_RESPONSE`, `ESCALATION`, and `PUP_LIMITED_DISABLED`; see the official reference for the full list.

### `promptFeedback.blockReason`

Present when the prompt is blocked, in which case no candidates are returned: `SAFETY` (safety reasons; check `promptFeedback.safetyRatings`), `BLOCKLIST` (contains forbidden terms), `PROHIBITED_CONTENT` (contains prohibited content), `IMAGE_SAFETY` (generated image content was unsafe), or `OTHER` (other reasons).

### `usageMetadata`

| Field | Description |
| --- | --- |
| `promptTokenCount` | Input tokens (including any cached portion) |
| `cachedContentTokenCount` | Input tokens served from cache. Implicit caching is on by default for Gemini 2.5 and newer models (Gemini 4 needs at least 4,096 input tokens); putting long, fixed content at the start of the prompt makes hits more likely |
| `candidatesTokenCount` | Output tokens across all candidates |
| `thoughtsTokenCount` | Thinking tokens |
| `toolUsePromptTokenCount` | Input tokens produced by tool use (such as Google Search results) |
| `totalTokenCount` | Total tokens = input + tool-use input + thinking + output |
| `promptTokensDetails` / `candidatesTokensDetails` / `cacheTokensDetails` / `toolUsePromptTokensDetails` | Token counts broken down by modality (`TEXT`, `IMAGE`, `VIDEO`, `AUDIO`, `DOCUMENT`); each item is `{"modality": ..., "tokenCount": ...}` |

### Error Response

When you call through BeeRoute, errors always use the structure below (which differs from Google's native error format):

```json
{
  "error": {
    "message": "Error description",
    "type": "new_api_error",
    "param": "",
    "code": "insufficient_user_quota"
  }
}
```

- **Errors raised by the BeeRoute gateway**: `type` is `new_api_error` and `code` is a string error code (possibly empty); common cases are listed below;
- **Errors returned by Google upstream**: Google's HTTP status code and `message` are kept, `type` is `upstream_error`, and `code` is the numeric status code (such as `400`); the `status` (such as `INVALID_ARGUMENT`) and `details` fields of Google's original error are not kept.

When handling errors, read `error.message` first, then act on the HTTP status code.

**Common BeeRoute gateway errors:**

| HTTP status | `code` | Cause and fix |
| --- | --- | --- |
| 401 | (empty) | Missing or invalid token. Make sure `x-goog-api-key` holds your BeeRoute `sk-` token, not a Google key |
| 403 | `insufficient_user_quota` | Insufficient account balance; top up your account |
| 403 | (empty) or `access_denied` | The token is not allowed to use this group, or the request IP is not on the token's allowlist |
| 429 | (empty) | BeeRoute's request rate limit was hit; retry later |
| 503 | `model_not_found` | No channel is available for this model in the token's group. Check the model name and make sure the token group is `default` |
| 413 | `read_request_body_failed` | The request body is too large |
| 500 | `invalid_request` | The request body could not be parsed, for example `contents` / `parts` written as objects, invalid JSON, or missing `contents`. Retrying will not help; fix the request according to `message` |

**Google upstream status codes** (from Google's [API errors page](https://aistudio.google.com/docs/api-errors?generate-content=true)):

| HTTP status | Google status | Meaning and fix |
| --- | --- | --- |
| 400 | `INVALID_ARGUMENT` | The request body is malformed or missing a required field, for example a missing thought signature on a function call, or `thinkingBudget` sent together with `thinkingLevel`. Fix the request according to `message` |
| 400 | `FAILED_PRECONDITION` | The upstream project does not meet the requirements (for example, the free tier is unavailable); this is an upstream channel issue, so retry later or contact support |
| 403 | `PERMISSION_DENIED` | The upstream key lacks permission or the project is restricted; this is an upstream channel issue |
| 404 | `NOT_FOUND` | A resource referenced in the request was not found, for example a `fileUri` that cannot be reached |
| 429 | `RESOURCE_EXHAUSTED` | The upstream hit a rate or quota limit; retry later |
| 499 | `CANCELLED` | The request was cancelled, typically because the client closed the connection early (for example, a client timeout that is too short) |
| 500 | `INTERNAL` | An unexpected upstream error, sometimes caused by an overly long input context. Shorten the input or retry later |
| 503 | `UNAVAILABLE` | The upstream is temporarily overloaded or down; retry later |
| 504 | `DEADLINE_EXCEEDED` | The upstream could not finish within the deadline; increase your client timeout, and use streaming for long replies |

?> When calling Google directly, an invalid Google API key returns 400 `INVALID_ARGUMENT` (reason `API_KEY_INVALID`). Through BeeRoute, an invalid BeeRoute token is rejected by the gateway with the 401 shown in the table above.
