Gemini 文本聊天(generateContent)
通过 UniGateway 调用 Gemini 原生 generateContent 接口,适用于文本生成、多轮对话、结构化输出和工具调用。
前置条件
- 已获取 UniGateway API Key,保存在环境变量
UNIGATEWAY_API_KEY中 - 已通过
GET /v1/models确认目标 Gemini 模型在当前账号中可用
接口说明
- 方法:
POST - 路径:
/v1beta/models/{model}:generateContent - 流式路径:
/v1beta/models/{model}:streamGenerateContent?alt=sse - Base URL:
https://api.unigateway.ai - 请求头:
Authorization: Bearer <YOUR_UNIGATEWAY_API_KEY>Content-Type: application/json
UniGateway 使用 Bearer Token 鉴权。请求时不要传 x-goog-api-key 或 key= 查询参数。
说明:这是 Gemini 原生格式接口,字段命名使用
contents、parts、generationConfig、systemInstruction等 Gemini 风格字段;如果你使用 OpenAI SDK,请优先接入/v1/chat/completions。
如果使用 SDK 接入,建议先用 cURL 或普通 HTTP 请求验证接口可用。不同版本的 Gemini SDK 对自定义 Base URL 的处理可能不同。
基本请求
curl "https://api.unigateway.ai/v1beta/models/gemini-3-pro-preview:generateContent" \
-H "Authorization: Bearer $UNIGATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [
{
"role": "user",
"parts": [
{"text": "用一段话解释 AI Gateway 的价值。"}
]
}
]
}'
请求体
最小结构
{
"contents": [
{
"role": "user",
"parts": [{"text": "你好"}]
}
]
}
参数说明
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
contents | array | 是 | 当前对话内容。单轮请求传 1 条 user content;多轮请求传完整历史。 |
contents[].role | string | 否 | user 或 model。 |
contents[].parts | array | 是 | 消息片段数组,文本使用 { "text": "..." }。 |
systemInstruction | object | 否 | 系统指令,通常包含 parts: [{"text":"..."}]。 |
generationConfig | object | 否 | 生成参数,如 temperature、topP、maxOutputTokens、responseMimeType 等。 |
tools | array | 否 | 工具定义,如 function calling、Google Search、code execution。 |
toolConfig | object | 否 | 工具调用策略。 |
safetySettings | array | 否 | 安全策略。 |
多轮对话
Gemini 原生 generateContent 是无状态接口。多轮对话需要客户端传入历史消息:
{
"contents": [
{
"role": "user",
"parts": [{"text": "法国首都是哪里?"}]
},
{
"role": "model",
"parts": [{"text": "巴黎。"}]
},
{
"role": "user",
"parts": [{"text": "它的人口大约是多少?"}]
}
]
}
系统指令
curl "https://api.unigateway.ai/v1beta/models/gemini-3-pro-preview:generateContent" \
-H "Authorization: Bearer $UNIGATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"systemInstruction": {
"parts": [{"text": "你是一个回答简洁、适合生产环境接入的技术助手。"}]
},
"contents": [
{"parts": [{"text": "给出 Redis 缓存穿透的处理方案。"}]}
]
}'
生成参数
{
"generationConfig": {
"temperature": 0.7,
"topP": 0.95,
"topK": 40,
"maxOutputTokens": 2048,
"stopSequences": ["\n\n"]
},
"contents": [
{"parts": [{"text": "写一个 API 网关接入 checklist。"}]}
]
}
| 字段 | 说明 |
|---|---|
temperature | 控制随机性。Gemini 3 系列建议优先使用默认值。 |
topP | 核采样参数。 |
topK | Top-K 采样参数。 |
maxOutputTokens | 最大输出 token 数。 |
stopSequences | 停止序列数组。 |
thinkingConfig | 推理配置,例如 thinkingLevel。支持情况以具体模型为准。 |
结构化输出
需要 JSON 输出时,在 generationConfig 中设置 responseMimeType 和 responseJsonSchema:
curl "https://api.unigateway.ai/v1beta/models/gemini-3-pro-preview:generateContent" \
-H "Authorization: Bearer $UNIGATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [
{"parts": [{"text": "从这句话中抽取城市和温度:上海今天 18 摄氏度。"}]}
],
"generationConfig": {
"responseMimeType": "application/json",
"responseJsonSchema": {
"type": "object",
"properties": {
"city": {"type": "string"},
"temperature_celsius": {"type": "number"}
},
"required": ["city", "temperature_celsius"]
}
}
}'
返回的文本通常位于 candidates[0].content.parts[0].text,内容是符合 schema 的 JSON 字符串。
Function calling
{
"contents": [
{
"parts": [{"text": "查询东京今天的天气。"}]
}
],
"tools": [
{
"functionDeclarations": [
{
"name": "get_weather",
"description": "获取指定城市的当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "城市名称"}
},
"required": ["location"]
}
}
]
}
]
}
模型可能返回 functionCall part。应用侧需要执行函数,并在下一轮把 functionResponse 连同历史一起传回。
内置工具
Gemini 原生格式支持部分内置工具,具体可用性取决于模型和账号权限。
{
"tools": [
{"googleSearch": {}},
{"codeExecution": {}}
],
"contents": [
{"parts": [{"text": "搜索并总结最近的 AI Gateway 趋势。"}]}
]
}
常见工具:
| 工具 | 说明 |
|---|---|
googleSearch | 搜索增强 / grounding。 |
codeExecution | 代码执行。 |
urlContext | 读取 URL 上下文。 |
functionDeclarations | 客户端函数调用。 |
流式输出
使用 :streamGenerateContent?alt=sse 路径接收 SSE:
curl "https://api.unigateway.ai/v1beta/models/gemini-3-pro-preview:streamGenerateContent?alt=sse" \
-H "Authorization: Bearer $UNIGATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [
{"parts": [{"text": "用三句话解释 SSE。"}]}
]
}'
客户端需要按 SSE 事件逐段解析 candidates[].content.parts[].text。
响应格式
{
"candidates": [
{
"content": {
"role": "model",
"parts": [
{"text": "AI Gateway 可以统一模型接入、路由和计费..."}
]
},
"finishReason": "STOP",
"index": 0
}
],
"usageMetadata": {
"promptTokenCount": 12,
"candidatesTokenCount": 64,
"totalTokenCount": 76
}
}
响应字段
| 字段 | 说明 |
|---|---|
candidates[] | 候选输出数组。 |
candidates[].content.parts[] | 输出内容片段。文本输出在 text 字段。 |
candidates[].finishReason | 结束原因,如 STOP。 |
usageMetadata | token 使用量统计。 |
常见错误
| 状态码 | 原因 | 处理方式 |
|---|---|---|
400 | 请求体字段不符合 Gemini 原生格式 | 检查 contents[].parts[]、generationConfig 等字段。 |
401 | API Key 无效或缺失 | 检查 Authorization: Bearer ...。 |
404 | 模型不存在或当前账号不可用 | 重新确认 GET /v1/models。 |
429 | 触发限流 | 增加退避并重试。 |
5xx | 服务异常 | 指数退避重试,必要时切换模型。 |