此示例演示了如何使用 Scenario 框架进行基于代理的模拟测试。Scenario 使您能够模拟代理、用户模拟器和裁判之间的对话,从而在受控环境中轻松测试和评估代理行为。

提示: 有关更高级的场景测试示例,请查看 客户支持场景,其中包含更复杂的代理,包括工具调用和高级场景功能。

基本场景测试

cookbook/agent_concepts/other/scenario_testing.py
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, # 传递 thread id,这允许代理跟踪历史记录
            )
            return response.content

    # 2. 运行场景模拟
    result = await scenario.run(
        name="晚餐食谱请求",
        description="用户正在寻找素食晚餐的想法。",
        agents=[
            VegetarianRecipeAgentAdapter(),
            scenario.UserSimulatorAgent(),
            scenario.JudgeAgent(
                criteria=[
                    "代理不应提出超过两个后续问题",
                    "代理应生成食谱",
                    "食谱应包括配料表",
                    "食谱应包含分步烹饪说明",
                    "食谱应为素食,不含任何肉类",
                ]
            ),
        ],
    )

    # 3. 断言并检查结果
    assert result.success

使用方法

1

创建虚拟环境

打开 Terminal 并创建一个 python 虚拟环境。

python3 -m venv .venv
source .venv/bin/activate
2

设置您的 API 密钥

export OPENAI_API_KEY=xxx
export LANGWATCH_API_KEY=xxx # 可选,模拟监控必需
3

安装库

pip install -U openai agno langwatch-scenario pytest pytest-asyncio
# 或
uv add agno langwatch-scenario openai pytest
4

运行 Agent

pytest cookbook/agent_concepts/other/scenario_testing.py