当前位置: 首页 > news >正文

Google Gen AI Python SDK 开发教程

简介

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 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 genaiclient = genai.Client()

API 版本选择

Vertex AI (v1):

from google import genai
from 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 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)
  • 示例文件链接: 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 BaseModel
from google.genai import typesclass CountryInfo(BaseModel):name: strpopulation: intcapital: 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]

相关文章:

  • 代码案例分析
  • 内容中台智能推荐系统构建与演进
  • 大学之大:墨西哥国立自治大学2025.5.18
  • 串口通讯协议学习
  • 通过觅思文档项目实现Obsidian文章浏览器在线访问
  • 代码随想录-数组
  • Qt 信号和槽-核心知识点小结(11)
  • 创业分析平台Web端-三大前端核心语言详解-首页index
  • 71. 简化路径
  • 低功耗模式介绍
  • Kotlin协程异常处理全解析
  • 渗透测试核心技术:信息收集与扫描
  • 计算机系统的工作原理
  • 学习wps的书写格式(题目黑体,加粗,三号)
  • Python列表全面解析:从入门到精通
  • defer关键字:延迟调用机制-《Go语言实战指南》
  • 【android bluetooth 协议分析 01】【HCI 层介绍 4】【LeSetEventMask命令介绍】
  • C++实现伽罗华域生成及四则运算(二)
  • UI架构的历史与基础入门
  • 楼宇【复习】
  • 吴双评《发展法学》|穷国致富的钥匙:制度,还是产业活动?
  • 前四月国家铁路发送货物12.99亿吨,同比增长3.6%
  • 三人在共享单车上印小广告被拘,北京警方专项打击非法小广告
  • 外媒:哈马斯一名高级指挥官尸体被发现,系辛瓦尔弟弟
  • 盐城经济技术开发区党工委书记王旭东接受纪律审查和监察调查
  • 首映|《星际宝贝史迪奇》真人电影,不变的“欧哈纳”