diff --git a/.changeset/chat-ui-stream.md b/.changeset/chat-ui-stream.md new file mode 100644 index 0000000..d4ad5e7 --- /dev/null +++ b/.changeset/chat-ui-stream.md @@ -0,0 +1,5 @@ +--- +"web": minor +--- + +API: `POST /chat` streams answers in the AI SDK UI message stream protocol (tool parts, evidence data parts, streamed text, Weave trace link), on one agent loop shared with `POST /ask`. diff --git a/.changeset/pack-check.md b/.changeset/pack-check.md new file mode 100644 index 0000000..d9e5641 --- /dev/null +++ b/.changeset/pack-check.md @@ -0,0 +1,5 @@ +--- +"web": minor +--- + +API: after a seal the agent checks the pack clip against the order lines and stores a verdict in `proofbox.checks`, served at `GET /packs/{pack_id}/check`. diff --git a/apps/api/pyproject.toml b/apps/api/pyproject.toml index 1d17483..56523bb 100644 --- a/apps/api/pyproject.toml +++ b/apps/api/pyproject.toml @@ -55,6 +55,7 @@ combine-as-imports = true [tool.pyrefly] python-version = "3.14" project-includes = ["src", "tests"] +search-path = ["tests"] [dependency-groups] dev = ["httpx2>=2.13.1", "pyrefly>=1.4.0", "pytest>=9.1.1", "ruff>=0.17.1"] diff --git a/apps/api/src/proofbox_api/__init__.py b/apps/api/src/proofbox_api/__init__.py index 97cc85d..276de32 100644 --- a/apps/api/src/proofbox_api/__init__.py +++ b/apps/api/src/proofbox_api/__init__.py @@ -1,12 +1,14 @@ import asyncio +import faulthandler import secrets +import signal from collections.abc import AsyncIterator from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import UTC, datetime from importlib.metadata import version from pathlib import Path -from typing import Annotated +from typing import Annotated, Literal import httpx import uvicorn @@ -22,14 +24,25 @@ Request, UploadFile, ) -from fastapi.responses import FileResponse +from fastapi.responses import FileResponse, StreamingResponse from openai import APIError, AsyncOpenAI -from pydantic import BaseModel, TypeAdapter, ValidationError +from openai.types.chat import ChatCompletionMessageParam +from pydantic import BaseModel, Field, TypeAdapter, ValidationError from proofbox_api import canary, settings -from proofbox_api.ask import Answer, Evidence, Toolbox, ask, summarize_pack +from proofbox_api.ask import ( + Answer, + Evidence, + Toolbox, + ask, + check_pack, + converse, + span_evidence, + summarize_pack, +) from proofbox_api.cosmos import Cosmos from proofbox_api.packing import ( + Check, Order, Pack, PackSummary, @@ -39,9 +52,9 @@ find_clip, judge, remux, - track_spans, ) from proofbox_api.store import Store +from proofbox_api.stream import HEADERS, ui_message_stream from proofbox_api.vss import VSS @@ -58,6 +71,8 @@ class Services: @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncIterator[None]: + # ptrace is locked on the VM, so `kill -USR1 ` is the only way to see a hung loop's stacks + faulthandler.register(signal.SIGUSR1, all_threads=True) config = settings.load() packs_dir = config.data_dir / "packs" packs_dir.mkdir(parents=True, exist_ok=True) @@ -154,6 +169,25 @@ class Question(BaseModel): order_id: str | None = None +class UIPart(BaseModel): + type: str + text: str = "" + + +class UIMessage(BaseModel): + id: str + role: Literal["system", "user", "assistant"] + parts: list[UIPart] + + +class ChatRequest(BaseModel): + id: str + messages: list[UIMessage] + trigger: Literal["submit-message", "regenerate-message"] + message_id: str | None = Field(None, alias="messageId") + order_id: str | None = None + + class Transcript(BaseModel): text: str @@ -261,6 +295,7 @@ async def seal_pack( ) await asyncio.to_thread(svc.store.insert_pack, sealed, points) background.add_task(summarize_pack, svc.tools, pack_id) + background.add_task(check_pack, svc.llm, svc.model, svc.tools, pack_id) return Sealed( pack_id=pack_id, order_id=order.order_id, @@ -292,23 +327,21 @@ def pack_summary(svc: Svc, pack_id: PackId) -> Summary: pack = svc.store.pack(pack_id) if text is None or pack is None: raise HTTPException(404, f"no summary yet for pack {pack_id}") - spans = track_spans(svc.store.track(pack_id)) return Summary( pack_id=pack_id, text=text, - evidence=[ - Evidence( - pack_id=pack_id, - order_id=pack.order_id, - start_s=first_ms / 1000, - end_s=last_ms / 1000, - text=f"{label} #{track_id}", - ) - for (label, track_id), (first_ms, last_ms) in spans.items() - ], + evidence=span_evidence(pack, svc.store.track(pack_id)), ) +@app.get("/packs/{pack_id}/check") +def pack_check(svc: Svc, pack_id: PackId) -> Check: + check = svc.store.check(pack_id) + if check is None: + raise HTTPException(404, f"no check yet for pack {pack_id}") + return check + + @app.post("/ask") async def answer_question(svc: Svc, body: Question) -> Answer: try: @@ -319,6 +352,36 @@ async def answer_question(svc: Svc, body: Question) -> Answer: raise HTTPException(502, f"W&B Inference: {error}") from error +def chat_history( + messages: list[UIMessage], +) -> list[ChatCompletionMessageParam]: + history: list[ChatCompletionMessageParam] = [] + for message in messages: + text = "\n\n".join( + part.text for part in message.parts if part.type == "text" + ) + if not text: + continue + if message.role == "user": + history.append({"role": "user", "content": text}) + elif message.role == "assistant": + history.append({"role": "assistant", "content": text}) + return history + + +@app.post("/chat") +async def chat(svc: Svc, body: ChatRequest) -> StreamingResponse: + history = chat_history(body.messages) + if not history: + raise HTTPException(422, "no text in messages") + events = converse(svc.llm, svc.model, svc.tools, history, body.order_id) + return StreamingResponse( + ui_message_stream(events), + media_type="text/event-stream", + headers=HEADERS, + ) + + @app.post("/transcribe") async def transcribe(svc: Svc, audio: UploadFile) -> Transcript: try: diff --git a/apps/api/src/proofbox_api/ask.py b/apps/api/src/proofbox_api/ask.py index 6b0ee8d..d9adb38 100644 --- a/apps/api/src/proofbox_api/ask.py +++ b/apps/api/src/proofbox_api/ask.py @@ -1,32 +1,44 @@ import asyncio import json import logging -from dataclasses import dataclass +import re +import time +from collections.abc import AsyncIterator +from dataclasses import dataclass, field from pathlib import Path from typing import Any +from uuid import uuid4 import httpx import weave -from openai import AsyncOpenAI +from openai import AsyncOpenAI, omit from openai.types.chat import ( - ChatCompletionMessageFunctionToolCall, ChatCompletionMessageParam, ChatCompletionToolParam, ) from pydantic import BaseModel from proofbox_api.cosmos import Cosmos -from proofbox_api.packing import find_clip +from proofbox_api.packing import ( + Check, + Pack, + PackSummary, + TrackPoint, + find_clip, + track_spans, +) from proofbox_api.store import Store from proofbox_api.vss import VSS MAX_TOOL_ROUNDS = 4 +logger = logging.getLogger(__name__) + TOOLS: list[ChatCompletionToolParam] = [ { "type": "function", "function": { - "name": "get_order", + "name": "getOrder", "description": "The order's expected items and, for every sealed pack, the live detector's per-label item counts and verdict.", "parameters": { "type": "object", @@ -38,7 +50,7 @@ { "type": "function", "function": { - "name": "watch_pack", + "name": "watchPack", "description": "Have the Cosmos video model watch the recorded clip of one pack and answer a question about what it sees.", "parameters": { "type": "object", @@ -53,7 +65,7 @@ { "type": "function", "function": { - "name": "search_archive", + "name": "searchArchive", "description": "Search the indexed video archive and get a grounded answer with matching clips. Pass order_id to restrict it to that order's packs.", "parameters": { "type": "object", @@ -68,16 +80,27 @@ ] SYSTEM_PROMPT = """You answer questions about orders packed at the ProofBox station. -Ground every claim in tool results: get_order for expected items and the detector counts and verdict of each sealed pack, watch_pack to have Cosmos look at a pack's clip, search_archive for the video archive. -For what went into a box or whether anything is missing, start with get_order, then watch_pack on its latest pack, and compare what was seen with the order's item lines; the detector counts can miss items, the clip is the stronger evidence. +Ground every claim in tool results: getOrder for expected items and the detector counts and verdict of each sealed pack, watchPack to have Cosmos look at a pack's clip, searchArchive for the video archive. +For what went into a box or whether anything is missing, start with getOrder, then watchPack on its latest pack, and compare what was seen with the order's item lines; the detector counts can miss items, the clip is the stronger evidence. Answer in two to four sentences: end with a verdict of complete, short (name what is missing) or unexpected (name what is extra), and name the pack ids you relied on.""" +CHECK_PROMPT = """Check pack {pack_id}: have Cosmos watch its clip and compare what it sees with the order's item lines. +Reply with the verdict alone on the first line, one of complete, short or unexpected, then one or two sentences naming what is missing or extra.""" + +VERDICT_LINE = re.compile( + r"^\W*(?:verdict\W*)?(complete|short|unexpected)\b\W*(.*)", + re.IGNORECASE | re.DOTALL, +) +# the shared system prompt asks every answer to name its packs; the check card shows the pack already +PACK_NOTE = re.compile(r"\(.*\bpacks?\b.*\)", re.IGNORECASE) + class Evidence(BaseModel): pack_id: str | None order_id: str | None start_s: float | None end_s: float | None + label: str text: str @@ -94,9 +117,96 @@ class Toolbox: packs_dir: Path +@dataclass(frozen=True) +class StepStarted: + pass + + +@dataclass(frozen=True) +class StepFinished: + pass + + +@dataclass(frozen=True) +class TextStarted: + id: str + + +@dataclass(frozen=True) +class TextDelta: + id: str + delta: str + + +@dataclass(frozen=True) +class TextEnded: + id: str + + +@dataclass(frozen=True) +class ToolCalled: + call_id: str + name: str + arguments: Any + + +@dataclass(frozen=True) +class ToolReturned: + call_id: str + output: dict[str, Any] + + +@dataclass(frozen=True) +class ToolFailed: + call_id: str + error: str + + +@dataclass(frozen=True) +class Found: + id: str + evidence: Evidence + + +@dataclass(frozen=True) +class Finished: + trace_url: str | None + + +type Event = ( + StepStarted + | StepFinished + | TextStarted + | TextDelta + | TextEnded + | ToolCalled + | ToolReturned + | ToolFailed + | Found + | Finished +) + type ToolResult = tuple[dict[str, Any], list[Evidence]] +class ToolError(Exception): + pass + + +def span_evidence(pack: Pack, track: list[TrackPoint]) -> list[Evidence]: + return [ + Evidence( + pack_id=pack.pack_id, + order_id=pack.order_id, + start_s=first_ms / 1000, + end_s=last_ms / 1000, + label=label, + text=f"{label} #{track_id}", + ) + for (label, track_id), (first_ms, last_ms) in track_spans(track).items() + ] + + @weave.op async def get_order(tools: Toolbox, order_id: str) -> ToolResult: order = await asyncio.to_thread(tools.store.order, order_id) @@ -109,6 +219,7 @@ async def get_order(tools: Toolbox, order_id: str) -> ToolResult: order_id=order_id, start_s=None, end_s=None, + label="detector", text=f"Detector verdict {pack.verdict}, counts {json.dumps(pack.counts)}", ) for pack in packs @@ -116,7 +227,7 @@ async def get_order(tools: Toolbox, order_id: str) -> ToolResult: return { **order.model_dump(), "packs": [ - pack.model_dump(mode="json", exclude={"object_key"}) + pack.model_dump(mode="json", include=set(PackSummary.model_fields)) for pack in packs ], }, evidence @@ -132,6 +243,7 @@ async def watch_pack(tools: Toolbox, pack_id: str, question: str) -> ToolResult: if order is None: raise LookupError(f"no order {pack.order_id}") expected = ", ".join(f"{item.qty} x {item.name}" for item in order.items) + started = time.monotonic() seen = await tools.cosmos.watch( clip, f"This clip should show order {order.order_id} being packed into a shipping box; the order lists {expected}. " @@ -139,14 +251,19 @@ async def watch_pack(tools: Toolbox, pack_id: str, question: str) -> ToolResult: "Then, for each listed item, say seen with the second it goes into the box, or not seen. " f"{question}", ) - return {"pack_id": pack_id, "cosmos": seen}, [ - Evidence( - pack_id=pack_id, - order_id=order.order_id, - start_s=None, - end_s=None, - text=seen, - ) + seconds = round(time.monotonic() - started, 1) + track = await asyncio.to_thread(tools.store.track, pack_id) + cosmos = Evidence( + pack_id=pack_id, + order_id=order.order_id, + start_s=None, + end_s=None, + label="Cosmos", + text=seen, + ) + return {"pack_id": pack_id, "seconds": seconds, "seen": seen}, [ + cosmos, + *span_evidence(pack, track), ] @@ -168,105 +285,213 @@ async def search_archive( order_id=pack.order_id if pack else None, start_s=chunk["best_match_start_sec"], end_s=chunk["best_match_end_sec"], + label="archive", text=chunk["filename"], ) ) return { + "query": query, "answer": found["answer"], - "matches": [item.model_dump() for item in evidence], + "hits": [item.model_dump(exclude={"label"}) for item in evidence], }, evidence -async def summarize_pack(tools: Toolbox, pack_id: str) -> None: - try: - content, _ = await watch_pack( - tools, pack_id, "Describe exactly what was packed into this box." - ) - except LookupError, httpx.HTTPError: - logging.getLogger(__name__).exception("no summary for pack %s", pack_id) - return - await asyncio.to_thread( - tools.store.insert_summary, pack_id, content["cosmos"] - ) - - TOOL_FUNCTIONS = { - "get_order": get_order, - "watch_pack": watch_pack, - "search_archive": search_archive, + "getOrder": get_order, + "watchPack": watch_pack, + "searchArchive": search_archive, } -async def call_tool( - tools: Toolbox, name: str, arguments: str -) -> tuple[str, list[Evidence]]: +async def run_tool(tools: Toolbox, name: str, arguments: Any) -> ToolResult: if name not in TOOL_FUNCTIONS: - return json.dumps({"error": f"no tool {name}"}), [] + raise ToolError(f"no tool {name}") try: - content, evidence = await TOOL_FUNCTIONS[name]( - tools, **json.loads(arguments) - ) - except (LookupError, TypeError, ValueError, httpx.HTTPError) as error: - return json.dumps({"error": str(error)}), [] - return json.dumps(content), evidence + return await TOOL_FUNCTIONS[name](tools, **arguments) + except LookupError as error: + raise ToolError(str(error)) from error + except (TypeError, ValueError) as error: + logger.exception("bad call to %s", name) + raise ToolError(f"invalid arguments for {name}") from error + except httpx.HTTPError as error: + logger.exception("%s failed", name) + raise ToolError(f"{name} could not reach its service") from error -@weave.op -async def ask( +def parse_arguments(arguments: str) -> Any: + try: + return json.loads(arguments or "{}") + except ValueError: + return arguments + + +@dataclass +class StreamedCall: + id: str = field(default_factory=lambda: f"call-{uuid4().hex}") + name: str = "" + arguments: str = "" + + +def gather(answer: Answer | None, event: Event) -> Answer: + answer = answer or Answer(answer="", evidence=[]) + match event: + case StepStarted(): + answer.answer = "" + case TextDelta(delta=delta): + answer.answer += delta + case Found(evidence=evidence): + answer.evidence.append(evidence) + return answer + + +@weave.op(accumulator=gather) +async def converse( llm: AsyncOpenAI, model: str, tools: Toolbox, - question: str, + history: list[ChatCompletionMessageParam], order_id: str | None, -) -> Answer: +) -> AsyncIterator[Event]: + call = weave.get_current_call() + trace_url = call.ui_url if call else None system = SYSTEM_PROMPT if order_id: system += f"\nThe operator is looking at order {order_id}; questions that name no order are about it." messages: list[ChatCompletionMessageParam] = [ {"role": "system", "content": system}, - {"role": "user", "content": question}, + *history, ] - evidence: list[Evidence] = [] - for _ in range(MAX_TOOL_ROUNDS): - completion = await llm.chat.completions.create( - model=model, messages=messages, tools=TOOLS + for tool_round in range(MAX_TOOL_ROUNDS + 1): + yield StepStarted() + stream = await llm.chat.completions.create( + model=model, + messages=messages, + tools=TOOLS if tool_round < MAX_TOOL_ROUNDS else omit, + stream=True, ) - message = completion.choices[0].message - calls = [ - call - for call in message.tool_calls or [] - if isinstance(call, ChatCompletionMessageFunctionToolCall) - ] + text, text_id = "", None + streamed: dict[int, StreamedCall] = {} + async for chunk in stream: + if not chunk.choices: + continue + delta = chunk.choices[0].delta + if delta.content: + if text_id is None: + text_id = f"text-{uuid4().hex}" + yield TextStarted(text_id) + text += delta.content + yield TextDelta(text_id, delta.content) + for part in delta.tool_calls or []: + pending = streamed.setdefault(part.index, StreamedCall()) + pending.id = part.id or pending.id + if part.function: + pending.name = part.function.name or pending.name + pending.arguments += part.function.arguments or "" + if text_id: + yield TextEnded(text_id) + calls = [streamed[index] for index in sorted(streamed)] if not calls: - return Answer(answer=message.content or "", evidence=evidence) + yield StepFinished() + yield Finished(trace_url) + return messages.append( { "role": "assistant", - "content": message.content, + "content": text or None, "tool_calls": [ { - "id": call.id, + "id": pending.id, "type": "function", "function": { - "name": call.function.name, - "arguments": call.function.arguments, + "name": pending.name, + "arguments": pending.arguments, }, } - for call in calls + for pending in calls ], } ) - for call in calls: - content, found = await call_tool( - tools, call.function.name, call.function.arguments - ) - evidence += found + for pending in calls: + arguments = parse_arguments(pending.arguments) + yield ToolCalled(pending.id, pending.name, arguments) + try: + output, evidence = await run_tool( + tools, pending.name, arguments + ) + except ToolError as error: + yield ToolFailed(pending.id, str(error)) + content = json.dumps({"error": str(error)}) + else: + yield ToolReturned(pending.id, output) + for index, item in enumerate(evidence): + yield Found(f"{pending.id}-{index}", item) + content = json.dumps(output) messages.append( - {"role": "tool", "tool_call_id": call.id, "content": content} + {"role": "tool", "tool_call_id": pending.id, "content": content} ) - completion = await llm.chat.completions.create( - model=model, messages=messages + yield StepFinished() + + +async def ask( + llm: AsyncOpenAI, + model: str, + tools: Toolbox, + question: str, + order_id: str | None, +) -> Answer: + answer = Answer(answer="", evidence=[]) + async for event in converse( + llm, model, tools, [{"role": "user", "content": question}], order_id + ): + answer = gather(answer, event) + return answer + + +async def summarize_pack(tools: Toolbox, pack_id: str) -> None: + try: + content, _ = await watch_pack( + tools, pack_id, "Describe exactly what was packed into this box." + ) + except LookupError, httpx.HTTPError: + logger.exception("no summary for pack %s", pack_id) + return + await asyncio.to_thread( + tools.store.insert_summary, pack_id, content["seen"] ) - return Answer( - answer=completion.choices[0].message.content or "", evidence=evidence + + +def parse_check(pack_id: str, reply: str) -> Check: + found = VERDICT_LINE.match(reply.strip()) + if found is None: + raise ValueError(f"no verdict in the check reply for pack {pack_id}") + return Check.model_validate( + { + "pack_id": pack_id, + "verdict": found[1].lower(), + "text": " ".join( + line.strip() + for line in found[2].splitlines() + if not PACK_NOTE.fullmatch(line.strip()) + ).strip(), + } ) + + +async def check_pack( + llm: AsyncOpenAI, model: str, tools: Toolbox, pack_id: str +) -> None: + try: + pack = await asyncio.to_thread(tools.store.pack, pack_id) + if pack is None: + raise LookupError(f"no sealed pack {pack_id}") + answer = await ask( + llm, + model, + tools, + CHECK_PROMPT.format(pack_id=pack_id), + pack.order_id, + ) + check = parse_check(pack_id, answer.answer) + await asyncio.to_thread(tools.store.insert_check, check) + except Exception: + logger.exception("no check for pack %s", pack_id) diff --git a/apps/api/src/proofbox_api/packing.py b/apps/api/src/proofbox_api/packing.py index 8b2b955..9945121 100644 --- a/apps/api/src/proofbox_api/packing.py +++ b/apps/api/src/proofbox_api/packing.py @@ -37,6 +37,12 @@ class PackSummary(BaseModel): counts: dict[str, int] +class Check(BaseModel): + pack_id: str + verdict: Verdict + text: str + + class Pack(PackSummary): order_id: str started_at: datetime diff --git a/apps/api/src/proofbox_api/store.py b/apps/api/src/proofbox_api/store.py index f820435..89b957c 100644 --- a/apps/api/src/proofbox_api/store.py +++ b/apps/api/src/proofbox_api/store.py @@ -9,7 +9,7 @@ from ibis import _ from vastdb.table import ITable -from proofbox_api.packing import Order, Pack, TrackPoint +from proofbox_api.packing import Check, Order, Pack, TrackPoint SCHEMA = "proofbox" @@ -40,6 +40,14 @@ ("created_at", pa.timestamp("us")), ] ), + "checks": pa.schema( + [ + ("pack_id", pa.utf8()), + ("verdict", pa.utf8()), + ("text", pa.utf8()), + ("created_at", pa.timestamp("us")), + ] + ), "detections": pa.schema( [ ("pack_id", pa.utf8()), @@ -202,6 +210,22 @@ def summary(self, pack_id: str) -> str | None: else None ) + def insert_check(self, check: Check) -> None: + row = check.model_dump() | { + "created_at": datetime.now(UTC).replace(tzinfo=None) + } + with self.table("checks") as table: + table.insert(pa.Table.from_pylist([row], TABLES["checks"])) + + def check(self, pack_id: str) -> Check | None: + rows = self.select("checks", _.pack_id == pack_id) + if not rows: + return None + latest = max(rows, key=lambda row: row["created_at"]) + return Check( + pack_id=pack_id, verdict=latest["verdict"], text=latest["text"] + ) + def track(self, pack_id: str) -> list[TrackPoint]: rows = sorted( self.select("detections", _.pack_id == pack_id), diff --git a/apps/api/src/proofbox_api/stream.py b/apps/api/src/proofbox_api/stream.py new file mode 100644 index 0000000..2a7f281 --- /dev/null +++ b/apps/api/src/proofbox_api/stream.py @@ -0,0 +1,90 @@ +import json +import logging +from collections.abc import AsyncIterator +from typing import Any +from uuid import uuid4 + +from proofbox_api.ask import ( + Event, + Finished, + Found, + StepFinished, + StepStarted, + TextDelta, + TextEnded, + TextStarted, + ToolCalled, + ToolFailed, + ToolReturned, +) + +HEADERS = { + "x-vercel-ai-ui-message-stream": "v1", + "cache-control": "no-cache", + "x-accel-buffering": "no", +} + +FAILED = "Something went wrong while answering. Try again." + +logger = logging.getLogger(__name__) + + +def ui_part(event: Event) -> dict[str, Any]: + match event: + case StepStarted(): + return {"type": "start-step"} + case StepFinished(): + return {"type": "finish-step"} + case TextStarted(id=text_id): + return {"type": "text-start", "id": text_id} + case TextDelta(id=text_id, delta=delta): + return {"type": "text-delta", "id": text_id, "delta": delta} + case TextEnded(id=text_id): + return {"type": "text-end", "id": text_id} + case ToolCalled(call_id=call_id, name=name, arguments=arguments): + return { + "type": "tool-input-available", + "toolCallId": call_id, + "toolName": name, + "input": arguments, + } + case ToolReturned(call_id=call_id, output=output): + return { + "type": "tool-output-available", + "toolCallId": call_id, + "output": output, + } + case ToolFailed(call_id=call_id, error=error): + return { + "type": "tool-output-error", + "toolCallId": call_id, + "errorText": error, + } + case Found(id=part_id, evidence=evidence): + return { + "type": "data-evidence", + "id": part_id, + "data": evidence.model_dump(), + } + case Finished(trace_url=None): + return {"type": "finish"} + case Finished(trace_url=trace_url): + return { + "type": "finish", + "messageMetadata": {"traceUrl": trace_url}, + } + + +def sse(part: dict[str, Any]) -> str: + return f"data: {json.dumps(part, separators=(',', ':'))}\n\n" + + +async def ui_message_stream(events: AsyncIterator[Event]) -> AsyncIterator[str]: + yield sse({"type": "start", "messageId": f"msg-{uuid4().hex}"}) + try: + async for event in events: + yield sse(ui_part(event)) + except Exception: + logger.exception("chat answer failed") + yield sse({"type": "error", "errorText": FAILED}) + yield "data: [DONE]\n\n" diff --git a/apps/api/tests/fakes.py b/apps/api/tests/fakes.py new file mode 100644 index 0000000..bdd068e --- /dev/null +++ b/apps/api/tests/fakes.py @@ -0,0 +1,181 @@ +import json +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import httpx2 +from openai import AsyncOpenAI + +from proofbox_api.cosmos import Cosmos +from proofbox_api.packing import Check, Item, Order, Pack, TrackPoint +from proofbox_api.store import Store +from proofbox_api.vss import VSS + +MODEL = "openai/gpt-oss-120b" + +ORDER = Order( + order_id="PB-1001", + customer="Kestrel Labs", + items=[Item(name="coffee mug", qty=1), Item(name="scissors", qty=1)], +) +PACK = Pack( + pack_id="0a1b2c3d", + order_id="PB-1001", + started_at=datetime(2026, 10, 17, 12, 0, tzinfo=UTC), + sealed_at=datetime(2026, 10, 17, 12, 1, tzinfo=UTC), + object_key="team-15/20261017_120100_PB-1001_0a1b2c3d.mp4", + counts={"coffee mug": 1}, + verdict="short", +) +TRACK = [ + TrackPoint( + t_ms=t_ms, track=7, label="coffee mug", conf=0.9, box=(0, 0, 1, 1) + ) + for t_ms in (2000, 3500) +] + + +class FakeStore(Store): + def __init__(self): + self.summaries: dict[str, str] = {} + self.checks: dict[str, Check] = {} + + def insert_summary(self, pack_id: str, text: str) -> None: + self.summaries[pack_id] = text + + def insert_check(self, check: Check) -> None: + self.checks[check.pack_id] = check + + def check(self, pack_id: str) -> Check | None: + return self.checks.get(pack_id) + + def order(self, order_id: str) -> Order | None: + return ORDER if order_id == ORDER.order_id else None + + def packs(self, order_id: str) -> list[Pack]: + return [PACK] if order_id == PACK.order_id else [] + + def pack(self, pack_id: str) -> Pack | None: + return PACK if pack_id == PACK.pack_id else None + + def track(self, pack_id: str) -> list[TrackPoint]: + return TRACK if pack_id == PACK.pack_id else [] + + def packs_by_object_key(self) -> dict[str, Pack]: + return {"team-15/20261017_120100_PB-1001_0a1b2c3d.mp4": PACK} + + +class FakeCosmos(Cosmos): + def __init__(self): + self.prompts: list[str] = [] + + async def watch(self, clip: Path, prompt: str) -> str: + self.prompts.append(prompt) + return "A mug goes in at 2 s; no scissors are seen." + + +class FakeVSS(VSS): + def __init__(self): + self.searches: list[tuple[str, list[str]]] = [] + + async def search_and_answer( + self, query: str, tags: list[str] + ) -> dict[str, Any]: + self.searches.append((query, tags)) + return { + "answer": "One matching pack.", + "evidence": { + "chunks": [ + { + "original_video": "s3://team-15-vss-chunks/team-15/20261017_120100_PB-1001_0a1b2c3d.mp4", + "filename": "20261017_120100_PB-1001_0a1b2c3d.mp4", + "best_match_start_sec": 1.5, + "best_match_end_sec": 4.0, + } + ] + }, + } + + +def tool_call(call_id: str, name: str, arguments: dict) -> dict: + return {"id": call_id, "name": name, "arguments": json.dumps(arguments)} + + +def chunk(delta: dict, finish_reason: str | None = None) -> str: + payload = { + "id": "chatcmpl-1", + "object": "chat.completion.chunk", + "created": 0, + "model": MODEL, + "choices": [ + {"index": 0, "delta": delta, "finish_reason": finish_reason} + ], + } + return f"data: {json.dumps(payload)}\n\n" + + +def streamed_reply(reply: dict) -> bytes: + """Splits text and every tool call's arguments over two chunks, the way + W&B Inference streams them, with the id and name only in the first.""" + events = [chunk({"role": "assistant", "content": ""})] + content = reply.get("content") or "" + half = len(content) // 2 + events += [ + chunk({"content": part}) + for part in (content[:half], content[half:]) + if part + ] + calls = reply.get("tool_calls", []) + for index, call in enumerate(calls): + cut = len(call["arguments"]) // 2 + events.append( + chunk( + { + "tool_calls": [ + { + "index": index, + "id": call["id"], + "type": "function", + "function": { + "name": call["name"], + "arguments": call["arguments"][:cut], + }, + } + ] + } + ) + ) + events.append( + chunk( + { + "tool_calls": [ + { + "index": index, + "function": {"arguments": call["arguments"][cut:]}, + } + ] + } + ) + ) + events.append(chunk({}, "tool_calls" if calls else "stop")) + events.append("data: [DONE]\n\n") + return "".join(events).encode() + + +def fake_llm(replies: list[dict]) -> tuple[AsyncOpenAI, list[dict]]: + requests: list[dict] = [] + + def wandb(request: httpx2.Request) -> httpx2.Response: + requests.append(json.loads(request.content)) + return httpx2.Response( + 200, + headers={"content-type": "text/event-stream"}, + content=streamed_reply(replies[len(requests) - 1]), + ) + + llm = AsyncOpenAI( + base_url="http://wandb/v1", + api_key="test", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(wandb)), + ) + return llm, requests diff --git a/apps/api/tests/test_ask.py b/apps/api/tests/test_ask.py index e4cb857..d6cb00a 100644 --- a/apps/api/tests/test_ask.py +++ b/apps/api/tests/test_ask.py @@ -1,225 +1,212 @@ import asyncio import json -from datetime import UTC, datetime from pathlib import Path -from typing import Any -import httpx2 -from openai import AsyncOpenAI +import pytest +from fakes import ( + MODEL, + PACK, + FakeCosmos, + FakeStore, + FakeVSS, + fake_llm, + tool_call, +) from proofbox_api.ask import ( MAX_TOOL_ROUNDS, Answer, + Event, + Finished, + Found, + StepFinished, + StepStarted, + TextDelta, + TextEnded, + TextStarted, Toolbox, + ToolCalled, + ToolFailed, + ToolReturned, ask, + check_pack, + converse, + parse_check, summarize_pack, ) -from proofbox_api.cosmos import Cosmos -from proofbox_api.packing import Item, Order, Pack -from proofbox_api.store import Store -from proofbox_api.vss import VSS - -ORDER = Order( - order_id="PB-1001", - customer="Kestrel Labs", - items=[Item(name="coffee mug", qty=1), Item(name="scissors", qty=1)], -) -PACK = Pack( - pack_id="0a1b2c3d", - order_id="PB-1001", - started_at=datetime(2026, 10, 17, 12, 0, tzinfo=UTC), - sealed_at=datetime(2026, 10, 17, 12, 1, tzinfo=UTC), - object_key="team-15/20261017_120100_PB-1001_0a1b2c3d.mp4", - counts={"coffee mug": 1}, - verdict="short", -) - - -class FakeStore(Store): - def __init__(self): - self.summaries: dict[str, str] = {} - - def insert_summary(self, pack_id: str, text: str) -> None: - self.summaries[pack_id] = text - - def order(self, order_id: str) -> Order | None: - return ORDER if order_id == ORDER.order_id else None - - def packs(self, order_id: str) -> list[Pack]: - return [PACK] if order_id == PACK.order_id else [] - - def pack(self, pack_id: str) -> Pack | None: - return PACK if pack_id == PACK.pack_id else None - - def packs_by_object_key(self) -> dict[str, Pack]: - return {"team-15/20261017_120100_PB-1001_0a1b2c3d.mp4": PACK} - - -class FakeCosmos(Cosmos): - def __init__(self): - self.prompts: list[str] = [] - async def watch(self, clip: Path, prompt: str) -> str: - self.prompts.append(prompt) - return "A mug goes in at 2 s; no scissors are seen." - - -class FakeVSS(VSS): - def __init__(self): - self.searches: list[tuple[str, list[str]]] = [] - - async def search_and_answer( - self, query: str, tags: list[str] - ) -> dict[str, Any]: - self.searches.append((query, tags)) - return { - "answer": "One matching pack.", - "evidence": { - "chunks": [ - { - "original_video": "s3://team-15-vss-chunks/team-15/20261017_120100_PB-1001_0a1b2c3d.mp4", - "filename": "20261017_120100_PB-1001_0a1b2c3d.mp4", - "best_match_start_sec": 1.5, - "best_match_end_sec": 4.0, - } - ] - }, - } - - -def tool_call(call_id: str, name: str, arguments: dict) -> dict: - return { - "id": call_id, - "type": "function", - "function": {"name": name, "arguments": json.dumps(arguments)}, - } - - -def completion(message: dict) -> dict: - return { - "id": "chatcmpl-1", - "object": "chat.completion", - "created": 0, - "model": "openai/gpt-oss-120b", - "choices": [ - { - "index": 0, - "finish_reason": "tool_calls" - if message.get("tool_calls") - else "stop", - "message": {"role": "assistant", **message}, - } +FULL_ROUND = [ + { + "content": None, + "tool_calls": [ + tool_call("c1", "getOrder", {"order_id": "PB-1001"}), + tool_call( + "c2", + "watchPack", + {"pack_id": PACK.pack_id, "question": "What went in?"}, + ), + tool_call( + "c3", + "searchArchive", + {"query": "scissors", "order_id": "PB-1001"}, + ), ], - } + }, + {"content": "The scissors are missing from pack 0a1b2c3d."}, +] -def run_ask( - replies: list[dict], tmp_path: Path, order_id: str | None = "PB-1001" -) -> tuple[Answer, list[dict], FakeCosmos, FakeVSS]: +def toolbox(tmp_path: Path) -> Toolbox: (tmp_path / f"{PACK.pack_id}.mp4").write_bytes(b"mp4") - requests: list[dict] = [] + return Toolbox(FakeStore(), FakeCosmos(), FakeVSS(), tmp_path) - def wandb(request: httpx2.Request) -> httpx2.Response: - requests.append(json.loads(request.content)) - return httpx2.Response(200, json=completion(replies[len(requests) - 1])) - cosmos, vss = FakeCosmos(), FakeVSS() - tools = Toolbox(FakeStore(), cosmos, vss, tmp_path) +def run_ask( + replies: list[dict], tools: Toolbox, order_id: str | None = "PB-1001" +) -> tuple[Answer, list[dict]]: + llm, requests = fake_llm(replies) async def go() -> Answer: - async with AsyncOpenAI( - base_url="http://wandb/v1", - api_key="test", - http_client=httpx2.AsyncClient( - transport=httpx2.MockTransport(wandb) - ), - ) as llm: + async with llm: return await ask( - llm, - "openai/gpt-oss-120b", - tools, - "Was anything missing?", - order_id, + llm, MODEL, tools, "Was anything missing?", order_id ) - return asyncio.run(go()), requests, cosmos, vss + return asyncio.run(go()), requests + + +def run_converse(replies: list[dict], tools: Toolbox) -> list[Event]: + llm, _ = fake_llm(replies) + + async def go() -> list[Event]: + async with llm: + return [ + event + async for event in converse( + llm, + MODEL, + tools, + [{"role": "user", "content": "Was anything missing?"}], + "PB-1001", + ) + ] + + return asyncio.run(go()) def test_dispatches_each_tool_and_collects_evidence(tmp_path: Path): - answer, requests, cosmos, vss = run_ask( - [ - { - "content": None, - "tool_calls": [ - tool_call("c1", "get_order", {"order_id": "PB-1001"}), - tool_call( - "c2", - "watch_pack", - {"pack_id": PACK.pack_id, "question": "What went in?"}, - ), - tool_call( - "c3", - "search_archive", - {"query": "scissors", "order_id": "PB-1001"}, - ), - ], - }, - {"content": "The scissors are missing from pack 0a1b2c3d."}, - ], - tmp_path, - ) + tools = toolbox(tmp_path) + answer, requests = run_ask(FULL_ROUND, tools) assert answer.answer == "The scissors are missing from pack 0a1b2c3d." assert "PB-1001" in requests[0]["messages"][0]["content"] + assert requests[0]["stream"] is True tool_messages = { message["tool_call_id"]: json.loads(message["content"]) for message in requests[1]["messages"] if message["role"] == "tool" } - assert tool_messages["c1"]["packs"][0]["verdict"] == "short" - assert tool_messages["c2"]["cosmos"].startswith("A mug goes in") - assert tool_messages["c3"]["answer"] == "One matching pack." - assert "lists 1 x coffee mug, 1 x scissors" in cosmos.prompts[0] - assert vss.searches == [("scissors", ["PB-1001"])] - assert [(e.pack_id, e.start_s) for e in answer.evidence] == [ - ("0a1b2c3d", None), - ("0a1b2c3d", None), - ("0a1b2c3d", 1.5), + assert tool_messages["c1"]["packs"][0] == { + "pack_id": PACK.pack_id, + "sealed_at": "2026-10-17T12:01:00Z", + "verdict": "short", + "counts": {"coffee mug": 1}, + } + assert tool_messages["c2"]["seen"].startswith("A mug goes in") + assert tool_messages["c3"]["hits"][0]["start_s"] == 1.5 + assert isinstance(tools.cosmos, FakeCosmos) + assert "lists 1 x coffee mug, 1 x scissors" in tools.cosmos.prompts[0] + assert isinstance(tools.vss, FakeVSS) + assert tools.vss.searches == [("scissors", ["PB-1001"])] + assert [(e.label, e.start_s, e.end_s) for e in answer.evidence] == [ + ("detector", None, None), + ("Cosmos", None, None), + ("coffee mug", 2.0, 3.5), + ("archive", 1.5, 4.0), ] -def test_tool_errors_go_back_to_the_model_instead_of_failing(tmp_path: Path): - answer, requests, _, _ = run_ask( - [ - { - "content": None, - "tool_calls": [ - tool_call("c1", "get_order", {"order_id": "PB-9999"}), - tool_call("c2", "drop_table", {}), - ], - }, - {"content": "I could not find that order."}, - ], - tmp_path, - order_id=None, +def test_streams_steps_tools_evidence_and_text_in_protocol_order( + tmp_path: Path, +): + events = run_converse(FULL_ROUND, toolbox(tmp_path)) + + kinds = [type(event).__name__ for event in events] + assert kinds == [ + "StepStarted", + "ToolCalled", + "ToolReturned", + "Found", + "ToolCalled", + "ToolReturned", + "Found", + "Found", + "ToolCalled", + "ToolReturned", + "Found", + "StepFinished", + "StepStarted", + "TextStarted", + "TextDelta", + "TextDelta", + "TextEnded", + "StepFinished", + "Finished", + ] + called = [event for event in events if isinstance(event, ToolCalled)] + assert called[1] == ToolCalled( + "c2", + "watchPack", + {"pack_id": PACK.pack_id, "question": "What went in?"}, ) + found_ids = [event.id for event in events if isinstance(event, Found)] + assert len(set(found_ids)) == len(found_ids) + text = "".join(e.delta for e in events if isinstance(e, TextDelta)) + assert text == "The scissors are missing from pack 0a1b2c3d." + assert {e.id for e in events if isinstance(e, TextStarted | TextEnded)} == { + e.id for e in events if isinstance(e, TextDelta) + } + assert events[-1] == Finished(None) + assert isinstance(events[0], StepStarted) + assert isinstance(events[-2], StepFinished) + + +def test_tool_errors_go_back_to_the_model_instead_of_failing(tmp_path: Path): + tools = toolbox(tmp_path) + replies = [ + { + "content": None, + "tool_calls": [ + tool_call("c1", "getOrder", {"order_id": "PB-9999"}), + tool_call("c2", "dropTable", {}), + ], + }, + {"content": "I could not find that order."}, + ] + answer, requests = run_ask(replies, tools, order_id=None) + events = run_converse(replies, tools) errors = [ json.loads(message["content"])["error"] for message in requests[1]["messages"] if message["role"] == "tool" ] - assert errors == ["no order PB-9999", "no tool drop_table"] + assert errors == ["no order PB-9999", "no tool dropTable"] + assert [e for e in events if isinstance(e, ToolFailed)] == [ + ToolFailed("c1", "no order PB-9999"), + ToolFailed("c2", "no tool dropTable"), + ] + assert not any(isinstance(e, ToolReturned) for e in events) assert answer.evidence == [] def test_stops_offering_tools_after_the_round_cap(tmp_path: Path): looping = { "content": None, - "tool_calls": [tool_call("c", "get_order", {"order_id": "PB-1001"})], + "tool_calls": [tool_call("c", "getOrder", {"order_id": "PB-1001"})], } - answer, requests, _, _ = run_ask( - [looping] * MAX_TOOL_ROUNDS + [{"content": "Done."}], tmp_path + answer, requests = run_ask( + [looping] * MAX_TOOL_ROUNDS + [{"content": "Done."}], toolbox(tmp_path) ) assert answer.answer == "Done." @@ -227,15 +214,104 @@ def test_stops_offering_tools_after_the_round_cap(tmp_path: Path): assert "tools" not in requests[-1] +def test_answer_keeps_only_the_last_step_text(tmp_path: Path): + answer, _ = run_ask( + [ + { + "content": "Let me look.", + "tool_calls": [ + tool_call("c1", "getOrder", {"order_id": "PB-1001"}) + ], + }, + {"content": "Complete."}, + ], + toolbox(tmp_path), + ) + + assert answer.answer == "Complete." + + def test_summary_stores_what_cosmos_saw_and_skips_unknown_packs(tmp_path: Path): - (tmp_path / f"{PACK.pack_id}.mp4").write_bytes(b"mp4") - store, cosmos = FakeStore(), FakeCosmos() - tools = Toolbox(store, cosmos, FakeVSS(), tmp_path) + tools = toolbox(tmp_path) asyncio.run(summarize_pack(tools, PACK.pack_id)) asyncio.run(summarize_pack(tools, "ffffffff")) - assert store.summaries == { + assert isinstance(tools.store, FakeStore) + assert tools.store.summaries == { PACK.pack_id: "A mug goes in at 2 s; no scissors are seen." } - assert "Describe exactly what was packed" in cosmos.prompts[0] + assert isinstance(tools.cosmos, FakeCosmos) + assert "Describe exactly what was packed" in tools.cosmos.prompts[0] + + +@pytest.mark.parametrize( + ("reply", "verdict", "text"), + [ + ( + "short\nThe scissors are missing.", + "short", + "The scissors are missing.", + ), + ("**Unexpected** A pen was packed.", "unexpected", "A pen was packed."), + ( + "Verdict: complete\nEverything is there.", + "complete", + "Everything is there.", + ), + ( + "short\nMissing coffee mug, scissors. \n(Analyzed pack a5ae7eb3.)", + "short", + "Missing coffee mug, scissors.", + ), + ], +) +def test_parses_the_verdict_from_the_first_line( + reply: str, verdict: str, text: str +): + check = parse_check(PACK.pack_id, reply) + assert (check.verdict, check.text) == (verdict, text) + + +def run_check(replies: list[dict], tools: Toolbox) -> list[dict]: + llm, requests = fake_llm(replies) + + async def go() -> None: + async with llm: + await check_pack(llm, MODEL, tools, PACK.pack_id) + + asyncio.run(go()) + return requests + + +def test_check_stores_the_agent_verdict(tmp_path: Path): + tools = toolbox(tmp_path) + requests = run_check( + [ + { + "content": None, + "tool_calls": [ + tool_call( + "c1", + "watchPack", + {"pack_id": PACK.pack_id, "question": "What went in?"}, + ) + ], + }, + {"content": "short\nNo scissors were packed."}, + ], + tools, + ) + + assert isinstance(tools.store, FakeStore) + assert tools.store.checks[PACK.pack_id].verdict == "short" + assert tools.store.checks[PACK.pack_id].text == "No scissors were packed." + assert PACK.pack_id in requests[0]["messages"][-1]["content"] + + +def test_check_stores_nothing_when_the_reply_has_no_verdict(tmp_path: Path): + tools = toolbox(tmp_path) + run_check([{"content": "I am not sure."}], tools) + + assert isinstance(tools.store, FakeStore) + assert tools.store.checks == {} diff --git a/apps/api/tests/test_stream.py b/apps/api/tests/test_stream.py new file mode 100644 index 0000000..f26daa6 --- /dev/null +++ b/apps/api/tests/test_stream.py @@ -0,0 +1,230 @@ +import asyncio +import json +from collections.abc import AsyncIterator, Iterator +from pathlib import Path + +import httpx +import pytest +from fakes import PACK, FakeCosmos, FakeStore, FakeVSS, fake_llm +from fastapi.testclient import TestClient + +from proofbox_api import Services, app, services +from proofbox_api.ask import ( + Event, + Evidence, + Finished, + Found, + StepFinished, + StepStarted, + TextDelta, + TextEnded, + TextStarted, + Toolbox, + ToolCalled, + ToolFailed, + ToolReturned, +) +from proofbox_api.packing import Check +from proofbox_api.stream import FAILED, ui_message_stream + +EVIDENCE = Evidence( + pack_id=PACK.pack_id, + order_id="PB-1001", + start_s=2.0, + end_s=3.5, + label="coffee mug", + text="coffee mug #7", +) + + +def encode(events: list[Event], fail: bool = False) -> list[str]: + async def scripted() -> AsyncIterator[Event]: + for event in events: + yield event + if fail: + raise RuntimeError("upstream said http://10.0.0.1 secret") + + async def go() -> list[str]: + return [line async for line in ui_message_stream(scripted())] + + return asyncio.run(go()) + + +def parts(lines: list[str]) -> list[dict]: + assert all( + line.startswith("data: ") and line.endswith("\n\n") for line in lines + ) + assert lines[-1] == "data: [DONE]\n\n" + return [json.loads(line.removeprefix("data: ")) for line in lines[:-1]] + + +def test_encodes_events_as_ui_message_stream_parts(): + lines = encode( + [ + StepStarted(), + ToolCalled("c1", "getOrder", {"order_id": "PB-1001"}), + ToolReturned("c1", {"order_id": "PB-1001"}), + ToolCalled("c2", "watchPack", {"pack_id": "ffffffff"}), + ToolFailed("c2", "no recorded clip for pack ffffffff"), + Found("c1-0", EVIDENCE), + StepFinished(), + StepStarted(), + TextStarted("text-1"), + TextDelta("text-1", "Short: "), + TextDelta("text-1", "no scissors."), + TextEnded("text-1"), + StepFinished(), + Finished("https://wandb.ai/team/project/r/call/abc"), + ] + ) + + decoded = parts(lines) + assert decoded[0]["type"] == "start" + assert decoded[0]["messageId"].startswith("msg-") + assert decoded[1:] == [ + {"type": "start-step"}, + { + "type": "tool-input-available", + "toolCallId": "c1", + "toolName": "getOrder", + "input": {"order_id": "PB-1001"}, + }, + { + "type": "tool-output-available", + "toolCallId": "c1", + "output": {"order_id": "PB-1001"}, + }, + { + "type": "tool-input-available", + "toolCallId": "c2", + "toolName": "watchPack", + "input": {"pack_id": "ffffffff"}, + }, + { + "type": "tool-output-error", + "toolCallId": "c2", + "errorText": "no recorded clip for pack ffffffff", + }, + { + "type": "data-evidence", + "id": "c1-0", + "data": { + "pack_id": PACK.pack_id, + "order_id": "PB-1001", + "start_s": 2.0, + "end_s": 3.5, + "label": "coffee mug", + "text": "coffee mug #7", + }, + }, + {"type": "finish-step"}, + {"type": "start-step"}, + {"type": "text-start", "id": "text-1"}, + {"type": "text-delta", "id": "text-1", "delta": "Short: "}, + {"type": "text-delta", "id": "text-1", "delta": "no scissors."}, + {"type": "text-end", "id": "text-1"}, + {"type": "finish-step"}, + { + "type": "finish", + "messageMetadata": { + "traceUrl": "https://wandb.ai/team/project/r/call/abc" + }, + }, + ] + + +def test_finish_omits_metadata_without_a_trace(): + assert parts(encode([Finished(None)]))[-1] == {"type": "finish"} + + +def test_a_failure_ends_with_a_generic_error_and_done(): + decoded = parts(encode([StepStarted()], fail=True)) + + assert decoded[-1] == {"type": "error", "errorText": FAILED} + assert "10.0.0.1" not in json.dumps(decoded) + + +@pytest.fixture +def client(tmp_path: Path) -> Iterator[tuple[TestClient, FakeStore]]: + (tmp_path / f"{PACK.pack_id}.mp4").write_bytes(b"mp4") + store = FakeStore() + llm, _ = fake_llm( + [ + { + "content": None, + "tool_calls": [ + { + "id": "c1", + "name": "getOrder", + "arguments": json.dumps({"order_id": "PB-1001"}), + } + ], + }, + {"content": "Nothing is missing."}, + ] + ) + vss = FakeVSS() + app.dependency_overrides[services] = lambda: Services( + store=store, + vss=vss, + canary=httpx.AsyncClient(), + llm=llm, + model="openai/gpt-oss-120b", + tools=Toolbox(store, FakeCosmos(), vss, tmp_path), + packs_dir=tmp_path, + ) + yield TestClient(app), store + app.dependency_overrides.clear() + + +def test_chat_streams_the_protocol_with_its_header( + client: tuple[TestClient, FakeStore], +): + test_client, _ = client + response = test_client.post( + "/chat", + json={ + "id": "chat-1", + "trigger": "submit-message", + "order_id": "PB-1001", + "messages": [ + { + "id": "m1", + "role": "user", + "parts": [ + {"type": "text", "text": "Was anything missing?"} + ], + } + ], + }, + ) + + assert response.status_code == 200 + assert response.headers["x-vercel-ai-ui-message-stream"] == "v1" + assert response.headers["content-type"].startswith("text/event-stream") + assert response.text.endswith("data: [DONE]\n\n") + types = [ + json.loads(line.removeprefix("data: "))["type"] + for line in response.text.split("\n\n") + if line.startswith("data: {") + ] + assert types[0] == "start" + assert "tool-output-available" in types + assert "data-evidence" in types + assert "text-delta" in types + assert types[-1] == "finish" + + +def test_check_is_404_until_stored(client: tuple[TestClient, FakeStore]): + test_client, store = client + url = f"/packs/{PACK.pack_id}/check" + + assert test_client.get(url).status_code == 404 + store.insert_check( + Check(pack_id=PACK.pack_id, verdict="short", text="No scissors.") + ) + assert test_client.get(url).json() == { + "pack_id": PACK.pack_id, + "verdict": "short", + "text": "No scissors.", + }