跳到正文

用 OpenAI 格式调用 Gemini

用 OpenAI 的对话补全接口(/v1/chat/completions)调用 Gemini 模型:带 -thinking、-nothinking 后缀的模型名,思考参数、图片、音频、视频、工具调用怎么转换,以及这种方式下用不了的 Gemini 能力。

已经在用 OpenAI SDK,或者工具只支持 OpenAI 格式时,把 model 换成 Gemini 的模型名,就能用对话补全接口调用 Gemini。网关把请求转换成 Gemini 的 generateContent 格式发给上游,再把返回转换回 OpenAI 的格式。能用的是模型广场里同时标了 OpenAI 接口类型的 Gemini 模型,密钥的分组决定其中哪些能用(见分组说明)。

POST https://codaapi.com/v1/chat/completions

Base URL 用 https://codaapi.com/v1。Google 官方文档里的 OpenAI 兼容地址(…/v1beta/openai/)在网关上只有模型列表,对话请求发到那里会返回 404。需要 Gemini 特有的能力时(见用不了的 Gemini 能力),改用 generateContent 原生接口。

请求头

名称 必填 说明
Authorization 是 Bearer sk-…。这个接口不认 x-goog-api-key 和 ?key=
Content-Type 是 application/json

请求参数

写法与 OpenAI 的 Chat Completions 一样,下表说明常用参数转换成 Gemini 的什么。表里没有的参数(例如 n、logprobs、frequency_penalty、presence_penalty)不会发给上游。

参数 类型 必填 转换成 Gemini 的
model string 是 Gemini 模型名,例如 gemini-2.5-flash;带后缀的名字见模型名后缀
messages array 是 system、developer 消息合并成 systemInstruction;assistant 变成 model;tool_calls 变成 functionCall;tool 消息变成 functionResponse
max_completion_tokens 或 max_tokens integer 否 generationConfig.maxOutputTokens
temperature、top_p、seed number 否 generationConfig 里的 temperature、topP、seed
stop string 或 array 否 generationConfig.stopSequences,最多 5 个,多的丢掉
stream boolean 否 流式返回,见流式返回
response_format object 否 json_object、json_schema 变成 responseMimeType: "application/json",json_schema 里的结构作为输出结构发给上游(模型不支持完整 JSON Schema 时,网关会去掉它不支持的关键字)
reasoning_effort、reasoning — 否 generationConfig.thinkingConfig,见思考参数
extra_body.google.thinking_config object 否 直接写 Gemini 的思考设置,见思考参数
extra_body.google.image_config object 否 图像模型的 imageConfig,写法是 aspect_ratio、image_size,见 Nano Banana
tools、tool_choice — 否 functionDeclarations 和 toolConfig,见工具调用

模型名后缀

模型广场里有一些带后缀的 Gemini 模型名。这是网关提供的写法,不是 Google 官方的模型名:网关去掉后缀,用原模型名发给上游,并按后缀改写思考设置。原生接口和 OpenAI 格式都适用。

后缀 例子 含义
-thinking gemini-3-pro-preview-thinking 打开思考,并在返回里带思考摘要。Gemini 2.5 系列写了 max_tokens 时,思考预算按它的一定比例设置
-nothinking gemini-2.5-flash-nothinking、gemini-3-flash-preview-nothinking 关闭思考。能关闭思考的模型(例如 Gemini 2.5 Flash)设为 thinkingBudget: 0;不能完全关闭的模型(Gemini 2.5 Pro、Gemini 3 系列)改用它支持的最低档
-thinking- 加数字 模型广场里名字以 -thinking-* 结尾的一行,表示可以接任意数字,例如在 gemini-2.5-pro 后面加 -thinking-8192 思考预算设为这个 tokens 数。Gemini 2.5 系列直接用作 thinkingBudget,超出模型允许的范围会被调整到范围内;Gemini 3 系列换算成相近的 thinkingLevel

后缀和请求里的思考参数冲突时,以模型名为准。能用哪些带后缀的名字、各自的价格,以模型广场列出的为准。

思考参数

不用后缀时,可以在请求里设置思考:

写法 效果
"reasoning_effort": "low"(可选 minimal、low、medium、high、xhigh、max) Gemini 3 系列换算成 thinkingLevel(模型没有的档位换成相近的档位);Gemini 2.5 系列按档位换算成 thinkingBudget
"reasoning_effort": "none" 或 "reasoning": {"enabled": false} 关闭思考;不能关闭的模型改用最低档
"reasoning": {"max_tokens": 4096} 指定思考预算;Gemini 3 系列换算成相近的 thinkingLevel
"extra_body": {"google": {"thinking_config": {…}}} 直接写 Gemini 的思考设置:thinking_budget、thinking_level、include_thoughts

reasoning_effort 写了上面以外的值,网关返回 400。thinking_config 和 reasoning_effort 同时写时,以 thinking_config 为准。extra_body 里的字段要用下划线写法(thinking_config、thinking_budget),写成驼峰(thinkingConfig)会返回错误,错误信息里会提示正确的写法。

只设置强度时,Gemini 不返回思考内容。要在返回里看到思考摘要,用 -thinking 后缀,或者在 thinking_config 里写 "include_thoughts": true。思考摘要放在 choices[0].message.reasoning_content(流式时在 delta.reasoning_content),这不是 OpenAI 的标准字段,有的客户端不显示。

用 OpenAI Python SDK 时,extra_body 参数的内容会合并进请求体的顶层,所以要再包一层:

response = client.chat.completions.create(
    model="gemini-2.5-flash",
    messages=[{"role": "user", "content": "9.11 和 9.9 哪个大?"}],
    extra_body={"extra_body": {"google": {"thinking_config": {"thinking_budget": 1024, "include_thoughts": True}}}},
)

图片

图片照 OpenAI 的写法放在 content 数组里:

{
  "role": "user",
  "content": [
    {"type": "text", "text": "图里有什么?"},
    {"type": "image_url", "image_url": {"url": "https://example.com/photo.jpg"}}
  ]
}

url 可以是公网能访问的地址,也可以是 data:image/png;base64,…。是地址时,网关先把图片下载下来,再以 inlineData 发给 Gemini,所以图片地址要能从公网访问;Gemini 不支持的文件类型会直接报错。

图像模型生成的图片,在 OpenAI 格式的返回里以 Markdown 图片(![image](data:image/png;base64,…))的形式放在 content 里,用法见 Nano Banana。

工具调用

tools 里的函数转成 Gemini 的 functionDeclarations,parameters 里 Gemini 不支持的 JSON Schema 关键字会被网关清理掉。tool_choice 转成 toolConfig。

模型要调用工具时,返回的 finish_reason 是 tool_calls,message.tool_calls 里是调用。执行完工具,把结果作为 role: "tool" 的消息(带上对应的 tool_call_id)加到 messages 里,再请求一次。

请求示例

curl

curl https://codaapi.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-2.5-pro",
    "messages": [{"role": "user", "content": "什么是 API 网关?"}]
  }'

Python(pip install openai)

from openai import OpenAI

client = OpenAI(
    base_url="https://codaapi.com/v1",
    api_key="sk-你的密钥",  # 建议改为从环境变量 OPENAI_API_KEY 读取
)

response = client.chat.completions.create(
    model="gemini-2.5-pro",
    messages=[{"role": "user", "content": "什么是 API 网关?"}],
)
print(response.choices[0].message.content)

Node.js(npm install openai)

import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://codaapi.com/v1',
  apiKey: process.env.OPENAI_API_KEY,
});

const completion = await client.chat.completions.create({
  model: 'gemini-2.5-pro',
  messages: [{ role: 'user', content: '什么是 API 网关?' }],
});
console.log(completion.choices[0].message.content);

强制返回思考

不设置思考参数时,Gemini 按模型默认的方式思考,返回里不带思考内容。要强制思考并返回思考摘要,把模型名换成带 -thinking 后缀的版本:

curl https://codaapi.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-pro-preview-thinking",
    "messages": [{"role": "user", "content": "你是谁?"}]
  }'
response = client.chat.completions.create(
    model="gemini-3-pro-preview-thinking",
    messages=[{"role": "user", "content": "你是谁?"}],
)
message = response.choices[0].message
print(message.content)
# 思考摘要不是 OpenAI 的标准字段,用 getattr 读取
print(getattr(message, "reasoning_content", None))

返回的 message 里,回答在 content,思考摘要在 reasoning_content:

{
  "role": "assistant",
  "content": "我是 Google 训练的大语言模型 Gemini。",
  "reasoning_content": "用户在问我的身份……"
}

强制不思考用 -nothinking 后缀,例如 gemini-2.5-flash-nothinking、gemini-3-flash-preview-nothinking。各后缀的含义见模型名后缀,不换模型名、用参数控制思考的写法见思考参数。

图片理解

curl https://codaapi.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-2.5-pro",
    "messages": [{
      "role": "user",
      "content": [
        {"type": "text", "text": "这张图片是什么?"},
        {"type": "image_url", "image_url": {"url": "https://example.com/photo.jpg"}}
      ]
    }]
  }'

图片地址和 base64 的要求见上文的图片。

音频理解

音频、PDF 等文件也可以写成 image_url 内容块,一条消息里可以放几个:

curl https://codaapi.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-2.5-pro",
    "messages": [{
      "role": "user",
      "content": [
        {"type": "text", "text": "我发了一段录音和一份 PDF,请分别概括它们的内容"},
        {"type": "image_url", "image_url": {"url": "https://example.com/meeting.mp3"}},
        {"type": "image_url", "image_url": {"url": "https://example.com/report.pdf"}}
      ]
    }]
  }'

网关先下载这些地址,按下载到的文件类型发给 Gemini,所以地址要能从公网直接下载;Gemini 不支持的文件类型会直接报错。url 也可以是 data:audio/mp3;base64,… 这样的 data URL。

视频理解

curl https://codaapi.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-2.5-pro",
    "messages": [{
      "role": "user",
      "content": [
        {"type": "text", "text": "用三句话概括这段视频"},
        {"type": "image_url", "image_url": {"url": "https://example.com/clip.mp4"}}
      ]
    }]
  }'

url 要填视频文件本身的地址:网关会下载这个地址再发给 Gemini,YouTube 这类视频网页的地址下载到的是网页,不是视频。视频按画面和声音折算成输入 tokens,几分钟的视频就可能有几万 tokens。

返回

返回的是 OpenAI Chat Completions 的格式:

{
  "object": "chat.completion",
  "model": "gemini-2.5-pro",
  "choices": [
    {
      "index": 0,
      "message": {"role": "assistant", "content": "API 网关是……"},
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 20,
    "completion_tokens": 260,
    "total_tokens": 280,
    "completion_tokens_details": {"reasoning_tokens": 230}
  }
}
字段 说明
choices[0].message.content 回答的文字(图像模型的图片也在这里,见上文)
choices[0].message.reasoning_content 思考摘要(要求返回时才有,见强制返回思考)
choices[0].message.tool_calls 要调用的工具
choices[0].finish_reason 由 Gemini 的 finishReason 换算:STOP → stop,MAX_TOKENS → length,SAFETY 等被拦下的情况 → content_filter,调用工具时是 tool_calls
usage.completion_tokens 输出的 tokens 数,包含思考用的 tokens
usage.completion_tokens_details.reasoning_tokens 其中思考用的 tokens 数

流式返回

加上 "stream": true 后按 OpenAI 的 SSE 格式返回:每段一行 data: {…},文字在 choices[0].delta.content,思考摘要在 choices[0].delta.reasoning_content,最后一行是 data: [DONE]。

用不了的 Gemini 能力

经过 OpenAI 格式转换后,下面这些用不了,需要的话改用 generateContent 原生接口:

  • 安全设置:safetySettings 在 OpenAI 格式里写不出来,用的是站点的默认设置。
  • generationConfig 里的部分字段:top_k 不会转给 Gemini;候选数(candidateCount)、语音输出(speechConfig)在 OpenAI 格式里写不出来,所以语音合成模型(名字里带 tts)只能用原生接口,见语音合成。
  • Gemini 专有的工具:OpenAI 格式的 tools 只能写函数,代码执行等 Gemini 内置工具写不出来。
  • 以地址引用文件:OpenAI 格式里的图片、文件都由网关下载后以 inlineData 发送,没有原生接口里 fileData 那样只传地址的写法。

错误

错误按 OpenAI 的格式返回({"error": {"message": …, "type": …, "code": …}}),message 末尾带 request id,说明见错误格式,各状态码的处理办法见问题排查。

计费

与用原生接口调用同一个模型的价格相同,以上游返回的用量计费,思考用的 tokens 按输出计。规则见价格与倍率,各分组的价格见价格表。

更新于