ADK 的 环境 模拟: 评 测 时 拦截 工具, 换 成 可 控 回复
环境模拟器在工具真正执行前拦截调用。注入配置按顺序匹配参数和概率,概率默认 1.0,延迟不超过 120 秒;都不命中时才用 LLM 按工具模式生成回复。工具不在配置里则返回 None,真工具照常执行。

本文目录
ADK 的环境模拟:评测时拦截工具,换成可控回复
评测依赖外部依赖的智能体时,例如 API、数据库或第三方服务,测试里真跑这些工具会慢、贵,或者不稳定。环境模拟器(Environment Simulator)让你在智能体执行期间安全地拦截这些工具调用,换成受控、确定的回复,而不改智能体本身。它可以补上智能体改进循环里的一块缺口:做出封闭、离线的测试运行,把智能体逻辑隔离开来,以便稳定打分。封闭(hermetic)是指运行不碰外部服务。本页在 ADK Python v1.24.0 中支持。ADK(Agent Development Kit)是 Google 的智能体开发工具包。
整体上,这个功能让你:
- 测试智能体如何处理 API 错误或边界回复。
- 在没有线上后端的情况下离线跑评测。
- 用一个大语言模型(LLM,按提示生成文字的模型)自动生成接近真实的模拟回复。
- 给概率注入设种子,得到可重复的测试运行。种子是固定随机序列起点的整数。
环境模拟通过 before_tool_callback 钩子或插件系统接进 ADK 的工具执行流水线,因此不用改智能体代码。钩子是工具真正执行前会被调用的函数。插件是挂到应用上的扩展。
它如何工作
用户模拟推动对话往前走,环境模拟提供稳定的后端。从高层看,环境模拟器坐在智能体和它的工具之间。智能体调用工具时,模拟器拦截这次调用,决定是返回合成回复——预先写好的注入,或 LLM 生成的模拟——还是让真工具执行。
对每个已配置的工具,判定按这个顺序:
- 先按顺序检查注入配置。如果找到匹配的注入(依据参数匹配和概率),立刻返回它的错误或回复。
- 没有注入配置适用时,用模拟策略作退路。模拟器调用 LLM,按工具的模式和有状态的上下文生成接近真实的回复。模式(schema)是工具参数和返回值的结构说明。
- 工具不在模拟器配置里时,返回空操作(
None),让真工具照常执行。
接入
EnvironmentSimulationFactory 提供两个接入点:
create_callback():返回一个异步可调用对象,适合作为任何LlmAgent上的before_tool_callback。create_plugin():返回一个EnvironmentSimulationPlugin实例,接入 ADK 插件系统。
用作回调
下面的例子把环境模拟做成 ADK 智能体的回调之一。
from google.adk.agents import LlmAgent
from google.adk.tools.environment_simulation import EnvironmentSimulationFactory
from google.adk.tools.environment_simulation.environment_simulation_config import (
EnvironmentSimulationConfig,
InjectedError,
InjectionConfig,
ToolSimulationConfig,
)
config = EnvironmentSimulationConfig(
tool_simulation_configs=[
ToolSimulationConfig(
tool_name="get_user_profile",
injection_configs=[
InjectionConfig(
injected_error=InjectedError(
injected_http_error_code=503,
error_message="Service temporarily unavailable.",
)
)
],
)
]
)
agent = LlmAgent(
name="my_agent",
model="gemini-flash-latest",
tools=[get_user_profile],
before_tool_callback=EnvironmentSimulationFactory.create_callback(config),
)用作插件
下面的例子把环境模拟做成 ADK 智能体插件。
from google.adk.apps import App
from google.adk.tools.environment_simulation import EnvironmentSimulationFactory
from google.adk.tools.environment_simulation.environment_simulation_config import (
EnvironmentSimulationConfig,
MockStrategy,
ToolSimulationConfig,
)
config = EnvironmentSimulationConfig(
tool_simulation_configs=[
ToolSimulationConfig(
tool_name="search_products",
mock_strategy_type=MockStrategy.MOCK_STRATEGY_TOOL_SPEC,
)
]
)
app = App(
name="my_app",
root_agent=my_agent,
plugins=[EnvironmentSimulationFactory.create_plugin(config)],
)配置参考
可以用一组数据类配置环境模拟器。下面各节给出每个配置对象的参考。数据类是主要用来装字段的 Python 类。
EnvironmentSimulationConfig
顶层配置对象。
| 字段 | 类型 | 默认 | 说明 |
|---|---|---|---|
tool_simulation_configs | List[ToolSimulationConfig] | 必填 | 每个要模拟的工具一条。不能为空,工具名必须唯一。 |
simulation_model | str | "gemini-flash-latest" | 用来做工具连接分析和生成模拟回复的 LLM。 |
simulation_model_configuration | GenerateContentConfig | 开启思考 | 模拟器内部调用的 LLM 生成配置。 |
environment_data | str | None` | None |
tracing | str | None` | None |
ToolSimulationConfig
定义一个具名工具应如何被模拟。
| 字段 | 类型 | 默认 | 说明 |
|---|---|---|---|
tool_name | str | 必填 | 必须与工具注册名完全一致。 |
injection_configs | List[InjectionConfig] | [] | 零条或多条注入配置,在模拟策略之前按顺序检查。 |
mock_strategy_type | MockStrategy | MOCK_STRATEGY_UNSPECIFIED | 没有注入被触发时的退路策略。 |
InjectionConfig
控制可以注入到一次工具调用里的单条合成回复。injected_error 和 injected_response 必须恰好设置其中一个。
| 字段 | 类型 | 默认 | 说明 |
|---|---|---|---|
injected_error | InjectedError | None` | None |
injected_response | Dict[str, Any] | None` | None |
injection_probability | float | 1.0 | 这条注入触发的概率,范围 [0.0, 1.0]。 |
match_args | Dict[str, Any] | None` | None |
injected_latency_seconds | float | 0.0 | 返回注入结果前加上的人为延迟,不超过 120 秒。 |
random_seed | int | None` | None |
InjectedError
定义一种 HTTP 风格的错误回复。
| 字段 | 类型 | 说明 |
|---|---|---|
injected_http_error_code | int | 要露出的 HTTP 状态码,在工具回复里作为 "error_code"。 |
error_message | str | 给人看的消息,在工具回复里作为 "error_message"。 |
MockStrategy
没有注入触发时,控制模拟器如何生成回复的枚举。
| 值 | 说明 |
|---|---|
MOCK_STRATEGY_TOOL_SPEC | 用工具模式和有状态上下文提示 LLM,生成接近真实的回复。 |
MOCK_STRATEGY_TRACING | 已弃用。请改用带轨迹输入的 MOCK_STRATEGY_TOOL_SPEC。 |
注入模式
用注入配置测试特定的失败或边界情形。注入按列表顺序评估;第一条满足 match_args、并且通过概率检查的,会被应用。
注入错误
下面的例子向智能体注入指定错误码和错误消息。
from google.adk.tools.environment_simulation.environment_simulation_config import (
InjectedError,
InjectionConfig,
ToolSimulationConfig,
)
ToolSimulationConfig(
tool_name="charge_payment",
injection_configs=[
InjectionConfig(
injected_error=InjectedError(
injected_http_error_code=402,
error_message="Payment declined.",
)
)
],
)智能体收到的是 {"error_code": 402, "error_message": "Payment declined."},而不是真工具结果,于是可以评测它如何处理支付失败。
注入固定回复
用下面的 InjectionConfig 指定一条带固定载荷的成功回复。
InjectionConfig(
injected_response={"status": "ok", "order_id": "ORD-9999"}
)按参数条件注入
用 match_args 只在传入特定参数时注入。
InjectionConfig(
match_args={"item_id": "ITEM-404"},
injected_error=InjectedError(
injected_http_error_code=404,
error_message="Item not found.",
),
)这里,只有工具以 item_id="ITEM-404" 被调用时才注入错误。其余调用进入下一条注入配置,或进入模拟策略。
概率注入
把 injection_probability 设在 0.0 和 1.0 之间,用来模拟不稳定行为。要让测试可重复,用 random_seed 钉住随机结果。
InjectionConfig(
injection_probability=0.3,
random_seed=42,
injected_error=InjectedError(
injected_http_error_code=500,
error_message="Internal server error.",
),
)注入延迟
用 injected_latency_seconds 模拟慢后端,便于测试超时处理,或降级条件下的使用体验。
InjectionConfig(
injected_latency_seconds=5.0,
injected_response={"result": "slow but successful"},
)组合多条注入配置
同一个工具上的多条注入配置按顺序检查。可以把它们合起来测多种情形:
ToolSimulationConfig(
tool_name="get_inventory",
injection_configs=[
# Always fail for a specific out-of-stock item
InjectionConfig(
match_args={"sku": "OOS-001"},
injected_response={"quantity": 0, "available": False},
),
# Randomly fail 20% of the time for all other items
InjectionConfig(
injection_probability=0.2,
random_seed=7,
injected_error=InjectedError(
injected_http_error_code=503,
error_message="Inventory service unavailable.",
),
),
],
)模拟策略模式
想让模拟器自动生成说得通的回复,而不是返回手写的值时,用 MOCK_STRATEGY_TOOL_SPEC。
模拟器用一个 LLM 做三件事:
- 分析智能体能用的全部工具的模式,并识别它们之间的有状态依赖。例如
create_order产出一个order_id,get_order再消费它。 - 跟踪会话期间创建的标识和资源,放进一个状态库。
- 生成与工具模式和当前状态一致的回复。如果消费方工具请求一个从未创建的资源,就返回 404 风格的错误。
from google.adk.tools.environment_simulation.environment_simulation_config import (
EnvironmentSimulationConfig,
MockStrategy,
ToolSimulationConfig,
)
config = EnvironmentSimulationConfig(
tool_simulation_configs=[
ToolSimulationConfig(
tool_name="create_order",
mock_strategy_type=MockStrategy.MOCK_STRATEGY_TOOL_SPEC,
),
ToolSimulationConfig(
tool_name="get_order",
mock_strategy_type=MockStrategy.MOCK_STRATEGY_TOOL_SPEC,
),
ToolSimulationConfig(
tool_name="cancel_order",
mock_strategy_type=MockStrategy.MOCK_STRATEGY_TOOL_SPEC,
),
]
)用这份配置,模拟 create_order 时会自动生成一个 order_id;之后调用 get_order 或 cancel_order 时,用它返回一致的结果,或返回未找到错误。
提供环境数据
通过 environment_data 传入领域上下文,让模拟回复更真实。它可以是表示数据库快照的 JSON 字符串,或 LLM 生成回复时应使用的任何结构化上下文。
import json
db_snapshot = {
"products": [
{"id": "P-001", "name": "Wireless Headphones", "price": 79.99, "stock": 12},
{"id": "P-002", "name": "USB-C Hub", "price": 34.99, "stock": 0},
],
"warehouse_location": "US-WEST-2",
}
config = EnvironmentSimulationConfig(
tool_simulation_configs=[
ToolSimulationConfig(
tool_name="search_products",
mock_strategy_type=MockStrategy.MOCK_STRATEGY_TOOL_SPEC,
),
],
environment_data=json.dumps(db_snapshot),
)LLM 会用这些数据返回与你的领域相符的产品名、价格和库存,而不是任意占位值。
提供轨迹数据
把要被模拟的智能体产生的轨迹通过 tracing 喂进去,让模拟回复更真实。
import json
agent_traces = [
{
"invocation_id": "inv-001",
"user_content": {"role": "user", "parts": [{"text": "Search for high-end headphones"}]},
"intermediate_data": {
"tool_uses": [
{
"name": "search_products",
"args": {"query": "high-end headphones"},
"response": {"products": [{"id": "P-123", "name": "Premium Wireless ANC Headphones"}]}
}
]
}
}
]
config = EnvironmentSimulationConfig(
tool_simulation_configs=[
ToolSimulationConfig(
tool_name="search_products",
mock_strategy_type=MockStrategy.MOCK_STRATEGY_TOOL_SPEC,
),
],
tracing=json.dumps(agent_traces),
)LLM 会用这些数据返回与你的领域相符的产品名、价格和库存,而不是任意占位值。
把注入和模拟策略混用
同一个工具上可以同时有注入配置和模拟策略。注入总是先检查;只有没有任何注入适用时,才触发模拟策略。
ToolSimulationConfig(
tool_name="send_notification",
injection_configs=[
# Always fail for a known-bad recipient
InjectionConfig(
match_args={"recipient_id": "INVALID"},
injected_error=InjectedError(
injected_http_error_code=400,
error_message="Invalid recipient.",
),
),
],
# For all other recipients, generate a plausible success response
mock_strategy_type=MockStrategy.MOCK_STRATEGY_TOOL_SPEC,
)出处:Google,Environment simulation for evaluations,2026-11-10,https://adk.dev/evaluate/environment_simulation/,Apache License 2.0。
觉得有用,转给同事
微信扫码
用微信扫一扫,在手机上打开后即可转发。