Google Gen AI Python SDK 深度开发指南
简介
Google Gen AI Python SDK (google-genai) 是一个 Python 客户端库,用于与 Google 的生成式 AI API 进行交互。它为开发者提供了一个接口,以便将 Google 的生成模型(支持 Gemini Developer API 和 Vertex AI API)集成到他们的 Python 应用程序中。
相关链接:
安装
要开始使用,请通过 pip 安装 SDK:
pip install google-genai
导入库
导入必要的模块:
from google import genai
from google.genai import types
创建客户端
Gemini Developer API:
from google import genai
# 仅为 Gemini Developer API 运行此块
client = genai.Client(api_key='YOUR_GEMINI_API_KEY')
Vertex AI API:
from google import genai
# 仅为 Vertex AI API 运行此块
client = genai.Client(
vertexai=True, project='your-project-id', location='us-central1'
)
(可选) 使用环境变量:
Gemini Developer API: 设置 GOOGLE_API_KEY。 [cite: 8]
export GOOGLE_API_KEY='your-api-key'
Vertex AI 中的 Gemini API: 设置 GOOGLE_GENAI_USE_VERTEXAI, GOOGLE_CLOUD_PROJECT, 和 GOOGLE_CLOUD_LOCATION。 [cite: 8]
export GOOGLE_GENAI_USE_VERTEXAI=true
export GOOGLE_CLOUD_PROJECT='your-project-id'
export GOOGLE_CLOUD_LOCATION='us-central1'
from google import genai
client = genai.Client()
API 版本选择
Vertex AI (v1):
from google import genai
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 Developer API (v1alpha):
from google import genai
from google.genai import types
# 仅为 Gemini Developer API 运行此块
client = genai.Client(
api_key='YOUR_GEMINI_API_KEY',
http_options=types.HttpOptions(api_version='v1alpha')
)
生成内容
使用文本内容:
response = client.models.generate_content(
model='gemini-2.0-flash-001', # 根据需要选择模型
contents='天空为什么是蓝色的?'
)
print(response.text)
[cite: 13]
使用上传的文件 (仅限 Gemini Developer API):
!wget -q https://storage.googleapis.com/generativeai-downloads/data/a11.txt
然后,在 Python 中上传并使用文件:
file = client.files.upload(file='a11.txt')
response = client.models.generate_content(
model='gemini-2.0-flash-001', # 根据需要选择模型
contents=['请总结这个文件内容。', file]
)
print(response.text)
系统指令和配置
可以通过 generate_content 的 config 参数来影响模型输出,例如设置 max_output_tokens 或 temperature。
from google.genai import types
response = client.models.generate_content(
model='gemini-2.0-flash-001',
contents='我说高',
config=types.GenerateContentConfig(
system_instruction='我说高,你说低',
max_output_tokens=3,
temperature=0.3,
),
)
print(response.text)
更多关于模型能力和参数默认值的信息,请参阅:
函数调用
SDK 支持函数调用,允许模型与外部工具或 API 交互。
自动 Python 函数支持:
from google.genai import types
def get_current_weather(location: str) -> str:
"""返回当前天气。
Args:
location: 城市和州,例如 San Francisco, CA
"""
return '晴朗' # 示例实现
response = client.models.generate_content(
model='gemini-2.0-flash-001',
contents='波士顿现在天气怎么样?',
config=types.GenerateContentConfig(
tools=[get_current_weather],
),
)
print(response.text)
[cite: 37]
禁用自动函数调用:
from google.genai import types
# (get_current_weather 函数如上定义)
response = client.models.generate_content(
model='gemini-2.0-flash-001',
contents='波士顿现在天气怎么样?',
config=types.GenerateContentConfig(
tools=[get_current_weather],
automatic_function_calling=types.AutomaticFunctionCallingConfig(
disable=True
),
),
)
# response.function_calls 将包含函数调用部分
JSON 响应模式
可以要求模型以 JSON 格式返回响应,并可选择提供 Pydantic 模型或字典作为模式。 [cite: 52, 53]
from pydantic import BaseModel
from google.genai import types
class CountryInfo(BaseModel):
name: str
population: int
capital: str
# ... 其他字段
response = client.models.generate_content(
model='gemini-2.0-flash-001',
contents='告诉我关于美国的信息。',
config=types.GenerateContentConfig(
response_mime_type='application/json',
response_schema=CountryInfo,
),
)
print(response.text) # 将会是 JSON 字符串
[cite: 52]
流式生成内容
模型可以流式传输输出,而不是一次性返回所有内容。
文本内容流式处理:
for chunk in client.models.generate_content_stream(
model='gemini-2.0-flash-001', contents='给我讲一个300字的故事。'
):
print(chunk.text, end='')
错误处理
SDK 提供了 APIError 类来处理模型引发的错误。
from google.genai import errors # 假设 errors 模块已导入或可用
try:
client.models.generate_content(
model="invalid-model-name",
contents="你叫什么名字?",
)
except errors.APIError as e:
print(f"API Error Code: {e.code}")
print(f"API Error Message: {e.message}")
其他功能
Google Gen AI Python SDK 还支持许多其他高级功能,包括:
作者:这儿有一堆花