Google Vertex AI API: Generate Content
Non-streaming:
Streaming:
Path parameters
provider string Required
Model provider (e.g., google).
model string Required
Model name (e.g., gemini-2.5-pro).
Request headers
Authorization string Required
Bearer token authentication.
Content-Type string Required
Default: application/json
Request body
The request body is JSON.contents array<Content> Required
Current conversation content (single turn / multi-turn history + the current input).
role string Optional
The content producer (defaults to user).
- user: Indicates the message is sent by a human, typically user-generated.
- model: Indicates the message is generated by the model.
parts Part[] Required
At least 1 Part.
part
-
text
stringOptional Text prompt or code snippet. -
inlineData
BlobOptional Inline data as raw bytes.-
mimeType
stringOptional The media type of the file specified in the data or fileUri field. Acceptable values include:- application/pdf
- audio/mpeg
- audio/mp3
- audio/wav
- image/png
- image/jpeg
- image/webp
- text/plain
- video/mov
- video/mpeg
- video/mp4
- video/mpg
- video/avi
- video/wmv
- video/mpegps
- video/flv
- video/x-ms-wmv
-
data
bytesOptional Inline data as raw bytes.
-
mimeType
-
fileData
FileDataOptional Data stored in a file.-
mimeType
stringOptional -
fileUri
stringOptional The URI or URL of the file to include in the prompt.
-
mimeType
-
functionCall
FunctionCallOptional Contains a string representing the FunctionDeclaration.name field, plus a structured JSON object with all parameters of the function call predicted by the model.-
name
stringOptional The name of the function to call. -
args
Record<string,any>Optional Function parameters and values represented as a JSON object.
-
name
-
functionResponse
FunctionResponseOptional The output of a FunctionCall. Contains a string representing the FunctionDeclaration.name field and a structured JSON object containing any output of the function call. It is used as context for the model.-
name
stringOptional The name of the function to call. -
response
Record<string,any>Optional Function response represented as a JSON object.
-
name
-
videoMetadata
VideoMetadataOptional For video inputs: the start and end offsets (duration format), and the frame rate.-
startOffset
numberOptional Video start offset (duration format). -
endOffset
numberOptional Video end offset (duration format). -
fps
numberOptional Video frame rate.
-
startOffset
-
mediaResolution
enumOptional Controls how input media is processed. If specified, this configuration overrides the mediaResolution setting in generationConfig. LOW reduces the number of tokens per image/video, which may cause loss of detail, but allows longer videos to be included in the context. Supported values:HIGH,MEDIUM,LOW.
cachedContent string Optional
Cached content resource name (used as context):
projects/\{project\}/locations/\{location\}/cachedContents/\{cachedContent\}
tools array<Tool> Optional
List of tools (e.g., function calling, retrieval, search, code execution, etc.).
toolConfig ToolConfig Optional
Tool configuration (shared across all tools in this request).
safetySettings array<SafetySetting> Optional
Per-request safety settings (applies to candidates).
category string Required
The safety category to configure a threshold for.
HARM_CATEGORY_UNSPECIFIED: Unspecified harm category.HARM_CATEGORY_HATE_SPEECH: Harm category is hate speech.HARM_CATEGORY_HARASSMENT: Harm category is harassment.HARM_CATEGORY_SEXUALLY_EXPLICIT: Harm category is sexually explicit content.HARM_CATEGORY_DANGEROUS_CONTENT: Harm category is dangerous content.
threshold string Required
Threshold for blocking responses that fall into the specified safety category based on probability.
OFF: Turn off safety settings when all categories are disabled.BLOCK_NONE: Block nothing.BLOCK_ONLY_HIGH: Block only high-threshold content (i.e., block less).BLOCK_MEDIUM_AND_ABOVE: Block medium-threshold and above content.BLOCK_LOW_AND_ABOVE: Block low-threshold and above content (i.e., block more).HARM_BLOCK_THRESHOLD_UNSPECIFIED: Unspecified harm block threshold.
method string Optional
Specifies whether the threshold applies to probability scores or severity scores. If not specified, the threshold applies to probability scores.
HARM_BLOCK_METHOD_UNSPECIFIED: Unspecified harm block method.SEVERITY: Harm block method uses both probability and severity scores.PROBABILITY: Harm block method uses probability scores.
generationConfig GenerationConfig Optional
Generation parameters (controls sampling, length, stop conditions, structured output, logprobs, audio timestamps, thinking, media processing quality, etc.).
temperature number Optional
Controls randomness/diversity in the output. Lower values are more deterministic and “test-like”; higher values are more creative/diverse. 0 tends to always pick the highest-probability token, so it is closer to deterministic (but small variations can still occur). If replies are too templated/too short, try increasing it; if you see anomalies such as “runaway generation,” try raising it to at least 0.1. Ranges/defaults vary by model (for example, some Gemini Flash models commonly use 0.0~2.0 with a default of 1.0).
topP number Optional
Nucleus sampling threshold: the model samples only from the smallest set of tokens whose cumulative probability reaches topP. Lower values are more conservative/less random; higher values are more diverse. Range 0.0~1.0 (model defaults may vary). In general, it is recommended to primarily tune either temperature or topP, not both significantly.
topK integer Optional
Top-K sampling threshold: the model samples only from the topK tokens with the highest probability. For example, topK=40 means each step selects the next token only from the top 40 candidates. Smaller values are more conservative; larger values are more diverse. Model defaults may vary.
candidateCount integer Optional
Number of returned candidates (response variations). Output tokens for all candidates are billed (inputs are typically billed once). Multi-candidate is usually a preview capability and typically only supported by generateContent (not streamGenerateContent), and different models constrain the range/max (e.g., some support 1~8).
maxOutputTokens integer Optional
Maximum number of output tokens to limit response length; tokens can be roughly understood as ~4 characters in English. Smaller values produce shorter output; larger values allow longer output.
stopSequences array<string> Optional
Stop sequence list: generation stops immediately when any stop sequence is encountered in the output, and is truncated at the first occurrence; case-sensitive. The list can contain up to 5 elements.
presencePenalty number Optional
Presence penalty: penalizes tokens that have already appeared in the “generated text,” increasing the probability of generating new/different content. Range -2.0 ~ <2.0.
frequencyPenalty number Optional
Frequency penalty: penalizes tokens that are repeated, reducing the probability of repetitive output. Range -2.0 ~ <2.0.
seed integer Optional
Random seed: with a fixed seed, the model will “try” to return the same result for repeated requests, but does not guarantee full determinism; changes in model version or parameters (e.g., temperature) may also cause differences. If omitted, a random seed is used by default.
responseMimeType string Optional
Specifies the MIME type of candidate outputs. Common supported values:
text/plain(default): plain text outputapplication/json: JSON output (for structured output / JSON mode)text/x.enum: for classification tasks, outputs enum values defined byresponseSchema
responseSchema, you must set responseMimeType to a value other than text/plain (e.g., application/json).
responseSchema Schema Optional
Schema for structured output: constrains candidate text to conform to this schema (for “controlled generation output / JSON Schema” scenarios). When using this field, you must set responseMimeType to a supported non-text/plain type (e.g., application/json).
Schema object fields
-
typeenum (Type)Required Data type. Supported values:STRING: String type; supports constraints such asenum,format(e.g.,date-time,email,byte),minLength,maxLength,pattern, etc.INTEGER: Integer type; supportsformat(e.g.,int32,int64),minimum,maximum, etc.NUMBER: Floating-point number type; supportsformat(e.g.,float,double),minimum,maximum, etc.BOOLEAN: Boolean type.ARRAY: Array type; supportsitems,minItems,maxItems, etc.OBJECT: Object type; supportsproperties,required,propertyOrdering,nullable, etc.
-
formatstringOptional Additional format info. ForNUMBER:float,double; forINTEGER:int32,int64; forSTRING:email,byte,date,date-time,password, etc. -
descriptionstringOptional Text description of the property/field to help the model understand what to generate. -
enumarray<string>Optional List of allowed enum values; the model can only choose one. Typically used withtype: STRING. -
itemsSchemaOptional WhentypeisARRAY, specifies the schema for array elements. -
propertiesmap<string, Schema>Optional WhentypeisOBJECT, defines each property and its schema. -
requiredarray<string>Optional List of required properties in the object. -
propertyOrderingarray<string>Optional Specifies the output order of object properties. -
nullablebooleanOptional Whethernullis allowed. -
minimumnumberOptional WhentypeisINTEGERorNUMBER, the minimum allowed value. -
maximumnumberOptional WhentypeisINTEGERorNUMBER, the maximum allowed value. -
minItemsintegerOptional WhentypeisARRAY, the minimum number of elements. -
maxItemsintegerOptional WhentypeisARRAY, the maximum number of elements. -
minLengthintegerOptional WhentypeisSTRING, the minimum string length. -
maxLengthintegerOptional WhentypeisSTRING, the maximum string length. -
patternstringOptional WhentypeisSTRING, a regex constraint. Example:"^[\\w\\s,.-]+$". -
titlestringOptional Title for the schema. -
anyOfarray<Schema>Optional Union/conditional types: the value must satisfy at least one schema inanyOf.oneOfis also interpreted with the semantics ofanyOf.
Note: Excessive schema complexity (very long property names, too many enum values, overly deep nesting, etc.) may cause InvalidArgument: 400 errors. Keep schemas as simple as possible. Circular references are not supported (only limited expansion is allowed in non-required properties).
responseJsonSchema object Optional
A JSON Schema alternative to responseSchema. When this field is set, you must omit responseSchema, and set responseMimeType to application/json. Accepts standard JSON Schema syntax directly.
responseLogprobs boolean Optional
Whether to return log probabilities for output tokens. When set to true, the response includes per-token log probability details in logprobsResult. You must enable this parameter before using the logprobs field.
logprobs integer Optional
Returns log probabilities for the top candidate tokens at each generation step. Range 1~20. Requires responseLogprobs=true to use this field, and the token selected by the model is not necessarily the top candidate token.
responseModalities array<enum> Optional
Specifies which modalities to return in the response. Only some Gemini models support multimodal output. If not set, defaults to text only. Supported values:
TEXT: Text output (default).IMAGE: Image output; when used, must also includeTEXT, i.e.,["TEXT", "IMAGE"]. Only supported by some models (e.g.,gemini-2.5-flash-image,gemini-3-pro-image-preview).AUDIO: Audio output; mainly for Live API (real-time streaming) scenarios.
audioTimestamp boolean Optional
Audio timestamp understanding: timestamp understanding for audio-only files (preview). Only supported by some models (e.g., some Gemini Flash models).
thinkingConfig ThinkingConfig Optional
“Thinking” (internal reasoning) configuration for Gemini 2.5 and later. Setting this field on models that do not support thinking will return an error.
-
thinkingBudgetintegerOptional Token budget for thinking (applies to Gemini 2.5). Model-specific ranges:- Gemini 2.5 Pro:
128~32768(thinking cannot be disabled) - Gemini 2.5 Flash:
0~24576(0= disable thinking) - Gemini 2.5 Flash Lite:
512~24576
-1for dynamic thinking (the model adjusts budget based on request complexity). If omitted, the model controls it automatically.Note: Cannot be used together with
thinkingLevel.thinkingBudgetapplies only to Gemini 2.5. - Gemini 2.5 Pro:
-
thinkingLevelenum (ThinkingLevel)Optional Controls internal reasoning intensity (recommended for Gemini 3). Supported values:THINKING_LEVEL_UNSPECIFIED: Unspecified; use the model’s default dynamic behavior.MINIMAL: Use as few thinking tokens as possible (Gemini 3 Flash only).LOW: Low reasoning intensity; suitable for simple tasks.MEDIUM: Medium reasoning intensity (Gemini 3 Flash only).HIGH: High reasoning intensity (Gemini 3 default); suitable for complex tasks like math, code, and logical analysis.
Note: Cannot be used together with
thinkingBudget.thinkingLevelapplies only to Gemini 3. -
includeThoughtsbooleanOptional Whether to return a summary of the thinking process in the response. When set totrue, a thought summary is returned when available. This is best-effort: even if enabled, thoughts are not guaranteed to be returned.
mediaResolution enum (MediaResolution) Optional
Controls the token resolution when processing input media (images/videos/PDFs), balancing response quality and token usage. Higher resolution lets the model perceive more detail but consumes more tokens. Supported values:
MEDIA_RESOLUTION_UNSPECIFIED: Unspecified; use the model default (token counts differ across model generations).MEDIA_RESOLUTION_LOW: Low resolution; fewer tokens, faster, cheaper.MEDIA_RESOLUTION_MEDIUM: Medium resolution; balance between quality and cost.MEDIA_RESOLUTION_HIGH: High resolution; more tokens, finer detail.MEDIA_RESOLUTION_ULTRA_HIGH: Ultra-high resolution (Gemini 3 only).
Gemini 3 reference image token counts:ULTRA_HIGH≈ 2240,HIGH≈ 1120,MEDIUM≈ 560.
speechConfig SpeechConfig Optional
Speech generation configuration; used when responseModalities includes AUDIO.
-
voiceConfigVoiceConfigOptional Single-voice configuration (mutually exclusive withmultiSpeakerVoiceConfig).-
prebuiltVoiceConfigPrebuiltVoiceConfigOptional Prebuilt voice configuration.-
voiceNamestringOptional Prebuilt voice name (e.g.,Kore,Puck,Charon, etc.).
-
-
replicatedVoiceConfigReplicatedVoiceConfigOptional Replicated voice configuration (clone a voice from an audio sample).-
mimeTypestringOptional MIME type of the voice sample. Currently onlyaudio/wavis supported (16-bit signed little-endian, 24kHz sample rate). -
voiceSamplestring(bytes)Optional Custom voice sample (base64-encoded).
-
-
-
multiSpeakerVoiceConfigMultiSpeakerVoiceConfigOptional Multi-speaker voice configuration (mutually exclusive withvoiceConfig); for multi-role TTS scenarios.-
speakerVoiceConfigsarray<SpeakerVoiceConfig>List of voice configurations for each speaker.speakerstring: Speaker name.voiceConfigVoiceConfig: Voice configuration used by this speaker (same structure as above).
-
-
languageCodestringOptional Language code for speech output (e.g.,en-US).
routingConfig RoutingConfig Optional
Routing configuration (Vertex AI): routes requests to a specific model. autoMode and manualMode are mutually exclusive.
Note: This field is deprecated. Google recommends using modelConfig instead.
-
autoModeAutoRoutingModeOptional Auto routing: routing is determined by a pretrained routing model plus user preferences.-
modelRoutingPreferenceenum (ModelRoutingPreference)Optional Routing preference. Supported values includeBALANCED, etc.
-
-
manualModeManualRoutingModeOptional Manual routing: explicitly specify the target model.-
modelNamestringOptional Target model name (e.g.,gemini-1.5-pro-001).
-
imageConfig ImageConfig Optional
Image generation configuration; used when responseModalities includes IMAGE.
-
aspectRatiostringOptional Aspect ratio of generated images. Supported values:1:1,2:3,3:2,3:4,4:3,9:16,16:9,21:9; some models also support4:5,5:4. -
imageSizestringOptional Size of generated images. Supported values:1K,2K,4K. Default is1K. -
outputCompressionQualitynumberOptional Output compression quality for generated images (applies only toimage/jpeg). -
outputMimeTypestringOptional MIME type of generated images.
enableAffectiveDialog boolean Optional
Whether to enable affective dialogue: when enabled, the model detects the user’s emotion and adjusts the response style accordingly.
systemInstruction Content Optional
System instruction (guides the model’s overall behavior; recommended to use only text in parts, with each part as a separate paragraph).
Response (non-streaming)
The official response structure is as follows:candidates array<Candidate>
List of candidate results returned for this generation.
Candidate.content object
Candidate content.
- content.parts
array
Array of content parts.- parts[].text
string
Generated text.
- parts[].text
Candidate.finishReason enum (FinishReason)
Why the model stopped generating tokens; if empty, it indicates generation has not stopped yet.
Common values (as listed officially):
FINISH_REASON_STOP: Natural stopping point or matched a stop sequenceFINISH_REASON_MAX_TOKENS: Reached the requested max token limitFINISH_REASON_SAFETY: Stopped for safety reasons (if output is blocked by the filter,Candidate.contentis empty)FINISH_REASON_RECITATION: Stopped due to flagged unauthorized recitationFINISH_REASON_BLOCKLIST: Contains blocked termsFINISH_REASON_PROHIBITED_CONTENT: Contains prohibited content (e.g., CSAM)FINISH_REASON_IMAGE_PROHIBITED_CONTENT: An image in the prompt contains prohibited contentFINISH_REASON_NO_IMAGE: The prompt should include an image but none was providedFINISH_REASON_SPII: Contains sensitive personally identifiable information (SPII)FINISH_REASON_MALFORMED_FUNCTION_CALL: Function call is malformed and cannot be parsedFINISH_REASON_OTHER: Other reasonsFINISH_REASON_UNSPECIFIED: Unspecified
Candidate.safetyRatings array<SafetyRating>
Array of safety ratings.
- safetyRatings[].category
enum (HarmCategory)
Safety category (e.g.,HARM_CATEGORY_SEXUALLY_EXPLICIT,HARM_CATEGORY_HATE_SPEECH,HARM_CATEGORY_HARASSMENT,HARM_CATEGORY_DANGEROUS_CONTENT). - safetyRatings[].probability
enum (HarmProbability)
Harm probability level:NEGLIGIBLE/LOW/MEDIUM/HIGH, etc. - safetyRatings[].blocked
boolean
Indicates whether the model input or output was blocked.
Candidate.citationMetadata object
Citation information (when the output includes citations).
- citationMetadata.citations
array<Citation>- citations[].startIndex
integer
Start position of the citation incontent, measured in bytes of the UTF-8 response. - citations[].endIndex
integer
End position of the citation incontent, also measured in bytes. - citations[].uri
string
Source URL (official docs describe it as url/URL; in the example structure, the field name isuri). - citations[].title
string
Source title. - citations[].license
string
Associated license. - citations[].publicationDate
object
Publication date (valid formats:YYYY/YYYY-MM/YYYY-MM-DD).- publicationDate.year
integer - publicationDate.month
integer - publicationDate.day
integer
- publicationDate.year
- citations[].startIndex
Candidate.avgLogprobs double
Average log probability for the candidate.
Candidate.logprobsResult object
Returns top candidate tokens (topCandidates) and the actually selected tokens (chosenCandidates) for each step.
- logprobsResult.topCandidates
array- topCandidates[].candidates
array- candidates[].token
string: token (character/word/phrase, etc.) - candidates[].logProbability
float: log probability (confidence) of the token
- candidates[].token
- topCandidates[].candidates
- logprobsResult.chosenCandidates
array- chosenCandidates[].token
string - chosenCandidates[].logProbability
float
- chosenCandidates[].token
usageMetadata object
Token usage statistics.
- usageMetadata.promptTokenCount
integer
Number of tokens in the request. - usageMetadata.candidatesTokenCount
integer
Number of tokens in the response. - usageMetadata.totalTokenCount
integer
Total tokens for request + response. - (May appear) thoughtsTokenCount / toolUsePromptTokenCount / cachedContentTokenCount and per-modality details.
Note: The official docs add that for billing purposes, in Gemini 3 Pro and later models, tokens consumed for processing “document inputs” are billed as image tokens.
modelVersion string
Model and version used for generation (example: gemini-2.0-flash-lite-001).
Below is the Vertex AI streamGenerateContent (SSE streaming) response body for each chunk.Key point: In streaming mode, multiple chunks are returned, and each chunk’s JSON structure is still
GenerateContentResponse. Intermediate chunks often have an empty finishReason; only the final chunk provides termination info such as finishReason/finishMessage.
createTime string
Server receive time (RFC3339 Timestamp).
responseId string
Response identifier.
Response (streaming: response body of each stream chunk)
promptFeedback: Returned only in the first stream chunk, and appears only when no candidates are generated due to policy violations.
finishMessage: Returned only whenfinishReasonis present.
candidates array<Candidate>
List of candidate results in this chunk.
Candidate.index integer
Candidate index (starting from 0).
Candidate.content object
Candidate content (multiple parts).
content.role string
Producer role: typically 'user' or 'model'.
content.parts array<Part>
Array of content parts; each part is a “single-type” data block (text / inlineData / functionCall …).
Part object(content.parts[])
Part.thought boolean
Whether this is a “thought/reasoning” part.
Part.thoughtSignature string(bytes)
Reusable signature for the thought (base64).
Part.mediaResolution PartMediaResolution
Input media resolution (affects media tokenization).
- mediaResolution.level
enum (PartMediaResolutionLevel): LOW / MEDIUM / HIGH / ULTRA_HIGH / UNSPECIFIED. - mediaResolution.numTokens
integer: Expected media token sequence length.
Part.data (Union) Only one is present per part
Part.text string
Text content (the most common location for streaming incremental output).
Part.inlineData Blob
Inline binary data (base64).
- inlineData.mimeType
string: IANA MIME Type. - inlineData.data
string(bytes): base64 bytes. - inlineData.displayName
string: Optional display name (returned only in some scenarios).
Part.fileData FileData
Reference to an external file (e.g., GCS).
- fileData.mimeType
string: IANA MIME Type. - fileData.fileUri
string: File URI. - fileData.displayName
string: Optional display name.
Part.functionCall FunctionCall
A function call predicted by the model.
- functionCall.id
string: Function call id (used to match with functionResponse). - functionCall.name
string: Function name. - functionCall.args
object: Function arguments (JSON object). - functionCall.partialArgs
array<PartialArg>: Streaming function-argument deltas (available in some APIs/modes). - functionCall.willContinue
boolean: Whether additional deltas for this FunctionCall will follow.
PartialArg (for functionCall.partialArgs)
- jsonPath
string: Path to the parameter being streamed incrementally (RFC 9535). - stringValue / numberValue / boolValue / nullValue: The delta value for this chunk (one of four).
- willContinue
boolean: Whether more deltas will follow for this jsonPath.
Part.functionResponse FunctionResponse
Structure used when you send tool execution results back to the model (may also appear in responses in some modes).
- functionResponse.id
string: Corresponding functionCall.id. - functionResponse.name
string: Function name (matches functionCall.name). - functionResponse.response
object: Function result (JSON object; conventionally output/error). - functionResponse.parts
array<FunctionResponsePart>: Multi-part function response (can include files/inline data). - functionResponse.scheduling
enum (FunctionResponseScheduling): SILENT / WHEN_IDLE / INTERRUPT / … - functionResponse.willContinue
boolean: Whether more response fragments will follow.
Part.executableCode ExecutableCode
Code generated by the model for a code-execution tool.
- executableCode.language
enum (Language): e.g., PYTHON. - executableCode.code
string: Code string.
Part.codeExecutionResult CodeExecutionResult
Code execution result.
- codeExecutionResult.outcome
enum (Outcome): OUTCOME_OK / OUTCOME_FAILED / OUTCOME_DEADLINE_EXCEEDED. - codeExecutionResult.output
string: stdout or error message.
Part.metadata (Union)
Part.videoMetadata VideoMetadata
Metadata used only when the part carries video data.
- videoMetadata.startOffset
string: Start offset. - videoMetadata.endOffset
string: End offset. - videoMetadata.fps
number: Frame rate.
Candidate.avgLogprobs number
Candidate average logprob (length-normalized).
Candidate.logprobsResult LogprobsResult
Logprobs details.
- logprobsResult.topCandidates
array<LogprobsResultTopCandidates>: Per-step top-token lists.- topCandidates[].candidates
array<LogprobsResultCandidate>: Sorted by logProbability descending.
- topCandidates[].candidates
- logprobsResult.chosenCandidates
array<LogprobsResultCandidate>: The final sampled/selected token per step. - LogprobsResultCandidate.token / tokenId / logProbability: token, tokenId, log probability.
Candidate.finishReason enum (FinishReason)
Why generation stopped; if empty, it means “not stopped yet”.
Common values (example enums):
STOP/MAX_TOKENS/SAFETY/RECITATION/BLOCKLIST/PROHIBITED_CONTENT/SPII/MALFORMED_FUNCTION_CALL/OTHER/FINISH_REASON_UNSPECIFIED…
Candidate.safetyRatings array<SafetyRating>
Safety ratings for the candidate output (at most one entry per category).
- safetyRatings[].category
enum (HarmCategory): e.g., HATE_SPEECH / SEXUALLY_EXPLICIT / DANGEROUS_CONTENT / HARASSMENT / CIVIC_INTEGRITY … - safetyRatings[].probability
enum (HarmProbability): NEGLIGIBLE / LOW / MEDIUM / HIGH … - safetyRatings[].blocked
boolean: Whether it was filtered due to this rating.
Some APIs/SDKs may also provide finer-grained fields such as probabilityScore / severity / severityScore, which may not appear in all Vertex REST outputs.
Candidate.citationMetadata CitationMetadata
Citation information.
- citationMetadata.citations
array<Citation>- citations[].startIndex
integer: Citation start position - citations[].endIndex
integer: Citation end position - citations[].uri
string: Source URL/URI - citations[].title
string: Source title - citations[].license
string: License - citations[].publicationDate
\{year,month,day\}: Publication date
- citations[].startIndex
Candidate.groundingMetadata GroundingMetadata
Retrieval/evidence source metadata returned when grounding is enabled.
- groundingMetadata.webSearchQueries
string[]: Queries used for Google Search. - groundingMetadata.retrievalQueries
string[]: Queries actually executed by the retrieval tool. - groundingMetadata.groundingChunks
array<GroundingChunk>: Evidence chunks.- groundingChunks[].web
\{uri,title,domain\}: Web evidence. - groundingChunks[].retrievedContext / maps: Other evidence sources (object structure depends on the source).
- groundingChunks[].web
- groundingMetadata.searchEntryPoint
\{renderedContent,sdkBlob\}: Search entry-point info. - groundingMetadata.retrievalMetadata
\{googleSearchDynamicRetrievalScore\}: Retrieval-related metadata. - Plus sourceFlaggingUris / googleMapsWidgetContextToken, etc. (when using Google Maps grounding).
Candidate.urlContextMetadata UrlContextMetadata
URL retrieval metadata returned when the model uses the urlContext tool.
- urlContextMetadata.urlMetadata
array<UrlMetadata>: URL list.- urlMetadata[].retrievedUrl
string: The URL that was actually retrieved. - urlMetadata[].urlRetrievalStatus
enum (UrlRetrievalStatus): SUCCESS / ERROR / PAYWALL / UNSAFE / UNSPECIFIED.
- urlMetadata[].retrievedUrl
Candidate.finishMessage string
A more detailed explanation of finishReason (returned only when finishReason is present).
modelVersion string
Model version used for this generation.
createTime string
Server receive time (RFC3339 Timestamp).
responseId string
Response identifier.
promptFeedback object
Prompt content-filtering result: only appears in the first stream chunk and only when there are no candidates due to violations.
- promptFeedback.blockReason
enum (BlockedReason): Blocking reason. - promptFeedback.blockReasonMessage
string: Human-readable reason (may not be supported in all environments). - promptFeedback.safetyRatings
array<SafetyRating>: Safety ratings for the prompt.
usageMetadata object
Token usage.
- usageMetadata.promptTokenCount
integer: Prompt token count. - usageMetadata.candidatesTokenCount
integer: Total candidate output token count. - usageMetadata.totalTokenCount
integer: Total token count. - (May appear) thoughtsTokenCount / toolUsePromptTokenCount / cachedContentTokenCount and per-modality details.