
生成式 AI 模型正在改变我们创建内容的方式,无论是文本、图片、视频还是代码。借助 Google 的 Gen AI Python SDK,除了使用 Gemini Developer API 和 Vertex AI API 之外,您现在还可以更轻松地在 Python 应用程序中访问和使用 Google 的生成式 AI 模型。这意味着开发者可以更轻松地创建应用程序,包括聊天机器人、内容生成器或创意工具。在本文中,我们将介绍开始使用 Google Gen AI Python SDK 所需的所有知识。
什么是Google Gen AI Python SDK?
Google Gen AI Python SDK 是一个客户端库,开发者可以通过 Python 轻松使用 Google 的生成式 AI 功能。它提供:
- 支持 Gemini Developer API(Google 的高级文本和多模态生成模型)
- 与 Vertex AI API 集成,用于企业级 AI 工作负载
- 支持生成文本、图像、视频、嵌入、聊天对话等
- 文件管理、缓存和异步支持工具
- 高级函数调用和模式强制功能
此 SDK 还抽象了 API 调用的大部分复杂性,让您专注于构建 AI 驱动的应用程序。
安装
安装 SDK 非常简单。运行:
pip install google-genai
上述命令将使用 pip 安装 Google Gen AI Python SDK 软件包。此命令会下载启动 Google 生成式 AI 服务所需的 Python 环境的所有资源,包括资源和所有依赖项。
导入和客户端设置
安装 SDK 后,创建一个 Python 文件并导入 SDK:
from google import genai from google.genai import types
该 SDK 包含两个模块:genai 和 types。genai 模块创建用于 API 交互的客户端,而 types 模块包含数据结构和类,它们可作为辅助程序,用于构建请求和配置请求参数。
您将为与 Google 生成式 AI 模型的每次交互创建一个客户端实例。您将根据所使用的 API,使用不同的方法来实例化客户端。
对于 Gemini 开发者 API,您可以通过传递 API 密钥来实例化客户端:
client = genai.Client(api_key='YOUR_GEMINI_API_KEY')
实例化客户端后,您可以通过传入 API 密钥与 Gemini 开发者 API 进行交互。该客户端将负责访问令牌和请求管理。
可选:使用Google Cloud Vertex AI
client = genai.Client( vertexai=True, project='your-project-id', location='us-central1' )
如果您要使用 Google Cloud Vertex AI,则需要通过指定项目 ID 和位置来以不同的方式初始化客户端。
注意:使用 Vertex AI 是可选的。您可以在此处创建项目 ID。
如果您不使用 Vertex AI,则可以直接使用上面的 API 密钥方法。
API版本和配置
默认情况下,SDK 使用 Beta 版端点来访问 Beta 版功能。但是,如果您想使用稳定版 API,可以使用 http_options 参数指定 API 版本:
from google.genai import types client = genai.Client( vertexai=True, project='your-project-id', location='us-central1', http_options=types.HttpOptions(api_version='v1') )
如何平衡稳定性与前沿功能,完全取决于您。
使用环境变量(可选)
与其直接传递密钥,不如先设置环境变量:
Gemini 开发者 API:
export GEMINI_API_KEY='your-api-key'
Vertex AI:
export GOOGLE_GENAI_USE_VERTEXAI=true export GOOGLE_CLOUD_PROJECT='your-project-id' export GOOGLE_CLOUD_LOCATION='us-central1'
然后,简单地初始化客户端:
client = genai.Client()
Google Gen AI Python SDK用例
设置完成后,您可以通过多种方式使用 Google Gen AI Python SDK 的功能。
内容生成
该 SDK 的主要功能是生成 AI 内容。您可以以各种形式提供提示,例如简单的字符串、结构化内容或复杂的多模态输入。
基本文本生成
response = client.models.generate_content( model='gemini-2.0-flash-001', contents='Why Does the sun rises from east' ) print(response.text)
输出

这会向模型发送提示并返回生成的答案。
结构化内容输入
您可以跨各种角色插入结构化内容,例如,在聊天机器人、对话或多轮对话的语境中,插入用户或模型。
from google.genai import types content = types.Content( role='user', parts=[types.Part.from_text(text='Tell me a fun fact about work.')] ) response = client.models.generate_content(model='gemini-2.0-flash-001', contents=content) print(response.text)
输出

SDK 内部将多种不同的输入类型转换为模型所需的结构化数据格式。
文件上传和使用
Gemini Developers API 允许您上传文件供模型处理。这对于摘要或内容提取非常有用:
file = client.files.upload(file='/content/sample_file.txt') response = client.models.generate_content( model='gemini-2.0-flash-001', contents=[file, 'Please summarize this file.'] ) print(response.text)
输出

这是将 AI 功能添加到基于文档的任务的理想方法。
函数调用
一项独特的功能是能够将 Python 函数作为“工具”传递给模型,以便在生成补全时自动调用。
def get_current_weather(location: str) -> str: return 'sunny' response = client.models.generate_content( model='gemini-2.0-flash-001', contents='What is the weather like in Ranchi?', config=types.GenerateContentConfig(tools=[get_current_weather]) ) print(response.text)
输出

这使得 AI 响应中的动态实时数据集成成为可能。
高级配置
您可以使用温度、max_output_tokens 等参数以及安全设置来自定义生成,以管理随机性、长度并过滤有害内容。
config = types.GenerateContentConfig( temperature=0.3, max_output_tokens=100, safety_settings=[types.SafetySetting(category='HARM_CATEGORY_HATE_SPEECH', threshold='BLOCK_ONLY_HIGH')] ) response = client.models.generate_content( model='gemini-2.0-flash-001', contents='''Offer some encouraging words for someone starting a new journey.''', config=config ) print(response.text)
输出

这可以更细致地控制内容质量和安全性。
多媒体支持:图片和视频
该 SDK 允许您生成和编辑图片以及生成视频(预览版)。
- 使用文本提示生成图片。
- 放大或调整生成的图片。
- 从文本或图片生成视频。
图片生成示例:
response = client.models.generate_images( model='imagen-3.0-generate-002', prompt='A tranquil beach with crystal-clear water and colorful seashells on the shore.', config=types.GenerateImagesConfig(number_of_images=1) ) response.generated_images[0].image.show()
输出

视频生成示例:
import time operation = client.models.generate_videos( model='veo-2.0-generate-001', prompt='A cat DJ spinning vinyl records at a futuristic nightclub with holographic beats.', config=types.GenerateVideosConfig(number_of_videos=1, duration_seconds=5) ) while not operation.done: time.sleep(20) operation = client.operations.get(operation) video = operation.response.generated_videos[0].video video.show()
输出:
这可以实现富有创意的多模式 AI 应用。
聊天和对话
您可以发起聊天会话,并在聊天过程中保留上下文:
chat = client.chats.create(model='gemini-2.0-flash-001')
response = chat.send_message('Tell me a story')
print(response.text)

response = chat.send_message('Summarize that story in one sentence')
print(response.text)

这对于创建能够记住先前对话的对话式 AI 非常有用。
异步支持
所有主要 API 方法都包含异步函数,以便更好地集成到异步 Python 应用中:
response = await client.aio.models.generate_content( model='gemini-2.0-flash-001', contents='Tell a Horror story in 200 words.' ) print(response.text)

Token计数
Token 计数可以追踪输入中包含的词元(文本片段)数量。这有助于您控制在模型限制范围内,并做出经济高效的决策。
token_count = client.models.count_tokens( model='gemini-2.0-flash-001', contents='Why does the sky have a blue hue instead of other colors?' ) print(token_count)
![]()
嵌入
嵌入将文本转换为表示其含义的数字向量,可用于搜索、聚类和 AI 评估。
embedding = client.models.embed_content( model='text-embedding-004', contents='Why does the sky have a blue hue instead of other colors?' ) print(embedding)

使用 SDK,您可以轻松统计 token 数量并进行嵌入,从而改进和增强您的 AI 应用程序。
小结
Google Gen AI Python SDK 是一款功能强大且用途广泛的工具,可帮助开发者在其 Python 项目中访问 Google 的顶级生成式 AI 模型。从文本生成、聊天和聊天机器人,到图像/视频生成、函数调用等等,它提供了强大的功能集和简洁的界面。凭借便捷的软件包安装、简单的客户端配置流程以及对异步编程和多媒体的支持,该 SDK 使构建利用 AI 的应用程序变得非常容易。无论您是初学者还是经验丰富的开发者,使用该 SDK 都相对轻松,但在将生成式 AI 融入您的工作流程时却非常强大。


评论留言