"""User simulator for multi-turn scenarios (tau-bench style, Phase 14). A scenario with a ``user`` block is a conversation: after each agent run the simulator reads what the agent sent the customer and writes the customer's next message, until it says it is done or ``max_turns`` is reached. Every turn becomes a new inbound event (the scenario's ``user.event`` template with ``text`` replaced), run through the real runtime. * :class:`ScriptedUserSimulator` (offline, CI): replies from ``user.script`` in order. Deterministic, so pass^k measures the system, not the simulator. * :class:`LLMUserSimulator` (``--user-sim live``): a pinned model at temperature 0 plays the persona. The model string is pinned (``USER_SIM_MODEL`` / ``WP_EVAL_USER_SIM_MODEL``) and printed in the report, because a different simulator changes the task distribution. """ from __future__ import annotations import os from typing import Any, Protocol from pydantic import BaseModel, Field # Pinned simulator model (override with WP_EVAL_USER_SIM_MODEL); reported in docs/evals.md. USER_SIM_MODEL = "anthropic:claude-haiku-5-5" class UserSpec(BaseModel): persona: str script: list[str] = Field(default_factory=list) # offline replies, in order max_turns: int = Field(default=3, ge=1) # Template of the inbound event for each turn (``text`` is set per turn). event: dict[str, Any] goal: str = "" # what the simulated customer wants (live simulator only) class UserTurn(BaseModel): message: str | None = Field(default=None, description="next message to the business") done: bool = Field(default=False, description="true when the goal is met or abandoned") class UserSimulator(Protocol): name: str async def next_turn( self, spec: UserSpec, transcript: list[tuple[str, str]], turn: int ) -> UserTurn: ... class ScriptedUserSimulator: name = "scripted" async def next_turn( self, spec: UserSpec, transcript: list[tuple[str, str]], turn: int ) -> UserTurn: if turn < len(spec.script): return UserTurn(message=spec.script[turn]) return UserTurn(done=True) SIM_SYSTEM = """\ You are role-playing a customer writing to a small business on WhatsApp or email. Persona: {persona} Goal: {goal} Rules: write ONE short message, in the persona's language and style. Never invent order numbers, prices or dates you were not given. When the goal is met, or the business says a human will follow up, set done=true and leave message empty.""" class LLMUserSimulator: """Real-model simulator (needs provider API keys); temperature 0, pinned model.""" def __init__(self, model: str | None = None) -> None: from core.agent.models import LangChainLLM self.name = model or os.environ.get("WP_EVAL_USER_SIM_MODEL", USER_SIM_MODEL) self._llm = LangChainLLM(self.name) async def next_turn( self, spec: UserSpec, transcript: list[tuple[str, str]], turn: int ) -> UserTurn: convo = "\n".join(f"{who}: {msg}" for who, msg in transcript) or "(no reply yet)" return await self._llm.structured( UserTurn, SIM_SYSTEM.format(persona=spec.persona, goal=spec.goal or "get help"), f"Conversation so far:\n{convo}\n\nYour next message:", ) def agent_replies(changes: list[dict[str, Any]]) -> list[str]: """Customer-facing text the agent produced in a diff: outbound message rows (any pack) and demo message effects.""" out: list[str] = [] for c in changes: if c["op"] != "insert": continue row = c["row"] if row.get("direction") == "outbound" and row.get("body"): out.append(str(row["body"])) elif c["table"] == "demo_effects" and row.get("kind") == "message": p = row.get("payload") or {} if p.get("body") or p.get("text"): out.append(str(p.get("body") or p.get("text"))) return out