google-cloud-aiplatform 套件包含 AI 平台 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現在是獨立的輕量發行版,建議用於代理工作負載。如果只建構代理,請安裝不含生成式 AI 模組的google-cloud-agentplatform。agentplatform模組涵蓋常見的整合項目,例如[adk]、[a2a]、[agent_engines]、[langchain]、[ag2]、[llama_index]、[evaluation]、[bigquery]、[live]和[all]。
不受影響的項目
傳統機器學習介面 (資料集、訓練、模型、預測、追蹤、管道) 獲得完整支援,不受 2.0.1 版異動影響,且 Google Gen AI SDK 中沒有對應項目。您還是可以安裝 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()。Before
# 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沒有類似功能。google-genai2.20.0 版起接受較新的enterprise=True拼寫,但舊版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變更。每個包覆在.text周圍的try/except ValueError都會變成無效程式碼,而每個未受保護的.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。
Before
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]。每個區塊都是完整的回應物件,其 .text 屬性有時可能是 None,因此請先使用 if chunk.text: 檢查,再存取文字。
Before
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:。
Before
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)是新方法,在舊版中沒有對應項目。
Before
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 中,system_instruction是在建構GenerativeModel時設定一次。現在,每次呼叫都必須傳遞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。
Before
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傳遞內嵌位元組。
Before
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。
Before
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。
Before
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為基準)。- 新增
client.models.compute_tokens(...),用於詞元 ID 和字串片段。 離線計數功能是透過
google.genai.local_tokenizer.LocalTokenizer新增。
Before
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會傳回新物件,而不是就地變動。
Before
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"。
Before
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,提供內建工作階段、沙箱程式碼執行和內容記憶體設定)
client.memory_banks.create(建立獨立的 Agent Platform 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 錯誤。呼叫端擷取一般包裝錯誤時,不會再比對。將一般程式庫包裝函式例外狀況的 catch 替換為google.api_core.exceptions.GoogleAPICallError(或ResourceExhausted和NotFound等特定狀態錯誤)。更新用戶端呼叫端或中介軟體,在每項要求中加入使用者的 OAuth 存取權杖,因為權杖現在是暫時性的,不會與工作階段狀態一起保留。確保在用戶端管理權杖更新。
請注意,
a2a.tasks模組已移除,且沒有任何更換內容。