Gemini 对话接入
Google Gemini 模型支持 OpenAI 兼容格式 与 Gemini 原生格式 两种调用方式。
方式一:OpenAI 兼容格式(推荐)
端点
POST $URL/v1/chat/completions支持模型
| 模型 | 定位 |
|---|---|
gemini-3.5-flash | 最新高速版 |
gemini-3.1-pro | 3.1 旗舰 |
gemini-3.1-flash-lite | 3.1 轻量版 |
gemini-3-pro-preview | 3.0 Pro 预览版 |
gemini-3-flash-preview | 3.0 轻量预览版 |
gemini-2.5-pro / gemini-2.5-flash | 2.5 稳定版 |
gemini-2.5-pro-preview-tts | 支持语音输出 |
更多版本(gemini-pro-latest / gemini-flash-latest 等别名)见控制台「模型广场」。
请求示例
bash
curl $URL/v1/chat/completions \
-H "Authorization: Bearer $YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-2.5-pro",
"messages": [
{"role": "user", "content": "用相对论解释 GPS 卫星为什么需要时钟校准"}
]
}'python
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY", base_url="$URL/v1")
resp = client.chat.completions.create(
model="gemini-2.5-pro",
messages=[{"role": "user", "content": "用相对论解释 GPS 卫星为什么需要时钟校准"}],
)
print(resp.choices[0].message.content)ts
import OpenAI from 'openai'
const client = new OpenAI({
apiKey: process.env.YOUR_API_KEY,
baseURL: '$URL/v1',
})
const resp = await client.chat.completions.create({
model: 'gemini-2.5-pro',
messages: [{ role: 'user', content: '用相对论解释 GPS 卫星为什么需要时钟校准' }],
})
console.log(resp.choices[0].message.content)方式二:Gemini 原生格式
如需使用 Gemini SDK 或原生端点,可调用:
POST $URL/v1/models/{model}:generateContent请求体(Gemini 原生)
json
{
"contents": [
{
"role": "user",
"parts": [{ "text": "Explain the theory of relativity in simple terms." }]
}
],
"systemInstruction": {
"parts": [{ "text": "You are a helpful physics tutor." }]
},
"generationConfig": {
"temperature": 0.7,
"maxOutputTokens": 1024
}
}cURL 示例
bash
curl $URL/v1/models/gemini-2.5-pro:generateContent \
-H "Authorization: Bearer $YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [
{
"role": "user",
"parts": [{"text": "Explain the theory of relativity in simple terms."}]
}
]
}'选择建议
| 场景 | 推荐方式 |
|---|---|
| 已有 OpenAI SDK 代码 | 方式一,改 model 即可 |
| 需要 Gemini 特有功能( grounding、function calling 原生语法) | 方式二 |
| 多模型统一管理 | 方式一 |
