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()
response = client.models.generate_content(
model="gemini-4-carbon",
contents="Explain how AI works in a few words",
)
print(response.text)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const response = await ai.models.generateContent({
model: "gemini-4-carbon",
contents: "Explain how AI works in a few words",
});
console.log(response.text);
}
await main();
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
result, err := client.Models.GenerateContent(
ctx,
"gemini-4-carbon",
genai.Text("Explain how AI works in a few words"),
nil,
)
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Text())
}
package com.example;
import com.google.genai.Client;
import com.google.genai.types.GenerateContentResponse;
public class GenerateTextFromTextInput {
public static void main(String[] args) {
Client client = new Client();
GenerateContentResponse response =
client.models.generateContent(
"gemini-4-carbon",
"Explain how AI works in a few words",
null);
System.out.println(response.text());
}
}
using System.Threading.Tasks;
using Google.GenAI;
using Google.GenAI.Types;
public class GenerateContentSimpleText {
public static async Task main() {
var client = new Client();
var response = await client.Models.GenerateContentAsync(
model: "gemini-4-carbon", contents: "Explain how AI works in a few words"
);
Console.WriteLine(response.Candidates[0].Content.Parts[0].Text);
}
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-carbon:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"parts": [
{
"text": "Explain how AI works in a few words"
}
]
}
]
}'
认识 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 → 图像、文本
查看全部模型
探索核心能力 #
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-nano-banana-2.1",
contents=["Generate an image of a nano banana dish in a fancy restaurant"],
config=types.GenerateContentConfig(
response_modalities=["TEXT", "IMAGE"],
image_config=types.ImageConfig(aspect_ratio="16:9", image_size="2K"),
),
)
for part in response.parts:
if part.inline_data is not None:
image = part.as_image()
image.save("nano_banana.png")
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
const ai = new GoogleGenAI({});
const response = await ai.models.generateContent({
model: "gemini-nano-banana-2.1",
contents: "Generate an image of a nano banana dish in a fancy restaurant",
config: {
responseModalities: ["TEXT", "IMAGE"],
imageConfig: { aspectRatio: "16:9", imageSize: "2K" },
},
});
for (const part of response.candidates[0].content.parts) {
if (part.inlineData) {
fs.writeFileSync(
"nano_banana.png",
Buffer.from(part.inlineData.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
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="Find the flaw in this distributed lock protocol and fix it.",
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_level="high",
include_thoughts=True,
)
),
)
for part in response.candidates[0].content.parts:
if part.thought:
print("Thought summary:", part.text)
else:
print("Answer:", part.text)
import { GoogleGenAI, ThinkingLevel } from "@google/genai";
const ai = new GoogleGenAI({});
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: "Find the flaw in this distributed lock protocol and fix it.",
config: {
thinkingConfig: {
thinkingLevel: ThinkingLevel.HIGH,
includeThoughts: true,
},
},
});
for (const part of response.candidates[0].content.parts) {
if (part.thought) {
console.log("Thought summary:", part.text);
} else {
console.log("Answer:", part.text);
}
}
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="Who won the latest F1 Grand Prix and what were the lap times?",
config=types.GenerateContentConfig(
tools=[
types.Tool(google_search=types.GoogleSearch()),
types.Tool(code_execution=types.ToolCodeExecution()),
]
),
)
print(response.text)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: "Who won the latest F1 Grand Prix and what were the lap times?",
config: {
tools: [{ googleSearch: {} }, { codeExecution: {} }],
},
});
console.log(response.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()
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="The new dashboard is fast, but exporting CSVs fails on mobile.",
config={
"response_mime_type": "application/json",
"response_json_schema": FeedbackAnalysis.model_json_schema(),
},
)
print(response.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 response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: "The new dashboard is fast, but exporting CSVs fails on mobile.",
config: {
responseMimeType: "application/json",
responseJsonSchema: z.toJSONSchema(FeedbackSchema),
},
});
console.log(JSON.parse(response.text));
from google import genai
client = genai.Client()
uploaded_file = client.files.upload(file="full_codebase_archive.txt")
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents=[
uploaded_file,
"Trace how authentication tokens are refreshed across all services.",
],
)
print(response.text)
import { GoogleGenAI, createPartFromUri } from "@google/genai";
const ai = new GoogleGenAI({});
const uploadedFile = await ai.files.upload({
file: "full_codebase_archive.txt",
});
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: [
createPartFromUri(uploadedFile.uri, uploadedFile.mimeType),
"Trace how authentication tokens are refreshed across all services.",
],
});
console.log(response.text);
from google import genai
from google.genai import types
schedule_meeting = {
"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()
tools = types.Tool(function_declarations=[schedule_meeting])
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="Schedule a meeting with Bob and Alice tomorrow at 10:00 AM about Q3 planning.",
config=types.GenerateContentConfig(tools=[tools]),
)
print(response.function_calls[0])
import { GoogleGenAI, Type } from "@google/genai";
const ai = new GoogleGenAI({});
const scheduleMeeting = {
name: "schedule_meeting",
description: "Schedules a meeting with attendees at a given date and time.",
parameters: {
type: Type.OBJECT,
properties: {
attendees: { type: Type.ARRAY, items: { type: Type.STRING } },
date: { type: Type.STRING },
time: { type: Type.STRING },
topic: { type: Type.STRING },
},
required: ["attendees", "date", "time", "topic"],
},
};
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: "Schedule a meeting with Bob and Alice tomorrow at 10:00 AM about Q3 planning.",
config: {
tools: [{ functionDeclarations: [scheduleMeeting] }],
},
});
console.log(response.functionCalls[0]);
from google import genai
from google.genai import types
client = genai.Client()
with open("financial_report.pdf", "rb") as f:
pdf_bytes = f.read()
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents=[
types.Part.from_bytes(data=pdf_bytes, mime_type="application/pdf"),
"Summarize the key revenue drivers and extract the Q4 table.",
],
)
print(response.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 response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: [
{
inlineData: {
data: pdfData,
mimeType: "application/pdf",
},
},
"Summarize the key revenue drivers and extract the Q4 table.",
],
});
console.log(response.text);