Skip to contentSkip to page list

Docs

Write Scenarios in Code

Write scenarios with the Scenario SDK in Python or TypeScript, run them with your test runner, and see every run in LangWatch.

On this page

Quick setup? Copy the scenarios prompt into your coding agent to add scenario tests automatically.

The Scenario SDK is open source and runs inside your own test runner and CI. To run scenarios from the platform against your agent's HTTP endpoint instead, with no test code, see Connect your agent.

This guide will walk you through the basic setup required to run your first scenario and see the results in LangWatch.

For advanced use cases, see the scenario library documentation.

1. Installation

Install the scenario library in your project:

bash uv add langwatch-scenario

2. Configure Environment Variables

Create a .env file in the root of your project:

.envBash
LANGWATCH_API_KEY="your-api-key"LANGWATCH_ENDPOINT="https://app.langwatch.ai"

You can find your LANGWATCH_API_KEY in your LangWatch project settings.

3. Create a Basic Scenario

Create an agent adapter that calls your agent, then run a scenario against it. For the integration patterns, see the agent integration guide.

example.pyPython
import pytestimport scenarioimport litellm​# Configure the default model for simulationsscenario.configure(default_model="openai/gpt-6-luna")​@pytest.mark.agent_test@pytest.mark.asyncioasync def test_vegetarian_recipe_agent():    # 1. Create your agent adapter    class RecipeAgent(scenario.AgentAdapter):        async def call(self, input: scenario.AgentInput) -> scenario.AgentReturnTypes:            return vegetarian_recipe_agent(input.messages)​    # 2. Run the scenario    result = await scenario.run(        name="dinner recipe request",        description="""            It's saturday evening, the user is very hungry and tired,            but have no money to order out, so they are looking for a recipe.        """,        agents=[            RecipeAgent(),            scenario.UserSimulatorAgent(),            scenario.JudgeAgent(criteria=[                "Agent should not ask more than two follow-up questions",                "Agent should generate a recipe",                "Recipe should include a list of ingredients",                "Recipe should include step-by-step cooking instructions",                "Recipe should be vegetarian and not include any sort of meat",            ])        ],    )​    # 3. Assert the result    assert result.success​# Example agent implementation using litellm@scenario.cache()def vegetarian_recipe_agent(messages) -> scenario.AgentReturnTypes:    response = litellm.completion(        model="openai/gpt-6-luna",        messages=[            {                "role": "system",                "content": """                    You are a vegetarian recipe agent.                    Given the user request, ask AT MOST ONE follow-up question,                    then provide a complete recipe. Keep your responses concise and focused.                """,            },            *messages,        ],    )    return response.choices[0].message

Run the test. The scenario run appears under Agent Testing > Results in your LangWatch project.

4. Grouping Your Scenarios into Test Suites and Batches

Set stable identifiers for your scenarios, test suites and batches, so LangWatch groups the runs the same way every time:

  • id: A unique and stable identifier for your scenario. Without it, the id comes from the name, and renaming the test starts a new history.
  • setId: The test suite of the scenario. It appears under From Code on the Scenarios tab, and its runs go under a run plan of the same name on the Results tab.
  • batchId: Groups every scenario run together in one execution, for example one CI job. A CI variable such as process.env.GITHUB_RUN_ID is a good value.
A From Code test suite on the Scenarios tab, with the scenarios of the setId and their last run
example.pyPython
import os​result = await scenario.run(    id="vegetarian-recipe-scenario",    name="dinner recipe request",    description="Test that the agent can provide vegetarian recipes.",    set_id="recipe-test-suite",    batch_id=os.environ.get("GITHUB_RUN_ID", "local-run"),    agents=[        RecipeAgent(),        scenario.UserSimulatorAgent(),        scenario.JudgeAgent(criteria=[            "Agent should generate a recipe",            "Recipe should be vegetarian",        ])    ])

5. Let the Judge Read Your Traces

When your adapter calls an agent that runs as a separate service, the judge cannot see what happens inside it. Turn on trace fetching and the judge also reads the traces your agent reports to LangWatch, one per conversation turn, before its verdict:

example.pyPython
scenario.configure(    default_model="openai/gpt-6-luna",    fetch_remote_traces=True,    trace_wait_timeout=60.0,  # seconds to wait for traces before the verdict)

Spread input.propagation_headers (Python) or input.propagationHeaders (TypeScript) onto your adapter's outgoing HTTP request, so the remote service joins each turn's trace. Linking your traces covers the mechanism, the wait behavior, and how to write trace-aware criteria.

Also check: Evaluators on Scenarios in the Scenario documentation, for an evaluator declared in the test itself that grades every run against a golden answer, with the same mappings and the same gate as one attached on the platform.

Documentation