{% two-column-layout %}
{% left-column %}
# Google Gemini 中文使用指南  {% class="h0" %}

使用 Gemini API，从简单提示开始，构建可投入生产的应用和智能体。借助 Gemini 处理复杂编程与多模态推理，使用 Decisions API 进行经过校准的决策评分，或将多步骤任务交给托管智能体。通过 Live API 实时传输语音与视频，也可以使用 Nano Banana 生成图像、Gemini Omni 生成视频，以及 Lyria 生成音乐。

{% button href="/docs/get-started" size="large" variant="ais" %}快速入门{% /button %} {% button href="https://aistudio.google.com/apikey" size="large" variant="primary" %}创建 API 密钥{% /button %}
{% /left-column %}

{% right-column %}
{% tabs %}
{% tab label="智能体" %}
```bash
# Set up your coding agent with these tools

# Search live docs with the MCP server
npx add-mcp "https://gemini-api-docs-mcp.dev"

# Add skills for current SDK syntax and rules
npx skills add google-gemini/gemini-skills --skill gemini-api-dev

# In Antigravity, install both with one plugin
agy plugin install https://github.com/google-gemini/gemini-skills

# Let your agent call the API from the terminal
curl -fsSL https://raw.githubusercontent.com/google-gemini/gemini-api-cli/main/scripts/install.sh | bash
```
{% /tab %}

{% tab filename="main.py" label="Python" %}
```python
from google import genai

client = genai.Client()

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

print(interaction.output_text)
```
{% /tab %}

{% tab filename="index.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

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

console.log(interaction.output_text);
```
{% /tab %}

{% tab label="REST" %}
```bash
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-4-carbon",
    "input": "Explain how AI works in a few words"
  }'
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-4-carbon"))
        .input(InteractionsInput.of("Explain how AI works in a few words"))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));
```
{% /tab %}

{% tab label="Go" %}
```go
package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-4-carbon"),
            Input: interactions.NewInteractionsInput("Explain how AI works in a few words"),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}
```
{% /tab %}

{% tab label="CLI" %}
```bash
gemini-api generate "Explain how AI works in a few words" -m gemini-4-carbon
```
{% /tab %}
{% /tabs %}
{% /right-column %}
{% /two-column-layout %}

## 认识 Gemini 模型  {% class="hide-from-toc" #meet-the-models %}

{% card-grid columns="3" %}
{% card
   description="我们能力最强的推理模型，拥有输入输出共享的 100 万 token 上下文窗口，并支持最长 100 万 token 的长输出。"
   title="Gemini 4 Carbon"
   variant="model-card" %}
{% section class="model-specs" %}
* *模型代码* **gemini-4-carbon**
* *上下文* **100 万 token**
* *最大输出* **64K / 100 万 token**
* *模态* **文本、图像、音频、视频、PDF**
{% /section %}

{% section class="card-actions" %}
{% button href="https://aistudio.google.com/prompts/new_chat?model=gemini-4-carbon" tooltip="在 AI Studio 中尝试 Gemini 4 Carbon" variant="primary" %}在 AI Studio 中体验{% /button %} {% button href="/docs/models/gemini-4-carbon" icon="arrow_forward" tooltip="查看 Gemini 4 Carbon 模型详情" variant="icon-primary" /%}
{% /section %}
{% /card %}

{% card
   description="面向日常编程与智能体工作流，以出色的速度和效率提供前沿智能，拥有输入输出共享的 100 万 token 上下文窗口，并支持最长 100 万 token 的长输出。"
   title="Gemini 4 Hydrogen"
   variant="model-card" %}
{% section class="model-specs" %}
* *模型代码* **gemini-4-hydrogen**
* *上下文* **100 万 token**
* *最大输出* **64K / 100 万 token**
* *模态* **文本、图像、音频、视频、PDF**
{% /section %}

{% section class="card-actions" %}
{% button href="https://aistudio.google.com/prompts/new_chat?model=gemini-4-hydrogen" tooltip="在 AI Studio 中尝试 Gemini 4 Hydrogen" variant="primary" %}在 AI Studio 中体验{% /button %} {% button href="/docs/models/gemini-4-hydrogen" icon="arrow_forward" tooltip="查看 Gemini 4 Hydrogen 模型详情" variant="icon-primary" /%}
{% /section %}
{% /card %}

{% card
   description="专用于快速决策的多模态模型，支持经过校准的是非判断、选项判断和量规评分，不产生输出 token。"
   title="Gemini Decision 1"
   variant="model-card" %}
{% section class="model-specs" %}
* *模型代码* **gemini-decision-1**
* *上下文* **26.2 万 token**
* *最大输出* **0 token（最多 1,000 个问题）**
* *模态* **文本、图像、音频、视频、PDF**
{% /section %}

{% section class="card-actions" %}
{% button href="https://aistudio.google.com/apps/bundled/gemini-decisions-api-playground" tooltip="在 AI Studio 中尝试 Gemini Decision 1" variant="primary" %}在 AI Studio 中体验{% /button %} {% button href="/docs/models/gemini-decision-1" icon="arrow_forward" tooltip="查看 Gemini Decision 1 模型详情" variant="icon-primary" /%}
{% /section %}
{% /card %}

{% card
   description="旗舰创意文本转语音模型，提供录音室级声音保真度、富有表现力的演绎，以及声音设计和声音复刻能力。"
   title="Gemini 3.8 Flash TTS"
   variant="model-card" %}
{% section class="model-specs" %}
* *模型代码* **gemini-3.8-flash-tts**
* *上下文* **8K token**
* *最大输出* **16K token**
* *模态* **文本 → 音频**
{% /section %}

{% section class="card-actions" %}
{% button href="https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash-tts" tooltip="在 AI Studio 中尝试 Gemini 3.8 Flash TTS" variant="primary" %}在 AI Studio 中体验{% /button %} {% button href="/docs/models/gemini-3.8-flash-tts" icon="arrow_forward" tooltip="查看 Gemini 3.8 Flash TTS 模型详情" variant="icon-primary" /%}
{% /section %}
{% /card %}

{% card
   description="高效的图像生成与编辑模型，提升了视觉质量、文字排版和多轮交互的一致性。"
   title="Nano Banana 2.1"
   variant="model-card" %}
{% section class="model-specs" %}
* *模型代码* **gemini-nano-banana-2.1**
* *上下文* **12.8 万 token**
* *最大输出* **32K token**
* *模态* **文本、图像、视频、PDF → 图像、文本**
{% /section %}

{% section class="card-actions" %}
{% button href="https://aistudio.google.com/prompts/new_chat?model=gemini-nano-banana-2.1" tooltip="在 AI Studio 中尝试 Nano Banana 2.1" variant="primary" %}在 AI Studio 中体验{% /button %} {% button href="/docs/models/gemini-nano-banana-2.1" icon="arrow_forward" tooltip="查看 Nano Banana 2.1 模型详情" variant="icon-primary" /%}
{% /section %}
{% /card %}

{% card href="/docs/models" title="查看全部模型" variant="view-more" /%}
{% /card-grid %}

## 探索核心能力  {% class="hide-from-toc" #explore-capabilities %}

{% tabs variant="showcase" %}
{% tab label="图像" %}
{% two-column-layout class="capability-panel" %}
{% left-column %}
{% tabs %}
{% tab filename="image_gen.py" label="Python" %}
```python
import base64
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="Generate an image of a nano banana dish in a fancy restaurant",
    response_format={"type": "image", "aspect_ratio": "16:9", "image_size": "2K"},
)

with open("nano_banana.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))
```
{% /tab %}

{% tab filename="image_gen.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

const ai = new GoogleGenAI({});

const interaction = await ai.interactions.create({
  model: "gemini-nano-banana-2.1",
  input: "Generate an image of a nano banana dish in a fancy restaurant",
  response_format: { type: "image", aspect_ratio: "16:9", image_size: "2K" },
});

fs.writeFileSync("nano_banana.png", Buffer.from(interaction.output_image.data, "base64"));
```
{% /tab %}
{% /tabs %}
{% /left-column %}

{% right-column class="capability-details" %}
### 图像生成

通过文本、图像或交错多模态提示，使用 Nano Banana 模型原生生成和编辑充分理解上下文的图像。

{% section class="capability-highlights" %}
* {% icon name="check" /%} **最高 4K 分辨率** ，支持灵活的宽高比
* {% icon name="check" /%} **多轮编辑** 与角色一致性
* {% icon name="check" /%} **基于搜索的事实依据** ，提升视觉准确性与文字渲染效果
{% /section %}

{% button href="/docs/image-generation" tooltip="阅读图像生成文档" variant="ais" %}阅读文档{% /button %}
{% /right-column %}
{% /two-column-layout %}
{% /tab %}

{% tab label="视频" %}
{% two-column-layout class="capability-panel" %}
{% left-column %}
{% tabs %}
{% tab filename="video_gen.py" label="Python" %}
```python
import base64
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-omni-1.2-flash",
    input="A cinematic close-up of two people talking by a window in the rain",
)

with open("dialogue_example.mp4", "wb") as f:
    f.write(base64.b64decode(interaction.output_video.data))
```
{% /tab %}

{% tab filename="video_gen.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

const ai = new GoogleGenAI({});

const interaction = await ai.interactions.create({
  model: "gemini-omni-1.2-flash",
  input: "A cinematic close-up of two people talking by a window in the rain",
});

if (interaction.output_video?.data) {
  fs.writeFileSync(
    "dialogue_example.mp4",
    Buffer.from(interaction.output_video.data, "base64")
  );
}
```
{% /tab %}
{% /tabs %}
{% /left-column %}

{% right-column class="capability-details" %}
### 视频生成

根据文本或图像提示创建高清视频，原生同步生成对白、音效和环境音频。

{% section class="capability-highlights" %}
* {% icon name="check" /%} **原生音频与对白** ，与画面动作同步
* {% icon name="check" /%} **帧插值** ，支持首尾帧控制
* {% icon name="check" /%} **参考图像** ，保持角色与风格一致
{% /section %}

{% button href="/docs/video" tooltip="阅读视频生成文档" variant="ais" %}阅读文档{% /button %}
{% /right-column %}
{% /two-column-layout %}
{% /tab %}

{% tab label="语音" %}
{% two-column-layout class="capability-panel" %}
{% left-column %}
{% tabs %}
{% tab filename="live_agent.py" label="Python" %}
```python
import asyncio
from google import genai
from google.genai import types

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

async def main():
    config = types.LiveConnectConfig(response_modalities=["AUDIO"])
    async with client.aio.live.connect(
        model="gemini-3.8-live-preview", config=config
    ) as session:
        await session.send_client_content(
            turns={"parts": [{"text": "Hello! Tell me a quick fun fact."}]}
        )
        async for response in session.receive():
            if response.data is not None:
                # Stream raw PCM audio bytes to speaker
                pass

asyncio.run(main())
```
{% /tab %}

{% tab filename="live_agent.js" label="JavaScript" %}
```javascript
import { GoogleGenAI, Modality } from "@google/genai";

const ai = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

const session = await ai.live.connect({
  model: "gemini-3.8-live-preview",
  config: { responseModalities: [Modality.AUDIO] },
  callbacks: {
    onmessage: (message) => {
      if (message.serverContent?.modelTurn) {
        // Handle low-latency streaming audio chunks
      }
    },
  },
});

session.sendClientContent({
  turns: [{ parts: [{ text: "Hello! Tell me a quick fun fact." }] }],
});
```
{% /tab %}
{% /tabs %}
{% /left-column %}

{% right-column class="capability-details" %}
### 使用 Live API 构建语音智能体

构建实时双向语音与视频智能体，支持亚秒级延迟、自然打断和实时工具调用。

{% section class="capability-highlights" %}
* {% icon name="check" /%} **实时 WebSocket 流式传输** 音频与视频
* {% icon name="check" /%} **自然的语音活动检测** 和打断处理
* {% icon name="check" /%} **富有表现力的多语言声音** ，支持情感对话
{% /section %}

{% button href="/docs/live-api" tooltip="阅读 Live API 文档" variant="ais" %}阅读文档{% /button %}
{% /right-column %}
{% /two-column-layout %}
{% /tab %}

{% tab label="决策" %}
{% two-column-layout class="capability-panel" %}
{% left-column %}
{% tabs %}
{% tab filename="decisions.py" label="Python" %}
```python
from google import genai

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

result = client.decisions.create(
    model="gemini-decision-1",
    input="The blue mug I ordered on Monday arrived cracked on Wednesday.",
    questions={
        "is_damaged": {
            "type": "noul",
            "instructions": "Did the item arrive damaged?",
        },
    },
)

answer = result.answers["is_damaged"]
print(f"P(damaged)={answer.noul:.2f} confidence={answer.confidence:.2f}")
```
{% /tab %}

{% tab filename="decisions.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiVersion: "v1beta" });

const result = await ai.decisions.create({
  model: "gemini-decision-1",
  input: "The blue mug I ordered on Monday arrived cracked on Wednesday.",
  questions: {
    is_damaged: {
      type: "noul",
      instructions: "Did the item arrive damaged?",
    },
  },
});

const answer = result.answers?.is_damaged;
if (answer?.type === "noul") {
  console.log(`P(damaged)=${answer.noul} confidence=${answer.confidence}`);
}
```
{% /tab %}
{% /tabs %}
{% /left-column %}

{% right-column class="capability-details" %}
### 经过校准的决策

针对文本、图像、视频、音频和 PDF 中的是非、单选与量规评分问题，使用 [Gemini Decision 1](/docs/models/gemini-decision-1)
进行评估，且不产生输出 token。

{% section class="capability-highlights" %}
* {% icon name="check" /%} **经过校准的概率** ，涵盖是非、选择和有序评分量规
* {% icon name="check" /%} **最多 1,000 个独立问题** ，通过一次预填充处理共享输入
* {% icon name="check" /%} **零输出 token** ，适用于文本、图像、音频、视频和 PDF 输入
{% /section %}

{% button href="/docs/decisions-api" tooltip="阅读 Decisions API 文档" variant="ais" %}阅读文档{% /button %}
{% /right-column %}
{% /two-column-layout %}
{% /tab %}

{% tab label="思考" %}
{% two-column-layout class="capability-panel" %}
{% left-column %}
{% tabs %}
{% tab filename="thinking.py" label="Python" %}
```python
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Find the flaw in this distributed lock protocol and fix it.",
    generation_config={
        "thinking_level": "high",
        "thinking_summaries": "auto",
    },
)

for step in interaction.steps:
    if step.type == "thought":
        for summary in step.summary or []:
            print("Thought summary:", summary.text)
print("Answer:", interaction.output_text)
```
{% /tab %}

{% tab filename="thinking.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const interaction = await ai.interactions.create({
  model: "gemini-4-hydrogen",
  input: "Find the flaw in this distributed lock protocol and fix it.",
  generation_config: {
    thinking_level: "high",
    thinking_summaries: "auto",
  },
});

for (const step of interaction.steps) {
  if (step.type === "thought") {
    for (const summary of step.summary ?? []) {
      console.log("Thought summary:", summary.text);
    }
  }
}
console.log("Answer:", interaction.output_text);
```
{% /tab %}
{% /tabs %}
{% /left-column %}

{% right-column class="capability-details" %}
### 自适应思考

控制 Gemini 在回答前的推理深度——从低延迟的 `low`
思考，到深入的多步骤 `xhigh` 推理。

{% section class="capability-highlights" %}
* {% icon name="check" /%} **可配置的思考级别** （最小、低、中、高、xhigh）
* {% icon name="check" /%} **透明的思考摘要** ，实时流式输出
* {% icon name="check" /%} **交错推理** ，贯穿工具调用与代码执行
{% /section %}

{% button href="/docs/thinking" tooltip="阅读适应性思维文档" variant="ais" %}阅读文档{% /button %}
{% /right-column %}
{% /two-column-layout %}
{% /tab %}

{% tab label="工具" %}
{% two-column-layout class="capability-panel" %}
{% left-column %}
{% tabs %}
{% tab filename="tools.py" label="Python" %}
```python
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Who won the latest F1 Grand Prix and what were the lap times?",
    tools=[{"type": "google_search"}, {"type": "code_execution"}],
)

print(interaction.output_text)
```
{% /tab %}

{% tab filename="tools.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const interaction = await ai.interactions.create({
  model: "gemini-4-hydrogen",
  input: "Who won the latest F1 Grand Prix and what were the lap times?",
  tools: [{ type: "google_search" }, { type: "code_execution" }],
});

console.log(interaction.output_text);
```
{% /tab %}
{% /tabs %}
{% /left-column %}

{% right-column class="capability-details" %}
### 内置工具与函数调用

通过托管工具和自定义函数声明，将 Gemini 连接到实时信息、计算能力及你自己的后端 API。

{% section class="capability-highlights" %}
* {% icon name="check" /%} **Google 搜索与 URL 上下文** ，提供实时网络事实依据
* {% icon name="check" /%} **代码执行** ，在安全的 Python 沙盒中运行
* {% icon name="check" /%} **自定义函数调用** ，支持并行编排多个工具
{% /section %}

{% button href="/docs/tools" tooltip="阅读工具和函数调用文档" variant="ais" %}阅读文档{% /button %}
{% /right-column %}
{% /two-column-layout %}
{% /tab %}

{% tab label="结构化输出" %}
{% two-column-layout class="capability-panel" %}
{% left-column %}
{% tabs %}
{% tab filename="structured.py" label="Python" %}
```python
from google import genai
from pydantic import BaseModel, Field

class FeedbackAnalysis(BaseModel):
    sentiment: str = Field(description="positive, neutral, or negative")
    summary: str = Field(description="One-sentence summary of the feedback.")
    action_items: list[str]

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="The new dashboard is fast, but exporting CSVs fails on mobile.",
    response_format={
        "type": "text",
        "mime_type": "application/json",
        "schema": FeedbackAnalysis.model_json_schema(),
    },
)

print(interaction.output_text)
```
{% /tab %}

{% tab filename="structured.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";
import { z } from "zod";

const FeedbackSchema = z.object({
  sentiment: z.enum(["positive", "neutral", "negative"]),
  summary: z.string(),
  actionItems: z.array(z.string()),
});

const ai = new GoogleGenAI({});

const interaction = await ai.interactions.create({
  model: "gemini-4-hydrogen",
  input: "The new dashboard is fast, but exporting CSVs fails on mobile.",
  response_format: {
    type: "text",
    mime_type: "application/json",
    schema: z.toJSONSchema(FeedbackSchema),
  },
});

console.log(JSON.parse(interaction.output_text));
```
{% /tab %}
{% /tabs %}
{% /left-column %}

{% right-column class="capability-details" %}
### 结构化输出

约束 Gemini 的回答，使其严格遵循 JSON Schema、Pydantic 模型或 Zod 类型，从而实现可靠的下游自动化。

{% section class="capability-highlights" %}
* {% icon name="check" /%} **保证符合 JSON Schema** ，适用于每次响应
* {% icon name="check" /%} **原生 Pydantic 与 Zod** 模式集成
* {% icon name="check" /%} **兼容工具** ，例如 Google 搜索与代码执行
{% /section %}

{% button href="/docs/structured-output" tooltip="阅读结构化输出文档" variant="ais" %}阅读文档{% /button %}
{% /right-column %}
{% /two-column-layout %}
{% /tab %}

{% tab label="长上下文" %}
{% two-column-layout class="capability-panel" %}
{% left-column %}
{% tabs %}
{% tab filename="long_context.py" label="Python" %}
```python
from google import genai

client = genai.Client()

uploaded_file = client.files.upload(file="full_codebase_archive.txt")

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "file", "file_uri": uploaded_file.uri},
        {
            "type": "text",
            "text": "Trace how authentication tokens are refreshed across all services.",
        },
    ],
)

print(interaction.output_text)
```
{% /tab %}

{% tab filename="long_context.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const uploadedFile = await ai.files.upload({
  file: "full_codebase_archive.txt",
});

const interaction = await ai.interactions.create({
  model: "gemini-4-hydrogen",
  input: [
    { type: "file", fileUri: uploadedFile.uri },
    {
      type: "text",
      text: "Trace how authentication tokens are refreshed across all services.",
    },
  ],
});

console.log(interaction.output_text);
```
{% /tab %}
{% /tabs %}
{% /left-column %}

{% right-column class="capability-details" %}
### 长上下文

在一次提示中输入最多 100 万 token 的代码、视频、音频或文档，进行深入的跨文件推理和上下文学习。

{% section class="capability-highlights" %}
* {% icon name="check" /%} **超过 100 万 token 的上下文窗口** （约 50,000 行代码或 8 本小说）
* {% icon name="check" /%} **接近完美的召回能力** ，适用于长多模态输入
* {% icon name="check" /%} **上下文缓存** ，降低重复提示的成本与延迟
{% /section %}

{% button href="/docs/long-context" tooltip="阅读长上下文文档" variant="ais" %}阅读文档{% /button %}
{% /right-column %}
{% /two-column-layout %}
{% /tab %}

{% tab label="函数调用" %}
{% two-column-layout class="capability-panel" %}
{% left-column %}
{% tabs %}
{% tab filename="function_calling.py" label="Python" %}
```python
from google import genai

schedule_meeting = {
    "type": "function",
    "name": "schedule_meeting",
    "description": "Schedules a meeting with attendees at a given date and time.",
    "parameters": {
        "type": "object",
        "properties": {
            "attendees": {"type": "array", "items": {"type": "string"}},
            "date": {"type": "string"},
            "time": {"type": "string"},
            "topic": {"type": "string"},
        },
        "required": ["attendees", "date", "time", "topic"],
    },
}

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Schedule a meeting with Bob and Alice tomorrow at 10:00 AM about Q3 planning.",
    tools=[schedule_meeting],
)

for step in interaction.steps:
    if step.type == "function_call":
        print(step.name, step.arguments)
```
{% /tab %}

{% tab filename="function_calling.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const scheduleMeeting = {
  type: "function",
  name: "schedule_meeting",
  description: "Schedules a meeting with attendees at a given date and time.",
  parameters: {
    type: "object",
    properties: {
      attendees: { type: "array", items: { type: "string" } },
      date: { type: "string" },
      time: { type: "string" },
      topic: { type: "string" },
    },
    required: ["attendees", "date", "time", "topic"],
  },
};

const interaction = await ai.interactions.create({
  model: "gemini-4-hydrogen",
  input: "Schedule a meeting with Bob and Alice tomorrow at 10:00 AM about Q3 planning.",
  tools: [scheduleMeeting],
});

for (const step of interaction.steps) {
  if (step.type === "function_call") {
    console.log(step.name, step.arguments);
  }
}
```
{% /tab %}
{% /tabs %}
{% /left-column %}

{% right-column class="capability-details" %}
### 函数调用

通过结构化函数声明与自动参数提取，将 Gemini 连接到你自己的 API、数据库和后端服务。

{% section class="capability-highlights" %}
* {% icon name="check" /%} **并行与组合式** 多步骤函数调用
* {% icon name="check" /%} **严格遵循模式约束** ，适用于工具参数
* {% icon name="check" /%} **无缝集成** 内置工具与思考能力
{% /section %}

{% button href="/docs/function-calling" tooltip="阅读函数调用文档" variant="ais" %}阅读文档{% /button %}
{% /right-column %}
{% /two-column-layout %}
{% /tab %}

{% tab label="文档理解" %}
{% two-column-layout class="capability-panel" %}
{% left-column %}
{% tabs %}
{% tab filename="document_understanding.py" label="Python" %}
```python
import base64
from google import genai

client = genai.Client()

with open("financial_report.pdf", "rb") as f:
    pdf_base64 = base64.b64encode(f.read()).decode("utf-8")

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {
            "type": "document",
            "data": pdf_base64,
            "mime_type": "application/pdf",
        },
        {
            "type": "text",
            "text": "Summarize the key revenue drivers and extract the Q4 table.",
        },
    ],
)

print(interaction.output_text)
```
{% /tab %}

{% tab filename="document_understanding.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

const ai = new GoogleGenAI({});

const pdfData = fs.readFileSync("financial_report.pdf", {
  encoding: "base64",
});

const interaction = await ai.interactions.create({
  model: "gemini-4-hydrogen",
  input: [
    {
      type: "document",
      data: pdfData,
      mime_type: "application/pdf",
    },
    {
      type: "text",
      text: "Summarize the key revenue drivers and extract the Q4 table.",
    },
  ],
});

console.log(interaction.output_text);
```
{% /tab %}
{% /tabs %}
{% /left-column %}

{% right-column class="capability-details" %}
### 文档理解

处理最多 1,000 页的 PDF，以原生视觉与文本理解能力读取表格、图表、示意图和页面布局。

{% section class="capability-highlights" %}
* {% icon name="check" /%} **基于原生视觉的 PDF 解析** ，超越简单的 OCR
* {% icon name="check" /%} **最多 1,000 页** ，在单次请求中处理一份文档
* {% icon name="check" /%} **结构化提取** 复杂表格、表单与图形中的信息
{% /section %}

{% button href="/docs/document-processing" tooltip="阅读文档了解文档" variant="ais" %}阅读文档{% /button %}
{% /right-column %}
{% /two-column-layout %}
{% /tab %}
{% /tabs %}

## 创建智能体  {% class="hide-from-toc" #create-agents %}

{% two-column-layout %}
{% left-column %}
托管智能体为 Gemini 提供工作空间，使其能够自主规划并完成任务。在一次请求中，Gemini 可以编写和运行代码、搜索网络，并在托管的沙盒环境中创建文件。你可以从预构建的 Antigravity 智能体开始，也可以使用自己的指令和工具进行定制。

{% button href="/docs/managed-agents-quickstart" variant="ais" %}智能体快速入门{% /button %} {% button href="https://aistudio.google.com/prompts/new_chat?model=antigravity-preview-09-2026" tooltip="在 AI Studio 中尝试托管智能体" variant="primary" %}在 AI Studio 中体验{% /button %}
{% /left-column %}

{% right-column %}
{% tabs %}
{% tab filename="agent.py" label="Python" %}
```python
from google import genai

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

interaction = client.interactions.create(
    agent="antigravity-preview-09-2026",
    input=(
        "Research the top 5 sustainable fashion brands, "
        "compare their materials and pricing tiers, and "
        "build an interactive dashboard in analysis.html."
    ),
    environment="remote"
)

print(interaction.output_text)
```
{% /tab %}

{% tab filename="agent.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

const interaction = await ai.interactions.create({
  agent: "antigravity-preview-09-2026",
  input:
    "Research the top 5 sustainable fashion brands, " +
    "compare their materials and pricing tiers, and " +
    "build an interactive dashboard in analysis.html.",
  environment: "remote",
});

console.log(interaction.output_text);
```
{% /tab %}

{% tab filename="agent.sh" label="REST" %}
```bash
curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "agent": "antigravity-preview-09-2026",
    "input": "Research the top 5 sustainable fashion brands, compare their materials and pricing tiers, and build an interactive dashboard in analysis.html.",
    "environment": "remote"
  }'
```
{% /tab %}

{% tab filename="AgentQuickstart.java" label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

CreateAgentInteraction params =
    CreateAgentInteraction.builder()
        .agent(AgentOption.of("antigravity-preview-09-2026"))
        .input(
            InteractionsInput.of(
                "Research the top 5 sustainable fashion brands, "
                    + "compare their materials and pricing tiers, and "
                    + "build an interactive dashboard in analysis.html."))
        .environment(CreateAgentInteractionEnvironment.of("remote"))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params))
        .interaction()
        .get();

System.out.println(interaction.outputText().orElse(""));
```
{% /tab %}

{% tab label="Go" %}
```go
package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, &genai.ClientConfig{HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta"}})
    if err != nil {
        log.Fatal(err)
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
            Agent: interactions.AgentOption("antigravity-preview-09-2026"),
            Input: interactions.NewInteractionsInput(
                "Research the top 5 sustainable fashion brands, " +
                    "compare their materials and pricing tiers, and " +
                    "build an interactive dashboard in analysis.html.",
            ),
            Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment("remote")),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}
```
{% /tab %}

{% tab filename="agent.sh" label="CLI" %}
```bash
gemini-api agent run "Research the top 5 sustainable fashion brands, compare their materials and pricing tiers, and build an interactive dashboard in analysis.html." \
  --agent antigravity-preview-09-2026 \
  --body '{"environment":"remote"}'
```
{% /tab %}
{% /tabs %}
{% /right-column %}
{% /two-column-layout %}

## Interactions API  {% class="hide-from-toc" #interactions-api %}

该 **Interactions API** 自 2026 年 6 月起成为默认接口，也是今后使用 Gemini 模型与智能体进行开发的推荐方式。新项目应使用 Interactions API。虽然仍然受到支持， `generateContent` API 现已被视为旧版接口。

{% card-grid columns="3" %}
{% card
   description="了解 Interactions API 如何管理对话状态、消息和输出格式。"
   href="/docs/interactions-overview"
   icon="hub"
   title="Interactions API 概览"
   variant="stacked-icon" /%}

{% card
   description="按照步骤，将代码从 generateContent 迁移到 Interactions API。"
   href="/docs/migrate-to-interactions"
   icon="swap_horiz"
   title="迁移指南"
   variant="stacked-icon" /%}

{% card
   description="以流式方式接收实时 token、增量思考和工具调用事件。"
   href="/docs/streaming"
   icon="sensors"
   title="流式输出"
   variant="stacked-icon" /%}
{% /card-grid %}
