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 现在是一个独立的轻量级发行版,建议安装此发行版来运行代理工作负载。如果您只构建智能体,请安装不包含生成式 AI 模块的 google-cloud-agentplatformagentplatform 模块涵盖了常见的集成,例如 [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-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 密钥。
    • 模型名称从构造函数移到了每个调用中。没有 bind-once 模型对象。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 会话

请注意聊天会话任务的以下变化:

  • 对话是从客户端创建的,而不是从模型对象创建的。
  • 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)

配置、安全设置和系统指令

请注意,配置、安全设置和系统指令任务有以下变化:

  • 以下实参会折叠为 GenerateContentConfig 的字段,并合并为一个 config=

    • generation_config
    • safety_settings
    • tools
    • tool_config
    • labels
    • system_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()]

  • 枚举可作为纯字符串接受并强制转换。

  • 标量字段名称保持不变: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
  • types.Part.from_uri() 中,mime_type 是可选的(在服务器端推断),但在 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",
)

函数调用和接地

请注意以下针对函数调用和 grounding 任务的更改:

  • 工具移至 config=。调用或模型对象上没有 tools= 实参。
  • Tool.from_google_search_retrieval(grounding.GoogleSearchRetrieval()) 变为 types.Tool(google_search=types.GoogleSearch())。工厂方法变为普通字段。types.Tool 还有一个单独的 google_search_retrieval 字段。
  • response.function_calls 是惯用的访问器,当第 0 部分恰好是文本时,不会失败。旧的遍历方式仍然有效。
  • 原始 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())

Embeddings

请注意以下嵌入任务的变化:

  • 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)

token 计数

请注意,对于令牌计数任务,有以下变化:

  • 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_model 重命名为 model,将 input_dataset 重命名为 src,将 output_uri_prefix 重命名为 config.dest,将 job_display_name 重命名为 config.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,该实例提供内置的会话、沙盒代码执行和上下文记忆配置)
    client.memory_banks.create(创建独立的记忆库资源,用于在互动中持久保存、管理和检索记忆)
    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 错误。捕获一般封装错误的调用方不再匹配。将针对通用库封装容器异常的 catch 替换为 google.api_core.exceptions.GoogleAPICallError(或特定状态错误,如 ResourceExhaustedNotFound)。

  7. 更新客户端调用方或中间件,以在每个请求中包含用户的 OAuth 访问令牌,因为令牌现在是临时性的,不会随会话状态一起保留。确保在客户端管理令牌刷新。

  8. 请注意,a2a.tasks 模块已移除,且未提供任何替换项。