步骤 1:为 Google AI Studio 设置 API 密钥
要设置 API 密钥,请前往Google AI Studio 并点击“Create API Key”按钮。记得复制该密钥,并将其粘贴到名为 .env 的文件中,格式如下:
GOOGLE_API_KEY=replace_this_with_api_key
如果您之前已使用相同的 Google 账户操作过 Google Cloud Platform,Google AI Studio 会提示您选择一个项目来启用该 API。
为了顺利跟进本教程,Python 代码需要与 .env 文件位于同一文件夹。
步骤 2:安装 Python 依赖
在本项目中,我们将使用以下软件包:
google-genai:一个用于将 Google 生成式 AI 模型集成到应用中的 Python 库。pyautogui:一个跨平台库,可编程控制鼠标和键盘以自动化任务。在我们的场景中,用它将屏幕内容提供给 AI 模型。python-dotenv:一个库,用于通过将 环境变量 从 .env 文件加载到 Python 应用中来进行管理。sounddevice:一个用于通过简单 API 录制与播放声音的 Python 库,支持音频输入与输出。numpy:Python 数值计算的基础库,提供对数组、矩阵以及广泛数学运算的支持。
使用 pip 安装依赖:
pip install google-genai pyautogui python-dotenv sounddevice numpy
或者,从我为本项目创建的 GitHub 仓库下载 requirements.txt 文件,并使用它创建 Conda 环境:
conda create --name gemini python=3.11
conda activate gemini
pip install -r requirements.txt
步骤 3:使用 Google GenAI API 创建文本聊天机器人
我们先使用 google.genai 库,基于 Google 的 Gemini 2 Flash 模型创建一个简单的命令行 AI 聊天界面。建议在遇到问题时查阅Gemini 2.0 官方文档。
本示例的完整代码见 text.py 文件,位于我的 GitHub 仓库。
创建并连接 Google GenAI 客户端
第一步是安全加载 API 密钥并初始化 Google GenAI 客户端。脚本使用 dotenv 从 .env 文件加载环境变量。
以下是使用必要凭据设置客户端的方法:
from google import genai
from dotenv import load_dotenv
import os
# Load environment variables from a .env file
load_dotenv()
client = genai.Client(
api_key=os.getenv("GOOGLE_API_KEY"),
http_options={"api_version": "v1alpha"},
)
print("Connected to the AI model!")
进行异步 API 调用
在使用 Google GenAI 这样的 API 时,我们经常需要处理异步操作。异步编程允许在等待网络请求的同时继续执行其他操作,使应用更具响应性。这在处理网络请求等高延迟操作时尤为重要。
在 Python 中,异步编程可通过 asyncio 库与 async/await 语法实现。
以下展示如何向 Google GenAI 发起一个异步请求:
from google import genai
from dotenv import load_dotenv
import os
import asyncio
# Load environment variables from a .env file
load_dotenv()
async def main():
client = genai.Client(
api_key=os.getenv("GOOGLE_API_KEY"),
http_options={"api_version": "v1alpha"},
)
# Define the AI model and configuration
model_id = "gemini-2.0-flash-exp"
config = {"response_modalities": ["TEXT"]}
async with client.aio.live.connect(model=model_id, config=config) as session:
await session.send("Hello", end_of_turn=True)
# Process responses from the AI
async for response in session.receive():
if not response.server_content.turn_complete:
for part in response.server_content.model_turn.parts:
print(part.text, end="", flush=True)
# Run the main function
asyncio.run(main())
此版本会连接到 AI 模型并发送一条“Hello”消息。响应会逐字打印到控制台。
让它可交互
为了实现与 AI 模型的双向对话,我们添加一个循环,让用户可以多次发送消息。循环在用户输入 "exit" 时结束。
from google import genai
from dotenv import load_dotenv
import os
import asyncio
# Load environment variables from a .env file
load_dotenv()
async def main():
client = genai.Client(
api_key=os.getenv("GOOGLE_API_KEY"),
http_options={"api_version": "v1alpha"},
)
# Define the AI model and configuration
model_id = "gemini-2.0-flash-exp"
config = {"response_modalities": ["TEXT"]}
async with client.aio.live.connect(model=model_id, config=config) as session:
while True:
message = input("> ")
print()
# Exit the loop if the user types "exit"
if message == "exit":
print("Exiting...")
break
# Send the user's message to the AI model, marking the end of the turn
await session.send(message, end_of_turn=True)
# Receive responses asynchronously and process each response
async for response in session.receive():
if not response.server_content.turn_complete:
for part in response.server_content.model_turn.parts:
print(part.text, end="", flush=True)
print()
# Run the main function
asyncio.run(main())
就是这样!通过上述脚本,我们用 Google GenAI API 创建了一个命令行 AI 聊天机器人。效果如下所示:
步骤 4:加入音频模式
音频模式使模型能以语音而非文本进行回应。要让前面的示例支持音频响应,我们需要:
- 导入用于音频播放的
sounddevice和用于处理音频数据的numpy。 - 将响应模态从
TEXT改为AUDIO:
config = {"response_modalities": ["AUDIO"]}
- 在连接客户端前初始化一个音频流:
with sd.OutputStream(
samplerate=24000,
channels=1,
dtype="int16",
) as audio_stream:
- 从响应片段中获取音频数据并将其写入音频流进行播放:
for part in response.server_content.model_turn.parts:
# Get the audio data from the response part and add it to the steam
inline_data = part.inline_data
audio_data = np.frombuffer(inline_data.data, dtype="int16")
audio_stream.write(audio_data)
audio.py 文件(见仓库)包含应用了这些更改的完整脚本。脚本对变更行附有注释。
步骤 5:使用工具添加代码执行能力
现代 AI 模型的一大特性是能够在我们的代码中自主调用自定义函数,Gemini 2 也不例外。
其工作方式是:我们将可被调用的函数注册为工具,告知模型有哪些函数可用。随后,模型会基于提示、函数名称与描述来决定是否进行函数调用。一旦决定调用,它会发送一条特殊响应,其中包含要调用的函数名及其参数。
要定义一个工具,我们需要:
- 编写一个 Python 函数,其名称与参数与架构中定义的一致。
- 创建函数架构(schema),即包含函数元数据的字典,例如名称、文字描述以及参数规范。
- 将函数架构提供给 AI 模型。
- 当模型请求时执行该函数。
为说明这一点,我们定义一个可以读取文件的工具,让模型能够回答关于本地机器文件的问题。
定义函数
这部分就是常规的 Python 代码。若函数成功,模型期望返回包含 “result” 键的字典,否则为 “error”。
def load_file_content(filename):
try:
with open(filename, "rt") as f:
return {
"result": f.read()
}
except Exception as e:
return {
"error": "Could not load file content",
}
指定架构
以下是为该函数定义架构的方法:
load_file_content_schema = {
"name": "load_file_content",
"description": "Load the content of a file",
"parameters": {
"type": "object",
"properties": {
"filename": {
"type": "string",
"description": "The name of the file",
},
},
"required": ["filename"],
},
"output": {
"type": "string",
"description": "The text content of the file",
},
}
我们提供了四个字段:
“name”:函数名称。“description”:文字描述。模型据此决定是否调用该函数。“properties”:函数参数的描述。“output”:函数输出的描述。
关于函数架构的更多信息,请参阅官方文档。
将函数提供给模型
为了让模型知晓我们的函数,我们在模型配置中提供函数架构:
config = {
"tools": [{"function_declarations": [load_file_content_schema]}],
"response_modalities": ["TEXT"]
}
处理模型发起的函数调用请求
当模型决定执行函数调用时,它会在 response 中添加一个 tool_call。其中包含函数名和参数。它可能包含多个调用请求,因此我们需要遍历全部请求、调用相应函数,并将结果返回给模型:
# A dictionary mapping the function names to the actual functions
FUNCTIONS = {"load_file_content": load_file_content}
if response.tool_call is not None:
for fc in tool_call.function_calls:
f = FUNCTIONS.get(fc.name)
tool_response = types.LiveClientToolResponse(
function_responses=[
types.FunctionResponse(
name=fc.name,
id=fc.id,
response=f(**fc.args),
)
]
)
await session.send(tool_response)
该示例的完整实现见仓库中的 tool.py 文件(链接)包含应用这些更改的完整脚本。函数与架构定义位于tool_spec.py 文件。
网页访问
通过工具,我们还可以为模型添加网页访问能力,例如加入 Google 搜索工具:
search_tool = {"google_search": {}}
config = {
"tools": [search_tool],
"response_modalities": ["TEXT"],
}
此工具为内置工具,因此无需提供对应的函数。
代码执行
另一个内置功能是代码执行。代码执行允许模型编写并运行 Python 代码来回答复杂问题,通常涉及数学计算。比如,使用该工具时,如果我们要求它计算前 10 个质数之和,它会先编写用于计算的 Python 代码、执行,然后给出答案。
要启用该工具,我们这样做:
code_execution_tool = {"code_execution": {}}
config = {
"tools": [code_execution_tool],
"response_modalities": ["TEXT"],
}
以下展示了启用代码执行后模型的行为示例:
> add the first 10 prime numbers
Okay, I understand. You want me to add the first 10 prime numbers.
Here's my plan:
1. **Identify the first 10 prime numbers:** I will use a python code to find prime numbers.
2. **Sum the prime numbers:** I will also sum them using python.
3. **Report the result**
The first 10 prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29. Their sum is 129.
步骤 6:构建视觉助手
在最后一节中,我们将探索 Gemini 2 的视觉能力。目标是创建一个 AI 助手,能够理解我们屏幕上的内容并回答相关问题。例如,当我们要求它解释终端中出现的错误,或提供屏幕上当前显示内容的信息时,这会很有用。
在前面的示例中,我们使用异步编程连接 AI 模型,并在实时处理响应的同时来回发送数据。遗憾的是,当前版本的 SDK 还不支持与图像进行实时通信。相反,我们通过请求-响应的工作流提供图像数据。请注意,这并非 Gemini 2.0 本身的限制——只是当前的测试版 API 暂不支持。
向 Google GenAI 发送同步请求
先学习如何向 Google GenAI API 发送包含图像数据的请求。以下是发送同步请求的方式:
from google import genai
from dotenv import load_dotenv
import os
load_dotenv()
client = genai.Client(
api_key=os.getenv("GOOGLE_API_KEY"),
http_options={"api_version": "v1alpha"},
)
response = client.models.generate_content(
model="gemini-2.0-flash-exp",
contents=["Hello"],
)
print(response.text)
此示例的主要不同在于我们使用 client.models.generate_content 向 API 发送请求。这是同步请求,因此无法提供实时对话体验。
发送图像
我们可以通过加载图像并将其添加到 contents 列表来发送图像。我们使用 PIL 包创建一个名为 load_and_resize_image() 的函数来加载并调整图像大小。
from PIL import Image
def load_and_resize_image(image_path):
with Image.open(image_path) as img:
aspect_ratio = img.height / img.width
new_height = int(img.width * aspect_ratio)
return img.resize((img.width, new_height), Image.Resampling.LANCZOS)
image = load_and_resize_image("example_image.jpeg")
response = client.models.generate_content(
model="gemini-2.0-flash-exp",
contents=["Describe the image", image],
)
print(response.text)
创建 AI 视觉助手
AI 视觉助手会处理文本提示与屏幕截图,以帮助我们回答有关屏幕内容的问题。我做了大量实验,即使同时打开多个窗口,模型也能理解屏幕内容。
向模型提供屏幕内容的最简单方法是截屏。为此我们使用 pyautogui 包,这是一款跨平台库,可编程控制鼠标与键盘以实现自动化任务。在我们的场景中,我们仅用于截屏,但也可以扩展其功能,让 AI 在计算机上自主执行任务。
以下是一个截屏函数:
def capture_screen():
timestamp = time.strftime("%Y%m%d-%H%M%S")
filename = f"screenshot_{timestamp}.jpeg"
screenshot = pyautogui.screenshot()
screenshot = screenshot.convert("RGB")
screenshot.save(filename, format="JPEG")
return filename
为了实现交互,我们重复以下步骤,直到用户决定退出应用:
- 请用户输入提示词。
- 截取屏幕,并将其与提示词一起发送给 AI 模型。
- 将结果展示给用户。
使用该方式有一点需要注意:应用运行在终端中,而终端窗口也显示在屏幕上。因此,最好指示模型忽略终端窗口。可通过在配置中添加 system_instruction 实现:
client.models.generate_content(
model="gemini-2.0-flash-exp",
contents=[prompt, screen],
config=types.GenerateContentConfig(
system_instruction="Ignore the terminal window in the image when analyzing the image",
),
)
把上述部分整合起来,就是我们的视觉 AI 助手。完整代码也可在仓库中的 vision.py 文件找到:链接。
from google import genai
from google.genai import types
from PIL import Image
import pyautogui
import time
import os
from dotenv import load_dotenv
load_dotenv()
# Initialize the GenAI client
client = genai.Client(
api_key=os.getenv("GOOGLE_API_KEY"),
http_options={"api_version": "v1alpha"},
)
def capture_screen():
timestamp = time.strftime("%Y%m%d-%H%M%S")
filename = f"screenshot_{timestamp}.jpeg"
screenshot = pyautogui.screenshot()
screenshot = screenshot.convert("RGB")
screenshot.save(filename, format="JPEG")
return filename
def load_and_resize_image(image_path):
with Image.open(image_path) as img:
aspect_ratio = img.height / img.width
new_height = int(img.width * aspect_ratio)
return img.resize((img.width, new_height), Image.Resampling.LANCZOS)
def get_genai_response(prompt):
print("Analyzing screen...")
screen = load_and_resize_image(capture_screen())
response = client.models.generate_content(
model="gemini-2.0-flash-exp",
contents=[prompt, screen],
config=types.GenerateContentConfig(
system_instruction="Ignore the terminal window in the image when analyzing the image",
),
)
return response.text
def main():
while True:
prompt = input("> ")
print()
if prompt == "exit":
break
answer = get_genai_response(prompt)
print(answer)
print()
if __name__ == "__main__":
main()
当前版本的交互略显笨拙,需要将终端置于当前视图顶层以触发操作。下一步的自然改进是让它在后台运行,并使用语音输入与输出替代文本。
结语
我们学习了如何将 Gemini 2.0 Flash 模型用于多种应用场景,例如开发可进行实时文字与语音对话的聊天机器人,让 AI 模型通过函数调用执行操作,以及构建能够分析电脑屏幕内容的视觉助手。
如果您想进一步探索,Google 提供了两个示例,展示了模型通过给出带标签的边界框来检测图像中的对象。此示例聚焦于 2D 空间理解,让模型在图片中识别并标注纸杯蛋糕。Gemini 也能理解图像的 3D 语境,展示见这里。
总的来说,尽管当前 API 版本尚未让我们充分发挥其全部潜力,Gemini 2.0 依然非常有前景。我期待在不久的将来全面使用其多模态实时能力。

Google 近期发布了 Gemini 2.0,其中核心是 Gemini 2.0 Flash 模型——一个更快、更强大的版本,旨在提升图像与声音处理能力。
在本教程中,我将带您一步步使用 Gemini 2.0 Flash 创建一款视觉助手,它可以读取屏幕上的内容并回答相关问题。
以下是我们将要构建的演示: