1. 简介 👋

在此 Codelab 中,您将以开发者的身份全面了解 Gemini 生态。具体而言,您将了解不同的 Gemini 模型、由 Gemini 提供支持的不同工具,以及用于与 Gemini 集成的 Google Gen AI SDK。您还将探索 Gemini 的各种功能,例如长上下文、思考模式、空间理解、Live API、原生图片和音频输出等。
完成此 Codelab 后,您应该对 Gemini 生态有扎实的了解!
💡您将学到什么
- 不同的 Gemini 模型。
- 由 Gemini 模型提供支持的工具。
- 如何使用 Google Gen AI SDK 与 Gemini 集成。
- Gemini 的长上下文窗口。
- Gemini 的思考模式。
- 不同的内置工具,例如 Google 搜索、Google 地图。
- 如何使用 Interactions API 与研究智能体互动。
- 图片和文字转语音生成。
- Gemini 的空间理解。
- 用于实时语音和视频交互的 Live API。
⚠️ 您需要准备什么
- 用于 Google AI Studio 示例的 API 密钥。
- 启用了结算功能的 Google Cloud 项目,用于 Vertex AI 示例。
- 本地开发环境或 Google Cloud 中的 Cloud Shell 编辑器。
2. Gemini 系列 🫂
Gemini 是 Google 的 AI 模型,可将任何想法变为现实。它是一款出色的多模态理解模型,也是智能体和氛围编程模型,所有功能都建立在先进的推理技术基础上。您可以观看此视频,快速了解 Gemini 模型:
Gemini 不仅仅是一个模型,它还是 Google 产品中使用的总品牌
这些产品利用了 Gemini 模型。Gemini 产品种类繁多,从面向消费者的 Gemini 应用 和 NotebookLM,到面向开发者的 AI Studio,再到面向企业的 Google Cloud Vertex AI。此外,还有由 Gemini 提供支持的开发者工具,例如 Gemini CLI 和 Google Antigravity。

3. 由 Gemini 提供支持的工具 🧰
我们来简要了解一下由 Gemini 提供支持的工具。
Gemini 应用 💬
Gemini 应用 ( gemini.google.com) 是一款基于聊天的消费者应用。它是与 Gemini 互动最简单的方式。它提供了 Deep Research、图片、视频、音乐生成等工具。它还提供了最新 Gemini 模型(快速、思考、Pro)的不同版本。Gemini 应用非常适合日常使用。

NotebookLM 📓
NotebookLM ( notebooklm.google.com) 是 AI 赋能的研究助手。只需上传 PDF、网站、YouTube 视频、音频文件、Google 文档、Google 幻灯片等内容,NotebookLM 就能为您总结要点,并巧妙地将不同主题关联起来,这一切都离不开最新版 Gemini 的多模态理解能力。它还会根据您上传的来源生成有趣且引人入胜的音频概览、视频概览、信息图表等。

Google AI Studio 🎨
借助 Google AI Studio ( ai.dev),您可以快速开始使用 Gemini 进行构建。通过 Google AI Studio 中的游乐场 面板,您可以试用不同的模型来生成文本、图片、视频,还可以通过 Gemini Live API 试用实时语音和视频。通过 Google AI Studio 中的构建 面板,您可以对 Web 应用进行氛围编程,并将其部署到 Google Cloud 上的 Cloud Run,然后将代码推送到 GitHub。

Vertex AI Studio ☁️
Vertex AI 是一个全托管式统一 AI 开发平台,用于在 Google Cloud 中构建和使用生成式 AI。Vertex AI Studio ( console.cloud.google.com/vertex-ai/studio) 可帮助您测试、调优和部署企业级生成式 AI 应用。

Gemini CLI ⚙️
Gemini CLI ( geminicli.com) 是一款开源 AI 智能体,可将 Gemini 的强大功能直接引入您的终端。它旨在成为开发者、工程师、SRE 等人员的首选终端工具,具有可扩展性和强大的功能。Gemini CLI 可与您的本地环境集成。它可以读取和编辑文件、执行 shell 命令以及搜索网络,同时保持您的项目上下文。

Google Antigravity 🚀
Google Antigravity ( antigravity.google) 是一个智能体式开发平台,可将 IDE 发展为智能体优先的时代。Antigravity 使开发者能够在更高的任务导向型级别上运行,跨工作区管理智能体,同时保留熟悉的 AI IDE 体验。
Antigravity 将智能体提取到自己的界面中,并为它们提供在编辑器、终端和浏览器中自主运行所需的工具,同时强调通过任务和工件进行验证和更高级别的通信。借助此功能,智能体可以规划和执行更复杂的端到端软件任务,从而全面提升开发效率,从构建功能、界面迭代、修复错误到研究和生成报告。

您可以随意下载并试用这些工具。 以下是一些关于何时使用哪个工具的一般指导:
- 如果您刚刚入门,可能会使用 Gemini 应用来提问或生成一些基本代码。
- 如果您要对 Web 应用进行氛围编程,Google AI Studio 可能是您选择的工具。
- 如果您想使用本地开发环境中的上下文构建复杂的应用,那么您会选择 Gemini CLI 或 Google Antigravity。
- 如果您想部署或已在使用 Google Cloud,并且需要企业级支持和功能,那么您会选择 Vertex AI 及其 Studio。
当然,您可以混合搭配使用这些工具。例如,先在 AI Studio 中进行氛围编程,然后推送到 GitHub,再使用 Antigravity 继续编码,然后部署到 Google Cloud。
4. Gemini 模型 🧠
Gemini 模型会不断改进,每隔几个月就会推出新版本。截至今天(2026 年 2 月),以下是 Google Cloud 上 Vertex AI 的精选模型:

还有许多其他 正式版 Gemini 模型、 预览版 Gemini 模型、开放式 Gemma 模型、 嵌入模型、 Imagegen 模型、 Veo 模型等。
您可以访问 Google 模型文档页面,了解 Vertex AI 上适用于不同用例的主要模型。
5. Google Gen AI SDK 📦
如需将 Gemini 与您的应用集成,您可以使用 Google Gen AI SDK。
如前所述,您可以通过 Google AI Studio 或 Vertex AI Studio 访问 Gemini 模型。 Google Gen AI SDK 通过 Google AI API 和 Google Cloud API 提供与 Gemini 模型交互的统一接口。除少数例外情况外,在一个平台上运行的代码将在两个平台上运行。

Google Gen AI SDK 目前支持 Python、Go、Node、Java 和 C#。
例如,以下是在 Python 中与 Google AI 中的 Gemini 对话的方式:
client = genai.Client(
api_key=your-gemini-api-key)
response = client.models.generate_content(
model="gemini-3-flash-preview",
contents="Why is the sky blue?")
如需在 Vertex AI 中对 Gemini 执行相同的操作,您只需更改客户端初始化,其余部分保持不变:
client = genai.Client(
vertexai=True,
project=your-google-cloud-project,
location="us-central1")
response = client.models.generate_content(
model="gemini-3-flash-preview",
contents="Why is the sky blue?")
如需自行运行这些示例,您可以在 main.py 中运行 github.com/meteatamel/genai-samples/tree/main/vertexai/gemini2/hello-world。
6. Interactions API 🔄
Interactions API(Beta 版)是一个用于与 Gemini 模型和智能体互动的新统一接口。作为 generateContent API 的改进替代方案,它简化了状态管理、工具编排和长时间运行的任务。
以下是与新 API 进行基本互动的方式:
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Tell me a short joke."
)
print(interaction.outputs[-1].text)
您可以通过传递上一次互动的互动 ID 来进行有状态的对话:
interaction1 = client.interactions.create(
model="gemini-3-flash-preview",
input="Hi, my name is Phil."
)
print(f"Model: {interaction1.outputs[-1].text}")
interaction2 = client.interactions.create(
model="gemini-3-flash-preview",
input="What is my name?",
previous_interaction_id=interaction1.id
)
print(f"Model: {interaction2.outputs[-1].text}")
Interactions API 专为构建智能体和与智能体互动而设计,支持函数调用、内置工具、结构化输出和 Model Context Protocol (MCP)。如需了解如何将其与 Deep Research 智能体搭配使用,请参阅下面的智能体 🤖 步骤。
如需自行运行这些示例,您可以在 main.py 中运行 github.com/meteatamel/genai-samples/blob/main/vertexai/interactions-api。
7. 长上下文窗口 🪟
许多 Gemini 模型都配备了 100 万个或更多词元的大上下文窗口。过去,大语言模型 (LLM) 受到一次可传递给模型的文本(或词元)数量的极大限制。Gemini 的长上下文窗口发掘了许多新的应用场景和开发者模式。

如需查看长上下文窗口的实际效果,您可以前往 Vertex AI Studio 提示库,然后选择 Extract Video Chapters 提示。此提示会将视频内容分组到各个章节中,并为每个章节提供摘要。
使用提供的视频运行后,您应该会获得类似于以下内容的输出:
[
{
"timecode": "00:00",
"chapterSummary": "The video opens with scenic views of Rio de Janeiro, introducing the \"Marvelous City\" and its famous beaches like Ipanema and Copacabana, before pivoting to the existence of the favelas."
},
{
"timecode": "00:20",
"chapterSummary": "The narrator describes the favelas, home to one in five Rio residents, highlighting that while often associated with crime and poverty, this is only a small part of their story."
},
{
"timecode": "00:36",
"chapterSummary": "Google introduces its project to map the favelas, emphasizing that providing addresses to these uncharted areas is a crucial step in giving residents an identity."
},
{
"timecode": "00:43",
"chapterSummary": "The video concludes by focusing on the people of the favelas, inviting viewers to go beyond the map and explore their world through a 360-degree experience."
}
]
这完全得益于 Gemini 的长上下文窗口!
8. 思考模式 🧠
Gemini 模型使用内部思考过程,可显著提高其对复杂任务的推理能力。思考级别 (Gemini 3) 和预算 (Gemini 2.5) 控制着思考行为。您还可以启用 include_thoughts 标志来查看模型的原始想法。
如需查看思考模式的实际效果,我们来打开 Google AI Studio ( ai.dev) 并开始新的聊天。在右侧边栏中,您可以设置思考级别:

如果您点击右上角的 Get code 按钮,还可以看到如何在代码中设置思考级别,类似于以下内容:
response = client.models.generate_content(
model="gemini-3-pro-preview",
contents="How does AI work?",
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_level="low",
include_thoughts=True
)
),
)
您可以尝试使用不同的提示和不同的思考级别,看看模型的行为。
9. 工具 🧰
Gemini 附带了许多内置工具,例如 Google 搜索、Google 地图、代码执行、计算机使用、文件搜索等。您还可以使用函数调用定义自定义工具。我们来简要了解一下如何使用它们。
Google 搜索 🔎
您可以依托 Google 搜索结果对模型回答进行接地,从而获得更准确、更相关且时效性更强的回答。
在 Vertex AI Studio ( console.cloud.google.com/vertex-ai/studio) 或 Google AI Studio ( ai.dev) 中,您可以开始新的聊天,并确保 Google 搜索接地处于关闭状态:

然后,您可以询问有关您所在位置的今天天气的问题。例如:
How's the weather in London today?
您通常会收到过去一天的回答,因为模型无法访问最新信息。例如:
In London today (Friday, May 24, 2025), the weather is a bit of a mixed bag, typical for late May.
现在,启用 Google 搜索接地并提出相同的问题。您应该会收到最新的天气信息,并附有接地来源的链接:
In London today (Wednesday, February 11, 2026), the weather is cool and mostly cloudy with a chance of light rain.
以下是在代码中进行 Google 搜索接地的方式。您还可以点击 Vertex AI Studio 中的“代码”按钮,获取接地示例:
google_search_tool = Tool(google_search=GoogleSearch())
response = client.models.generate_content(
model="gemini-3-flash-preview",
contents="How's the weather like today in London?",
config=GenerateContentConfig(tools=[google_search_tool])
)
Google 地图 🗺️
您还可以使用 Google 地图对模型回答进行接地,Google 地图可以访问超过 2.5 亿个地点的信息。
如需查看实际效果,您可以在 Vertex AI Studio 的模型设置中的“接地”部分选择 Google 地图,而不是 Google 搜索,然后提出需要地图数据的问题,例如:
Can you show me some Greek restaurants and their map coordinates near me?
相应的代码如下所示:
google_maps_tool = Tool(google_maps=GoogleMaps())
response = client.models.generate_content(
model="gemini-3-flash-preview",
contents="What are the best restaurants near here?",
config=GenerateContentConfig(tools=[google_maps_tool]),
# Optional: Provide location context (this is in Los Angeles)
tool_config=ToolConfig(
retrieval_config=types.RetrievalConfig(
lat_lng=types.LatLng(
latitude=34.050481, longitude=-118.248526))),
)
代码执行 🧑💻
Gemini 可以生成并运行 Python 代码,并支持一系列库(pandas、numpy、PyPDF2 等)。这对于受益于基于代码的推理(例如求解方程)的应用非常有用
如需试用此功能,请切换到 Google AI Studio,开始新的聊天,并确保 Code execution 开关处于开启状态。然后,提出一个可能需要使用代码执行工具的问题。例如:
What is the sum of the first 50 prime numbers?
Gemini 应该会生成一些 Python 代码并运行它。最终,正确答案是 5117。
您可以按如下方式从代码运行代码执行工具:
code_execution_tool = Tool(code_execution=ToolCodeExecution())
response = client.models.generate_content(
model="gemini-3-flash-preview",
contents="What is the sum of the first 50 prime numbers?",
config=GenerateContentConfig(
tools=[code_execution_tool],
temperature=0))
计算机使用 🖥️
借助 Gemini 计算机使用模型(预览版),您可以构建浏览器控制智能体来自动执行任务。它的工作方式如下:

如需查看实际效果,您可以在 main.py 中运行 github.com/google-gemini/computer-use-preview。按照代码库中的说明创建 Python 虚拟环境并安装依赖项。
例如,您可以从 Google AI Studio 获取 API 密钥,然后问问 Gemini 为您搜索航班:
export GEMINI_API_KEY=your-api-key
python main.py --query "Find me top 5 fights sorted by price with the following constraints:
Flight site to use: www.google.com/travel/flights
From: London
To: Larnaca
One-way or roundtrip: One way
Date to leave: Sometime next week
Date to return: N/A
Travel preferences:
-Direct flights
-No flights before 10am
-Carry-on luggage"
您应该会看到 Gemini 打开一个无痕模式浏览器,并开始为您搜索航班!
文件搜索 📁
借助文件搜索工具,您可以轻松实现检索增强生成 (RAG)。只需上传文件,它就会为您完成所有 RAG 详细信息,包括分块、嵌入和检索。
如需查看实际效果,您可以在 main.py 中运行 github.com/meteatamel/genai-beyond-basics/blob/main/samples/grounding/file-search-tool。
从 Google AI Studio 获取 API 密钥,然后创建文件搜索存储区:
export GEMINI_API_KEY=your-gemini-api-key
python main.py create_store my-file-search-store
将 PDF 上传到存储区:
python main.py upload_to_store fileSearchStores/myfilesearchstore-5a9x71ifjge9 cymbal-starlight-2024.pdf
提出有关指向存储区的 PDF 的问题:
python main.py generate_content "What's the cargo capacity of Cymbal Starlight?" fileSearchStores/myfilesearchstore-5a9x71ifjge9
您应该会收到依托 PDF 的回答:
Generating content with file search store: fileSearchStores/myfilesearchstore-5a9x71ifjge9
Response: The Cymbal Starlight 2024 has a cargo capacity of 13.5 cubic feet, which is located in the trunk of the vehicle. It is important to distribute the weight evenly and not overload the trunk, as this could impact the vehicle's handling and stability. The vehicle can also accommodate up to two suitcases in the trunk, and it is recommended to use soft-sided luggage to maximize space and cargo straps to secure it while driving.
Grounding sources: cymbal-starlight-2024.pdf
函数调用 📲
如果内置工具不够用,您还可以在 Gemini 中定义自己的工具(函数)。您只需提交 Python 函数作为工具(而不是提交函数的详细 OpenAPI 规范)。模型和 SDK 会自动将其用作工具。
例如,您可以创建一个函数来返回某个位置的纬度和经度:
def location_to_lat_long(location: str):
"""Given a location, returns the latitude and longitude
Args:
location: The location for which to get the weather.
Returns:
The latitude and longitude information in JSON.
"""
logger.info(f"Calling location_to_lat_long({location})")
url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1"
return api_request(url)
您还可以创建一个函数来返回纬度和经度的天气信息:
def lat_long_to_weather(latitude: str, longitude: str):
"""Given a latitude and longitude, returns the weather information
Args:
latitude: The latitude of a location
longitude: The longitude of a location
Returns:
The weather information for the location in JSON.
"""
logger.info(f"Calling lat_long_to_weather({latitude}, {longitude})")
url = (f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t=temperature_2m,"
f"relative_humidity_2m,surface_pressure,wind_speed_10m,wind_direction_10m&forecast_days=1")
return api_request(url)
现在,您可以将这两个函数作为工具传递给 Gemini,让它使用这些函数来获取某个位置的天气信息:
def generate_content_with_function_calls():
client = genai.Client(
vertexai=True,
project=PROJECT_ID,
location=LOCATION)
response = client.models.generate_content(
model=MODEL_ID,
contents=PROMPT,
config=GenerateContentConfig(
system_instruction=[
"You are a helpful weather assistant.",
"Your mission is to provide weather information for different cities."
"Make sure your responses are in plain text format (no markdown) and include all the cities asked.",
],
tools=[location_to_lat_long, lat_long_to_weather],
temperature=0),
)
print(response.text)
#print(response.automatic_function_calling_history)
如需查看实际效果,您可以在 github.com/meteatamel/genai-beyond-basics/blob/main/samples/function-calling/weather 中运行 main_genaisdk.py。
10. 智能体 🤖
Gemini 的 Interactions API 专为构建智能体和与智能体互动而设计。您可以使用 Gemini Deep Research 智能体等专用智能体。Gemini Deep Research 智能体可自主规划、执行和综合多步骤研究任务。它使用网络搜索和您自己的数据来浏览复杂的信息环境,生成详细的引用报告。
以下是如何使用 Interaction API 与 Deep Research 智能体互动:
interaction = client.interactions.create(
input="Research the history of the Google TPUs.",
agent="deep-research-pro-preview-12-2025",
background=True
)
while True:
if interaction.status == "completed":
print("\nFinal Report:\n",
interaction.outputs[-1].text)
break
如需自行运行此示例,您可以在 main.py 中运行 github.com/meteatamel/genai-samples/blob/main/vertexai/interactions-api。
export GOOGLE_API_KEY=your-api-key
python main.py agent
过一段时间后,您应该会看到完成的研究:
User: Research the history of the Google TPUs with a focus on 2025 and 2026
Status: in_progress
Status: in_progress
Status: in_progress
...
Model Final Report:
# Architectural Convergence and Commercial Expansion: The History of Google TPUs (2015–2026)
## Key Findings
* **Strategic Pivot (2025):** Google transitioned the Tensor Processing Unit (TPU) from a primarily internal differentiator to a commercial merchant-silicon competitor, epitomized by the massive "Ironwood" (TPU v7) deployment and external sales strategy.
* **Technological Leap:** The introduction of TPU v7 "Ironwood" in 2025 marked a paradigm shift, utilizing 3nm process technology to deliver 42.5 exaFLOPS per pod, directly challenging NVIDIA's Blackwell architecture in the high-performance computing (HPC) sector.
...
11. 图片生成 📷
Nano Banana 🍌 是 Gemini 原生图片生成功能的名称。Gemini 能够以对话方式生成并处理图片,可以使用文本、图片或两者结合的方式。这让您可以灵活地创建、修改和迭代视觉内容。
Nano Banana 是指 Gemini API 中提供的两个不同的模型:
- Nano Banana:Gemini 2.5 Flash Image 模型 (
gemini-2.5-flash-image)。此模型专为速度和效率而设计,针对高容量、低延迟任务进行了优化。 - Nano Banana Pro:Gemini 3 Pro Image Preview 模型 (
gemini-3-pro-image-preview)。此模型专为专业资源制作而设计,利用高级推理来遵循复杂的说明并呈现高保真文本。
以下代码段展示了如何传递现有图片并让 Nano Banana 编辑图片:
from google import genai
from google.genai import types
from PIL import Image
client = genai.Client()
prompt = (
"Create a picture of my cat eating a nano-banana in a "
"fancy restaurant under the Gemini constellation",
)
image = Image.open("/path/to/cat_image.png")
response = client.models.generate_content(
model="gemini-2.5-flash-image",
contents=[prompt, image],
)
for part in response.parts:
if part.text is not None:
print(part.text)
elif part.inline_data is not None:
image = part.as_image()
image.save("generated_image.png")
Nano Banana 可在 Gemini 应用、AI Studio 或 Vertex AI Studio 中使用。最简单的试用方式是在 Gemini 应用中。在 Gemini 应用 ( gemini.google.com) 中,选择 🍌 Create images 下的 Tools。然后,上传图片并尝试一些有趣的功能。例如,您可以说:
Can you transform this picture of mine to a nice beach on a tropical island?

12. 文字转语音生成 🎶
Gemini 可以使用 Gemini 文字转语音 (TTS) 生成功能将文本输入转换为单人或多人音频。TTS 生成是可控的,这意味着您可以使用自然语言来构建互动,并指导音频的风格、口音、节奏和语气。
有 2 个模型支持 TTS:
TTS 功能不同于通过 Live API 提供的语音生成,后者专为互动式非结构化音频以及多模态输入和输出而设计。虽然 Live API 在动态对话上下文中表现出色,但通过 Gemini API 进行的 TTS 专为需要精确文本朗读且对风格和声音进行精细控制的场景量身定制,例如播客或有声读物生成。
以下是单人 TTS 的代码段:
from google import genai
from google.genai import types
import wave
# Set up the wave file to save the output:
def wave_file(filename, pcm, channels=1, rate=24000, sample_width=2):
with wave.open(filename, "wb") as wf:
wf.setnchannels(channels)
wf.setsampwidth(sample_width)
wf.setframerate(rate)
wf.writeframes(pcm)
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash-preview-tts",
contents="Say cheerfully: Have a wonderful day!",
config=types.GenerateContentConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(
voice_name='Kore',
)
)
),
)
)
data = response.candidates[0].content.parts[0].inline_data.data
file_name='out.wav'
wave_file(file_name, data) # Saves the file to current directory
您可以在 文字转语音生成 (TTS) 文档 中查看更多示例。
您还可以在 Google AI Studio 游乐场中尝试生成语音。在 generate-speech 应用中尝试不同的提示:

13. 空间理解 🌐
Gemini 具有先进的对象检测和空间理解能力。
了解此功能的最佳方式是查看实际效果。前往 AI Studio 中的 空间理解入门应用。选择一些图片,然后尝试使用 Gemini 检测图片中的一些项。
例如,您可以检测不同图片中的“阴影”或“水果”:

您可以尝试使用不同的图片,看看 Gemini 检测和标记不同对象的效果如何。
14. Live API 🎤
Live API 支持与 Gemini 进行低延迟、实时的语音和视频交互。它能够处理连续的音频、视频或文本流,以提供即时、自然逼真的语音回答,为用户打造自然的对话式体验。

您可以前往 Google AI Studio 或 Vertex AI Studio 试用 Live API。在这两个应用中,您都可以共享语音、视频和屏幕,并与 Gemini 进行实时对话。

您可以开始共享视频或屏幕,并通过语音问问 Gemini 一般问题。例如:
Can you describe what you see on the screen?
您会惊讶于 Gemini 的回答听起来多么自然。
15. 总结
在此 Codelab 中,我们介绍了 Gemini 生态,首先介绍了 Gemini 系列产品,然后学习了如何使用统一的 Google Gen AI SDK 将模型集成到我们的应用中。我们探索了 Gemini 的尖端功能,包括长上下文窗口、思考模式、内置接地工具、Live API 和空间理解。我们建议您深入了解参考文档,并继续尝试 Gemini 的全部潜力。