譯者 | 火鳳凰
生成式 AI 模型正在改變我們創作內容的方式,無論是文本、圖像、視頻還是代碼。通過 Google 的 Gen AI Python SDK,你現在可以更輕松地在 Python 應用程序中訪問和交互 Google 的生成式 AI 模型,此外還可以使用 Gemini Developer API 和 Vertex AI API。這意味著開發者可以更便捷地創建應用程序,包括聊天機器人、內容生成器或創意工具。在本文中,我們將介紹開始使用 Google Gen AI Python SDK 所需了解的一切。
目錄
1.什么是 Google Gen AI Python SDK?
- 安裝
- 導入和客戶端設置
- 可選:使用 Google Cloud Vertex AI
- API 版本和配置
- 使用環境變量(可選)
2.Google Gen AI Python SDK 用例
- 內容生成
- 文件上傳和使用
- 函數調用
- 高級配置
- 多媒體支持:圖像和視頻
- 聊天和對話
- 異步支持
- 令牌計數
- 嵌入
3.結論
什么是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 包。此命令會下載 Python 環境啟動 Google 生成式 AI 服務所需的一切,包括資源和所有依賴項。
導入和客戶端設置
安裝 SDK 后,創建一個 Python 文件并導入 SDK:
from google import genai
from google.genai import types該SDK包含兩個模塊:genai和types。genai模塊創建用于API交互的客戶端,而types模塊則包含用作構建請求和配置請求參數的數據結構和類。
每次與Google生成式AI模型進行交互時,你都需要創建一個客戶端實例。根據所使用的API不同,你將使用不同的方法來實例化客戶端。
對于Gemini Developer API,你可以通過傳遞API密鑰來實例化客戶端:
client = genai.Client(api_key='YOUR_GEMINI_API_KEY')實例化客戶端后,你可以通過傳入 API 密鑰與Gemini Developer API進行交互。該客戶端將負責訪問令牌和請求管理。
可選:使用 Google Cloud Vertex AI
client = genai.Client(
vertexai=True,
project='your-project-id',
location='us-central1'
)如果你要使用谷歌云 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 Developer 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', cnotallow=content)
print(response.text)輸出:

SDK 在內部將許多不同的輸入類型轉換為模型所需的結構化數據格式。
文件上傳和使用
Gemini Developer API允許你上傳文件供模型處理。這對于摘要或內容提取非常有用:
file = client.files.upload(file='/content/sample_file.txt')
response = client.models.generate_content(
model='gemini-2.0-flash-001',
cnotallow=[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',
cnotallow='What is the weather like in Ranchi?',
cnotallow=types.GenerateContentConfig(tools=[get_current_weather])
)
print(response.text)輸出:

這使得AI響應能夠實現動態、實時的數據整合。
高級配置
你可以通過調節溫度、最大輸出標記數和安全設置等參數來定制生成內容,從而管理隨機性、長度并過濾有害內容。
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',
cnotallow='''Offer some encouraging words for someone starting a new journey.''',
cnotallow=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.',
cnotallow=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.',
cnotallow=types.GenerateVideosConfig(number_of_videos=1, duration_secnotallow=5)
)
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
video = operation.response.generated_videos[0].video
video.show()輸出:

這使得創建創新的多模式人工智能應用程序成為可能。
聊天和對話
你可以啟動聊天會話,并在聊天過程中保持上下文連貫:
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',
cnotallow='Tell a Horror story in 200 words.'
)
print(response.text)
令牌計數
令牌計數用于追蹤輸入文本中包含多少令牌(文本片段)。這有助于你在模型限制范圍內進行成本控制并做出經濟高效的決策。
token_count = client.models.count_tokens(
model='gemini-2.0-flash-001',
cnotallow='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',
cnotallow='Why does the sky have a blue hue instead of other colors?'
)
print(embedding)
使用 SDK,你可以輕松計算令牌并生成嵌入,從而改進和增強你的 AI 應用程序。
結論
Google Gen AI Python SDK 是一個強大且多功能的工具,允許開發者在他們的 Python 項目中訪問 Google 頂級的生成式 AI 模型。從文本生成、聊天和聊天機器人,到圖片/視頻生成、函數調用等等,它通過簡單的接口提供了豐富的功能集。通過簡單的包安裝、便捷的客戶配置過程,以及支持異步編程和多媒體,該 SDK 顯著簡化了構建 AI 應用程序的流程。無論你是初學者還是經驗豐富的開發者,使用該 SDK 在將生成式 AI 集成到工作流程中都相對輕松且功能強大。
原文標題:Google Gen AI Python SDK: A Complete Guide,作者:Janvi Kumari























