文本生成/Gemini generateContent API

Gemini 原生 generateContent 接口,用于文本生成、多轮对话、结构化输出与工具调用。

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-keykey= 查询参数。

说明:这是 Gemini 原生格式接口,字段命名使用 contentspartsgenerationConfigsystemInstruction 等 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": "你好"}]
    }
  ]
}

参数说明

字段类型必填说明
contentsarray当前对话内容。单轮请求传 1 条 user content;多轮请求传完整历史。
contents[].rolestringusermodel
contents[].partsarray消息片段数组,文本使用 { "text": "..." }
systemInstructionobject系统指令,通常包含 parts: [{"text":"..."}]
generationConfigobject生成参数,如 temperature、topP、maxOutputTokens、responseMimeType 等。
toolsarray工具定义,如 function calling、Google Search、code execution。
toolConfigobject工具调用策略。
safetySettingsarray安全策略。

多轮对话

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核采样参数。
topKTop-K 采样参数。
maxOutputTokens最大输出 token 数。
stopSequences停止序列数组。
thinkingConfig推理配置,例如 thinkingLevel。支持情况以具体模型为准。

结构化输出

需要 JSON 输出时,在 generationConfig 中设置 responseMimeTyperesponseJsonSchema

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
usageMetadatatoken 使用量统计。

常见错误

状态码原因处理方式
400请求体字段不符合 Gemini 原生格式检查 contents[].parts[]generationConfig 等字段。
401API Key 无效或缺失检查 Authorization: Bearer ...
404模型不存在或当前账号不可用重新确认 GET /v1/models
429触发限流增加退避并重试。
5xx服务异常指数退避重试,必要时切换模型。

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"])