Google Gemini 中文使用指南
使用 Gemini API,从简单提示开始,构建可投入生产的应用和智能体。借助 Gemini 处理复杂编程与多模态推理,使用 Decisions API 进行经过校准的决策评分,或将多步骤任务交给托管智能体。通过 Live API 实时传输语音与视频,也可以使用 Nano Banana 生成图像、Gemini Omni 生成视频,以及 Lyria 生成音乐。
# 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
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)
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);
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"
}'
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(""));
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)
}
}
gemini-api generate "Explain how AI works in a few words" -m gemini-4-carbon
认识 Gemini 模型 #
Gemini 4 Carbon
我们能力最强的推理模型,拥有输入输出共享的 100 万 token 上下文窗口,并支持最长 100 万 token 的长输出。
- 模型代码 gemini-4-carbon
- 上下文 100 万 token
- 最大输出 64K / 100 万 token
- 模态 文本、图像、音频、视频、PDF
Gemini 4 Hydrogen
面向日常编程与智能体工作流,以出色的速度和效率提供前沿智能,拥有输入输出共享的 100 万 token 上下文窗口,并支持最长 100 万 token 的长输出。
- 模型代码 gemini-4-hydrogen
- 上下文 100 万 token
- 最大输出 64K / 100 万 token
- 模态 文本、图像、音频、视频、PDF
Gemini Decision 1
专用于快速决策的多模态模型,支持经过校准的是非判断、选项判断和量规评分,不产生输出 token。
- 模型代码 gemini-decision-1
- 上下文 26.2 万 token
- 最大输出 0 token(最多 1,000 个问题)
- 模态 文本、图像、音频、视频、PDF
Gemini 3.8 Flash TTS
旗舰创意文本转语音模型,提供录音室级声音保真度、富有表现力的演绎,以及声音设计和声音复刻能力。
- 模型代码 gemini-3.8-flash-tts
- 上下文 8K token
- 最大输出 16K token
- 模态 文本 → 音频
Nano Banana 2.1
高效的图像生成与编辑模型,提升了视觉质量、文字排版和多轮交互的一致性。
- 模型代码 gemini-nano-banana-2.1
- 上下文 12.8 万 token
- 最大输出 32K token
- 模态 文本、图像、视频、PDF → 图像、文本
查看全部模型
探索核心能力 #
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))
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"));
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))
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")
);
}
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())
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." }] }],
});
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}")
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}`);
}
经过校准的决策#
针对文本、图像、视频、音频和 PDF 中的是非、单选与量规评分问题,使用 Gemini Decision 1 进行评估,且不产生输出 token。
- 经过校准的概率 ,涵盖是非、选择和有序评分量规
- 最多 1,000 个独立问题 ,通过一次预填充处理共享输入
- 零输出 token ,适用于文本、图像、音频、视频和 PDF 输入
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)
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);
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)
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);
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)
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));
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)
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);
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)
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);
}
}
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)
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);
创建智能体 #
托管智能体为 Gemini 提供工作空间,使其能够自主规划并完成任务。在一次请求中,Gemini 可以编写和运行代码、搜索网络,并在托管的沙盒环境中创建文件。你可以从预构建的 Antigravity 智能体开始,也可以使用自己的指令和工具进行定制。
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)
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);
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"
}'
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(""));
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)
}
}
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"}'
Interactions API #
该 Interactions API 自 2026 年 6 月起成为默认接口,也是今后使用 Gemini 模型与智能体进行开发的推荐方式。新项目应使用 Interactions API。虽然仍然受到支持, generateContent API 现已被视为旧版接口。