1. 簡介 👋
在本程式碼研究室中,您將以開發人員的身分,全面瞭解 Gemini 生態系統。具體來說,您將瞭解不同的 Gemini 模型、由 Gemini 支援的各種工具,以及與 Gemini 整合的 Google Gen AI SDK。您也會瞭解 Gemini 的各種功能,例如長篇脈絡、思考型模式、空間理解、Live API、原生圖像和音訊輸出等。
完成本程式碼研究室後,您應該會對 Gemini 生態系統有深入瞭解。
💡學習內容
- 不同的 Gemini 模型。
- 採用 Gemini 模型技術的工具。
- 如何使用 Google Gen AI SDK 整合 Gemini。
- Gemini 的長脈絡窗口。
- Gemini 的思考模式。
- 內建各種工具,例如 Google 搜尋、Google 地圖。
- 如何使用 Interactions API 與研究代理程式互動。
- 生成圖像和文字轉語音內容。
- Gemini 的空間理解能力。
- Live API 可用於即時語音和視訊互動。
⚠️ 事前準備
- Google AI Studio 範例的 API 金鑰。
- 已啟用 Google Cloud 範例計費功能的 Google Cloud 專案。
- 本機開發環境或 Google Cloud 中的 Cloud Shell 編輯器。
2. Gemini 系列 🫂
Gemini 是 Google 的 AI 模型,可將任何想法化為現實。這款模型非常適合多模態理解、代理式和直覺式程式開發,一切都建立在最先進的推論技術基礎。如要快速瞭解 Gemini 模型,請觀看這部影片:
Gemini 不只是模型,這也是 Google 產品使用的傘狀品牌
使用 Gemini 模型。從以消費者為主的 Gemini 應用程式和 NotebookLM,到以開發人員為主的 AI Studio,再到以企業為主的 Google Cloud Agent Platform,我們提供一系列 Gemini 產品。此外,還有採用 Gemini 技術的開發人員工具,例如 Antigravity、Antigravity IDE 和 Antigravity CLI。

3. Gemini 輔助工具 🧰
我們將簡單介紹 Gemini 支援的工具。
Gemini 應用程式 💬
Gemini 應用程式 ( gemini.google.com) 是以對話為基礎的消費者應用程式,這是與不同思考層級的各種 Gemini 模型 (Flash-Lite、Flash、Pro) 互動的最簡單方式。

還提供 Deep Research、圖像、影片、音樂生成等工具。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 的「Playground」面板中,測試「Models」部分的不同模型,生成文字、圖片和影片,也可以使用 Gemini Live API 試用即時語音和視訊功能。

在「代理」部分下方,您可以試用 Gemini 中的受管理代理。您可以在 Google AI Studio 的「Build」面板中,以「感覺」編寫全端網頁應用程式,然後部署到 Google Cloud 的 Cloud Run,並將程式碼推送至 GitHub。您也可以建構 Android 應用程式。

Gemini Enterprise Agent Platform Studio ☁️
Gemini Enterprise Agent Platform 是全代管的統合式 AI 開發平台,用於在 Google Cloud 中建構及使用生成式 AI。Gemini Enterprise Agent Platform Studio ( console.cloud.google.com/agent-platform) 可協助您測試、調整及部署企業可用的生成式 AI 應用程式。

Google Antigravity 🚀
Antigravity ( antigravity.google) 是代理式開發平台,Antigravity 可讓開發人員以工作為導向,更全面地管理各工作區的代理。此外,這項服務還提供 Antigravity IDE,也就是您熟悉的 AI 驅動 IDE 體驗,以及 Antigravity CLI,也就是指令列介面。

歡迎下載並試用這些工具。以下提供一般指南,說明何時該使用哪項工具:
- 如果您剛開始使用,可能會使用 Gemini 應用程式提問或生成一些基本程式碼。
- 如果您要以感覺編寫網頁應用程式,Google AI Studio 可能是您的首選工具。
- 如果您想使用本機開發環境的內容建構複雜的應用程式,請選擇 Google Antigravity。
- 如果您想部署或已使用 Google Cloud,並需要企業級支援和功能,請選擇 Agent Platform 及其工作室。
當然,您也可以混搭使用這些工具。舉例來說,您可以先在 AI Studio 中進行直覺式程式開發,然後將程式碼推送至 GitHub,再使用 Antigravity 繼續開發,最後部署至 Google Cloud。
4. Gemini 模型 🧠
Gemini 模型每隔幾個月就會推出新版本,持續提升效能。截至今天 (2026 年 2 月),Google Cloud 上的精選模型如下:

此外,還有許多其他正式發布的 Gemini 模型、預先發布的 Gemini 模型、開放原始碼的 Gemma 模型、嵌入模型、Imagegen 模型、Veo 模型等。
請參閱 Google Models 說明文件頁面,瞭解 Google Cloud 提供的主要模型,以及這些模型適用的不同用途。
5. Google Gen AI SDK 📦
如要將 Gemini 整合至應用程式,可以使用 Google Gen AI SDK。
如先前所述,您可以透過 Google AI Studio 或 Agent Platform 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.5-flash",
contents="Why is the sky blue?")
如要對 Google Cloud 的 Agent Platform 中的 Gemini 執行相同操作,您只需要變更用戶端初始化,其餘部分則相同:
client = genai.Client(
vertexai=True,
project=your-google-cloud-project,
location="us-central1")
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="Why is the sky blue?")
如要自行執行這些範例,請在 github.com/meteatamel/genai-samples/tree/main/vertexai/gemini2/hello-world 中執行 main.py。
6. Interactions API 🔄
Interactions API (Beta 版) 是與 Gemini 模型和代理程式互動的全新統一介面。這個 API 是 generateContent API 的改良替代方案,可簡化狀態管理、工具自動化調度管理和長時間執行的工作。
以下是與新版 API 的基本互動方式:
interaction = client.interactions.create(
model="gemini-3.5-flash",
input="Tell me a short joke."
)
print(interaction.outputs[-1].text)
您可以傳遞先前互動的互動 ID,進行有狀態的對話:
interaction1 = client.interactions.create(
model="gemini-3.5-flash",
input="Hi, my name is Phil."
)
print(f"Model: {interaction1.outputs[-1].text}")
interaction2 = client.interactions.create(
model="gemini-3.5-flash",
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 Agent 使用,請參閱下方的「Agents 🤖」步驟。
如要自行執行這些範例,可以在 github.com/meteatamel/genai-samples/blob/main/vertexai/interactions-api 中執行 main.py。
7. 長脈絡窗口 🪟
許多 Gemini 模型都提供 100 萬個以上的詞元脈絡窗口。過去,大型語言模型 (LLM) 一次可傳遞給模型的文字 (或權杖) 數量受到大幅限制。Gemini 長脈絡窗口可開創許多新的用途和開發人員範例。
如要查看長內容視窗的實際運作情形,請前往 Agent Platform 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.5-flash",
contents="How does AI work?",
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_level="low",
include_thoughts=True
)
),
)
嘗試使用不同的提示和思考層次,瞭解模型的行為。
9. 工具 🧰
Gemini 內建多種工具,例如 Google 搜尋、Google 地圖、程式碼執行、電腦使用、檔案搜尋等。您也可以使用函式呼叫功能定義自訂工具。讓我們簡單瞭解如何使用這些功能。
Google 搜尋 🔎
模型回覆內容如果使用 Google 搜尋結果做為基準,便能生成更準確、符合現況且相關的回覆。
在 Agent Platform Studio ( console.cloud.google.com/agent-platform/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 搜尋為基準。您也可以按一下「程式碼」按鈕,取得基礎範例:
google_search_tool = Tool(google_search=GoogleSearch())
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="How's the weather like today in London?",
config=GenerateContentConfig(tools=[google_search_tool])
)
Google 地圖 🗺️
您也可以使用 Google 地圖做為模型回覆內容的基準,Google 地圖可存取超過 2.5 億個地點的資訊。
如要查看實際運作情形,請在 Agent Platform 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.5-flash",
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.5-flash",
contents="What is the sum of the first 50 prime numbers?",
config=GenerateContentConfig(
tools=[code_execution_tool],
temperature=0))
電腦使用 🖥️
您可以使用 Gemini Computer Use 模型 (預先發布版) 建構瀏覽器控制代理,自動執行工作。運作方式如下:

如要查看實際運作情形,請在 github.com/google-gemini/computer-use-preview 中執行 main.py。按照存放區中的指示建立 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 詳細資料,包括分塊、嵌入和擷取。
如要查看實際運作情況,請在 github.com/meteatamel/genai-beyond-basics/blob/main/samples/grounding/file-search-tool 中執行 main.py。
從 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,讓 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 Agent 等專業代理程式。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
如要自行執行這個範例,可以在 github.com/meteatamel/genai-samples/blob/main/vertexai/interactions-api 中執行 main.py。
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 Flash Image 模型。這個模型專為速度和效率而設計,已針對高資料量、低延遲的工作完成最佳化調整。
- Nano Banana Pro:Gemini Pro Image 模型。這個模型專為專業素材資源製作而設計,採用進階推論技術,可遵循複雜的指令,並轉譯高保真文字。
以下是程式碼片段,您可以傳遞現有圖片,並要求 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-3.1-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 或 Agent Platform Studio 中推出。如要試用,最簡單的方法是使用 Gemini 應用程式。在 Gemini 應用程式 ( gemini.google.com) 中,選取 Tools 下方的 🍌 Create images。接著上傳圖片,體驗各種有趣功能。例如,你可以說出:
Can you transform this picture of mine to a nice beach on a tropical island?

12. 文字轉語音生成 🎶
Gemini 可使用 Gemini 文字轉語音 (TTS) 生成功能,將文字輸入內容轉換為單人或多人語音。您可以控制 TTS 生成的語音,也就是使用自然語言建構互動,並引導音訊的風格、口音、語速和語氣。
TTS 功能與 Live API 提供的語音生成功能不同,後者專為互動式非結構化音訊,以及多模態輸入和輸出內容而設計。Live API 擅長處理動態對話情境,而 Gemini API 的 TTS 則專為需要準確朗讀文字,並精細控制風格和聲音的情境而設計,例如生成 Podcast 或有聲書。
以下是單人 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-3.1-flash-tts-preview",
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 具備進階物件偵測和空間理解能力,如要瞭解這項功能,最簡單的方法就是實際操作。
前往 Google AI Studio Starter Applets,然後找到「Spatial Understanding」應用程式。
使用 Google AI Studio 金鑰更新 .env 檔案,並將 src/consts.tsx 中的模型更新為最新模型。安裝依附元件並啟動應用程式:
npm install
npm run dev
現在你可以開始選擇圖片,並嘗試使用 Gemini 偵測圖片中的項目。
舉例來說,您可以在不同圖片中偵測「陰影」或「水果」:

嘗試使用不同圖片,看看 Gemini 偵測及標記不同物件的準確度。
14. Live API 🎤
Live API 可與 Gemini 進行低延遲的即時語音和視訊互動。這項服務可處理連續的音訊、影片或文字,並立即以類似人類的口語回應,為使用者打造自然的對話體驗。
歡迎試用 Google AI Studio 中的 Live API 或 Agent Platform Studio 中的 Live API。在兩款應用程式中,你都可以分享語音、影片和螢幕畫面,並與 Gemini 進行即時對話。
開始分享影片或畫面,然後透過語音詢問 Gemini 一般問題。例如:
Can you describe what you see on the screen?
你會發現 Gemini 的回覆聽起來非常自然。
15. 結語
在本程式碼實驗室中,我們介紹了 Gemini 生態系統,從 Gemini 系列產品開始,瞭解如何使用統一的 Google Gen AI SDK 將模型整合到應用程式中。我們探討了 Gemini 的尖端功能,包括長篇脈絡視窗、思考型模式、內建基礎工具、Live API 和空間理解。建議您深入瞭解參考文件,並繼續發掘 Gemini 的無限潛力。