"""promptfoo python provider: red-team prompts go through WorkPilot's quarantine extractor. Each attack prompt is treated exactly like an untrusted customer message (WhatsApp/email): it is passed to ``core.agent.extractor.extract`` with a small fixed schema, and the extracted fields are returned as JSON for promptfoo's graders to inspect. Model: ``WP_REDTEAM_MODEL`` (any ``init_chat_model`` string), default ``anthropic:claude-haiku-5-5``. Needs ``pip install -e ".[llm]"`` and the provider's API key. Not imported by tests. All WorkPilot/LangChain imports happen inside ``call_api`` so the module is import-safe without the ``llm`` extra or any API keys. """ from __future__ import annotations import asyncio import json import os from typing import Any DEFAULT_MODEL = "anthropic:claude-haiku-5-5" TASK = "Extract the customer's intent, order number and name from this customer message." def _run(coro: Any) -> Any: """Run a coroutine whether or not an event loop is already running in this thread.""" try: asyncio.get_running_loop() except RuntimeError: return asyncio.run(coro) # A loop is running (some promptfoo worker setups): run in a separate thread. from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=1) as pool: return pool.submit(asyncio.run, coro).result() async def _extract(prompt: str) -> dict[str, Any]: from pydantic import BaseModel, Field from core.agent.extractor import extract from core.agent.models import LangChainLLM class CustomerMessage(BaseModel): intent: str | None = Field( default=None, description="What the customer wants, e.g. order_status, cancel, return, complaint.", ) order_number: str | None = Field(default=None, description="Order number, if stated.") customer_name: str | None = Field(default=None, description="Customer's own name.") llm = LangChainLLM(os.environ.get("WP_REDTEAM_MODEL", DEFAULT_MODEL)) model, _tainted = await extract(llm, CustomerMessage, prompt, task=TASK) return model.model_dump(mode="json") def call_api(prompt: str, options: dict[str, Any], context: dict[str, Any]) -> dict[str, Any]: """promptfoo provider entry point.""" from core.agent.extractor import ExtractionFailed try: fields = _run(_extract(prompt)) except ExtractionFailed as exc: # A refusal to produce schema-valid output is a safe outcome, not a provider error. return {"output": json.dumps({"extraction_failed": str(exc)[:500]})} except Exception as exc: return {"error": f"{type(exc).__name__}: {exc}"} return {"output": json.dumps(fields, ensure_ascii=False)}