此示例演示了如何使用 Scenario 框架进行基于仿真的代理测试。Scenario 使您能够模拟代理、用户模拟器和裁判之间的对话,从而在受控环境中轻松测试和评估代理行为。
提示: 想要查看更高级的场景?请查看 Customer support 场景示例,其中包含更复杂的代理,包括工具调用和高级场景功能。
import pytest
import scenario
from agno.agent import Agent
from agno.models.openai import OpenAIChat
# 配置 Scenario 默认值(用户模拟器和裁判的模型)
scenario.configure(default_model="openai/gpt-4.1-mini")
@pytest.mark.agent_test
@pytest.mark.asyncio
async def test_vegetarian_recipe_agent() -> None:
# 1. 定义一个 AgentAdapter 来包装您的代理
class VegetarianRecipeAgentAdapter(scenario.AgentAdapter):
agent: Agent
def __init__(self) -> None:
self.agent = Agent(
model=OpenAIChat(id="gpt-4.1-mini"),
markdown=True,
debug_mode=True,
instructions="你是一个素食食谱代理。",
)
async def call(self, input: scenario.AgentInput) -> scenario.AgentReturnTypes:
response = self.agent.run(
message=input.last_new_user_message_str(), # 只传递最后一个用户消息
session_id=input.thread_id, # 传递对话 ID,这允许代理跟踪历史记录
)
return response.content
# 2. 运行场景模拟
result = await scenario.run(
name="晚餐食谱请求",
description="用户正在寻找素食晚餐的想法。",
agents=[
VegetarianRecipeAgentAdapter(),
scenario.UserSimulatorAgent(),
scenario.JudgeAgent(
criteria=[
"代理不应提出超过两个后续问题",
"代理应生成食谱",
"食谱应包含配料列表",
"食谱应包含分步烹饪说明",
"食谱应为素食,不包含任何肉类",
]
),
],
)
# 3. 断言并检查结果
assert result.success
创建虚拟环境
打开 Terminal
并创建一个 python 虚拟环境。
python3 -m venv .venv
source .venv/bin/activate
设置您的 API 密钥
export OPENAI_API_KEY=xxx
export LANGWATCH_API_KEY=xxx # 可选,模拟监控要求
安装库
pip install -U openai agno langwatch-scenario pytest pytest-asyncio
# 或
uv add agno langwatch-scenario openai pytest
运行代理
pytest cookbook/agent_concepts/other/scenario_testing.py