Agent Platform SDK for Python:2.0.1 版遷移指南

google-cloud-aiplatform 套件包含 AI Platform SDK for Python 和 Gemini Enterprise Agent Platform Python 用戶端程式庫。本頁面涵蓋 google-cloud-aiplatform 套件的下列變更類別:

  • 生成式 AI 模組移至 Google Gen AI SDKvertexai 套件中的下列生成式 AI 模組已淘汰,並遷移至 Google Gen AI SDK (google-genai):

    • vertexai.generative_models
    • vertexai.language_models
    • vertexai.vision_models
    • vertexai.caching
    • vertexai.tuning

    如要瞭解如何將已淘汰的模組遷移至 Google Gen AI SDK,請參閱「將生成式 AI 模組遷移至 Google Gen AI SDK」。

  • 代理程式介面重組:我們對 google-cloud-aiplatformagentplatform 模組進行了以下變更:

    • 重新命名
    • 升級至頂層
    • 移除全域初始化器

    如要瞭解如何遷移至新的 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-aiplatformgoogle-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):

  1. 設定 google-cloud-aiplatform < 2.0.0,這樣不相關的依附元件升級就不會移除您底下的模組。

  2. 在程式碼中搜尋已淘汰的模組:

    • vertexai.generative_models
    • vertexai.language_models
    • vertexai.vision_models
    • vertexai.caching
    • vertexai.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 執行測試套件,找出您遺漏的匯入項目。

  3. 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=global
    
    from 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_bucketexperimentencryption_spec_key_nameservice_accountnetworkgenai.Client 沒有對應的項目。
    • 較新的 enterprise=True 拼字方式自 google-genai 2.20.0 起已可接受,但舊版 vertexai=True 適用於所有版本,是較安全的選擇。
  4. 稽核程式碼,找出行為發生差異但沒有錯誤的無聲變更。這些程式碼會編譯並執行,但會改變意義。

    行為 早於 晚於
    response.text 封鎖或空白的回覆 發出 ValueError 傳回 None
    response.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,
        )
    
  5. 如果您使用評估、Agent Runtime、提示、資料集、技能和整個傳統機器學習介面,請保留 google-cloud-aiplatform

  6. 將呼叫變更為新版本。先進行機械式重新命名,然後繼續進行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_messagesend_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_config
    • safety_settings
    • tools
    • tool_config
    • labels
    • system_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()]

  • 列舉會以純字串形式接受並強制轉換。

  • 純量欄位名稱則維持不變:temperaturetop_ptop_kcandidate_countmax_output_tokensstop_sequencespresence_penaltyfrequency_penaltyseedresponse_mime_typeresponse_schemaresponse_logprobslogprobs

  • 沒有舊版對應項目的新欄位包括 thinking_configcached_contentautomatic_function_callinghttp_optionsmedia_resolutionspeech_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_typetypes.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_executionurl_contextgoogle_mapscomputer_usefile_searchenterprise_web_searchmcp_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_typetitle 現在是依要求計費,因此混合工作批次必須拆分成多個呼叫。
  • 傳回類型已從直接清單變更為回應物件。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_tokensresponse.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.stateJOB_STATE_* 字串。
  • 批次重新命名:source_modelmodelinput_datasetsrcoutput_uri_prefixconfig.destjob_display_nameconfig.display_name
  • 新版 SDK 移除了批次機器形狀控制項,且沒有對應的項目。machine_typeaccelerator_typeaccelerator_countstarting_replica_countmax_replica_count 不再是 CreateBatchJobConfig 的欄位。
  • 下列方法已重新命名:
    • sft.trainclient.tunings.tune
    • source_modelbase_model
    • train_datasettraining_dataset
    • epochsepoch_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-aiplatformagentplatform 模組,請按照下列建議遷移至新的 SDK 結構:

  1. google-cloud-agentplatform 現在是獨立的輕量型發行版本,建議您安裝這個版本來處理代理程式工作負載。如果不需要使用傳統機器學習介面,請將安裝項目從 pip install google-cloud-aiplatform 切換為 pip install google-cloud-agentplatform

  2. 請使用下表更新匯入項目和屬性路徑:

    返回 新增
    client.agent_engines.create client.runtimes.create (在 Gemini Enterprise Agent Platform 執行個體上部署 Agent Runtime,提供內建工作階段、Sandbox 程式碼執行和內容記憶體設定)
    client.memory_banks.create (建立獨立的 Memory Bank 資源,用於保存、管理及擷取互動中的記憶)
    client.agent_engines.sandboxes client.sandboxes
    client.agent_engines.sandboxes.snapshots client.sandboxes.snapshots
    client.agent_engines.sandboxes.templates client.sandboxes.templates
    client.agent_engines.sessions client.sessions
    client.agent_engines.sessions.events client.sessions.events
    client.agent_engines.runtimes.revisions client.runtimes.revisions
    client.agent_engines.memories client.memory_banks.memories
    agentplatform.agent_engines.templates agentplatform.frameworks
  3. 系統會移除全域初始設定,代理程式架構也不會再從 aiplatform.init()vertexai.init() 狀態讀取專案和位置。對於在代理程式架構內執行的任何項目,請將衍生自初始設定的設定替換為環境變數。如果程式碼依賴初始值設定已部署的代理程式,系統會無聲無息地中斷,而不是引發錯誤。

  4. 更新 evals.run_inference(agent=...) 呼叫網站以傳遞 types.Runtime,因為 SDK 不再接受 types.AgentEngine

  5. 進行下列變更:

    • vertexai.Clientagentplatform.Client
    • vertexai.ragagentplatform.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(...)
    
  6. 更新 AdkApp 和工作階段呼叫的錯誤處理機制。同步工作階段方法和串流代理程式執行作業現在會顯示基礎 API 錯誤。擷取一般包裝錯誤的呼叫端不再相符。將一般程式庫包裝函式例外狀況的擷取內容,替換為 google.api_core.exceptions.GoogleAPICallError (或 ResourceExhaustedNotFound 等特定狀態錯誤)。

  7. 更新用戶端呼叫端或中介軟體,在每個要求中加入使用者的 OAuth 存取權杖,因為權杖現在是暫時性的,不會與工作階段狀態一起保存。確保權杖更新作業是在用戶端管理。

  8. 請注意,a2a.tasks 模組已移除,且沒有任何更換內容。