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。
代理 Surface 重构:对
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]。
不受影响的方面
传统机器学习界面(数据集、训练、模型、预测、跟踪、流水线)受到全面支持,不受 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()。之前
# 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。
之前
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_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)
配置、安全设置和系统指令
请注意,配置、安全设置和系统指令任务有以下变化:
以下实参会作为
GenerateContentConfig的字段收起为一个config=: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。
之前
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()中仍然是必需的。只有 Gemini Developer API 支持
client.files.upload(...)。对于 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是惯用访问函数,当第 0 部分恰好是文本时,它不会失败。旧遍历仍然有效。- 原始 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())
Embeddings
请注意嵌入任务的以下变化:
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)
Token 计数
请注意,词元计数任务有以下变化:
total_billable_characters已移除,且没有替代项。任何以total_billable_characters为键的费用估算都必须通过生成调用进行重新计算(例如,针对total_tokens或response.usage_metadata)。- 为 token 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,该实例提供内置会话、沙盒代码执行和上下文记忆配置)
client.memory_banks.create(创建独立的 Agent Platform 记忆库资源,用于在互动过程中持久化、管理和检索记忆)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模块已被移除,且未提供任何替换项。