Gemini Generate Content API Guide

To chat with Gemini in an MCP-compatible client, you can select a supported model and conversation tool from the AI Chat MCP model list. The native GenerateContent request format is described in this document. AI Chat MCP Integration Guide

Google Gemini is a powerful AI conversation system that can generate fluent, natural responses within seconds from a prompt. This document primarily describes how to use the Gemini Generate Content API, which uses Google's official native API format and supports the generateContent and streamGenerateContent endpoints.

Differences from the Chat Completions API

The Gemini Generate Content API uses Google's official native request format (the contents field), rather than the OpenAI-compatible format (the messages field). If you already use the Google Gemini SDK or are familiar with the official API format, you can use this API directly without modifying the request format.

Current Support Scope

The API accepts text, image, video, and audio inputs (inlineData or fileData), thinking configuration, and custom function declarations. Native fields such as audio output, built-in tools, and explicit context caching are not yet guaranteed to be uniformly available; please refer to the actual response from each model.

When submitting audio or other files using fileData.fileUri, please ensure that the files are directly accessible via HTTPS without requiring an authenticated session, and that signed links remain valid throughout the entire request processing period. Non-streaming audio analysis returns results only after the model has completed processing, which may take more than 90 seconds; clients should set a sufficiently long total timeout based on file size and the use case to avoid disconnecting while the server is still processing.

Application Process

Before using the Gemini Generate Content API, please visit the Gemini Generate Content API page and click the "Get" button to obtain the credentials required for requests.

If you have not logged in or registered, you will be automatically redirected to the login page. Free credits are available for the first application.

Basic Usage

Non-Streaming

Send a POST request to /v1beta/models/{model}:generateContent:

Tip: Flash models in the gemini-3.x series are thinking models and consume reasoning tokens first; set generationConfig.maxOutputTokens above 512, or the response may contain only empty content.

curl -X POST "https://api.acedata.cloud/v1beta/models/gemini-3.5-flash:generateContent" \
  -H "Authorization: Bearer your_token_here" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "你好,请介绍一下你自己"
          }
        ]
      }
    ]
  }'

Example response:

{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [{"text": "你好!很高兴与你交流。"}]
      },
      "finishReason": "MAX_TOKENS"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 6,
    "candidatesTokenCount": 19,
    "thoughtsTokenCount": 489,
    "totalTokenCount": 514
  },
  "usage": {
    "prompt_tokens": 6,
    "completion_tokens": 19,
    "total_tokens": 514,
    "thoughts_tokens": 489,
    "cost": {
      "amount": 0.008860916380159999,
      "currency": "credit",
      "list_amount": 0.009631430847999998
    }
  },
  "modelVersion": "gemini-3.5-flash",
  "model": "gemini-3.5-flash"
}

The token fields in usageMetadata are billed according to native Gemini semantics:

  • promptTokenCount includes cachedContentTokenCount; cache hits are billed at the cache read rate and are not counted again as regular input.
  • promptTokensDetails and cacheTokensDetails are normalized into text_tokens, image_tokens, video_tokens, audio_tokens, and the corresponding cached_* details under usage.prompt_tokens_details. These values are included in prompt_tokens and cached_tokens, respectively; different modalities are recalculated only at their respective rates and are not billed twice.
  • candidatesTokenCount and thoughtsTokenCount are both billed at the output token rate.
  • toolUsePromptTokenCount represents separate tool input tokens, billed at the input token rate.

Ace Data Cloud additionally returns a normalized usage object; across model protocols, the cost of the current call is consistently available from usage.cost. cost is an optional cost preview; when the price preview is temporarily unavailable, the model response will still be returned normally but may not include this field. The final bill is based on usage records.

Streaming

Send a POST request to /v1beta/models/{model}:streamGenerateContent?alt=sse:

curl -X POST "https://api.acedata.cloud/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse" \
  -H "Authorization: Bearer your_token_here" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "写一首关于春天的诗"
          }
        ]
      }
    ]
  }'

The streaming response returns content incrementally in SSE (Server-Sent Events) format. Intermediate events usually contain only incremental content; the terminal event containing authoritative usage includes usageMetadata and the normalized usage, with the cost still located in usage.cost:

data: {"candidates":[{"content":{"parts":[{"text":"Hello!"}],"role":"model"},"index":0}],"modelVersion":"gemini-3.1-flash-lite","model":"gemini-3.1-flash-lite"}

data: {"candidates":[{"content":{"parts":[],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":7,"candidatesTokenCount":89,"totalTokenCount":96},"usage":{"prompt_tokens":7,"completion_tokens":89,"total_tokens":96,"cost":{"amount":0.00026161075472,"currency":"credit","list_amount":0.000284359516}},"modelVersion":"gemini-3.1-flash-lite","model":"gemini-3.1-flash-lite"}

The stream ends when the connection closes; native Gemini streams do not send data: [DONE]. If the terminal price preview is temporarily unavailable, usage will still return token usage but will omit cost.

Supported Models

Model Name Description
gemini-4-carbon Complex reasoning and engineering model; native calls are temporarily unavailable, Chat Completions can be used
gemini-4-neon Software engineering and information analysis; supports Generate Content, thinking tokens are billed as output
gemini-4-hydrogen Model for everyday coding and multi-step tasks; native calls are temporarily unavailable, Chat Completions can be used
gemini-4-argon Deep reasoning model; supports this API's generateContent and streaming text generation
gemini-3.8-flash Latest Flash model, suitable for high-quality general-purpose tasks
gemini-3.7-flash High-quality general-purpose Flash model
gemini-3.6-flash Stable high-performance multimodal model
gemini-3.5-flash High-throughput multimodal model
gemini-3.5-flash-lite Low-latency, low-cost model
gemini-3.1-flash-lite Stable lightweight model
gemini-3.1-pro-preview Complex reasoning and coding model
gemini-3-flash-preview Gemini 3 Flash preview model
gemini-2.5-pro Gemini 2.5 Pro model
gemini-2.5-flash Gemini 2.5 Flash model
gemini-2.5-flash-lite Gemini 2.5 Flash-Lite model
gemini-3.1-flash-image Image generation model
gemini-3-pro-image High-quality image generation model
gemini-2.5-flash-image Gemini 2.5 image generation model

gemini-4-carbon and gemini-4-hydrogen can currently be called through Chat Completions; native Generate Content is temporarily unavailable. The official model specifications list text, image, video, audio, and PDF inputs and text output; this does not mean that the current platform has verified all input types. Once native calls are restored, please submit requests according to the API contract on this page and separately verify the required inputs and parameters. The million-token output of the official long decode is not included in the current API contract. Both only support implicit caching, and thinking tokens are calculated at output prices; the prepared pricing rules use the same input token unit price for each input modality, and cache hits are calculated at the cache read unit price. See the current pricing page for details.

Advanced Features

System Instructions

{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "你好"}]
    }
  ],
  "systemInstruction": {
    "parts": [{"text": "你是一个专业的诗人,所有回复都用诗歌形式。"}]
  }
}

Generation Configuration

{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "讲一个故事"}]
    }
  ],
  "generationConfig": {
    "temperature": 0.7,
    "maxOutputTokens": 1024,
    "topP": 0.9,
    "topK": 40
  }
}

JSON Mode

{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "列出三个中国城市及其人口"}]
    }
  ],
  "generationConfig": {
    "responseMimeType": "application/json",
    "responseSchema": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "city": {"type": "string"},
          "population": {"type": "integer"}
        }
      }
    }
  }
}

Internal Thinking and Thought Summaries

The model's internal thinking and the return of thought summaries to the caller are two independent settings:

  • thinkingBudget or thinkingLevel controls the model's internal thinking budget or depth; supported fields and values depend on the model.
  • includeThoughts controls whether thought summaries are returned and defaults to false. When this field is omitted or set to false, neither ordinary JSON nor SSE streaming responses return text marked as thought: true; this text is retained only when the Boolean value true is explicitly passed.

When a request does not set includeThoughts, the API passes false by default to generative models that support thinking configuration, avoiding requests for unwanted summaries; values, thinking budgets, and levels explicitly passed by the customer are retained. The field is not automatically added for gemini-2.5-flash-image, which is known not to support thinking configuration, and generation configuration is not added to countTokens requests.

Turning off summaries is not the same as turning off internal thinking, and does not guarantee a reduction in internal thinking tokens. If a response still contains unrequested thought text, the ordinary JSON and SSE outputs filter it further, retaining normal answers, signatures, and actual usage.

To view summaries, explicitly enable them as follows. If the model does not generate an available summary, there may be no thought text even when enabled:

{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "解释量子纠缠"}]
    }
  ],
  "generationConfig": {
    "thinkingConfig": {
      "includeThoughts": true
    }
  }
}

thoughtSignature is encrypted state needed for subsequent turns, not thought summary text, and is not controlled by the includeThoughts switch. A signature may be on a normal answer, a function call, or an empty-text Part; when thought text is filtered, the signature and other fields in the same Part are retained, so the response may still contain Parts that carry only a signature and have empty text. When manually maintaining multi-turn history, preserve the order of these Parts and the positions of their signatures; do not move the signatures or merge the Parts.

usageMetadata and usage still record actual usage. Hiding summaries does not reset thoughtsTokenCount to zero, and billing is still calculated according to actual usage and current pricing rules.

See Google's official thinking and thought summary documentation and thought signature rules.

Function Calling

{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "北京现在的天气怎么样?"}]
    }
  ],
  "tools": [
    {
      "functionDeclarations": [
        {
          "name": "get_weather",
          "description": "获取指定城市的天气信息",
          "parameters": {
            "type": "object",
            "properties": {
              "city": {
                "type": "string",
                "description": "城市名称"
              }
            },
            "required": ["city"]
          }
        }
      ]
    }
  ]
}

Multi-Turn Conversations

{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "你好,我叫小明"}]
    },
    {
      "role": "model",
      "parts": [{"text": "你好小明!很高兴认识你。"}]
    },
    {
      "role": "user",
      "parts": [{"text": "我叫什么名字?"}]
    }
  ]
}

Image Understanding

{
  "contents": [
    {
      "role": "user",
      "parts": [
        {"text": "描述这张图片"},
        {
          "inlineData": {
            "mimeType": "image/jpeg",
            "data": "base64_encoded_image_data..."
          }
        }
      ]
    }
  ]
}

Safety Settings

Content filtering can be controlled through safetySettings:

{
  "contents": [...],
  "safetySettings": [
    {
      "category": "HARM_CATEGORY_HARASSMENT",
      "threshold": "BLOCK_ONLY_HIGH"
    }
  ]
}

Error Handling

HTTP Status Code Meaning
400 Invalid request parameters
401 Authentication failed, please check the Token
403 Content blocked by the safety filter
429 Requests are too frequent
500 Internal server error