google-cloud-aiplatform 套件包含 AI Platform SDK for Python 和 Gemini Enterprise Agent Platform Python 用戶端程式庫。本頁面涵蓋 google-cloud-aiplatform 套件的下列變更類別:
生成式 AI 模組移至 Google Gen AI SDK:
vertexai套件中的下列生成式 AI 模組已淘汰,並遷移至 Google Gen AI SDK (google-genai):vertexai.generative_modelsvertexai.language_modelsvertexai.vision_modelsvertexai.cachingvertexai.tuning
如要瞭解如何將已淘汰的模組遷移至 Google Gen AI SDK,請參閱「將生成式 AI 模組遷移至 Google Gen AI SDK」。
代理程式介面重組:我們對
google-cloud-aiplatform的agentplatform模組進行了以下變更:- 重新命名
- 升級至頂層
- 移除全域初始化器
如要瞭解如何遷移至新的 SDK 結構,請參閱「Agent Platform SDK 結構重整」。
agentplatform解除耦合:google-cloud-agentplatform現在是獨立的輕量型發布版本,建議您安裝這個版本來處理代理程式工作負載。如果您只建構代理程式,請安裝google-cloud-agentplatform,其中不含生成式 AI 模組。agentplatform模組涵蓋常見的整合項目,例如[adk]、[a2a]、[agent_engines]、[langchain]、[ag2]、[llama_index]、[evaluation]、[bigquery]、[live]和[all]。
不受影響的項目
Google Gen AI SDK 沒有對應項目,但經典機器學習介面 (資料集、訓練、模型、預測、追蹤、管道) 完全不受 2.0.1 版變更影響,仍可正常運作。您還是可以安裝 google-cloud-aiplatform,存取評估、Agent Runtime、提示和技能。google-cloud-aiplatform 和 google-genai 都存在於同一個環境中,而 google-genai 現在是 google-cloud-aiplatform 的硬性依附元件:
import agentplatform
client = agentplatform.Client(project="my-project", location="global")
# client.evals client.prompts
# client.prompt_optimizer client.datasets client.skills
vertexai.batch_prediction 並未淘汰,但 Google Gen AI SDK 也有對應功能,且是建議使用的工具。
將生成式 AI 模組移至 Google Gen AI SDK
如果您使用 google-cloud-aiplatform 套件中的生成式 AI 模組,請按照下列建議遷移至 Google Gen AI SDK (google-genai):
設定
google-cloud-aiplatform < 2.0.0,這樣不相關的依附元件升級就不會移除您底下的模組。在程式碼中搜尋已淘汰的模組:
vertexai.generative_modelsvertexai.language_modelsvertexai.vision_modelsvertexai.cachingvertexai.tuning
如果您匯入任何受影響的 Python 模組,就會收到下列淘汰警告:
UserWarning: This feature is deprecated as of June 24, 2025 and will be removed on June 24, 2026. For details, see https://cloud.google.com/vertex-ai/generative-ai/docs/deprecations/genai-vertexai-sdk.使用
-W error::UserWarning執行測試套件,找出您遺漏的匯入項目。將
vertexai.init(...)替換為明確的genai.Client(enterprise=True, project=..., location=...)。如果您也使用傳統機器學習介面,請保留vertexai.init()。事前
# pip install google-cloud-aiplatform import vertexai from vertexai.generative_models import GenerativeModel vertexai.init(project="my-project", location="us-central1") # Model identity and config are bound at construction time. model = GenerativeModel("gemini-2.5-flash")完成後
# pip install google-genai from google import genai from google.genai import types client = genai.Client( enterprise=True, project="my-project", location="global", )或從環境設定:
export GOOGLE_GENAI_USE_ENTERPRISE=true export GOOGLE_CLOUD_PROJECT=my-project export GOOGLE_CLOUD_LOCATION=globalfrom google import genai client = genai.Client()重要注意事項:
- 全域狀態會成為明確的用戶端。
vertexai.init()設定整個程序;genai.Client()是您傳遞的物件。使用genai.Client()時,您可以在一個程序中使用兩個專案或區域。 - 「
enterprise=True」是必填欄位。如果省略,用戶端會以無訊息方式指定 Gemini Developer API,然後在應用程式預設憑證上失敗,或要求 API 金鑰。 - 模型名稱會從建構階段移至每次呼叫。沒有繫結一次的模型物件。
model=是每次client.models.*呼叫時的必要關鍵字引數。 - 驗證方式維持不變。應用程式預設憑證仍適用,且
credentials=在兩個 SDK 中都接受google.auth.credentials.Credentials。 vertexai.init()也包含非生成式設定,例如staging_bucket、experiment、encryption_spec_key_name、service_account、network。genai.Client沒有對應的項目。- 較新的
enterprise=True拼字方式自google-genai2.20.0 起已可接受,但舊版vertexai=True適用於所有版本,是較安全的選擇。
- 全域狀態會成為明確的用戶端。
稽核程式碼,找出行為發生差異但沒有錯誤的無聲變更。這些程式碼會編譯並執行,但會改變意義。
行為 早於 晚於 response.text封鎖或空白的回覆發出 ValueError傳回 Noneresponse.text包含多位候選人發出 ValueError記錄警告,傳回第一個候選項目 指定目標客戶 vertexai.init()隱含 Agent Platform省略 vertexai=True會以無聲方式指定 Gemini Developer API嵌入 auto_truncate預設值為 True未設定;套用伺服器預設值 以工具形式傳遞的 Python 函式 不支援 由 SDK 自動執行 system_instruction模型上繫結一次 每次呼叫都必須傳遞 請先搜尋
response.text變更。凡是包在try/except ValueError中的.text都會變成無效程式碼,而每個未受保護的.text現在都可以產生None,先前則是傳回str:if response.text is None: print( "blocked or empty:", response.prompt_feedback, response.candidates[0].finish_reason if response.candidates else None, )如果您使用評估、Agent Runtime、提示、資料集、技能和整個傳統機器學習介面,請保留
google-cloud-aiplatform。將呼叫變更為新版本。先進行機械式重新命名,然後繼續進行
config=合併。
以工作為主的通話異動
根據工作查看變更後的呼叫:
文字生成
如果是文字生成工作,所有引數都只能是關鍵字。位置呼叫會引發 TypeError。
事前
model = GenerativeModel("gemini-2.5-flash")
response = model.generate_content("Why is the sky blue?")
print(response.text)
完成後
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="Why is the sky blue?",
)
print(response.text)
生成串流
如果是串流生成工作,系統會移除 stream=True 旗標。串流現在是傳回 Iterator[types.GenerateContentResponse] 的獨立方法。存取文字前,請先使用 if chunk.text: 檢查,因為每個區塊都是完整的回應物件,且 .text 屬性有時可能是 None。
事前
stream = model.generate_content("Tell me a story in 300 words.", stream=True)
for chunk in stream:
print(chunk.text, end="")
完成後
for chunk in client.models.generate_content_stream(
model="gemini-3.5-flash",
contents="Tell me a story in 300 words.",
):
if chunk.text:
print(chunk.text, end="")
非同步生成
對於非同步生成工作,系統已移除 _async 方法名稱後置字元。每個非同步呼叫都會位於 client.aio.<module> 下方,且方法名稱與對應的同步呼叫相同。使用 await client.aio.aclose() 關閉用戶端,或使用 async with genai.Client(...).aio as aclient:。
事前
response = await model.generate_content_async("Why is the sky blue?")
async_stream = await model.generate_content_async("Why is the sky blue?", stream=True)
async for chunk in async_stream:
print(chunk.text, end="")
完成後
response = await client.aio.models.generate_content(
model="gemini-3.5-flash",
contents="Why is the sky blue?",
)
# Note the `await` in front of the async iterator.
async for chunk in await client.aio.models.generate_content_stream(
model="gemini-3.5-flash",
contents="Tell me a story in 300 words.",
):
print(chunk.text, end="")
即時通訊工作階段
請注意,聊天工作階段工作有以下異動:
- 對話是從用戶端建立,而不是從模型物件建立。
chat.history(屬性) 會變成chat.get_history()(方法)。新方法會採用curated: bool = False。傳遞True只會傳回保留的回合,沒有舊版對應項目。client.aio.chats.create(...)會直接傳回AsyncChat。系統只會等待send_message和send_message_stream。- 每回合的選項會摺疊成一個引數:
send_message(message, config=types.GenerateContentConfig(...))。第一個參數也從content重新命名為message。 start_chat(response_validation=False)是新方法,舊版沒有對應項目。
事前
model = GenerativeModel("gemini-2.5-flash")
chat = model.start_chat()
print(chat.send_message("Tell me a story").text)
for content in chat.history:
print(content.role, content.parts)
完成後
chat = client.chats.create(model="gemini-3.5-flash")
print(chat.send_message("Tell me a story").text)
for content in chat.get_history():
print(content.role, content.parts)
設定、安全設定和系統指令
請注意,設定、安全防護設定和系統指令工作有以下變更:
下列引數會摺疊成一個
config=,做為GenerateContentConfig的欄位:generation_configsafety_settingstoolstool_configlabelssystem_instruction
純
dict可在任何設定類型適用的位置運作。system_instruction會從模型建構函式移至每次呼叫的設定。在舊版 SDK 中,建構GenerativeModel時會設定一次system_instruction。現在,每次呼叫時都必須傳遞system_instruction,或將其納入client.chats.create(config=...)中。安全設定從
dict變更為list。例如:[types.SafetySetting(category=c, threshold=t) for c, t in old_dict.items()]。列舉會以純字串形式接受並強制轉換。
純量欄位名稱則維持不變:
temperature、top_p、top_k、candidate_count、max_output_tokens、stop_sequences、presence_penalty、frequency_penalty、seed、response_mime_type、response_schema、response_logprobs、logprobs。沒有舊版對應項目的新欄位包括
thinking_config、cached_content、automatic_function_calling、http_options、media_resolution和speech_config。
事前
from vertexai.generative_models import (
GenerativeModel, GenerationConfig, HarmCategory, HarmBlockThreshold,
)
model = GenerativeModel(
"gemini-2.5-flash",
system_instruction=["Talk like a pirate.", "Don't use rude words."],
)
response = model.generate_content(
contents="Why is the sky blue?",
generation_config=GenerationConfig(temperature=0, top_p=0.95, max_output_tokens=100),
safety_settings={
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
},
)
完成後
from google.genai import types
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="Why is the sky blue?",
config=types.GenerateContentConfig(
system_instruction="Talk like a pirate. Don't use rude words.",
temperature=0,
top_p=0.95,
max_output_tokens=100,
safety_settings=[
types.SafetySetting(
category="HARM_CATEGORY_HATE_SPEECH",
threshold="BLOCK_MEDIUM_AND_ABOVE",
),
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=types.HarmBlockThreshold.BLOCK_ONLY_HIGH,
),
],
),
)
多模態輸入內容
請注意,多模態輸入工作有下列異動:
| 舊優惠 | 新增 |
|---|---|
Part.from_uri(uri, mime_type),允許位置 |
Part.from_uri(file_uri=, mime_type=)、僅限關鍵字、參數已重新命名 |
Part.from_data(data, mime_type) |
Part.from_bytes(data=, mime_type=),方法已重新命名 |
Part.from_text(text) |
Part.from_text(text=),僅限關鍵字 |
Image.load_from_file(path) |
沒有對應功能,請開啟檔案並使用 Part.from_bytes |
mime_type在types.Part.from_uri()中為選填屬性 (伺服器端會推斷),但在types.Part.from_bytes()中仍為必填屬性。client.files.upload(...)僅支援 Gemini Developer API。對於 Agent Platform 工作負載,請繼續使用from_uri傳遞 Cloud Storage URI,或使用from_bytes傳遞內嵌位元組。
事前
from vertexai.generative_models import GenerativeModel, Part, Image
image = Image.load_from_file("image.jpg")
print(model.generate_content(["What is shown in this image?", image]).text)
image_part = Part.from_uri(
"gs://cloud-samples-data/generative-ai/image/scones.jpg",
mime_type="image/jpeg",
)
完成後
from google.genai import types
# Image.load_from_file has no equivalent: read the bytes yourself.
with open("image.jpg", "rb") as f:
image = types.Part.from_bytes(data=f.read(), mime_type="image/jpeg")
response = client.models.generate_content(
model="gemini-3.5-flash",
contents=["What is shown in this image?", image],
)
image_part = types.Part.from_uri(
file_uri="gs://cloud-samples-data/generative-ai/image/scones.jpg",
mime_type="image/jpeg",
)
函式呼叫和建立基準
請注意,函式呼叫和基礎工作有下列異動:
- 工具會移至「
config=」。呼叫或模型物件上沒有tools=引數。 - 「
Tool.from_google_search_retrieval(grounding.GoogleSearchRetrieval())」變成「types.Tool(google_search=types.GoogleSearch())」。工廠方法會變成一般欄位。types.Tool也有獨立的google_search_retrieval欄位。 response.function_calls是慣用的存取子,且當第零部分剛好是文字時,不會失敗。舊版遍歷仍可運作。- 原始 JSON 結構定義是在
parameters_json_schema中指定。parameters中指定了已輸入的types.Schema。 - 您現在可以將 Python 函式當做工具傳遞,且傳遞函式時,系統預設會開啟自動函式呼叫功能。如果您移植手動工具迴圈並傳遞函式物件,SDK 就會開始執行程式碼。使用
automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)停用預設的自動函式呼叫功能。 下列新工具類型在舊版中沒有對應項目:
code_execution、url_context、google_maps、computer_use、file_search、enterprise_web_search、mcp_servers。
事前
from vertexai.generative_models import GenerativeModel, FunctionDeclaration, Tool, grounding
weather_tool = Tool(function_declarations=[
FunctionDeclaration(
name="get_current_weather",
description="Get the current weather in a given location",
parameters={
"type": "object",
"properties": {"location": {"type": "string"}},
"required": ["location"],
},
)
])
model = GenerativeModel("gemini-2.5-flash", tools=[weather_tool])
response = model.generate_content("What is the weather in Boston?")
call = response.candidates[0].content.parts[0].function_call
# Grounding
search_tool = Tool.from_google_search_retrieval(grounding.GoogleSearchRetrieval())
完成後
from google.genai import types
weather_tool = types.Tool(function_declarations=[
types.FunctionDeclaration(
name="get_current_weather",
description="Get the current weather in a given location",
parameters_json_schema={
"type": "object",
"properties": {"location": {"type": "string"}},
"required": ["location"],
},
)
])
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="What is the weather in Boston?",
config=types.GenerateContentConfig(tools=[weather_tool]),
)
call = response.function_calls[0]
# Grounding
search_tool = types.Tool(google_search=types.GoogleSearch())
嵌入
請注意,嵌入工作有以下異動:
- 已移除「
TextEmbeddingInput」。task_type和title現在是依要求計費,因此混合工作批次必須拆分成多個呼叫。 - 傳回類型已從直接清單變更為回應物件。
get_embeddings()直接傳回list[TextEmbedding],因此呼叫端會直接為清單建立索引 (embeddings[0].values)。在新版本中,embed_content()會傳回包含.embeddings清單的EmbedContentResponse物件,因此您必須存取response.embeddings[0].values。個別嵌入欄位 (.values和.statistics) 會保留原始名稱。 auto_truncate不再預設為True。新欄位預設為unset。如果您依賴過長輸入內容的無聲截斷,請明確設定auto_truncate。
事前
from vertexai.language_models import TextEmbeddingModel, TextEmbeddingInput
model = TextEmbeddingModel.from_pretrained("gemini-embedding-001")
text_input = TextEmbeddingInput(
text="How do I get a driver's license?",
task_type="RETRIEVAL_DOCUMENT", # per input
title="Driver's License", # per input
)
embeddings = model.get_embeddings([text_input], output_dimensionality=3072, auto_truncate=True)
print(embeddings[0].values)
完成後
from google.genai import types
response = client.models.embed_content(
model="gemini-embedding-2",
contents="How do I get a driver's license?",
config=types.EmbedContentConfig(
task_type="RETRIEVAL_DOCUMENT", # now per request
title="Driver's License", # now per request
output_dimensionality=3072,
auto_truncate=True,
),
)
print(response.embeddings[0].values)
計算權杖
請注意,權杖計數工作有以下異動:
total_billable_characters已移除,且沒有任何更換內容。凡是根據total_billable_characters鍵入的任何費用估算值,都必須從生成呼叫中重新計算 (例如根據total_tokens或response.usage_metadata)。- 已為權杖 ID 和字串片段新增
client.models.compute_tokens(...)。 透過
google.genai.local_tokenizer.LocalTokenizer新增離線計算。
事前
model = GenerativeModel("gemini-2.5-flash")
response = model.count_tokens(["Why is the sky blue?"])
print(response.total_tokens)
print(response.total_billable_characters)
完成後
response = client.models.count_tokens(
model="gemini-3.5-flash",
contents=["Why is the sky blue?"],
)
print(response.total_tokens)
print(response.cached_content_token_count)
脈絡快取
請注意,內容快取工作有下列異動:
ttl會將類型從datetime.timedelta變更為持續時間字串,例如"86400s"。- 資源物件方法會變成用戶端模組呼叫。
update會傳回新物件,而不是就地變動。
事前
import datetime
from vertexai.caching import CachedContent
cache = CachedContent.create(
model_name="gemini-2.5-flash",
system_instruction="Please answer my question formally",
contents=contents,
ttl=datetime.timedelta(days=1),
)
cache.update(ttl=datetime.timedelta(days=2))
cache.delete()
完成後
from google.genai import types
cache = client.caches.create(
model="gemini-3.5-flash",
config=types.CreateCachedContentConfig(
contents=contents,
system_instruction="Please answer my question formally",
ttl="86400s",
),
)
cache = client.caches.update(
name=cache.name, config=types.UpdateCachedContentConfig(ttl="172800s")
)
client.caches.delete(name=cache.name)
批次預測和微調
請注意批次預測和微調工作的下列異動:
- 輪詢是根據重新繫結,而非就地進行。沒有
job.refresh()和job.has_ended。從client.batches.get(name=...)擷取新物件,並比較job.state與JOB_STATE_*字串。 - 批次重新命名:
source_model為model、input_dataset為src、output_uri_prefix為config.dest、job_display_name為config.display_name。 - 新版 SDK 移除了批次機器形狀控制項,且沒有對應的項目。
machine_type、accelerator_type、accelerator_count、starting_replica_count和max_replica_count不再是CreateBatchJobConfig的欄位。 - 下列方法已重新命名:
sft.train至client.tunings.tunesource_model至base_modeltrain_dataset至training_datasetepochs至epoch_count
- 調整用資料集已封裝。空白
"gs://..."字串會變成types.TuningDataset(gcs_uri=...)。 adapter_size會將類型從int變更為列舉字串,例如"ADAPTER_SIZE_FOUR"。
事前
from vertexai.batch_prediction import BatchPredictionJob
from vertexai.tuning import sft
job = BatchPredictionJob.submit(
source_model="gemini-2.5-flash",
input_dataset="bq://my-project.my-dataset.my-table",
output_uri_prefix="bq://my-project.my-dataset.output",
)
while not job.has_ended:
job.refresh()
tuning_job = sft.train(
source_model="gemini-2.5-flash",
train_dataset="gs://bucket/train.jsonl",
epochs=1,
adapter_size=4,
)
完成後
from google.genai import types
job = client.batches.create(
model="gemini-3.5-flash",
src="bq://my-project.my-dataset.my-table",
config=types.CreateBatchJobConfig(dest="bq://my-project.my-dataset.output"),
)
completed = {"JOB_STATE_SUCCEEDED", "JOB_STATE_FAILED", "JOB_STATE_CANCELLED", "JOB_STATE_PAUSED"}
while job.state not in completed:
job = client.batches.get(name=job.name)
tuning_job = client.tunings.tune(
base_model="gemini-3.5-flash",
training_dataset=types.TuningDataset(gcs_uri="gs://bucket/train.jsonl"),
config=types.CreateTuningJobConfig(
epoch_count=1,
adapter_size="ADAPTER_SIZE_FOUR",
),
)
Agent Platform SDK 重組
如果您使用 google-cloud-aiplatform 的 agentplatform 模組,請按照下列建議遷移至新的 SDK 結構:
google-cloud-agentplatform現在是獨立的輕量型發行版本,建議您安裝這個版本來處理代理程式工作負載。如果不需要使用傳統機器學習介面,請將安裝項目從pip install google-cloud-aiplatform切換為pip install google-cloud-agentplatform。請使用下表更新匯入項目和屬性路徑:
返回 新增 client.agent_engines.createclient.runtimes.create(在 Gemini Enterprise Agent Platform 執行個體上部署 Agent Runtime,提供內建工作階段、Sandbox 程式碼執行和內容記憶體設定)
client.memory_banks.create(建立獨立的 Memory Bank 資源,用於保存、管理及擷取互動中的記憶)client.agent_engines.sandboxesclient.sandboxesclient.agent_engines.sandboxes.snapshotsclient.sandboxes.snapshotsclient.agent_engines.sandboxes.templatesclient.sandboxes.templatesclient.agent_engines.sessionsclient.sessionsclient.agent_engines.sessions.eventsclient.sessions.eventsclient.agent_engines.runtimes.revisionsclient.runtimes.revisionsclient.agent_engines.memoriesclient.memory_banks.memoriesagentplatform.agent_engines.templatesagentplatform.frameworks系統會移除全域初始設定,代理程式架構也不會再從
aiplatform.init()或vertexai.init()狀態讀取專案和位置。對於在代理程式架構內執行的任何項目,請將衍生自初始設定的設定替換為環境變數。如果程式碼依賴初始值設定已部署的代理程式,系統會無聲無息地中斷,而不是引發錯誤。更新
evals.run_inference(agent=...)呼叫網站以傳遞types.Runtime,因為 SDK 不再接受types.AgentEngine。進行下列變更:
vertexai.Client至agentplatform.Clientvertexai.rag至agentplatform.Client().rag
vertexai.Client會在首次例項化時發出FutureWarning:The vertexai.Client class is deprecated. Please use agentplatform.Client instead.vertexai.rag會在匯入模組時發出UserWarning,而不是在呼叫時發出。遷移至下列項目:import agentplatform client = agentplatform.Client(project="your-project", location="global") client.rag.create_corpus(...)更新
AdkApp和工作階段呼叫的錯誤處理機制。同步工作階段方法和串流代理程式執行作業現在會顯示基礎 API 錯誤。擷取一般包裝錯誤的呼叫端不再相符。將一般程式庫包裝函式例外狀況的擷取內容,替換為google.api_core.exceptions.GoogleAPICallError(或ResourceExhausted和NotFound等特定狀態錯誤)。更新用戶端呼叫端或中介軟體,在每個要求中加入使用者的 OAuth 存取權杖,因為權杖現在是暫時性的,不會與工作階段狀態一起保存。確保權杖更新作業是在用戶端管理。
請注意,
a2a.tasks模組已移除,且沒有任何更換內容。