Gemini 中文指南
获取 API 密钥 ↗

快速入门

↓ 下载 Markdown

本指南将帮助你通过以下接口开始使用 Gemini API: Interactions API。你将在一分钟内完成首次 API 调用,并探索文本生成、多模态理解、图像生成、结构化输出、工具、函数调用、智能体和后台执行。

你可以使用以下语言的 SDK 调用 Interactions API: Python 和 JavaScript SDK,也可以直接使用 REST 接口。

1. 获取 API 密钥 #

使用 Gemini API 需要 API 密钥,用于验证请求、实施安全限制,并将用量关联到你的账号。

  • Google AI Studio 自动为新用户创建项目和 API 密钥。您可以从以下位置复制它 API 密钥页面.
  • 如果您需要新密钥,请单击 创建 API 密钥 在 AI Studio 中,然后按照对话框添加新的关键项目对。
  • 可能需要额外的项目和从 Google Cloud 导入的项目 项目验证 在他们可以使用免费套餐之前。

创建 Gemini API 密钥

将密钥设置为环境变量:

bash
export GEMINI_API_KEY="YOUR_API_KEY"

要提高速率限制,请单击 设置结算 于 API 密钥 页面或查看 结算指南.

2. 安装 SDK 并发起首次调用 #

安装 SDK,通过一次 API 调用生成文本。

安装 SDK:

bash
pip install -U google-genai

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

python
from google import genai

client = genai.Client()

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

虽然 SDK 公开了完整的响应,但它们还提供了便利的属性,例如 interaction.output_text 和 interaction.output_image 直接访问最终输出。了解有关响应结构的更多信息 交互概述 或阅读 文本生成指南 有关系统指令和生成配置的详细信息。

3. 流式接收响应 #

为了获得更流畅的交互,请在生成响应时对其进行流式传输。每个 step.delta 事件提供一段可以立即显示的文本。

python
from google import genai

client = genai.Client()

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

有关处理流事件和增量类型的详细信息,请参阅 流媒体互动指南.

4. 多轮对话 #

Interactions API 支持两种方式的多轮对话:

  • 有状态(推荐):使用以下命令在服务器上继续对话 previous_interaction_id。非常适合您希望服务器管理历史记录和优化缓存的大多数聊天和智能体工作流程。
  • 无状态:通过在每个请求中传递所有先前回合(包括中间模型思想和工具步骤)来管理客户端上的对话历史记录。

通过传递进行链式交互 previous_interaction_id。服务器为您管理完整的对话历史记录。

python
from google import genai

client = genai.Client()

# Server-side state (recommended)
interaction1 = client.interactions.create(
    model="gemini-4-hydrogen",
    input="I have 2 dogs in my house.",
)
print("Response 1:", interaction1.output_text)

interaction2 = client.interactions.create(
    model="gemini-4-hydrogen",
    input="How many paws are in my house?",
    previous_interaction_id=interaction1.id,
)
print("Response 2:", interaction2.output_text)

5. 多模态理解 #

Gemini 模型本身可以理解图像、音频、视频和文档。在单个请求中将媒体与文本一起传递。

python
import base64
from google import genai

client = genai.Client()

# Load a local image
with open("sample.jpg", "rb") as f:
    image_bytes = f.read()
image_b64 = base64.b64encode(image_bytes).decode("utf-8")

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "text", "text": "Compare this local image and this remote audio file."},
        {
            "type": "image",
            "data": image_b64,
            "mime_type": "image/jpeg"
        },
        {
            "type": "audio",
            "uri": "https://storage.googleapis.com/generativeai-downloads/data/sample.mp3",
            "mime_type": "audio/mp3"
        }
    ]
)
print(interaction.output_text)

探索如何在网络中传递图像、视频和音频文件 图像理解指南.

6. 多模态生成 #

Gemini 可以使用以下模型原生生成图像: Nano Banana 图像模型。

python
import base64
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.1-flash-image",
    input="Generate an image of a futuristic city skyline at sunset",
)

with open("generated_image.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))

当模型生成图像时,它会在步骤中返回base64编码的图像数据 steps 数组,以及通过 output_image 便利属性。查看 图像生成指南 了解宽高比、图像编辑和参考。

7. 使用结构化输出 #

配置模型以返回与您定义的架构匹配的 JSON。结构化输出适用于 Pydantic (Python)和 Zod (JavaScript)。

python
from google import genai
from pydantic import BaseModel, Field
from typing import List, Optional

class Recipe(BaseModel):
    recipe_name: str = Field(description="Name of the recipe.")
    ingredients: List[str] = Field(description="List of ingredients.")
    prep_time_minutes: Optional[int] = Field(description="Prep time in minutes.")

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Give me a recipe for banana bread",
    response_format={
        "type": "text",
        "mime_type": "application/json",
        "schema": Recipe.model_json_schema()
    },
)

recipe = Recipe.model_validate_json(interaction.output_text)
print(recipe)

输出文本块包含完全符合请求架构的有效 JSON 字符串。要了解如何定义更复杂的结构和递归模式,请参阅 结构化输出指南.

8. 使用工具 #

使用 Google 搜索将模型的响应基于实时信息。 API 自动搜索、处理结果并返回引文。

python
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Who won the euro 2024?",
    tools=[{"type": "google_search"}]
)

print(interaction.output_text)

# Print citations
for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text" and content_block.annotations:
                print("\nCitations:")
                for annotation in content_block.annotations:
                    if annotation.type == "url_citation":
                        print(f" [{annotation.title}]({annotation.url})")

交互历史记录中详细介绍了搜索步骤,最终输出包括指向网络资源的内嵌引用。

您可以了解如何提取搜索引文 Google 搜索事实依据指南,或了解如何组合多个工具 工具组合指南.

9. 调用自定义函数 #

函数调用允许您将模型连接到代码。您声明函数的名称和参数,模型决定何时调用它并返回结构化参数,然后您在本地执行它并将结果发送回。

python
import json
from google import genai

client = genai.Client()

weather_tool = {
    "type": "function",
    "name": "get_current_temperature",
    "description": "Gets the current temperature for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The city name, e.g. San Francisco",
            },
        },
        "required": ["location"],
    },
}

available_functions = {
    "get_current_temperature": lambda location: {
        "location": location, "temperature": "22", "unit": "celsius"
    },
}

user_input = "What is the temperature in London?"
previous_id = None

while True:
    interaction = client.interactions.create(
        model="gemini-4-hydrogen",
        input=user_input,
        tools=[weather_tool],
        previous_interaction_id=previous_id,
    )

    function_results = []
    for step in interaction.steps:
        if step.type == "function_call":
            result = available_functions[step.name](**step.arguments)
            print(f"Called {step.name}({step.arguments}) → {result}")
            function_results.append({
                "type": "function_result",
                "name": step.name,
                "call_id": step.id,
                "result": [{"type": "text", "text": json.dumps(result)}],
            })

    if not function_results:
        break

    user_input = function_results
    previous_id = interaction.id

print(interaction.output_text)

有关并行函数调用或功能选择模式等高级功能,请参阅 函数调用指南.

10. 运行托管智能体 #

托管智能体在远程沙箱中运行,可以访问代码执行和文件管理等工具。通过一个 agent 而不是 model 并设置 environment="remote".

python
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

interaction = client.interactions.create(
    agent="antigravity-preview-09-2026",
    input="Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents.",
    environment="remote",
)
print(f"Environment: {interaction.environment_id}")
print(interaction.output_text)

您还可以定义并保存 定制智能体 使用您自己的指示、技能和数据源。

11. 在后台运行任务 #

套装 background=True 异步运行长任务。投票结果 interactions.get().

python
import time
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Write a detailed analysis of the impact of artificial intelligence on modern healthcare.",
    background=True,
)
print(f"Started background task: {interaction.id}")
print(f"Status: {interaction.status}")

# Poll for completion
while True:
    result = client.interactions.get(interaction.id)
    print(f"Status: {result.status}")
    if result.status == "completed":
        print(f"\nResult:\n{result.output_text}")
        break
    elif result.status == "failed":
        print(f"Failed: {result.error}")
        break
    time.sleep(5)

阅读有关异步运行模型和智能体的信息 后台执行引导.

后续步骤 #

  • 文本生成:系统指令、生成配置和高级文本模式。
  • 图像生成:宽高比、图像编辑和样式参考。
  • 图像理解:分类、目标检测和视觉问答。
  • 思考:使用思维链推理来完成复杂的任务。
  • 函数调用:并行、组合和约束函数模式。
  • Google 搜索:事实依据、引用和搜索建议。
  • 托管智能体:预构建智能体,具有代码执行和文件管理功能。
  • Deep Research:具有规划和综合的自主多步骤研究。
  • 结构化输出:JSON 模式、枚举和递归类型定义。

搜索标题、API 名称或正文内容