使用入门

本指南将引导您开始使用 Interactions API 来使用 Gemini API。您将在不到一分钟的时间内进行首次 API 调用,并探索文本生成、多模态理解、图片生成、结构化输出、工具、函数调用、代理和后台执行。

您可以通过 PythonJavaScript SDK 以及 REST 来使用 Interactions API。

1. 获取 API 密钥

如需使用 Gemini API,您需要拥有一个 API 密钥,以便对请求进行身份验证、强制执行安全限制,以及跟踪您账号的使用情况。

  • Google AI Studio 会自动为新用户创建项目和 API 密钥。 您可以从 API 密钥页面复制该密钥。
  • 如果您需要新密钥,请在 AI Studio 中点击 Create API key,然后按照对话框中的说明添加新的密钥-项目对。

创建 Gemini API 密钥

将密钥设置为环境变量:

export GEMINI_API_KEY="YOUR_API_KEY"

升级到付费层级

升级到付费层级可提高速率限制,但需要设置 Cloud Billing。

  • 在 AI Studio 的 API 密钥项目页面上,点击设置结算信息
  • 按照 Cloud Billing 对话框的提示创建或关联结算账号、添加支付方式,并预付至少 10 美元(或等值的本地货币)的付费积分。
  • Google AI Studio 中,依次点击信息中心 > 使用情况,即可查看 API 使用情况。

如需了解详情,请参阅“结算”页面

2. 安装 SDK 并进行首次调用

安装 SDK 并通过单个 API 调用生成文本。

Python

安装 SDK:

pip install -U google-genai

初始化客户端并发出请求:

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.6-flash",
    input="Explain how AI works in a few words"
)
print(interaction.output_text)

JavaScript

安装 SDK:

npm install @google/genai

初始化客户端并发出请求:

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const interaction = await ai.interactions.create({
  model: "gemini-3.6-flash",
  input: "Explain how AI works in a few words",
});
console.log(interaction.output_text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.6-flash",
    "input": "Explain how AI works in a few words"
  }'

响应

{
  "id": "v1_ChdpQUFvYXI...",
  "status": "completed",
  "usage": {
    "total_tokens": 197,
    "total_input_tokens": 8,
    "total_output_tokens": 12
  },
  "created": "2026-06-09T12:01:25Z",
  "steps": [
    {
      "type": "thought",
      "signature": "EvEFCu4FAQw..."
    },
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "AI learns patterns from data, then uses those patterns to make predictions or decisions on new data."
        }
      ]
    }
  ],
  "object": "interaction",
  "model": "gemini-3.6-flash",
}

使用 REST 时,API 会返回完整的 Interaction 资源,其中包含元数据、使用情况统计信息以及对话的逐步历史记录。

虽然 SDK 会公开完整响应,但它们还提供 interaction.output_textinteraction.output_image 等便捷属性,以便直接访问最终输出。如需详细了解响应结构,请参阅互动概览;如需详细了解系统说明和生成配置,请参阅文本生成指南

3. 以流式传输回答

为了实现更流畅的互动,请在生成响应时对其进行流式传输。每个 step.delta 事件都会传递一个可立即显示的文本块。

Python

from google import genai

client = genai.Client()

stream = client.interactions.create(
    model="gemini-3.6-flash",
    input="Explain how AI works",
    stream=True
)
for event in stream:
    print(event)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const stream = await ai.interactions.create({
  model: "gemini-3.6-flash",
  input: "Explain how AI works",
  stream: true,
});

for await (const event of stream