> 技术文档 > Google Gen AI Python SDK 开发教程_from google import genai

Google Gen AI Python SDK 开发教程_from google import genai


简介

Google Gen AI Python SDK (google-genai) 是一个 Python 客户端库,用于与 Google 的生成式 AI API 进行交互。它为开发者提供了一个接口,以便将 Google 的生成模型(支持 Gemini Developer API 和 Vertex AI API)集成到他们的 Python 应用程序中。

相关链接

  • Google Gen AI SDK GitHub 仓库: https://github.com/googleapis/python-genai [cite: 1]

安装

要开始使用,请通过 pip 安装 SDK:

pip install google-genai

导入库

导入必要的模块:

from google import genaifrom 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=trueexport GOOGLE_CLOUD_PROJECT=\'your-project-id\'export GOOGLE_CLOUD_LOCATION=\'us-central1\'
from google import genaiclient = genai.Client()

API 版本选择

Vertex AI (v1):

from google import genaifrom google.genai import typesclient = 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 genaifrom 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)
  • 示例文件链接: https://storage.googleapis.com/generativeai-downloads/data/a11.txt [cite: 14]

系统指令和配置

可以通过 generate_contentconfig 参数来影响模型输出,例如设置 max_output_tokenstemperature

from google.genai import typesresponse = 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)

更多关于模型能力和参数默认值的信息,请参阅:

  • Vertex AI 文档: https://cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/2-5-flash [cite: 32]
  • Gemini API 文档: https://ai.google.dev/gemini-api/docs/models [cite: 32]

函数调用

SDK 支持函数调用,允许模型与外部工具或 API 交互。

自动 Python 函数支持:

from google.genai import typesdef 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 BaseModelfrom google.genai import typesclass 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}\")
  • APIError 参考: https://github.com/googleapis/python-genai/blob/main/google/genai/errors.py [cite: 88]

其他功能

Google Gen AI Python SDK 还支持许多其他高级功能,包括:

  • 聊天 (Chats): 用于多轮对话。 [cite: 69]
  • 文件 (Files): 上传、获取和删除文件 (仅限 Gemini Developer API)。 [cite: 73]
  • 缓存 (Caches): 用于缓存内容以提高性能和降低成本。 [cite: 75]
  • 微调 (Tunings): 支持监督式微调模型。 [cite: 80]
  • Imagen: 生成和编辑图像。 [cite: 64, 66]
  • Veo: 生成视频。 [cite: 68]
  • 批量预测 (Batch Prediction): (仅限 Vertex AI)。 [cite: 85]