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现在是一个独立的轻量级发行版,建议安装此发行版来运行代理工作负载。如果您只构建智能体,请安装不包含生成式 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()。之前
# 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 密钥。- 模型名称从构造函数移到了每个调用中。没有 bind-once 模型对象。
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已安装。
基于任务的通话变更
查看根据任务更改的调用:
文本生成
对于文本生成任务,所有实参都只能是关键字实参。位置调用会引发 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 |
- 在
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_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)。- 为令牌 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(创建独立的记忆库资源,用于在互动中持久保存、管理和检索记忆)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模块已移除,且未提供任何替换项。