BeeRoute logoBeeRoute.

Home / Docs / Gemini Native API (Generate Content)

Gemini Native API (Generate Content)

Official docs: generateContent reference | Thinking | Function calling | Thought signatures | Structured output | API errors

๐Ÿ“ 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.

Quick Notes

ItemDetails
Generate contentPOST https://beeroute.ai/v1beta/models/{model}:generateContent
StreamingPOST https://beeroute.ai/v1beta/models/{model}:streamGenerateContent?alt=sse
List modelsGET https://beeroute.ai/v1beta/models
Base URLhttps://beeroute.ai (what you enter in SDKs and tools such as Gemini CLI; do not append /v1beta)
Authenticationx-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 typeContent-Type: application/json
Get a keyhttps://beeroute.ai/keys; choose the default token group (Gemini models are in the default group)
Models and pricinghttps://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:

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

ModelDescription (from Google)Supported thinkingLevel (default in bold)
gemini-4-carbonGoogle's strongest Gemini 4 reasoning model, built for complex software engineering, multimodal knowledge work, and scientific reasoninglow / medium / high
gemini-4-neonFrontier-level intelligence with fast end-to-end task completion across complex software engineering, knowledge work, and sciencelow / medium / high / xhigh
gemini-4-hydrogenSpeed and efficiency for everyday coding and agentic workflowslow / 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 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 โœ…

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:

{
  "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.

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.

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.

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):

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:

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:

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

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):

{
  "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:

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:

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):

{
  "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:

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):

{
  "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.

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):

{
  "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.

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.

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):

{
  "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:

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 for details. To call these models in the OpenAI images format and get image URLs back directly, see Nano-banana Image Generation/Editing.

Python SDK (google-genai) โœ…

pip install -U google-genai
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

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.

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

ParameterTypeRequiredDescription
contentsarray of ContentYesThe conversation. One message for a single turn; the full history plus the latest message for multi-turn
systemInstructionContentNoSystem instruction; text only for now
toolsarray of ToolNoTools the model may use: function declarations, Google Search, code execution, and so on
toolConfigobjectNoTool configuration, mainly the function calling mode
safetySettingsarray of SafetySettingNoSafety filter settings, at most one per category
generationConfigobjectNoGeneration settings: output length, structured output, thinking, images, and so on
cachedContentstringNoName of an explicit cache. BeeRoute does not provide the cachedContents endpoint, so this cannot be used

contents

Content object:

FieldTypeDescription
rolestringuser or model. Function results (functionResponse) also go in a message whose role is user. Can be omitted for single-turn requests
partsarray of PartRequired. 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):

FieldTypeDescription
textstringText
inlineDataobjectInline media: mimeType (MIME type) + data (base64 string)
fileDataobjectMedia by URL: fileUri (required; a public HTTPS or YouTube URL) + mimeType (optional)
functionCallobjectA function call returned by the model: name + args (used when sending history back)
functionResponseobjectA function result: name (required) + response (required, a JSON object; use an error key to report failures)
executableCodeobjectCode generated by the code execution tool: language (PYTHON) + code
codeExecutionResultobjectResult of running the code: outcome + output
thoughtbooleanWhether the part is a thought summary (appears in responses)
thoughtSignaturestringThought signature; when sending history back it must stay unchanged in its original part
videoMetadataobjectVideo clipping settings: startOffset, endOffset, fps (default 1.0, range (0, 24])
mediaResolutionobjectResolution for this media item, such as {"level": "MEDIA_RESOLUTION_HIGH"}; see mediaResolution below

tools

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

FieldDescription
functionDeclarationsList of function declarations; see the table below
googleSearchGoogle Search; write it as {}
urlContextURL context: the model reads web pages whose URLs appear in the prompt (Google allows up to 20 URLs per request); write it as {}
codeExecutionCode execution; write it as {}
googleMapsGrounding 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:

FieldRequiredDescription
nameYesFunction name; letters, digits, underscores, colons, dots, and dashes only, up to 128 characters
descriptionYesWhat the function does; explain when to call it and what the parameters mean, as this directly affects call accuracy
parametersNoParameter definition as an OpenAPI Schema subset; the top level is usually {"type": "object", "properties": {...}, "required": [...]}
parametersJsonSchemaNoParameters described in standard JSON Schema; use either this or parameters
response / responseJsonSchemaNoDescribes the structure of the function's return value; use one or the other

toolConfig

FieldDescription
functionCallingConfig.modeFunction calling mode; see the table below
functionCallingConfig.allowedFunctionNamesRestricts the model to these functions; only set it with ANY or VALIDATED mode
retrievalConfigUser location (latLng, languageCode), used with tools such as Google Maps
includeServerSideToolInvocationsWhether 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:

ValueDescription
AUTOThe model decides whether to return a function call or text. This is the default when the mode is not set
ANYThe model must call a function (only from allowedFunctionNames if that is set)
NONEFunction calls are not allowed; equivalent to sending no function declarations
VALIDATEDThe 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.

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

HarmCategory:

ValueDescription
HARM_CATEGORY_HARASSMENTHarassment
HARM_CATEGORY_HATE_SPEECHHate speech
HARM_CATEGORY_SEXUALLY_EXPLICITSexually explicit content
HARM_CATEGORY_DANGEROUS_CONTENTDangerous content
HARM_CATEGORY_JAILBREAKPrompts 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:

ValueDescription
OFFTurn the filter off for this category
BLOCK_NONENever block, regardless of the probability of unsafe content
BLOCK_ONLY_HIGHBlock only content with a high probability of being unsafe
BLOCK_MEDIUM_AND_ABOVEBlock content with a medium or high probability of being unsafe
BLOCK_LOW_AND_ABOVEBlock 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

FieldTypeDescription
maxOutputTokensintegerMaximum output tokens per candidate (including thinking tokens); the default varies by model
stopSequencesarray of stringUp to 5 stop sequences; generation stops at the first match, which is not included in the output
candidateCountintegerNumber of candidates to return; defaults to 1. Google states it is unsupported on Gemini 3 and later models, so do not set it
responseMimeTypestringOutput MIME type: text/plain (default), application/json, or text/x.enum
responseJsonSchemaobjectJSON Schema for the output, used together with responseMimeType; see "Structured Output" above
responseSchemaobjectOutput structure as an OpenAPI Schema subset; use either this or responseJsonSchema
responseModalitiesarray of stringRequested output modalities: TEXT, IMAGE, AUDIO; must match a combination the model supports
thinkingConfigobjectThinking settings; see below
imageConfigobjectImage generation settings: aspectRatio, imageSize; see "Image Generation" above
speechConfigobjectSpeech generation settings; see below
mediaResolutionstringDefault resolution for all media inputs; see below
seedintegerDecoding seed; random if not set
temperature / topP / topKnumber / number / integerSampling 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 / frequencyPenaltynumberPresence penalty / frequency penalty
responseLogprobs / logprobsboolean / integerWhether to return log probabilities, and how many top candidates to return per step (0 to 20)
enableEnhancedCivicAnswersbooleanEnables 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
FieldTypeDescription
thinkingLevelstringReasoning 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
includeThoughtsbooleanWhen true, the response includes thought summaries (parts with "thought": true)
thinkingBudgetintegerThinking 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:

ValueImageVideo (per frame)PDF
MEDIA_RESOLUTION_UNSPECIFIED (default)112070560
MEDIA_RESOLUTION_LOW28070280 + native text
MEDIA_RESOLUTION_MEDIUM56070560 + native text
MEDIA_RESOLUTION_HIGH11202801120 + native text
MEDIA_RESOLUTION_ULTRA_HIGH (per part only)2240N/AN/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

FieldDescription
candidatesList of candidate replies, usually just one
promptFeedbackSafety feedback on the prompt. When the prompt is blocked, blockReason is set and no candidates are returned
usageMetadataToken usage
modelVersionThe model version that generated the reply
responseIdResponse ID

Candidate

FieldDescription
contentThe generated content (role is model; parts may contain text, function calls, thought summaries, images, and so on)
finishReasonWhy generation stopped; see the table below
finishMessageDetails on why generation stopped; present only when finishReason is set
safetyRatingsRatings per safety category (category, probability, blocked)
citationMetadataCitation sources (citationSources: startIndex, endIndex, uri, license)
groundingMetadataSource information when grounding tools such as Google Search are used: webSearchQueries, searchEntryPoint, groundingChunks, groundingSupports, and more
urlContextMetadataRetrieval results for each URL when the URL context tool is used: urlMetadata[].retrievedUrl and urlRetrievalStatus (URL_RETRIEVAL_STATUS_SUCCESS, _ERROR, _PAYWALL, _UNSAFE)
avgLogprobs / logprobsResultLog probability information, returned only when responseLogprobs is requested
tokenCount / indexToken count of this candidate / candidate index

finishReason

ValueDescription
STOPNatural stop point or a stop sequence was hit
MAX_TOKENSThe maxOutputTokens limit was reached
SAFETYThe reply was blocked for safety reasons
RECITATIONThe reply was blocked for possibly reciting copyrighted material
LANGUAGEThe reply used an unsupported language
BLOCKLIST / PROHIBITED_CONTENT / SPIIThe reply contains forbidden terms / may contain prohibited content / may contain sensitive personally identifiable information
MALFORMED_FUNCTION_CALLThe function call generated by the model is invalid
UNEXPECTED_TOOL_CALLThe model called a tool, but no tools were enabled in the request
TOO_MANY_TOOL_CALLSThe model called tools too many times in a row, so the system stopped execution
MISSING_THOUGHT_SIGNATUREThe request is missing a thought signature
IMAGE_SAFETY / IMAGE_PROHIBITED_CONTENT / IMAGE_RECITATION / IMAGE_OTHER / NO_IMAGEImage generation stopped for safety, prohibited content, recitation, or other reasons, or an image was expected but none was generated
CONTINUATIONThe per-request cap was reached before generation finished (Long decode). BeeRoute does not support continuing; see the generationConfig notes above
OTHEROther 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

FieldDescription
promptTokenCountInput tokens (including any cached portion)
cachedContentTokenCountInput 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
candidatesTokenCountOutput tokens across all candidates
thoughtsTokenCountThinking tokens
toolUsePromptTokenCountInput tokens produced by tool use (such as Google Search results)
totalTokenCountTotal tokens = input + tool-use input + thinking + output
promptTokensDetails / candidatesTokensDetails / cacheTokensDetails / toolUsePromptTokensDetailsToken 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):

{
  "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 statuscodeCause and fix
401(empty)Missing or invalid token. Make sure x-goog-api-key holds your BeeRoute sk- token, not a Google key
403insufficient_user_quotaInsufficient account balance; top up your account
403(empty) or access_deniedThe 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
503model_not_foundNo channel is available for this model in the token's group. Check the model name and make sure the token group is default
413read_request_body_failedThe request body is too large
500invalid_requestThe 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):

HTTP statusGoogle statusMeaning and fix
400INVALID_ARGUMENTThe 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
400FAILED_PRECONDITIONThe 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
403PERMISSION_DENIEDThe upstream key lacks permission or the project is restricted; this is an upstream channel issue
404NOT_FOUNDA resource referenced in the request was not found, for example a fileUri that cannot be reached
429RESOURCE_EXHAUSTEDThe upstream hit a rate or quota limit; retry later
499CANCELLEDThe request was cancelled, typically because the client closed the connection early (for example, a client timeout that is too short)
500INTERNALAn unexpected upstream error, sometimes caused by an overly long input context. Shorten the input or retry later
503UNAVAILABLEThe upstream is temporarily overloaded or down; retry later
504DEADLINE_EXCEEDEDThe 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.

Last updated 2026-11-29 ยท Markdown source ยท llms.txt