Gemini API 快速入门
本快速入门介绍了如何安装我们的库 ,以及如何使用 Interactions API 发出第一个 Gemini API 请求。
准备工作
如需使用 Gemini API,您需要一个 API 密钥来对请求进行身份验证、强制执行安全限制,以及跟踪您账号的使用情况。
在 AI Studio 上免费创建一个,即可开始使用:
安装 Google GenAI SDK
Python
使用 Python 3.9+,使用以下
pip 命令安装
google-genai 软件包:
pip install -q -U google-genai
JavaScript
使用 Node.js v18+,安装适用于 TypeScript 和 JavaScript 的 Google Gen AI SDK,使用以下 npm command:
npm install @google/genai
提交第一个请求
您可以通过以下两种方式向 Gemini API 发送请求:
- (推荐) Interactions API 是一种新的基元,通过类型化执行步骤原生支持多步工具使用、编排和复杂的推理流程。今后,除了核心主线系列之外的新模型,以及新的智能体功能和工具,都将仅在 Interactions API 上发布。
generateContent提供了一种从模型生成简单无状态响应的方法。虽然我们建议使用 Interactions API,但generateContent受到完全支持。
此示例使用 Interactions API,通过 Gemini 3 Flash 模型向 Gemini API 发送请求。
如果您将 API 密钥设置为
环境变量 GEMINI_API_KEY,则在使用 Gemini API 库时,客户端会自动获取该密钥。
否则,您需要在初始化客户端时将 API 密钥 作为
实参传递。
请注意,Gemini API 文档中的所有代码示例都假定您已设置环境变量 GEMINI_API_KEY。
Python
# This will only work for SDK newer than 2.0.0
from google import genai
# The client gets the API key from the environment variable `GEMINI_API_KEY`.
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Explain how AI works in a few words"
)
# Print the model's text response
for step in interaction.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text":
print(content_block.text)
JavaScript
// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from "@google/genai";
// The client gets the API key from the environment variable `GEMINI_API_KEY`.
const ai = new GoogleGenAI({});
async function main() {
const interaction = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "Explain how AI works in a few words",
});
const modelStep = interaction.steps.find(s => s.type === 'model_output');
if (modelStep) {
for (const contentBlock of modelStep.content) {
if (contentBlock.type === 'text') console.log(contentBlock.text);
}
}
}
main();
REST
# Specifies the API revision to avoid breaking changes when they become default
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-H "Api-Revision: 2026-05-20" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Explain how AI works in a few words"
}'
无状态模式
默认情况下,当您使用 previous_interaction_id 时,Interactions API 会在服务器端管理对话状态。如果您希望自己在客户端管理对话历史记录,可以通过设置 store=false 并在后续请求的 input 字段中传递累积的步骤,选择启用无状态模式。
如需了解详情和完整的无状态多轮对话示例,请参阅文本生成指南。
后续步骤
现在您已发出第一个 API 请求,不妨探索以下指南,了解 Gemini 的实际应用: