Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/chat-ui-stream.md
Original file line number Diff line number Diff line change
@@ -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`.
5 changes: 5 additions & 0 deletions .changeset/pack-check.md
Original file line number Diff line number Diff line change
@@ -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`.
1 change: 1 addition & 0 deletions apps/api/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
95 changes: 79 additions & 16 deletions apps/api/src/proofbox_api/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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,
Expand All @@ -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


Expand All @@ -58,6 +71,8 @@ class Services:

@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
# ptrace is locked on the VM, so `kill -USR1 <pid>` 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)
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down
Loading
Loading