Google Gemini-compatible API

2026-10-22

Google Gemini-compatible API

Base URL

Loading…

Get started

Loading…

Available models

  • The model name in the path is a platform model name (such as gemini-2.5-flash); see list models. Only models that declare Google protocol support can be called here; other models return 404.
  • For image output, include IMAGE in generationConfig.responseModalities; the request is served by the platform's image models.
  • Forcing a tool (toolConfig mode ANY) on a thinking model is passed through to the model just like the native Gemini API: the model decides, and a rejection comes back as a Google-formatted 400 error.

Endpoints

MethodPathDescriptionSupport
POST/v1beta/models/{modelsId}:generateContentGenerate content● Supported
POST/v1beta/models/{modelsId}:streamGenerateContentStream generated content● Supported
POST/v1beta/models/{modelsId}:countTokensCount tokens◐ Partial
POST/v1beta/models/{modelsId}:embedContentGenerate an embedding● Supported
POST/v1beta/models/{modelsId}:batchEmbedContentsGenerate batch embeddings● Supported
GET/v1beta/modelsList models● Supported
GET/v1beta/models/{modelsId}Get a model● Supported

Differences from Gemini API

  • Generate content:Forced tool use in toolConfig (functionCallingConfig mode ANY, including allowedFunctionNames) is forwarded unchanged on thinking models too — the same as the native Gemini API, so whether it is accepted is up to the upstream model; if the upstream answers 400, the error keeps the Google format and carries the upstream code and status.
  • Count tokens:Returns a model-family-calibrated estimate, including Chinese text and tool definitions, with the response header x-praxis-token-count: estimated. Do not use it as an exact usage or billing count.
  • Generate an embedding:Only text parts are accepted; images and other multimodal parts are rejected. taskType, title and retrieval settings such as autoTruncate / documentOcr / audioTrackExtraction have no equivalent on the platform: a request that carries them gets 400 (INVALID_ARGUMENT) instead of being silently ignored, because different taskType values produce vectors that behave differently and dropping one would quietly change retrieval quality. outputDimensionality maps to the dimension of the returned vector.
  • Generate batch embeddings:Each entry in requests follows the same rules as embedContent (text parts only, same rejections); every entry in a batch must use the same outputDimensionality. The current official JS and Python SDKs actually call this batch endpoint for embedContent.
  • List models:Embedding models are listed with embedContent as their only supported method. While the model catalog is temporarily unavailable, generateContent keeps working: requests that explicitly ask for image output (responseModalities includes IMAGE) still go to the image route, and older image requests that do not say so are handled as text chat for that window — every response during the fallback carries the X-Praxis-Route-Degraded: model-catalog-unavailable header so you can tell.

For authoritative parameter definitions, see the official Gemini API documentation.

Errors follow the Gemini API format, see errors; quotas and response headers are covered in rate limits.

Generate content

POST /google/v1beta/models/{modelsId}:generateContent● Supported

Official Gemini API docs ↗

Request parameters

  • modelstring必填

    path: Required. The name of the `Model` to use for generating the completion. Format: `models/{model}`.

  • contentsarray必填◐ Partially supported

    Required. The content of the current conversation with the model. For single-turn queries, this is a single instance. For multi-turn queries like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), this is a repeated field that contains the conversation history and the latest request.

    Multi-turn text, images and tool round trips work, including URL-safe base64 images. Inline audio/wav, text/plain and fileData URLs return 400.

    ▸ 展开子字段(2)
    • partsarray可选

      Ordered `Parts` that constitute a single message. Parts may have different MIME types.

      ▸ 展开子字段(16)
      • audioTranscriptionobject可选

        Optional. Audio (input or output) transcription. This is only set when this Part contains audio data.

      • codeExecutionResultobject可选

        Result of executing the `ExecutableCode`.

      • executableCodeobject可选

        Code generated by the model that is meant to be executed.

      • fileDataobject可选○ Unsupported

        URI based data.

        Tested HTTPS, gs, Files API and YouTube URLs all return 400.

      • functionCallobject可选

        A predicted `FunctionCall` returned from the model that contains a string representing the `FunctionDeclaration.name` with the arguments and their values.

      • functionResponseobject可选

        The result output of a `FunctionCall` that contains a string representing the `FunctionDeclaration.name` and a structured JSON object containing any output from the function is used as context to the model.

      • inlineDataobject可选◐ Partially supported

        Inline media bytes.

        image/png works, including URL-safe base64; audio/wav and text/plain return 400. PDF effects are unobservable.

      • mediaProcessingstring可选

        Optional. How the model processes this part's media for understanding. Only meaningful for video parts (`inline_data` or `file_data` with video mime). Non-video parts ignore this field.

        取值 AGENTICMEDIA_PROCESSING_UNSPECIFIEDSTATIC
      • mediaResolutionobject可选

        Optional. Media resolution for the input media.

      • partMetadataobject可选

        Custom metadata associated with the Part. Agents using genai.Part as content representation may need to keep track of the additional information. For example it can be name of a file/source from which the Part originates or a way to multiplex multiple Part streams.

      • textstring可选

        Inline text.

      • thoughtboolean可选

        Optional. Indicates if the part is thought from the model.

      • thoughtSignaturestring可选

        Optional. An opaque signature for the thought so it can be reused in subsequent requests.

      • toolCallobject可选

        Server-side tool call. This field is populated when the model predicts a tool invocation that should be executed on the server. The client is expected to echo this message back to the API.

      • toolResponseobject可选

        The output from a server-side `ToolCall` execution. This field is populated by the client with the results of executing the corresponding `ToolCall`.

      • videoMetadataobject可选

        Optional. Video metadata. The metadata should only be specified while the video data is presented in inline_data or file_data.

    • rolestring可选

      Optional. The producer of the content. Must be either 'user' or 'model'. Useful to set for multi-turn conversations, otherwise can be left blank or unset.

  • systemInstructionobject可选

    Optional. Developer set [system instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions). Currently, text only.

    Verified to take effect.

    ▸ 展开子字段(2)
    • partsarray可选

      Ordered `Parts` that constitute a single message. Parts may have different MIME types.

    • rolestring可选

      Optional. The producer of the content. Must be either 'user' or 'model'. Useful to set for multi-turn conversations, otherwise can be left blank or unset.

  • generationConfigobject可选

    Optional. Configuration options for model generation and outputs.

    ▸ 展开子字段(25)
    • _responseJsonSchemaany可选○ Currently ignored

      Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. Deprecated. Use `response_format` instead.

      Accepted but currently has no effect. Use responseJsonSchema instead.

    • audioTranscriptionConfigobject可选○ Currently ignored

      Optional. Config for audio transcription (speech recognition).

      Accepted but currently has no effect. Tested text models do not apply this option.

    • candidateCountinteger可选◐ Partially supported

      Optional. Number of generated responses to return. If unset, this will default to 1. Please note that this doesn't work for previous generation models (Gemini 1.0 family)

      Multiple candidates work in non-streaming requests; streaming with 2 returns 400.

    • enableAffectiveDialogboolean可选○ Currently ignored

      Optional. If enabled, the model will detect emotions and adapt its responses accordingly.

      Accepted but currently has no effect. Tested text models do not apply this option.

    • enableEnhancedCivicAnswersboolean可选○ Unsupported

      Optional. Enables enhanced civic answers. It may not be available for all models.

      Passing this to the tested text models returns 400.

    • frequencyPenaltynumber可选◐ Partially supported

      Optional. Frequency penalty applied to the next token's logprobs, multiplied by the number of times each token has been seen in the respponse so far. A positive penalty will discourage the use of tokens that have already been used, proportional to the number of times the token has been used: The more a token is used, the more difficult it is for the model to use that token again increasing the vocabulary of responses. Caution: A _negative_ penalty will encourage the model to reuse tokens proportional to the number of times the token has been used. Small negative values will reduce the vocabulary of a response. Larger negative values will cause the model to start repeating a common token until it hits the max_output_tokens limit.

      An occasional effect was observed on gemini-2.5-flash; ignored on gemini-2.5-flash-lite. 2.0 may return 400.

    • imageConfigobject可选○ Unsupported

      Optional. Config for image generation. An error will be returned if this field is set for models that don't support these config options.

      Passing this to the tested text models returns 400.

    • logprobsinteger可选

      Optional. Only valid if response_logprobs=True. This sets the number of top logprobs, including the chosen candidate, to return at each decoding step in the Candidate.logprobs_result. The number must be in the range of [0, 20].

      Verified to take effect.

    • maxOutputTokensinteger可选◐ Partially supported

      Optional. The maximum number of tokens to include in a response candidate. Note: The default value varies by model, see the `Model.output_token_limit` attribute of the `Model` returned from the `getModel` function.

      Limits output budget including thinking; very small budgets may return only thinking or error, and gemini-3.5-flash may truncate early.

    • mediaResolutionstring可选

      Optional. If specified, the media resolution specified will be used.

      LOW/MEDIUM/HIGH change image token usage on gemini-2.5-flash.

      取值 MEDIA_RESOLUTION_HIGHMEDIA_RESOLUTION_LOWMEDIA_RESOLUTION_MEDIUMMEDIA_RESOLUTION_UNSPECIFIED
    • presencePenaltynumber可选○ Currently ignored

      Optional. Presence penalty applied to the next token's logprobs if the token has already been seen in the response. This penalty is binary on/off and not dependant on the number of times the token is used (after the first). Use frequency_penalty for a penalty that increases with each use. A positive penalty will discourage the use of tokens that have already been used in the response, increasing the vocabulary. A negative penalty will encourage the use of tokens that have already been used in the response, decreasing the vocabulary.

      Accepted but currently has no effect. Outputs did not change on gemini-2.5-flash or gemini-2.5-flash-lite.

    • responseFormatobject可选○ Currently ignored

      Optional. Configuration for the response output format. Allows specifying output configuration per modality (text, audio, image) in a flat structure.

      Accepted but currently has no effect. Tested text models do not apply this option.

    • responseJsonSchemaany可选◐ Partially supported

      Optional. An internal detail. Use `responseJsonSchema` rather than this field.

      Works on the 2.5 models; 3.5 may truncate with insufficient budget. Cannot be combined with responseSchema.

    • responseLogprobsboolean可选

      Optional. If true, export the logprobs results in response.

      Verified to take effect.

    • responseMimeTypestring可选◐ Partially supported

      Optional. MIME type of the generated candidate text. Supported MIME types are: `text/plain`: (default) Text output. `application/json`: JSON response in the response candidates. `text/x.enum`: ENUM as a string response in the response candidates. Refer to the [docs](https://ai.google.dev/gemini-api/docs/prompting_with_media#plain_text_formats) for a list of all supported text MIME types.

      application/json works on the 2.5 models; 3.5 may return non-JSON. text/x.enum works on flash-lite.

    • responseModalitiesarray可选◐ Partially supported

      Optional. The requested modalities of the response. Represents the set of modalities that the model can return, and should be expected in the response. This is an exact match to the modalities of the response. A model may have multiple combinations of supported modalities. If the requested modalities do not match any of the supported combinations, an error will be returned. An empty list is equivalent to requesting only text.

      Tested text models support TEXT; AUDIO returns 400 and IMAGE errors.

    • responseSchemaobject可选◐ Partially supported

      Optional. Output schema of the generated candidate text. Schemas must be a subset of the [OpenAPI schema](https://spec.openapis.org/oas/v3.0.3#schema) and can be objects, primitives or arrays. If set, a compatible `response_mime_type` must also be set. Compatible MIME types: `application/json`: Schema for JSON response. Refer to the [JSON text generation guide](https://ai.google.dev/gemini-api/docs/json-mode) for more details. Deprecated. Use `response_format` instead.

      JSON constraints work on the 2.5 models; 3.5 may truncate with insufficient budget. Requires the matching responseMimeType.

    • seedinteger可选◐ Partially supported

      Optional. Seed used in decoding. If not set, the request uses a randomly generated seed.

      Reproducible on gemini-2.5-flash-lite; accepted but currently ignored on gemini-2.5-flash.

    • speechConfigobject可选○ Currently ignored

      Optional. The speech generation config.

      Accepted but currently has no effect. Tested text models do not apply this option.

    • stopSequencesarray可选

      Optional. The set of character sequences (up to 5) that will stop output generation. If specified, the API will stop at the first appearance of a `stop_sequence`. The stop sequence will not be included as part of the response.

      Works on gemini-2.5-flash and gemini-2.5-flash-lite; at most five sequences.

    • temperaturenumber可选◐ Partially supported

      Optional. Controls the randomness of the output. Note: The default value varies by model, see the `Model.temperature` attribute of the `Model` returned from the `getModel` function. Values can range from [0.0, 2.0].

      An effect was observed on gemini-2.5-flash-lite; sampling effects on gemini-2.5-flash are unobservable.

    • thinkingConfigobject可选

      Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking.

      ▸ 展开子字段(3)
      • includeThoughtsboolean可选◐ Partially supported

        Indicates whether to include thoughts in the response. If true, thoughts are returned only when available.

        true/false controls returned thinking when thinking is enabled. Passing it alone to flash-lite with thinking disabled by default returns 400.

      • thinkingBudgetinteger可选

        The number of thoughts tokens that the model should generate.

        Zero disables thinking; positive values control the budget and -1 is automatic. Out-of-range values return 400.

      • thinkingLevelstring可选◐ Partially supported

        Optional. Controls the maximum depth of the model's internal reasoning process before it produces a response. The default value is model-dependent. Refer to the [Thinking levels guide](https://ai.google.dev/gemini-api/docs/thinking#thinking-levels) for more details. Recommended for Gemini 3 or later models. Use with earlier models results in an error.

        gemini-3.5-flash supports MINIMAL/LOW/MEDIUM/HIGH; using it on the 2.5 models returns 400.

        取值 HIGHLOWMEDIUMMINIMALTHINKING_LEVEL_UNSPECIFIED
    • topKinteger可选○ Currently ignored

      Accepted but not effective; sampling does not use topK.

      Accepted but currently has no effect. gemini-2.5-flash-lite still returns different outputs with topK=1; effects on gemini-2.5-flash are unobservable.

    • topPnumber可选

      Optional. The maximum cumulative probability of tokens to consider when sampling. The model uses combined Top-k and Top-p (nucleus) sampling. Tokens are sorted based on their assigned probabilities so that only the most likely tokens are considered. Top-k sampling directly limits the maximum number of tokens to consider, while Nucleus sampling limits the number of tokens based on the cumulative probability. Note: The default value varies by `Model` and is specified by the`Model.top_p` attribute returned from the `getModel` function. An empty `top_k` attribute indicates that the model doesn't apply top-k sampling and doesn't allow setting `top_k` on requests.

      Verified on gemini-2.5-flash and gemini-2.5-flash-lite.

    • translationConfigobject可选○ Currently ignored

      Optional. Config for translation.

      Accepted but currently has no effect. Tested text models do not apply this option.

  • toolsarray可选

    Optional. A list of `Tools` the `Model` may use to generate the next response. A `Tool` is a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of the `Model`. Supported `Tool`s are `Function` and `code_execution`. Refer to the [Function calling](https://ai.google.dev/gemini-api/docs/function-calling) and the [Code execution](https://ai.google.dev/gemini-api/docs/code-execution) guides to learn more.

    ▸ 展开子字段(9)
    • codeExecutionobject可选○ Unsupported

      Optional. Enables the model to execute code as part of generation.

      Tested requests return 502; currently unavailable.

    • computerUseobject可选○ Unsupported

      Optional. Tool to support the model interacting directly with the computer. If enabled, it automatically populates computer-use specific Function Declarations.

      Tested gemini-2.5-flash requests return 400.

    • fileSearchobject可选○ Unsupported

      Optional. FileSearch tool type. Tool to retrieve knowledge from Semantic Retrieval corpora.

      Tested gemini-2.5-flash requests return 400.

    • functionDeclarationsarray可选

      Optional. A list of `FunctionDeclarations` available to the model that can be used for function calling. The model or system does not execute the function. Instead the defined function may be returned as a FunctionCall with arguments to the client side for execution. The model may decide to call a subset of these functions by populating FunctionCall in the response. The next conversation turn may contain a FunctionResponse with the Content.role "function" generation context for the next model turn.

      ▸ 展开子字段(7)
      • behaviorstring可选○ Currently ignored

        Optional. Specifies the function Behavior. Currently only supported by the BidiGenerateContent method.

        Accepted but currently has no effect.

        取值 BLOCKINGNON_BLOCKINGUNSPECIFIED
      • descriptionstring可选

        Required. A brief description of the function.

      • namestring可选

        Required. The name of the function. Must be a-z, A-Z, 0-9, or contain underscores, colons, dots, and dashes, with a maximum length of 128.

      • parametersobject可选

        Optional. Describes the parameters to this function. Reflects the Open API 3.03 Parameter Object string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter.

        Verified to take effect.

      • parametersJsonSchemaany可选

        Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`.

        Verified to take effect.

      • responseobject可选○ Currently ignored

        Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function.

        Accepted but currently has no effect.

      • responseJsonSchemaany可选

        Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`.

    • googleMapsobject可选

      Optional. Tool that allows grounding the model's response with geospatial context related to the user's query.

    • googleSearchobject可选

      Optional. GoogleSearch tool type. Tool to support Google Search in Model. Powered by Google.

      gemini-2.5-flash returns groundingMetadata.

    • googleSearchRetrievalobject可选○ Unsupported

      Optional. Retrieval tool that is powered by Google search.

      Tested gemini-2.5-flash requests return 400.

    • mcpServersarray可选○ Unsupported

      Optional. MCP Servers to connect to.

      Tested gemini-2.5-flash requests return 400.

    • urlContextobject可选

      Optional. Tool to support URL context retrieval.

  • toolConfigobject可选

    Optional. Tool configuration for any `Tool` specified in the request. Refer to the [Function calling guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode) for a usage example.

    ▸ 展开子字段(3)
    • functionCallingConfigobject可选

      Optional. Function calling config.

      ▸ 展开子字段(2)
      • allowedFunctionNamesarray可选

        Optional. A set of function names that, when provided, limits the functions the model will call. This should only be set when the Mode is ANY or VALIDATED. Function names should match [FunctionDeclaration.name]. When set, model will predict a function call from only allowed function names.

        Verified to take effect.

      • modestring可选◐ Partially supported

        Optional. Specifies the mode in which function calling should execute. If unspecified, the default value will be set to AUTO.

        ANY/AUTO/VALIDATED work; NONE occasionally still called tools on flash-lite, then worked on retest.

        取值 ANYAUTOMODE_UNSPECIFIEDNONEVALIDATED
    • includeServerSideToolInvocationsboolean可选

      Optional. If true, the API response will include the server-side tool calls and responses within the `Content` message. This allows clients to observe the server's tool interactions.

    • retrievalConfigobject可选

      Optional. Retrieval config.

  • safetySettingsarray可选

    Accepted but not effective; safety settings never block or alter responses.

    ▸ 展开子字段(2)
    • categorystring可选

      Required. The category for this setting.

      取值 HARM_CATEGORY_CIVIC_INTEGRITYHARM_CATEGORY_DANGEROUSHARM_CATEGORY_DANGEROUS_CONTENTHARM_CATEGORY_DEROGATORYHARM_CATEGORY_HARASSMENTHARM_CATEGORY_HATE_SPEECHHARM_CATEGORY_JAILBREAKHARM_CATEGORY_MEDICALHARM_CATEGORY_SEXUALHARM_CATEGORY_SEXUALLY_EXPLICITHARM_CATEGORY_TOXICITYHARM_CATEGORY_UNSPECIFIEDHARM_CATEGORY_VIOLENCE
    • thresholdstring可选

      Required. Controls the probability threshold at which harm is blocked.

      取值 BLOCK_LOW_AND_ABOVEBLOCK_MEDIUM_AND_ABOVEBLOCK_NONEBLOCK_ONLY_HIGHHARM_BLOCK_THRESHOLD_UNSPECIFIEDOFF
  • cachedContentstring可选○ Unsupported

    Cached content is not supported on this platform; passing it returns a 400 in Google's error format.

    Passing it returns 400; cached-content references are not supported.

  • labelsobject可选

    Accepted but not effective; labels are not stored and do not affect request processing.

  • modelstring可选○ Currently ignored

    Required. The name of the `Model` to use for generating the completion. Format: `models/{model}`.

    Accepted but currently has no effect. The model in the URL path takes precedence.

  • ▸ 更多参数(2)
    • serviceTierstring可选

      Accepted but not effective; every request is served at the platform's current service tier.

      取值 flexprioritystandardunspecified
    • storeboolean可选

      Optional. Configures the logging behavior for a given request. If set, it takes precedence over the project-level logging config.

Returns

200

Forced tool use in toolConfig (functionCallingConfig mode ANY, including allowedFunctionNames) is forwarded unchanged on thinking models too — the same as the native Gemini API, so whether it is accepted is up to the upstream model; if the upstream answers 400, the error keeps the Google format and carries the upstream code and status.

Errors follow the Gemini API format — see error codes

Response

HTTP 200

Successful response

application/json

NameTypeDescription
candidatesarray<object>Candidate responses from the model.
candidates[].avgLogprobsnumberOutput only. Average log probability score of the candidate.
candidates[].citationMetadataobjectOutput only. Citation information for model-generated candidate. This field may be populated with recitation information for any text included in the `content`. These are passages that are "recited" from copyrighted material in the foundational LLM's training data.
candidates[].contentobjectOutput only. Generated content returned from the model.
candidates[].finishMessagestringOptional. Output only. Details the reason why the model stopped generating tokens. This is populated only when `finish_reason` is set.
candidates[].finishReasonstringOptional. Output only. The reason why the model stopped generating tokens. If empty, the model has not stopped generating tokens.
candidates[].groundingAttributionsarray<object>Output only. Attribution information for sources that contributed to a grounded answer. This field is populated for `GenerateAnswer` calls.
candidates[].groundingMetadataobjectOutput only. Grounding metadata for the candidate. This field is populated for `GenerateContent` calls.
candidates[].indexintegerOutput only. Index of the candidate in the list of response candidates.
candidates[].logprobsResultobjectOutput only. Log-likelihood scores for the response tokens and top tokens
candidates[].safetyRatingsarray<object>List of ratings for the safety of a response candidate. There is at most one rating per category.
candidates[].tokenCountintegerOutput only. Token count for this candidate.
candidates[].urlContextMetadataobjectOutput only. Metadata related to url context retrieval tool.
modelStatusobjectOutput only. The current model status of this model.
modelStatus.messagestringA message explaining the model status.
modelStatus.modelStagestringThe stage of the underlying model.
modelStatus.retirementTimestringThe time at which the model will be retired.
modelVersionstringOutput only. The model version used to generate the response.
promptFeedbackobjectReturns the prompt's feedback related to the content filters.
promptFeedback.blockReasonstringOptional. If set, the prompt was blocked and no candidates are returned. Rephrase the prompt.
promptFeedback.safetyRatingsarray<object>Ratings for safety of the prompt. There is at most one rating per category.
responseIdstringOutput only. response_id is used to identify each response.
usageMetadataobjectOutput only. Metadata on the generation requests' token usage.
usageMetadata.cacheTokensDetailsarray<object>Output only. List of modalities of the cached content in the request input.
usageMetadata.cachedContentTokenCountintegerNumber of tokens in the cached part of the prompt (the cached content)
usageMetadata.candidatesTokenCountintegerTotal number of tokens across all the generated response candidates.
usageMetadata.candidatesTokensDetailsarray<object>Output only. List of modalities that were returned in the response.
usageMetadata.promptTokenCountintegerNumber of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content.
usageMetadata.promptTokensDetailsarray<object>Output only. List of modalities that were processed in the request input.
usageMetadata.serviceTierstringOutput only. Service tier of the request.
usageMetadata.thoughtsTokenCountintegerOutput only. Number of tokens of thoughts for thinking models.
usageMetadata.toolUsePromptTokenCountintegerOutput only. Number of tokens present in tool-use prompt(s).
usageMetadata.toolUsePromptTokensDetailsarray<object>Output only. List of modalities that were processed for tool-use request inputs.
usageMetadata.totalTokenCountintegerTotal token count for the generation request (prompt + thoughts + response candidates).

Stream generated content

POST /google/v1beta/models/{modelsId}:streamGenerateContent● Supported

Official Gemini API docs ↗

Request parameters

  • modelstring必填

    path: Required. The name of the `Model` to use for generating the completion. Format: `models/{model}`.

  • contentsarray必填◐ Partially supported

    Required. The content of the current conversation with the model. For single-turn queries, this is a single instance. For multi-turn queries like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), this is a repeated field that contains the conversation history and the latest request.

    Multi-turn text, images and tool round trips work, including URL-safe base64 images. Inline audio/wav, text/plain and fileData URLs return 400.

    ▸ 展开子字段(2)
    • partsarray可选

      Ordered `Parts` that constitute a single message. Parts may have different MIME types.

      ▸ 展开子字段(16)
      • audioTranscriptionobject可选

        Optional. Audio (input or output) transcription. This is only set when this Part contains audio data.

      • codeExecutionResultobject可选

        Result of executing the `ExecutableCode`.

      • executableCodeobject可选

        Code generated by the model that is meant to be executed.

      • fileDataobject可选○ Unsupported

        URI based data.

        Tested HTTPS, gs, Files API and YouTube URLs all return 400.

      • functionCallobject可选

        A predicted `FunctionCall` returned from the model that contains a string representing the `FunctionDeclaration.name` with the arguments and their values.

      • functionResponseobject可选

        The result output of a `FunctionCall` that contains a string representing the `FunctionDeclaration.name` and a structured JSON object containing any output from the function is used as context to the model.

      • inlineDataobject可选◐ Partially supported

        Inline media bytes.

        image/png works, including URL-safe base64; audio/wav and text/plain return 400. PDF effects are unobservable.

      • mediaProcessingstring可选

        Optional. How the model processes this part's media for understanding. Only meaningful for video parts (`inline_data` or `file_data` with video mime). Non-video parts ignore this field.

        取值 AGENTICMEDIA_PROCESSING_UNSPECIFIEDSTATIC
      • mediaResolutionobject可选

        Optional. Media resolution for the input media.

      • partMetadataobject可选

        Custom metadata associated with the Part. Agents using genai.Part as content representation may need to keep track of the additional information. For example it can be name of a file/source from which the Part originates or a way to multiplex multiple Part streams.

      • textstring可选

        Inline text.

      • thoughtboolean可选

        Optional. Indicates if the part is thought from the model.

      • thoughtSignaturestring可选

        Optional. An opaque signature for the thought so it can be reused in subsequent requests.

      • toolCallobject可选

        Server-side tool call. This field is populated when the model predicts a tool invocation that should be executed on the server. The client is expected to echo this message back to the API.

      • toolResponseobject可选

        The output from a server-side `ToolCall` execution. This field is populated by the client with the results of executing the corresponding `ToolCall`.

      • videoMetadataobject可选

        Optional. Video metadata. The metadata should only be specified while the video data is presented in inline_data or file_data.

    • rolestring可选

      Optional. The producer of the content. Must be either 'user' or 'model'. Useful to set for multi-turn conversations, otherwise can be left blank or unset.

  • systemInstructionobject可选

    Optional. Developer set [system instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions). Currently, text only.

    Verified to take effect.

    ▸ 展开子字段(2)
    • partsarray可选

      Ordered `Parts` that constitute a single message. Parts may have different MIME types.

    • rolestring可选

      Optional. The producer of the content. Must be either 'user' or 'model'. Useful to set for multi-turn conversations, otherwise can be left blank or unset.

  • generationConfigobject可选

    Optional. Configuration options for model generation and outputs.

    ▸ 展开子字段(25)
    • _responseJsonSchemaany可选○ Currently ignored

      Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. Deprecated. Use `response_format` instead.

      Accepted but currently has no effect. Use responseJsonSchema instead.

    • audioTranscriptionConfigobject可选○ Currently ignored

      Optional. Config for audio transcription (speech recognition).

      Accepted but currently has no effect. Tested text models do not apply this option.

    • candidateCountinteger可选◐ Partially supported

      Optional. Number of generated responses to return. If unset, this will default to 1. Please note that this doesn't work for previous generation models (Gemini 1.0 family)

      Multiple candidates work in non-streaming requests; streaming with 2 returns 400.

    • enableAffectiveDialogboolean可选○ Currently ignored

      Optional. If enabled, the model will detect emotions and adapt its responses accordingly.

      Accepted but currently has no effect. Tested text models do not apply this option.

    • enableEnhancedCivicAnswersboolean可选○ Unsupported

      Optional. Enables enhanced civic answers. It may not be available for all models.

      Passing this to the tested text models returns 400.

    • frequencyPenaltynumber可选◐ Partially supported

      Optional. Frequency penalty applied to the next token's logprobs, multiplied by the number of times each token has been seen in the respponse so far. A positive penalty will discourage the use of tokens that have already been used, proportional to the number of times the token has been used: The more a token is used, the more difficult it is for the model to use that token again increasing the vocabulary of responses. Caution: A _negative_ penalty will encourage the model to reuse tokens proportional to the number of times the token has been used. Small negative values will reduce the vocabulary of a response. Larger negative values will cause the model to start repeating a common token until it hits the max_output_tokens limit.

      An occasional effect was observed on gemini-2.5-flash; ignored on gemini-2.5-flash-lite. 2.0 may return 400.

    • imageConfigobject可选○ Unsupported

      Optional. Config for image generation. An error will be returned if this field is set for models that don't support these config options.

      Passing this to the tested text models returns 400.

    • logprobsinteger可选

      Optional. Only valid if response_logprobs=True. This sets the number of top logprobs, including the chosen candidate, to return at each decoding step in the Candidate.logprobs_result. The number must be in the range of [0, 20].

      Verified to take effect.

    • maxOutputTokensinteger可选◐ Partially supported

      Optional. The maximum number of tokens to include in a response candidate. Note: The default value varies by model, see the `Model.output_token_limit` attribute of the `Model` returned from the `getModel` function.

      Limits output budget including thinking; very small budgets may return only thinking or error, and gemini-3.5-flash may truncate early.

    • mediaResolutionstring可选

      Optional. If specified, the media resolution specified will be used.

      LOW/MEDIUM/HIGH change image token usage on gemini-2.5-flash.

      取值 MEDIA_RESOLUTION_HIGHMEDIA_RESOLUTION_LOWMEDIA_RESOLUTION_MEDIUMMEDIA_RESOLUTION_UNSPECIFIED
    • presencePenaltynumber可选○ Currently ignored

      Optional. Presence penalty applied to the next token's logprobs if the token has already been seen in the response. This penalty is binary on/off and not dependant on the number of times the token is used (after the first). Use frequency_penalty for a penalty that increases with each use. A positive penalty will discourage the use of tokens that have already been used in the response, increasing the vocabulary. A negative penalty will encourage the use of tokens that have already been used in the response, decreasing the vocabulary.

      Accepted but currently has no effect. Outputs did not change on gemini-2.5-flash or gemini-2.5-flash-lite.

    • responseFormatobject可选○ Currently ignored

      Optional. Configuration for the response output format. Allows specifying output configuration per modality (text, audio, image) in a flat structure.

      Accepted but currently has no effect. Tested text models do not apply this option.

    • responseJsonSchemaany可选◐ Partially supported

      Optional. An internal detail. Use `responseJsonSchema` rather than this field.

      Works on the 2.5 models; 3.5 may truncate with insufficient budget. Cannot be combined with responseSchema.

    • responseLogprobsboolean可选

      Optional. If true, export the logprobs results in response.

      Verified to take effect.

    • responseMimeTypestring可选◐ Partially supported

      Optional. MIME type of the generated candidate text. Supported MIME types are: `text/plain`: (default) Text output. `application/json`: JSON response in the response candidates. `text/x.enum`: ENUM as a string response in the response candidates. Refer to the [docs](https://ai.google.dev/gemini-api/docs/prompting_with_media#plain_text_formats) for a list of all supported text MIME types.

      application/json works on the 2.5 models; 3.5 may return non-JSON. text/x.enum works on flash-lite.

    • responseModalitiesarray可选◐ Partially supported

      Optional. The requested modalities of the response. Represents the set of modalities that the model can return, and should be expected in the response. This is an exact match to the modalities of the response. A model may have multiple combinations of supported modalities. If the requested modalities do not match any of the supported combinations, an error will be returned. An empty list is equivalent to requesting only text.

      Tested text models support TEXT; AUDIO returns 400 and IMAGE errors.

    • responseSchemaobject可选◐ Partially supported

      Optional. Output schema of the generated candidate text. Schemas must be a subset of the [OpenAPI schema](https://spec.openapis.org/oas/v3.0.3#schema) and can be objects, primitives or arrays. If set, a compatible `response_mime_type` must also be set. Compatible MIME types: `application/json`: Schema for JSON response. Refer to the [JSON text generation guide](https://ai.google.dev/gemini-api/docs/json-mode) for more details. Deprecated. Use `response_format` instead.

      JSON constraints work on the 2.5 models; 3.5 may truncate with insufficient budget. Requires the matching responseMimeType.

    • seedinteger可选◐ Partially supported

      Optional. Seed used in decoding. If not set, the request uses a randomly generated seed.

      Reproducible on gemini-2.5-flash-lite; accepted but currently ignored on gemini-2.5-flash.

    • speechConfigobject可选○ Currently ignored

      Optional. The speech generation config.

      Accepted but currently has no effect. Tested text models do not apply this option.

    • stopSequencesarray可选

      Optional. The set of character sequences (up to 5) that will stop output generation. If specified, the API will stop at the first appearance of a `stop_sequence`. The stop sequence will not be included as part of the response.

      Works on gemini-2.5-flash and gemini-2.5-flash-lite; at most five sequences.

    • temperaturenumber可选◐ Partially supported

      Optional. Controls the randomness of the output. Note: The default value varies by model, see the `Model.temperature` attribute of the `Model` returned from the `getModel` function. Values can range from [0.0, 2.0].

      An effect was observed on gemini-2.5-flash-lite; sampling effects on gemini-2.5-flash are unobservable.

    • thinkingConfigobject可选

      Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking.

      ▸ 展开子字段(3)
      • includeThoughtsboolean可选◐ Partially supported

        Indicates whether to include thoughts in the response. If true, thoughts are returned only when available.

        true/false controls returned thinking when thinking is enabled. Passing it alone to flash-lite with thinking disabled by default returns 400.

      • thinkingBudgetinteger可选

        The number of thoughts tokens that the model should generate.

        Zero disables thinking; positive values control the budget and -1 is automatic. Out-of-range values return 400.

      • thinkingLevelstring可选◐ Partially supported

        Optional. Controls the maximum depth of the model's internal reasoning process before it produces a response. The default value is model-dependent. Refer to the [Thinking levels guide](https://ai.google.dev/gemini-api/docs/thinking#thinking-levels) for more details. Recommended for Gemini 3 or later models. Use with earlier models results in an error.

        gemini-3.5-flash supports MINIMAL/LOW/MEDIUM/HIGH; using it on the 2.5 models returns 400.

        取值 HIGHLOWMEDIUMMINIMALTHINKING_LEVEL_UNSPECIFIED
    • topKinteger可选○ Currently ignored

      Accepted but not effective; sampling does not use topK.

      Accepted but currently has no effect. gemini-2.5-flash-lite still returns different outputs with topK=1; effects on gemini-2.5-flash are unobservable.

    • topPnumber可选

      Optional. The maximum cumulative probability of tokens to consider when sampling. The model uses combined Top-k and Top-p (nucleus) sampling. Tokens are sorted based on their assigned probabilities so that only the most likely tokens are considered. Top-k sampling directly limits the maximum number of tokens to consider, while Nucleus sampling limits the number of tokens based on the cumulative probability. Note: The default value varies by `Model` and is specified by the`Model.top_p` attribute returned from the `getModel` function. An empty `top_k` attribute indicates that the model doesn't apply top-k sampling and doesn't allow setting `top_k` on requests.

      Verified on gemini-2.5-flash and gemini-2.5-flash-lite.

    • translationConfigobject可选○ Currently ignored

      Optional. Config for translation.

      Accepted but currently has no effect. Tested text models do not apply this option.

  • toolsarray可选

    Optional. A list of `Tools` the `Model` may use to generate the next response. A `Tool` is a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of the `Model`. Supported `Tool`s are `Function` and `code_execution`. Refer to the [Function calling](https://ai.google.dev/gemini-api/docs/function-calling) and the [Code execution](https://ai.google.dev/gemini-api/docs/code-execution) guides to learn more.

    ▸ 展开子字段(9)
    • codeExecutionobject可选○ Unsupported

      Optional. Enables the model to execute code as part of generation.

      Tested requests return 502; currently unavailable.

    • computerUseobject可选○ Unsupported

      Optional. Tool to support the model interacting directly with the computer. If enabled, it automatically populates computer-use specific Function Declarations.

      Tested gemini-2.5-flash requests return 400.

    • fileSearchobject可选○ Unsupported

      Optional. FileSearch tool type. Tool to retrieve knowledge from Semantic Retrieval corpora.

      Tested gemini-2.5-flash requests return 400.

    • functionDeclarationsarray可选

      Optional. A list of `FunctionDeclarations` available to the model that can be used for function calling. The model or system does not execute the function. Instead the defined function may be returned as a FunctionCall with arguments to the client side for execution. The model may decide to call a subset of these functions by populating FunctionCall in the response. The next conversation turn may contain a FunctionResponse with the Content.role "function" generation context for the next model turn.

      ▸ 展开子字段(7)
      • behaviorstring可选○ Currently ignored

        Optional. Specifies the function Behavior. Currently only supported by the BidiGenerateContent method.

        Accepted but currently has no effect.

        取值 BLOCKINGNON_BLOCKINGUNSPECIFIED
      • descriptionstring可选

        Required. A brief description of the function.

      • namestring可选

        Required. The name of the function. Must be a-z, A-Z, 0-9, or contain underscores, colons, dots, and dashes, with a maximum length of 128.

      • parametersobject可选

        Optional. Describes the parameters to this function. Reflects the Open API 3.03 Parameter Object string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter.

        Verified to take effect.

      • parametersJsonSchemaany可选

        Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`.

        Verified to take effect.

      • responseobject可选○ Currently ignored

        Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function.

        Accepted but currently has no effect.

      • responseJsonSchemaany可选

        Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`.

    • googleMapsobject可选

      Optional. Tool that allows grounding the model's response with geospatial context related to the user's query.

    • googleSearchobject可选

      Optional. GoogleSearch tool type. Tool to support Google Search in Model. Powered by Google.

      gemini-2.5-flash returns groundingMetadata.

    • googleSearchRetrievalobject可选○ Unsupported

      Optional. Retrieval tool that is powered by Google search.

      Tested gemini-2.5-flash requests return 400.

    • mcpServersarray可选○ Unsupported

      Optional. MCP Servers to connect to.

      Tested gemini-2.5-flash requests return 400.

    • urlContextobject可选

      Optional. Tool to support URL context retrieval.

  • toolConfigobject可选

    Optional. Tool configuration for any `Tool` specified in the request. Refer to the [Function calling guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode) for a usage example.

    ▸ 展开子字段(3)
    • functionCallingConfigobject可选

      Optional. Function calling config.

      ▸ 展开子字段(2)
      • allowedFunctionNamesarray可选

        Optional. A set of function names that, when provided, limits the functions the model will call. This should only be set when the Mode is ANY or VALIDATED. Function names should match [FunctionDeclaration.name]. When set, model will predict a function call from only allowed function names.

        Verified to take effect.

      • modestring可选◐ Partially supported

        Optional. Specifies the mode in which function calling should execute. If unspecified, the default value will be set to AUTO.

        ANY/AUTO/VALIDATED work; NONE occasionally still called tools on flash-lite, then worked on retest.

        取值 ANYAUTOMODE_UNSPECIFIEDNONEVALIDATED
    • includeServerSideToolInvocationsboolean可选

      Optional. If true, the API response will include the server-side tool calls and responses within the `Content` message. This allows clients to observe the server's tool interactions.

    • retrievalConfigobject可选

      Optional. Retrieval config.

  • safetySettingsarray可选

    Accepted but not effective; safety settings never block or alter responses.

    ▸ 展开子字段(2)
    • categorystring可选

      Required. The category for this setting.

      取值 HARM_CATEGORY_CIVIC_INTEGRITYHARM_CATEGORY_DANGEROUSHARM_CATEGORY_DANGEROUS_CONTENTHARM_CATEGORY_DEROGATORYHARM_CATEGORY_HARASSMENTHARM_CATEGORY_HATE_SPEECHHARM_CATEGORY_JAILBREAKHARM_CATEGORY_MEDICALHARM_CATEGORY_SEXUALHARM_CATEGORY_SEXUALLY_EXPLICITHARM_CATEGORY_TOXICITYHARM_CATEGORY_UNSPECIFIEDHARM_CATEGORY_VIOLENCE
    • thresholdstring可选

      Required. Controls the probability threshold at which harm is blocked.

      取值 BLOCK_LOW_AND_ABOVEBLOCK_MEDIUM_AND_ABOVEBLOCK_NONEBLOCK_ONLY_HIGHHARM_BLOCK_THRESHOLD_UNSPECIFIEDOFF
  • cachedContentstring可选○ Unsupported

    Cached content is not supported on this platform; passing it returns a 400 in Google's error format.

    Passing it returns 400; cached-content references are not supported.

  • labelsobject可选

    Accepted but not effective; labels are not stored and do not affect request processing.

  • modelstring可选○ Currently ignored

    Required. The name of the `Model` to use for generating the completion. Format: `models/{model}`.

    Accepted but currently has no effect. The model in the URL path takes precedence.

  • ▸ 更多参数(2)
    • serviceTierstring可选

      Accepted but not effective; every request is served at the platform's current service tier.

      取值 flexprioritystandardunspecified
    • storeboolean可选

      Optional. Configures the logging behavior for a given request. If set, it takes precedence over the project-level logging config.

Returns

200

Errors follow the Gemini API format — see error codes

Response

HTTP 200

Successful response

application/json

NameTypeDescription
candidatesarray<object>Candidate responses from the model.
candidates[].avgLogprobsnumberOutput only. Average log probability score of the candidate.
candidates[].citationMetadataobjectOutput only. Citation information for model-generated candidate. This field may be populated with recitation information for any text included in the `content`. These are passages that are "recited" from copyrighted material in the foundational LLM's training data.
candidates[].contentobjectOutput only. Generated content returned from the model.
candidates[].finishMessagestringOptional. Output only. Details the reason why the model stopped generating tokens. This is populated only when `finish_reason` is set.
candidates[].finishReasonstringOptional. Output only. The reason why the model stopped generating tokens. If empty, the model has not stopped generating tokens.
candidates[].groundingAttributionsarray<object>Output only. Attribution information for sources that contributed to a grounded answer. This field is populated for `GenerateAnswer` calls.
candidates[].groundingMetadataobjectOutput only. Grounding metadata for the candidate. This field is populated for `GenerateContent` calls.
candidates[].indexintegerOutput only. Index of the candidate in the list of response candidates.
candidates[].logprobsResultobjectOutput only. Log-likelihood scores for the response tokens and top tokens
candidates[].safetyRatingsarray<object>List of ratings for the safety of a response candidate. There is at most one rating per category.
candidates[].tokenCountintegerOutput only. Token count for this candidate.
candidates[].urlContextMetadataobjectOutput only. Metadata related to url context retrieval tool.
modelStatusobjectOutput only. The current model status of this model.
modelStatus.messagestringA message explaining the model status.
modelStatus.modelStagestringThe stage of the underlying model.
modelStatus.retirementTimestringThe time at which the model will be retired.
modelVersionstringOutput only. The model version used to generate the response.
promptFeedbackobjectReturns the prompt's feedback related to the content filters.
promptFeedback.blockReasonstringOptional. If set, the prompt was blocked and no candidates are returned. Rephrase the prompt.
promptFeedback.safetyRatingsarray<object>Ratings for safety of the prompt. There is at most one rating per category.
responseIdstringOutput only. response_id is used to identify each response.
usageMetadataobjectOutput only. Metadata on the generation requests' token usage.
usageMetadata.cacheTokensDetailsarray<object>Output only. List of modalities of the cached content in the request input.
usageMetadata.cachedContentTokenCountintegerNumber of tokens in the cached part of the prompt (the cached content)
usageMetadata.candidatesTokenCountintegerTotal number of tokens across all the generated response candidates.
usageMetadata.candidatesTokensDetailsarray<object>Output only. List of modalities that were returned in the response.
usageMetadata.promptTokenCountintegerNumber of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content.
usageMetadata.promptTokensDetailsarray<object>Output only. List of modalities that were processed in the request input.
usageMetadata.serviceTierstringOutput only. Service tier of the request.
usageMetadata.thoughtsTokenCountintegerOutput only. Number of tokens of thoughts for thinking models.
usageMetadata.toolUsePromptTokenCountintegerOutput only. Number of tokens present in tool-use prompt(s).
usageMetadata.toolUsePromptTokensDetailsarray<object>Output only. List of modalities that were processed for tool-use request inputs.
usageMetadata.totalTokenCountintegerTotal token count for the generation request (prompt + thoughts + response candidates).

POST /google/v1beta/models/{modelsId}:countTokens◐ Partial

Official Gemini API docs ↗

Request parameters

  • modelstring必填

    path: Required. The model's resource name. This serves as an ID for the Model to use. This name should match a model name returned by the `ListModels` method. Format: `models/{model}`

  • contentsarray可选◐ Partially supported

    Optional. The input given to the model as a prompt. This field is ignored when `generate_content_request` is set.

    Forwarded natively or estimated locally. Sending both contents and generateContentRequest returns 400.

    ▸ 展开子字段(2)
    • partsarray可选

      Ordered `Parts` that constitute a single message. Parts may have different MIME types.

      ▸ 展开子字段(16)
      • audioTranscriptionobject可选

        Optional. Audio (input or output) transcription. This is only set when this Part contains audio data.

      • codeExecutionResultobject可选

        Result of executing the `ExecutableCode`.

      • executableCodeobject可选

        Code generated by the model that is meant to be executed.

      • fileDataobject可选

        URI based data.

      • functionCallobject可选

        A predicted `FunctionCall` returned from the model that contains a string representing the `FunctionDeclaration.name` with the arguments and their values.

      • functionResponseobject可选

        The result output of a `FunctionCall` that contains a string representing the `FunctionDeclaration.name` and a structured JSON object containing any output from the function is used as context to the model.

      • inlineDataobject可选◐ Partially supported

        Inline media bytes.

        Forwarded natively. Local estimates inspect PNG/JPEG/GIF headers without treating base64 as text; other media uses approximate allowances.

      • mediaProcessingstring可选

        Optional. How the model processes this part's media for understanding. Only meaningful for video parts (`inline_data` or `file_data` with video mime). Non-video parts ignore this field.

        取值 AGENTICMEDIA_PROCESSING_UNSPECIFIEDSTATIC
      • mediaResolutionobject可选

        Optional. Media resolution for the input media.

      • partMetadataobject可选

        Custom metadata associated with the Part. Agents using genai.Part as content representation may need to keep track of the additional information. For example it can be name of a file/source from which the Part originates or a way to multiplex multiple Part streams.

      • textstring可选

        Inline text.

      • thoughtboolean可选

        Optional. Indicates if the part is thought from the model.

      • thoughtSignaturestring可选

        Optional. An opaque signature for the thought so it can be reused in subsequent requests.

      • toolCallobject可选

        Server-side tool call. This field is populated when the model predicts a tool invocation that should be executed on the server. The client is expected to echo this message back to the API.

      • toolResponseobject可选

        The output from a server-side `ToolCall` execution. This field is populated by the client with the results of executing the corresponding `ToolCall`.

      • videoMetadataobject可选

        Optional. Video metadata. The metadata should only be specified while the video data is presented in inline_data or file_data.

    • rolestring可选

      Optional. The producer of the content. Must be either 'user' or 'model'. Useful to set for multi-turn conversations, otherwise can be left blank or unset.

  • generateContentRequestobject可选◐ Partially supported

    Optional. The overall input given to the `Model`. This includes the prompt as well as other model steering information like [system instructions](https://ai.google.dev/gemini-api/docs/system-instructions), and/or function declarations for [function calling](https://ai.google.dev/gemini-api/docs/function-calling). `Model`s/`Content`s and `generate_content_request`s are mutually exclusive. You can either send `Model` + `Content`s or a `generate_content_request`, but never both.

    Native counting preserves systemInstruction and tools and maps the model; local counting includes them in estimates.

    ▸ 展开子字段(11)
    • cachedContentstring可选○ 未支持

      Optional. The name of the content [cached](https://ai.google.dev/gemini-api/docs/caching) to use as context to serve the prediction. Format: `cachedContents/{cachedContent}`

    • contentsarray可选

      Required. The content of the current conversation with the model. For single-turn queries, this is a single instance. For multi-turn queries like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), this is a repeated field that contains the conversation history and the latest request.

    • generationConfigobject可选

      Optional. Configuration options for model generation and outputs.

    • labelsobject可选

      Optional. Labels with user-defined metadata for the request. Optional. Labels must follow standard unified Cloud label requirements: - Label keys must start with a letter. - Label keys and values can be no longer than 63 characters (Unicode codepoints) and can only contain lowercase letters, numeric characters, underscores, and dashes. - International characters are allowed. Usage: - Safety identifiers from aggregators: Use the key `safety_identifier` (e.g. `{"safety_identifier": "user_session_123"}`)

    • modelstring可选

      Required. The name of the `Model` to use for generating the completion. Format: `models/{model}`.

    • safetySettingsarray可选

      Optional. A list of unique `SafetySetting` instances for blocking unsafe content. This will be enforced on the `GenerateContentRequest.contents` and `GenerateContentResponse.candidates`. There should not be more than one setting for each `SafetyCategory` type. The API will block any contents and responses that fail to meet the thresholds set by these settings. This list overrides the default settings for each `SafetyCategory` specified in the safety_settings. If there is no `SafetySetting` for a given `SafetyCategory` provided in the list, the API will use the default safety setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY, HARM_CATEGORY_JAILBREAK are supported. Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings) for detailed information on available safety settings. Also refer to the [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to learn how to incorporate safety considerations in your AI applications.

    • serviceTierstring可选

      Optional. The service tier of the request.

      取值 flexprioritystandardunspecified
    • storeboolean可选

      Optional. Configures the logging behavior for a given request. If set, it takes precedence over the project-level logging config.

    • systemInstructionobject可选

      Optional. Developer set [system instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions). Currently, text only.

    • toolConfigobject可选

      Optional. Tool configuration for any `Tool` specified in the request. Refer to the [Function calling guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode) for a usage example.

    • toolsarray可选

      Optional. A list of `Tools` the `Model` may use to generate the next response. A `Tool` is a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of the `Model`. Supported `Tool`s are `Function` and `code_execution`. Refer to the [Function calling](https://ai.google.dev/gemini-api/docs/function-calling) and the [Code execution](https://ai.google.dev/gemini-api/docs/code-execution) guides to learn more.

Returns

200

Returns a model-family-calibrated estimate, including Chinese text and tool definitions, with the response header x-praxis-token-count: estimated. Do not use it as an exact usage or billing count.

Errors follow the Gemini API format — see error codes

Response

HTTP 200

Successful response

application/json

NameTypeDescription
cacheTokensDetailsarray<object>Output only. List of modalities that were processed in the cached content.
cacheTokensDetails[].modalitystringThe modality associated with this token count.
cacheTokensDetails[].tokenCountintegerNumber of tokens.
cachedContentTokenCountintegerNumber of tokens in the cached part of the prompt (the cached content).
promptTokensDetailsarray<object>Output only. List of modalities that were processed in the request input.
promptTokensDetails[].modalitystringThe modality associated with this token count.
promptTokensDetails[].tokenCountintegerNumber of tokens.
totalTokensintegerThe number of tokens that the `Model` tokenizes the `prompt` into. Always non-negative.

Generate an embedding

POST /google/v1beta/models/{modelsId}:embedContent● Supported

Official Gemini API docs ↗

Request parameters

  • modelstring必填

    path: Required. The model's resource name. This serves as an ID for the Model to use. This name should match a model name returned by the `ListModels` method. Format: `models/{model}`

  • contentobject必填◐ Partially supported

    Required. The content to embed. Only the `parts.text` fields will be counted.

    Text parts only; images return 400, including on multimodal embedding models.

    ▸ 展开子字段(2)
    • partsarray可选

      Ordered `Parts` that constitute a single message. Parts may have different MIME types.

    • rolestring可选

      Optional. The producer of the content. Must be either 'user' or 'model'. Useful to set for multi-turn conversations, otherwise can be left blank or unset.

  • embedContentConfigobject可选◐ Partially supported

    Optional. Configuration for the EmbedContent request.

    Only outputDimensionality is available, subject to model limits. Other options such as autoTruncate, documentOcr and audioTrackExtraction return 400.

    ▸ 展开子字段(6)
    • audioTrackExtractionboolean可选○ Unsupported

      Optional. Whether to extract audio from video content.

      Passing this returns 400; this embedding option is currently unsupported.

    • autoTruncateboolean可选○ Unsupported

      Optional. Whether to silently truncate the input content if it's longer than the maximum sequence length.

      Passing this returns 400; this embedding option is currently unsupported.

    • documentOcrboolean可选○ Unsupported

      Optional. Whether to enable OCR for document content.

      Passing this returns 400; this embedding option is currently unsupported.

    • outputDimensionalityinteger可选◐ Partially supported

      Optional. Reduced dimension for the output embedding. If set, excessive values in the output embedding are truncated from the end.

      Tested dimensions work on text-embedding-3-small and qwen3-vl-embedding; doubao-embedding-vision requires at least 1024. bge-m3 and qwen3-embedding-0.6b error.

    • taskTypestring可选○ Unsupported

      Optional. The task type of the embedding.

      Passing this returns 400; this embedding option is currently unsupported.

      取值 CLASSIFICATIONCLUSTERINGCODE_RETRIEVAL_QUERYFACT_VERIFICATIONQUESTION_ANSWERINGRETRIEVAL_DOCUMENTRETRIEVAL_QUERYSEMANTIC_SIMILARITYTASK_TYPE_UNSPECIFIED
    • titlestring可选○ Unsupported

      Optional. The title for the text.

      Passing this returns 400; this embedding option is currently unsupported.

  • modelstring可选

    Required. The model's resource name. This serves as an ID for the Model to use. This name should match a model name returned by the `ListModels` method. Format: `models/{model}`

    Must match the model in the URL path, otherwise returns 400.

  • outputDimensionalityinteger可选◐ Partially supported

    Optional. Deprecated: Please use EmbedContentConfig.output_dimensionality instead. Optional reduced dimension for the output embedding. If set, excessive values in the output embedding are truncated from the end. Supported by newer models since 2024 only. You cannot set this value if using the earlier model (`models/embedding-001`).

    Tested dimensions work on text-embedding-3-small and qwen3-vl-embedding; doubao-embedding-vision requires at least 1024. bge-m3 and qwen3-embedding-0.6b error.

  • taskTypestring可选○ Unsupported

    Optional. Deprecated: Please use EmbedContentConfig.task_type instead. Optional task type for which the embeddings will be used. Not supported on earlier models (`models/embedding-001`).

    Passing this returns 400.

    取值 CLASSIFICATIONCLUSTERINGCODE_RETRIEVAL_QUERYFACT_VERIFICATIONQUESTION_ANSWERINGRETRIEVAL_DOCUMENTRETRIEVAL_QUERYSEMANTIC_SIMILARITYTASK_TYPE_UNSPECIFIED
  • titlestring可选○ Unsupported

    Optional. Deprecated: Please use EmbedContentConfig.title instead. An optional title for the text. Only applicable when TaskType is `RETRIEVAL_DOCUMENT`. Note: Specifying a `title` for `RETRIEVAL_DOCUMENT` provides better quality embeddings for retrieval.

    Passing this returns 400.

Returns

200

Only text parts are accepted; images and other multimodal parts are rejected. taskType, title and retrieval settings such as autoTruncate / documentOcr / audioTrackExtraction have no equivalent on the platform: a request that carries them gets 400 (INVALID_ARGUMENT) instead of being silently ignored, because different taskType values produce vectors that behave differently and dropping one would quietly change retrieval quality. outputDimensionality maps to the dimension of the returned vector.

Errors follow the Gemini API format — see error codes

Response

HTTP 200

Successful response

application/json

NameTypeDescription
embeddingobjectOutput only. The embedding generated from the input content.
embedding.shapearray<integer>This field stores the soft tokens tensor frame shape (e.g. [1, 1, 256, 2048]).
embedding.valuesarray<number>The embedding values. This is for 3P users only and will not be populated for 1P calls.
usageMetadataobjectOutput only. The usage metadata for the request.
usageMetadata.promptTokenCountintegerOutput only. Number of tokens in the prompt.
usageMetadata.promptTokenDetailsarray<object>Output only. List of modalities that were processed in the request input.

Generate batch embeddings

POST /google/v1beta/models/{modelsId}:batchEmbedContents● Supported

Official Gemini API docs ↗

Request parameters

  • modelstring必填

    path: Required. The model's resource name. This serves as an ID for the Model to use. This name should match a model name returned by the `ListModels` method. Format: `models/{model}`

  • requestsarray必填

    Required. Embed requests for the batch. The model in each of these requests must match the model specified `BatchEmbedContentsRequest.model`.

    Accepts 1–100 items, returns them in input order, and requires matching dimensions.

    ▸ 展开子字段(6)
    • contentobject可选◐ Partially supported

      Required. The content to embed. Only the `parts.text` fields will be counted.

      Text parts only; images return 400, including on multimodal embedding models.

    • embedContentConfigobject可选◐ Partially supported

      Optional. Configuration for the EmbedContent request.

      Only outputDimensionality is available, subject to model limits. Other options such as autoTruncate, documentOcr and audioTrackExtraction return 400.

      ▸ 展开子字段(6)
      • audioTrackExtractionboolean可选○ Unsupported

        Optional. Whether to extract audio from video content.

        Passing this returns 400; this embedding option is currently unsupported.

      • autoTruncateboolean可选○ Unsupported

        Optional. Whether to silently truncate the input content if it's longer than the maximum sequence length.

        Passing this returns 400; this embedding option is currently unsupported.

      • documentOcrboolean可选○ Unsupported

        Optional. Whether to enable OCR for document content.

        Passing this returns 400; this embedding option is currently unsupported.

      • outputDimensionalityinteger可选◐ Partially supported

        Optional. Reduced dimension for the output embedding. If set, excessive values in the output embedding are truncated from the end.

        Tested dimensions work on text-embedding-3-small and qwen3-vl-embedding; doubao-embedding-vision requires at least 1024. bge-m3 and qwen3-embedding-0.6b error.

      • taskTypestring可选○ Unsupported

        Optional. The task type of the embedding.

        Passing this returns 400; this embedding option is currently unsupported.

        取值 CLASSIFICATIONCLUSTERINGCODE_RETRIEVAL_QUERYFACT_VERIFICATIONQUESTION_ANSWERINGRETRIEVAL_DOCUMENTRETRIEVAL_QUERYSEMANTIC_SIMILARITYTASK_TYPE_UNSPECIFIED
      • titlestring可选○ Unsupported

        Optional. The title for the text.

        Passing this returns 400; this embedding option is currently unsupported.

    • modelstring可选

      Required. The model's resource name. This serves as an ID for the Model to use. This name should match a model name returned by the `ListModels` method. Format: `models/{model}`

      Must match the model in the URL path, otherwise returns 400.

    • outputDimensionalityinteger可选◐ Partially supported

      Optional. Deprecated: Please use EmbedContentConfig.output_dimensionality instead. Optional reduced dimension for the output embedding. If set, excessive values in the output embedding are truncated from the end. Supported by newer models since 2024 only. You cannot set this value if using the earlier model (`models/embedding-001`).

      Tested dimensions work on text-embedding-3-small and qwen3-vl-embedding; doubao-embedding-vision requires at least 1024. bge-m3 and qwen3-embedding-0.6b error.

    • taskTypestring可选○ Unsupported

      Optional. Deprecated: Please use EmbedContentConfig.task_type instead. Optional task type for which the embeddings will be used. Not supported on earlier models (`models/embedding-001`).

      Passing this returns 400.

      取值 CLASSIFICATIONCLUSTERINGCODE_RETRIEVAL_QUERYFACT_VERIFICATIONQUESTION_ANSWERINGRETRIEVAL_DOCUMENTRETRIEVAL_QUERYSEMANTIC_SIMILARITYTASK_TYPE_UNSPECIFIED
    • titlestring可选○ Unsupported

      Optional. Deprecated: Please use EmbedContentConfig.title instead. An optional title for the text. Only applicable when TaskType is `RETRIEVAL_DOCUMENT`. Note: Specifying a `title` for `RETRIEVAL_DOCUMENT` provides better quality embeddings for retrieval.

      Passing this returns 400.

Returns

200

Each entry in requests follows the same rules as embedContent (text parts only, same rejections); every entry in a batch must use the same outputDimensionality. The current official JS and Python SDKs actually call this batch endpoint for embedContent.

Errors follow the Gemini API format — see error codes

Response

HTTP 200

Successful response

application/json

NameTypeDescription
embeddingsarray<object>Output only. The embeddings for each request, in the same order as provided in the batch request.
embeddings[].shapearray<integer>This field stores the soft tokens tensor frame shape (e.g. [1, 1, 256, 2048]).
embeddings[].valuesarray<number>The embedding values. This is for 3P users only and will not be populated for 1P calls.
usageMetadataobjectOutput only. The usage metadata for the request.
usageMetadata.promptTokenCountintegerOutput only. Number of tokens in the prompt.
usageMetadata.promptTokenDetailsarray<object>Output only. List of modalities that were processed in the request input.

List models

GET /google/v1beta/models● Supported

Official Gemini API docs ↗

Request parameters

  • pageSizeinteger可选

    query: The maximum number of `Models` to return (per page). If unspecified, 50 models will be returned per page. This method returns at most 1000 models per page, even if you pass a larger page_size.

    Pagination works; zero, negative and nonnumeric values return 400, while values above the limit are capped.

  • pageTokenstring可选

    query: A page token, received from a previous `ListModels` call. Provide the `page_token` returned by one request as an argument to the next request to retrieve the next page. When paginating, all other parameters provided to `ListModels` must match the call that provided the page token.

    Verified to take effect.

Returns

200

Embedding models are listed with embedContent as their only supported method. While the model catalog is temporarily unavailable, generateContent keeps working: requests that explicitly ask for image output (responseModalities includes IMAGE) still go to the image route, and older image requests that do not say so are handled as text chat for that window — every response during the fallback carries the X-Praxis-Route-Degraded: model-catalog-unavailable header so you can tell.

Errors follow the Gemini API format — see error codes

Response

HTTP 200

Successful response

application/json

NameTypeDescription
modelsarray<object>The returned Models.
models[].baseModelIdstringRequired. The name of the base model, pass this to the generation request. Examples: * `gemini-1.5-flash`
models[].descriptionstringA short description of the model.
models[].displayNamestringThe human-readable name of the model. E.g. "Gemini 1.5 Flash". The name can be up to 128 characters long and can consist of any UTF-8 characters.
models[].inputTokenLimitintegerMaximum number of input tokens allowed for this model.
models[].maxTemperaturenumberThe maximum temperature this model can use.
models[].namestringRequired. The resource name of the `Model`. Refer to Model variants for all allowed values. Format: `models/{model}` with a `{model}` naming convention of: * "{base_model_id}-{version}" Examples: * `models/gemini-1.5-flash-001`
models[].outputTokenLimitintegerMaximum number of output tokens available for this model.
models[].supportedGenerationMethodsarray<string>The model's supported generation methods. The corresponding API method names are defined as Pascal case strings, such as `generateMessage` and `generateContent`.
models[].temperaturenumberControls the randomness of the output. Values can range over `[0.0,max_temperature]`, inclusive. A higher value will produce responses that are more varied, while a value closer to `0.0` will typically result in less surprising responses from the model. This value specifies default to be used by the backend while making the call to the model.
models[].thinkingbooleanWhether the model supports thinking.
models[].topKintegerFor Top-k sampling. Top-k sampling considers the set of `top_k` most probable tokens. This value specifies default to be used by the backend while making the call to the model. If empty, indicates the model doesn't use top-k sampling, and `top_k` isn't allowed as a generation parameter.
models[].topPnumberFor Nucleus sampling. Nucleus sampling considers the smallest set of tokens whose probability sum is at least `top_p`. This value specifies default to be used by the backend while making the call to the model.
models[].versionstringRequired. The version number of the model. This represents the major version (`1.0` or `1.5`)
nextPageTokenstringA token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no more pages.

Get a model

GET /google/v1beta/models/{modelsId}● Supported

Official Gemini API docs ↗

Request parameters

  • namestring必填

    path: Required. The resource name of the model. This name should match a model name returned by the `ListModels` method. Format: `models/{model}`

Returns

200

Errors follow the Gemini API format — see error codes

Response

HTTP 200

Successful response

application/json

NameTypeDescription
baseModelIdstringRequired. The name of the base model, pass this to the generation request. Examples: * `gemini-1.5-flash`
descriptionstringA short description of the model.
displayNamestringThe human-readable name of the model. E.g. "Gemini 1.5 Flash". The name can be up to 128 characters long and can consist of any UTF-8 characters.
inputTokenLimitintegerMaximum number of input tokens allowed for this model.
maxTemperaturenumberThe maximum temperature this model can use.
namestringRequired. The resource name of the `Model`. Refer to Model variants for all allowed values. Format: `models/{model}` with a `{model}` naming convention of: * "{base_model_id}-{version}" Examples: * `models/gemini-1.5-flash-001`
outputTokenLimitintegerMaximum number of output tokens available for this model.
supportedGenerationMethodsarray<string>The model's supported generation methods. The corresponding API method names are defined as Pascal case strings, such as `generateMessage` and `generateContent`.
temperaturenumberControls the randomness of the output. Values can range over `[0.0,max_temperature]`, inclusive. A higher value will produce responses that are more varied, while a value closer to `0.0` will typically result in less surprising responses from the model. This value specifies default to be used by the backend while making the call to the model.
thinkingbooleanWhether the model supports thinking.
topKintegerFor Top-k sampling. Top-k sampling considers the set of `top_k` most probable tokens. This value specifies default to be used by the backend while making the call to the model. If empty, indicates the model doesn't use top-k sampling, and `top_k` isn't allowed as a generation parameter.
topPnumberFor Nucleus sampling. Nucleus sampling considers the smallest set of tokens whose probability sum is at least `top_p`. This value specifies default to be used by the backend while making the call to the model.
versionstringRequired. The version number of the model. This represents the major version (`1.0` or `1.5`)