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_contentconfig 参数来影响模型输出,例如设置 max_output_tokenstemperature

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 还支持许多其他高级功能,包括:

  • 聊天 (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]
<think>好的,我现在要处理用户关于高通AI工具链的查询。用户想了解使用说明、文档、教程以及下载方式。首先,我需要回忆之前提供的引用内容,确保信息准确。 根据用户提供的引用[1]和[2],高通AI Hub的入门指南和Neural Processing SDK文档是重点。我需要先整理这两个主要资源。用户可能指的是AI工具链,可能包括SDKAI Hub,所以需要明确两者的区别和联系。 接下来,用户需要文档、教程和下载链接。我应该分步骤说明,先介绍高通AI Hub,说明如何访问和下载,然后转向Neural Processing SDK的文档和资源。同时,确保使用中文回答,结构清晰,段落不要太长。 还要注意生成相关问题,这部分需要围绕工具链的使用、优化、兼容性等方面提问。问题要具体,帮助用户深入探索。 需要检查链接是否正确,引用标识是否对应。例如,引用[1]对应AI Hub文档,引用[2]对应SDK文档。确保没有格式错误,比如代码块或LaTeX的正确使用,但用户问题中可能不涉及数学公式,所以可能不需要处理这部分。 最后,回答要符合用户可见层的要求,结构清晰,分步骤说明,确保信息真实可靠,引用正确来源。可能还需要提醒用户需要注册账户或满足系统要求,这些细节需要明确。</think>### 高通 AI 工具链使用说明 #### 1. **高通 AI Hub 入门指南** 高通 AI Hub 提供了预优化模型库和端到端部署工具链,支持开发者快速在骁龙设备上部署AI模型。 - **文档入口**:访问 [Getting started — qai-hub documentation](https://docs.qualcomm.com/bundle/public/resource/topics/ai_hub_getting_started.html) 查看入门教程[^1]。 - **功能特性**: - 支持模型量化、编译和性能分析。 - 提供预训练模型(如MobileNet、BERT)的直接部署示例。 - **下载方式**:需注册高通开发者账户,登录后从资源中心下载SDK和工具包[^1]。 #### 2. **Qualcomm Neural Processing SDK** 该SDK专注于在骁龙平台上优化AI推理性能,支持TensorFlow、PyTorch等框架的模型转换。 - **核心功能**: - 模型转换工具(DLC格式) - 硬件加速库(如Hexagon DSP优化) - **文档与教程**: - 参考 [Qualcomm Neural Processing SDK Documentation](https://developer.qualcomm.com/docs/neural-processing-sdk/) 获取详细API说明和代码示例[^2]。 - 包含从模型导出到设备部署的完整流程。 #### 3. **工具链使用步骤** 1. **环境配置**: - 安装Python 3.8+和依赖库(如qai-hub包)。 ```bash pip install qai-hub ``` 2. **模型部署示例**: - 使用AI Hub上传模型并选择目标设备(如骁龙8 Gen 2)。 ```python from qai_hub import deploy deploy(model="mobilenet_v2.onnx", device="snapdragon_8_gen2") ``` 3. **性能分析**: - 通过SDK生成推理时延和内存占用报告。 #### 4. **资源下载** - **AI Hub工具包**:通过 [Qualcomm开发者平台](https://developer.qualcomm.com/) 登录后下载。 - **Neural Processing SDK**:在 [官方页面](https://developer.qualcomm.com/software/neural-processing-sdk) 获取最新版本[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值