譯者 | 火鳳凰
生成式 AI 模型正在改變我們創(chuàng)作內(nèi)容的方式,無(wú)論是文本、圖像、視頻還是代碼。通過(guò) Google 的 Gen AI Python SDK,你現(xiàn)在可以更輕松地在 Python 應(yīng)用程序中訪問(wèn)和交互 Google 的生成式 AI 模型,此外還可以使用 Gemini Developer API 和 Vertex AI API。這意味著開發(fā)者可以更便捷地創(chuàng)建應(yīng)用程序,包括聊天機(jī)器人、內(nèi)容生成器或創(chuàng)意工具。在本文中,我們將介紹開始使用 Google Gen AI Python SDK 所需了解的一切。
目錄
1.什么是 Google Gen AI Python SDK?
- 安裝
- 導(dǎo)入和客戶端設(shè)置
- 可選:使用 Google Cloud Vertex AI
- API 版本和配置
- 使用環(huán)境變量(可選)
2.Google Gen AI Python SDK 用例
- 內(nèi)容生成
- 文件上傳和使用
- 函數(shù)調(diào)用
- 高級(jí)配置
- 多媒體支持:圖像和視頻
- 聊天和對(duì)話
- 異步支持
- 令牌計(jì)數(shù)
- 嵌入
3.結(jié)論
什么是Google Gen AI Python SDK?
Google Gen AI Python SDK是一個(gè)客戶端庫(kù),讓開發(fā)者能夠使用Python輕松利用Google的生成式AI能力。它提供:
- 支持Gemini Developer API(Google的高級(jí)文本和多模態(tài)生成模型)
- 與Vertex AI API集成,支持企業(yè)級(jí)AI工作負(fù)載
- 支持生成文本、圖像、視頻、嵌入、聊天對(duì)話等
- 提供文件管理、緩存和異步支持工具
- 高級(jí)函數(shù)調(diào)用和模式執(zhí)行功能
該 SDK 還抽象了 API 調(diào)用的大部分復(fù)雜性,讓你專注于構(gòu)建AI驅(qū)動(dòng)的應(yīng)用程序。
安裝
安裝 SDK 很簡(jiǎn)單。運(yùn)行:
pip install google-genai上述命令將使用 pip 安裝 Google Gen AI Python SDK 包。此命令會(huì)下載 Python 環(huán)境啟動(dòng) Google 生成式 AI 服務(wù)所需的一切,包括資源和所有依賴項(xiàng)。
導(dǎo)入和客戶端設(shè)置
安裝 SDK 后,創(chuàng)建一個(gè) Python 文件并導(dǎo)入 SDK:
from google import genai
from google.genai import types該SDK包含兩個(gè)模塊:genai和types。genai模塊創(chuàng)建用于API交互的客戶端,而types模塊則包含用作構(gòu)建請(qǐng)求和配置請(qǐng)求參數(shù)的數(shù)據(jù)結(jié)構(gòu)和類。
每次與Google生成式AI模型進(jìn)行交互時(shí),你都需要?jiǎng)?chuàng)建一個(gè)客戶端實(shí)例。根據(jù)所使用的API不同,你將使用不同的方法來(lái)實(shí)例化客戶端。
對(duì)于Gemini Developer API,你可以通過(guò)傳遞API密鑰來(lái)實(shí)例化客戶端:
client = genai.Client(api_key='YOUR_GEMINI_API_KEY')實(shí)例化客戶端后,你可以通過(guò)傳入 API 密鑰與Gemini Developer API進(jìn)行交互。該客戶端將負(fù)責(zé)訪問(wèn)令牌和請(qǐng)求管理。
可選:使用 Google Cloud Vertex AI
client = genai.Client(
vertexai=True,
project='your-project-id',
location='us-central1'
)如果你要使用谷歌云 Vertex AI,你需要通過(guò)指定項(xiàng)目 ID 和位置來(lái)不同地初始化客戶端。
注意:Vertex AI 的使用是可選的。你可以在此處創(chuàng)建你的項(xiàng)目 ID。
如果你不使用 Vertex AI,你可以簡(jiǎn)單地使用上面的 API 密鑰方法。
API 版本和配置
默認(rèn)情況下,SDK 使用 beta 端點(diǎn)來(lái)訪問(wèn) beta 功能。但是,如果你想使用穩(wěn)定版本的 API,你可以通過(guò) http_options 參數(shù)來(lái)指定 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')
)如何在使用前沿功能的同時(shí)保持穩(wěn)定性,這取決于你想如何操作。
使用環(huán)境變量(可選)
我們應(yīng)該首先設(shè)置環(huán)境變量,而不是直接傳遞密鑰:
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 用例
設(shè)置完成后,你可以通過(guò)以下各種方式使用Google Gen AI Python SDK 的功能。
內(nèi)容生成
SDK 的主要功能是生成 AI 內(nèi)容。你可以通過(guò)各種形式提供提示,例如簡(jiǎn)單字符串、結(jié)構(gòu)化內(nèi)容或復(fù)雜的多模態(tài)輸入。
基本文本生成
response = client.models.generate_content(
model='gemini-2.0-flash-001',
contents='Why Does the sun rises from east'
)
print(response.text)輸出:

這會(huì)向模型發(fā)送提示并返回生成的答案。
結(jié)構(gòu)化內(nèi)容輸入
你可以在各種角色中插入結(jié)構(gòu)化內(nèi)容,例如用于聊天機(jī)器人、對(duì)話式或多輪對(duì)話場(chǎng)景的用戶或模型角色。
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 在內(nèi)部將許多不同的輸入類型轉(zhuǎn)換為模型所需的結(jié)構(gòu)化數(shù)據(jù)格式。
文件上傳和使用
Gemini Developer API允許你上傳文件供模型處理。這對(duì)于摘要或內(nèi)容提取非常有用:
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)輸出:

這是向基于文檔的任務(wù)添加 AI 功能的理想方法。
函數(shù)調(diào)用
一個(gè)獨(dú)特的功能是能夠?qū)?/span> Python 函數(shù)作為“工具”傳遞給模型,以便模型在生成完成時(shí)自動(dòng)調(diào)用。
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響應(yīng)能夠?qū)崿F(xiàn)動(dòng)態(tài)、實(shí)時(shí)的數(shù)據(jù)整合。
高級(jí)配置
你可以通過(guò)調(diào)節(jié)溫度、最大輸出標(biāo)記數(shù)和安全設(shè)置等參數(shù)來(lái)定制生成內(nèi)容,從而管理隨機(jī)性、長(zhǎng)度并過(guò)濾有害內(nèi)容。
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)輸出:

這可以提供內(nèi)容質(zhì)量和安全性的精細(xì)控制。
多媒體支持:圖片和視頻
SDK 允許你生成和編輯圖片以及生成視頻(預(yù)覽中)。
- 使用文本提示生成圖片
- 放大或調(diào)整生成的圖片
- 從文本或圖片生成視頻
圖片生成示例:
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()輸出:

這使得創(chuàng)建創(chuàng)新的多模式人工智能應(yīng)用程序成為可能。
聊天和對(duì)話
你可以啟動(dòng)聊天會(huì)話,并在聊天過(guò)程中保持上下文連貫:
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)
這對(duì)于創(chuàng)建能夠記住先前對(duì)話的會(huì)話式 AI 很有用。
異步支持
所有主要 API 方法都包含異步函數(shù),以便更好地集成到異步 Python 應(yīng)用程序中:
response = await client.aio.models.generate_content(
model='gemini-2.0-flash-001',
cnotallow='Tell a Horror story in 200 words.'
)
print(response.text)
令牌計(jì)數(shù)
令牌計(jì)數(shù)用于追蹤輸入文本中包含多少令牌(文本片段)。這有助于你在模型限制范圍內(nèi)進(jìn)行成本控制并做出經(jīng)濟(jì)高效的決策。
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)
嵌入
嵌入將文本轉(zhuǎn)換為代表其含義的數(shù)字向量,可用于搜索、聚類和 AI 評(píng)估。
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,你可以輕松計(jì)算令牌并生成嵌入,從而改進(jìn)和增強(qiáng)你的 AI 應(yīng)用程序。
結(jié)論
Google Gen AI Python SDK 是一個(gè)強(qiáng)大且多功能的工具,允許開發(fā)者在他們的 Python 項(xiàng)目中訪問(wèn) Google 頂級(jí)的生成式 AI 模型。從文本生成、聊天和聊天機(jī)器人,到圖片/視頻生成、函數(shù)調(diào)用等等,它通過(guò)簡(jiǎn)單的接口提供了豐富的功能集。通過(guò)簡(jiǎn)單的包安裝、便捷的客戶配置過(guò)程,以及支持異步編程和多媒體,該 SDK 顯著簡(jiǎn)化了構(gòu)建 AI 應(yīng)用程序的流程。無(wú)論你是初學(xué)者還是經(jīng)驗(yàn)豐富的開發(fā)者,使用該 SDK 在將生成式 AI 集成到工作流程中都相對(duì)輕松且功能強(qiáng)大。
原文標(biāo)題:Google Gen AI Python SDK: A Complete Guide,作者:Janvi Kumari
























