Gemini generateContent API
通过 UniGateway 的 Gemini API 兼容接口调用 Gemini model,完成文本生成、多轮对话、函数调用和流式输出。本文仅说明文本生成;图像生成请使用 Gemini Images API。UniGateway 当前不提供 Gemini 语音或视频生成接口。model ID、能力和可用性以 UniGateway 模型库 为准。
Example request
Run it in your stack
Pick the SDK style that matches your app and copy the snippet directly into your project.
import requests
api_key = "<YOUR_UNIGATEWAY_API_KEY>"
model = "gemini-3-pro-preview"
resp = requests.post(
f"https://api.unigateway.ai/v1beta/models/{model}:generateContent",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"contents": [
{"parts": [{"text": "Summarize the benefits of an AI gateway."}]}
]
},
)
print(resp.json()["candidates"][0]["content"]["parts"][0]["text"])接口说明
| 项目 | 值 |
|---|---|
| 方法 | POST |
| 文本路径 | /v1beta/models/{model}:generateContent |
| 流式路径 | /v1beta/models/{model}:streamGenerateContent |
| API 根地址 | https://api.unigateway.ai |
| 鉴权 | Authorization: Bearer $UNIGATEWAY_API_KEY |
| Content-Type | application/json |
| 渠道亲和性 | 可选:x-gemini-session-id: <session-id> |
将路径中的 {model} 替换为目标 model ID,例如 gemini-3.5-flash。图像生成请使用专门的 Gemini Images API 文档。
准备工作
请前往 UniGateway API Keys 创建或获取 API Key。有关 API Key 的创建、访问控制、轮换和安全管理,请参阅 账户与 API Key。
将 API Key 配置为服务端环境变量,不要将其写入浏览器前端代码、日志或代码仓库:
export UNIGATEWAY_API_KEY="<YOUR_UNIGATEWAY_API_KEY>"
Windows PowerShell:
$env:UNIGATEWAY_API_KEY = "<YOUR_UNIGATEWAY_API_KEY>"
渠道亲和性
需要将同一业务会话的 Gemini 请求路由到同一渠道时,在每个相关请求中携带以下请求头:
x-gemini-session-id: <session-id>
将 <session-id> 替换为应用生成的稳定会话标识。同一会话中的普通请求、流式请求、函数调用后的后续请求都必须使用相同的值;不同的独立会话应使用不同的值。未携带该请求头时,请求不会使用渠道亲和性。
该请求头仅用于渠道路由,不保存 Gemini 对话历史。多轮对话仍必须在每次请求的 contents 中传入完整历史。不要在 session ID 中写入 API Key、用户个人信息或其他敏感数据。
生成文本
请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
路径中的 {model} | string | 是 | 当前账户可用的 Gemini model ID。 |
contents | array<object> | 是 | 按顺序传入的对话内容。 |
contents[].role | string | 否 | 消息角色,常用 user 或 model。 |
contents[].parts | array<object> | 是 | 内容块数组。文本块使用 {"text": "..."};同一消息可按顺序包含多个内容块。 |
systemInstruction | object | 否 | 系统指令,格式为 {"parts": [{"text": "..."}]}。不要放入 contents。 |
generationConfig | object | 否 | 生成配置对象;字段使用 camelCase,例如 maxOutputTokens、temperature、topP、topK 和 stopSequences。 |
safetySettings | array<object> | 否 | 安全设置。每项包含 category 和 threshold;可用类别和阈值以目标 model 的实时响应为准。 |
tools | array<object> | 否 | 工具定义。函数调用使用 functionDeclarations;googleSearch、googleSearchRetrieval、codeExecution 和 urlContext 的可用性以实际请求响应为准。 |
toolConfig | object | 否 | 工具调用策略。可使用 functionCallingConfig、retrievalConfig 和 includeServerSideToolInvocations。 |
cachedContent | string | 否 | 已创建的 Gemini 缓存内容资源名。仅当当前 model、渠道和 API Key 可访问该资源时传入。 |
字段用法
contents 是完整对话历史。每条 user 或 model 消息都使用 parts 数组;多轮调用时仅在末尾追加新的内容,不要改变已有消息及内容块顺序。
systemInstruction 用于应用级系统规则。generationConfig 中常用字段如下:
| 字段 | 类型 | 说明 |
|---|---|---|
maxOutputTokens | integer | 本次响应允许生成的最大 token 数。 |
temperature | number | 控制输出随机性。未传入时使用 model 默认值。 |
topP | number | 核采样参数。 |
topK | integer | Top-K 采样参数。 |
stopSequences | array<string> | 生成内容匹配其中任一序列时停止。 |
responseMimeType | string | 输出 MIME 类型;结构化 JSON 输出时使用 application/json。 |
responseSchema | object | 与 responseMimeType: "application/json" 配合,约束 JSON 输出结构。 |
responseJsonSchema | object | 与 responseMimeType: "application/json" 配合,使用 JSON Schema 约束 JSON 输出结构。 |
candidateCount | integer | 请求返回的候选结果数量。实际允许范围以目标 model 的实时响应为准。 |
seed | integer | 采样随机种子;相同值不保证跨 model、版本或渠道得到完全相同的输出。 |
presencePenalty | number | 降低已出现内容再次出现的倾向。 |
frequencyPenalty | number | 降低高频 token 再次出现的倾向。 |
responseLogprobs | boolean | 是否返回输出 token 的对数概率信息。 |
logprobs | integer | 返回的候选 token 对数概率数量;仅在启用 responseLogprobs 且 model 支持时使用。 |
thinkingConfig | object | 思考配置,可包含 includeThoughts、thinkingBudget 和 thinkingLevel;具体支持情况由目标 model 决定。 |
enableEnhancedCivicAnswers | boolean | 增强公民问答配置;可用性以实际请求响应为准。 |
contents[].parts 在文本工作流中使用 text、functionCall、functionResponse、thought 或 thoughtSignature。工具调用后的后续请求应保留模型返回的 functionCall 与 thoughtSignature 内容块。图像输入请使用 Gemini Images API 中的 inline_data 格式;不要向文本接口传入音频或视频内容块。
函数调用使用 tools 声明函数,并通过 toolConfig.functionCallingConfig 控制调用方式。mode 可使用 AUTO(由 model 决定)、ANY(要求调用函数)或 NONE(禁止函数调用):
{
"tools": [
{
"functionDeclarations": [
{
"name": "get_order_status",
"description": "Get the status of an order by its ID.",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string"}
},
"required": ["order_id"]
}
}
]
}
],
"toolConfig": {
"functionCallingConfig": {
"mode": "AUTO"
}
}
}
以下请求体展示文本生成所需的完整基础结构。按业务需要增加请求字段;接口返回参数错误时,根据当前响应移除或调整对应字段。图像输入请使用 Gemini Images API 中说明的 inline_data 格式。
{
"systemInstruction": {
"parts": [
{"text": "You are a concise support assistant."}
]
},
"contents": [
{
"role": "user",
"parts": [
{"text": "Summarize the purpose of an API gateway in three points."}
]
}
],
"generationConfig": {
"maxOutputTokens": 512,
"temperature": 0.2,
"topP": 0.95,
"stopSequences": ["<END>"]
}
}
cURL 请求示例
curl https://api.unigateway.ai/v1beta/models/gemini-3.5-flash:generateContent \
-H "Authorization: Bearer $UNIGATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-H "x-gemini-session-id: <session-id>" \
-d '{
"systemInstruction": {
"parts": [
{"text": "You are a concise support assistant."}
]
},
"contents": [
{
"role": "user",
"parts": [
{"text": "Summarize the purpose of an API gateway in three points."}
]
}
],
"generationConfig": {
"maxOutputTokens": 512,
"temperature": 0.2
}
}'
Python 请求示例
安装依赖:
pip install google-genai
Google Gen AI SDK 的 base_url 使用 UniGateway 根地址,并通过 api_version 指定 v1beta:
需要渠道亲和性时,在 SDK 的 HttpOptions.headers 中设置 x-gemini-session-id,并在同一业务会话的全部调用中保持该值一致:
headers={"x-gemini-session-id": "<session-id>"}
import os
from google import genai
from google.genai import types
client = genai.Client(
api_key=os.environ["UNIGATEWAY_API_KEY"],
http_options=types.HttpOptions(
base_url="https://api.unigateway.ai",
api_version="v1beta",
headers={"x-gemini-session-id": "<session-id>"},
),
)
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="Summarize the purpose of an API gateway in three points.",
config=types.GenerateContentConfig(
system_instruction="You are a concise support assistant.",
max_output_tokens=512,
temperature=0.2,
),
)
print(response.text)
JavaScript 请求示例
安装依赖:
npm install @google/genai
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({
apiKey: process.env.UNIGATEWAY_API_KEY,
httpOptions: {
baseUrl: "https://api.unigateway.ai",
apiVersion: "v1beta",
headers: { "x-gemini-session-id": "<session-id>" },
},
});
const response = await client.models.generateContent({
model: "gemini-3.5-flash",
contents: "Summarize the purpose of an API gateway in three points.",
config: {
systemInstruction: "You are a concise support assistant.",
maxOutputTokens: 512,
temperature: 0.2,
},
});
console.log(response.text);
响应格式
generateContent 返回候选结果,生成内容位于 candidates[].content.parts[]。单次文本输出可读取 SDK 的 response.text;处理函数调用、多内容块或候选结果时,应遍历 parts[]。
{
"candidates": [
{
"content": {
"role": "model",
"parts": [
{
"text": "1. It provides a unified integration point.\n2. It centralizes access control and policies.\n3. It records usage for operations and cost analysis."
}
]
},
"finishReason": "STOP",
"index": 0
}
],
"usageMetadata": {
"promptTokenCount": 28,
"candidatesTokenCount": 47,
"totalTokenCount": 75
},
"modelVersion": "gemini-3.5-flash"
}
| 字段 | 类型 | 说明 |
|---|---|---|
candidates | array<object> | 候选结果数组。 |
candidates[].content.role | string | 模型消息角色,通常为 model。 |
candidates[].content.parts | array<object> | 文本、函数调用或其他输出内容块。 |
candidates[].finishReason | string / null | 生成结束原因,例如 STOP、MAX_TOKENS 或安全相关结束原因。 |
usageMetadata.promptTokenCount | integer | 输入 token 数。 |
usageMetadata.candidatesTokenCount | integer | 候选输出 token 数。 |
usageMetadata.totalTokenCount | integer | 本次请求的总 token 数。 |
modelVersion | string / null | 实际处理请求的 model 版本或标识。 |
响应字段会因 model、内容模态和生成配置而变化。candidates 为空或 parts 不含文本时,不应直接读取 response.text,应检查完整响应中的结束原因和内容块类型。
多轮对话
Gemini API 不在服务端保存会话历史。每轮调用都应传入完整的 contents,并在末尾追加新的 user 或 model 内容;不要重写或重排已存在的 parts。
contents = [
{
"role": "user",
"parts": [{"text": "What is an API gateway?"}],
}
]
first_response = client.models.generate_content(
model="gemini-3.5-flash",
contents=contents,
)
contents.append(
{
"role": "model",
"parts": [{"text": first_response.text}],
}
)
contents.append(
{
"role": "user",
"parts": [{"text": "Explain its security role in one sentence."}],
}
)
second_response = client.models.generate_content(
model="gemini-3.5-flash",
contents=contents,
)
print(second_response.text)
当首轮响应包含函数调用或多个内容块时,必须将响应中的原始 content.parts 完整追加到历史中,而不是只保留 response.text。
函数调用
在 tools 中声明应用允许调用的函数。模型返回 functionCall 后,应用应校验参数、执行允许的函数,并将 functionResponse 作为下一条内容传回模型。
from google.genai import types
get_order_status = types.FunctionDeclaration(
name="get_order_status",
description="Get the status of an order by its ID.",
parameters={
"type": "object",
"properties": {
"order_id": {
"type": "string",
"description": "The customer order ID.",
}
},
"required": ["order_id"],
},
)
tools = [types.Tool(function_declarations=[get_order_status])]
contents = [
types.Content(
role="user",
parts=[types.Part(text="What is the status of order UG-20260721-001?")],
)
]
response = client.models.generate_content(
model="gemini-3.5-flash",
contents=contents,
config=types.GenerateContentConfig(tools=tools),
)
function_call = next(
(
part.function_call
for part in response.candidates[0].content.parts
if part.function_call
),
None,
)
if function_call is not None:
order_id = function_call.args["order_id"]
# Replace this example with a validated application-side lookup.
result = {"order_id": order_id, "status": "in_transit"}
contents.append(response.candidates[0].content)
contents.append(
types.Content(
role="user",
parts=[
types.Part.from_function_response(
name=function_call.name,
response=result,
)
],
)
)
final_response = client.models.generate_content(
model="gemini-3.5-flash",
contents=contents,
config=types.GenerateContentConfig(tools=tools),
)
print(final_response.text)
函数参数由模型生成,应用必须验证字段、限制可访问资源并控制副作用。不要执行未声明的函数,也不要直接信任模型参数。
流式输出
使用 streamGenerateContent 或 SDK 的流式方法读取生成增量。每个数据块都可能不包含文本;客户端应检查候选结果和内容块后再输出。
Python 请求示例
stream = client.models.generate_content_stream(
model="gemini-3.5-flash",
contents="Explain how an API gateway handles rate limiting.",
)
for chunk in stream:
if chunk.text:
print(chunk.text, end="", flush=True)
JavaScript 请求示例
const response = await client.models.generateContentStream({
model: "gemini-3.5-flash",
contents: "Explain how an API gateway handles rate limiting.",
});
for await (const chunk of response) {
if (chunk.text) {
process.stdout.write(chunk.text);
}
}
原生请求
原生 REST 调用使用 :streamGenerateContent 路径,并通过 alt=sse 请求 SSE 响应:
curl -N "https://api.unigateway.ai/v1beta/models/gemini-3.5-flash:streamGenerateContent?alt=sse" \
-H "Authorization: Bearer $UNIGATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-H "x-gemini-session-id: <session-id>" \
-d '{
"contents": [
{
"role": "user",
"parts": [
{"text": "Explain how an API gateway handles rate limiting."}
]
}
]
}'
流式函数调用可能在多个数据块中返回。应用应在收到完整函数调用参数后再解析和执行,不能只拼接文本增量。
请求限制与错误处理
本文示例中的文本生成、多轮对话、函数调用和流式输出使用 Gemini API 通用字段。图像、文档和部分生成配置仅应在目标 model 支持时传入;接口返回参数错误时,按本节的错误码检查请求字段后再重试。
| HTTP 状态码 | 常见原因 | 处理方式 |
|---|---|---|
400 | 请求 JSON、内容块、函数声明或生成参数无效。 | 检查 {model}、contents、parts、generationConfig 和函数 schema。 |
401 | API Key 缺失、无效或环境变量未加载。 | 检查服务端的 UNIGATEWAY_API_KEY,重新加载应用配置后再次请求。 |
403 | API Key 已停用,或模型、IP 地址等访问策略不允许本次调用。 | 在 UniGateway 控制台检查 API Key 状态、模型白名单和 IP 地址白名单,再重新验证。 |
404 | model ID 或请求路径不正确。 | 确认使用 /v1beta/models/{model}:generateContent 或 :streamGenerateContent,并使用模型库中标注的 model ID。 |
429 | 请求频率或并发超过限制。 | 降低并发,使用有限次数的指数退避重试,并遵守响应中的重试提示(如有)。 |
5xx | 网关或模型服务暂时异常。 | 使用有限次数的指数退避重试;持续失败时记录请求时间、model 和错误响应以便排查。 |