用 Google GenAI SDK 调用 Gemini(Interactions API)
按照 Google 官方 Getting started 文档,安装 google-genai 或 @google/genai,设置 GEMINI_API_KEY,通过 Interactions API 调用 gemini-3.8-flash,并用服务端状态做多轮对话。
验证方式
- 测试环境
- 未知
- 测试日期
- 未知
- 最后更新
- 2026-11-11
本教程依据 Google 官方 Gemini API Getting started 页面编写。Google 的入门流程现在使用 Interactions API,可以通过 Python、JavaScript 版 GenAI SDK 或 REST 调用。代码照搬自该页面,我们没有实际运行过。
1. 获取 API Key
Google AI Studio 会为新用户自动创建项目和 API Key,可在 API keys 页面 复制,或点击 Create API key 新建。然后设置环境变量:
export GEMINI_API_KEY="YOUR_API_KEY"
免费层足够测试。付费层的速率限制更高,需要开通 Cloud Billing;官方页面说明要预付至少 5 美元(或等值货币)的额度。
2. Python
pip install -U google-genai
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Explain how AI works in a few words"
)
print(interaction.output_text)
3. JavaScript
npm install @google/genai
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Explain how AI works in a few words",
});
console.log(interaction.output_text);
这里的 genai.Client() 和 new GoogleGenAI({}) 都没有传 Key,SDK 会从环境变量 GEMINI_API_KEY 读取。
4. 多轮对话
Interactions API 可以把对话状态保存在服务端:把上一次交互的 id 作为 previous_interaction_id 传入即可。Google 推荐大多数聊天和智能体场景使用这种有状态方式:
from google import genai
client = genai.Client()
# Server-side state (recommended)
interaction1 = client.interactions.create(
model="gemini-3.8-flash",
input="I have 2 dogs in my house.",
)
print("Response 1:", interaction1.output_text)
interaction2 = client.interactions.create(
model="gemini-3.8-flash",
input="How many paws are in my house?",
previous_interaction_id=interaction1.id,
)
print("Response 2:", interaction2.output_text)
另一种是无状态方式:每次请求都由你自己带上之前所有轮次,包括模型中间的思考和工具步骤。
5. 返回内容
通过 REST 调用时,接口返回完整的 Interaction 资源:包括 id、status、usage 统计和 steps 列表(例如一个 thought 步骤和一个 model_output 步骤)。SDK 另外提供 output_text、output_image 等快捷属性。
6. 本站收录的 Gemini 模型
- Gemini 3.8 Flash:
gemini-3.8-flash,即快速入门所用模型 - Gemini 4 Argon:
gemini-4-argon
换模型只需改 model 字符串,费用对比见 价格 页面。
来源
- Getting started - Gemini API (Google AI Studio docs)aistudio
.google .com(在新标签页打开) · 核对于 2026-11-11