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
296 changes: 231 additions & 65 deletions backend/app/routers/ask.py

Large diffs are not rendered by default.

23 changes: 19 additions & 4 deletions backend/app/routers/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,16 +186,31 @@ def __init__(self, error: dict):
self.error = error


def _msearch(bodies: list[dict]) -> list[dict]:
searches = [part for body in bodies for part in ({"index": settings.idx_sessions}, body)]
def msearch(requests: list[tuple[str, dict]]) -> list[dict]:
"""One `msearch` over (index, body) pairs; raises SearchFailed for the first body that errored."""
searches = [part for index, body in requests for part in ({"index": index}, body)]
responses = es.msearch(searches=searches)["responses"]
for r in responses:
if "error" in r:
raise SearchFailed(r["error"])
return responses


def _native_failed(exc: Exception) -> bool:
def _msearch(bodies: list[dict]) -> list[dict]:
return msearch([(settings.idx_sessions, body) for body in bodies])


def native_rrf_ok() -> bool:
"""False once this cluster has refused the native rrf retriever (no licence)."""
return _native_rrf is not False


def remember_native_rrf(ok: bool) -> None:
global _native_rrf
_native_rrf = ok


def native_failed(exc: Exception) -> bool:
detail = exc.error if isinstance(exc, SearchFailed) else getattr(exc, "body", None)
return is_license_error(detail) or is_license_error(exc)

Expand All @@ -220,7 +235,7 @@ def run(p: SearchParams, mode: Mode, at: datetime) -> tuple[Used, dict, dict]:
_native_rrf = True
return "hybrid", results, facets
except (ApiError, SearchFailed) as exc:
if not _native_failed(exc):
if not native_failed(exc):
raise
_native_rrf = False
log.warning("native rrf retriever not licensed on this cluster; using client-side RRF from now on: %s", exc)
Expand Down
139 changes: 139 additions & 0 deletions backend/tests/test_ask.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,142 @@ def boom(**_kwargs):
def test_ask_needs_a_user_question_last():
body = {"messages": [{"role": "user", "content": "a"}, {"role": "assistant", "content": "b"}]}
assert TestClient(app).post("/api/ask", json=body).status_code == 422


# Retrieval: query bodies, fusion, source numbering.
VEC = [0.1, 0.2, 0.3]
SESSION = {"id": "s1", "title": "Cheap GPUs", "starts_at": "2026-11-09T10:00:00", "ends_at": "2026-11-09T10:30:00"} | {
"room": "Hall A",
"kind": "talk",
"speaker_names": ["Ana"],
}
ALICE = {"id": "alice", "name": "Alice Moreno", "title": "ML Engineer", "company": "Redwood Labs"} | {
"interests": ["GPU scheduling", "eBPF"],
"sample": True,
"bio": "Builds schedulers.",
}
BOB = {"id": "bob", "name": "Bob Ito", "title": "Maintainer", "company": None, "sample": False}


def test_plan_hybrid_is_one_native_rrf_body_per_index_plus_transcripts():
reqs = ask.plan("GPU scheduling today", "emma", MONDAY, VEC, "hybrid", True)
assert [i for i, _ in reqs] == ["confox-sessions", "confox-people", "confox-transcripts"]
sessions, people = reqs[0][1], reqs[1][1]
rrf = sessions["retriever"]["rrf"]
assert rrf["rank_constant"] == 60 and sessions["size"] == ask.SESSION_HITS
knn = rrf["retrievers"][1]["knn"]
assert knn["query_vector"] == VEC and knn["field"] == "embedding"
# "today" is a filter on both the BM25 and the kNN side, and breaks are excluded on both.
lexical = rrf["retrievers"][0]["standard"]["query"]["bool"]
assert {"term": {"day": "2026-11-09"}} in lexical["filter"] and lexical["filter"] == knn["filter"]
assert {"bool": {"must_not": {"terms": {"kind": ["break", "registration"]}}}} in knn["filter"]
p_rrf = people["retriever"]["rrf"]
fields = p_rrf["retrievers"][0]["standard"]["query"]["bool"]["must"]["multi_match"]["fields"]
assert "name^3" in fields and "interests_text^2" in fields and "bio" in fields
assert {"terms": {"kind": ["speaker", "attendee"]}} in p_rrf["retrievers"][1]["knn"]["filter"]
assert {"bool": {"must_not": {"ids": {"values": ["emma"]}}}} in p_rrf["retrievers"][1]["knn"]["filter"]
assert "embedding" in sessions["_source"]["excludes"]


def test_plan_without_a_named_day_nudges_today_instead_of_filtering():
q = ask.plan("kubeflow", "emma", MONDAY, None, "bm25", False)[0][1]["query"]["bool"]
assert q["should"] == [{"term": {"day": {"value": "2026-11-09", "boost": 1.5}}}]
assert not any("term" in f for f in q["filter"])


def test_plan_bm25_has_no_retriever_or_knn():
reqs = ask.plan("ebpf", "emma", MONDAY, None, "bm25", True)
assert [i for i, _ in reqs] == ["confox-sessions", "confox-people", "confox-transcripts"]
assert all("retriever" not in b and "knn" not in b for _, b in reqs)


def test_plan_client_side_has_a_bm25_and_a_knn_body_per_index():
reqs = ask.plan("ebpf", "emma", MONDAY, VEC, "hybrid-client", False)
assert [i for i, _ in reqs] == ["confox-sessions"] * 2 + ["confox-people"] * 2
assert "query" in reqs[0][1] and "knn" in reqs[1][1] and "query" in reqs[2][1] and "knn" in reqs[3][1]


def hit(i):
return {"_id": i, "_source": {"name": i}}


def resp(*ids):
return {"hits": {"hits": [hit(i) for i in ids]}}


def test_collect_fuses_client_side_lists_with_rrf():
responses = [resp("a", "b"), resp("b", "c"), resp("p1"), resp("p2", "p1"), resp()]
sessions, people, chunks = ask.collect(responses, "hybrid-client", True, True)
assert [s["id"] for s in sessions] == ["b", "a", "c"] # b is in both lists, so it wins
assert [p["id"] for p in people] == ["p1", "p2"]
assert chunks == []


def test_collect_native_reads_in_plan_order():
chunk = {"_id": "c", "_source": {"session_id": "s1", "chunk": 2, "text": "t"}}
responses = [resp("s1"), resp("alice"), {"hits": {"hits": [chunk]}}]
sessions, people, chunks = ask.collect(responses, "hybrid", True, True)
assert [s["id"] for s in sessions] == ["s1"] and [p["id"] for p in people] == ["alice"]
assert chunks == [{"session_id": "s1", "chunk": 2, "text": "t"}]


def test_person_context_marks_sample_people_and_never_adds_contacts():
line = ask.person_context(7, ALICE)
assert line.startswith("[7] Person: Alice Moreno, ML Engineer at Redwood Labs; interests: GPU scheduling, eBPF;")
assert "sample attendee" in line and "@" not in line
assert ask.person_context(2, BOB) == "[2] Person: Bob Ito, Maintainer; speaker"


def test_build_sources_numbers_sessions_then_people_then_chunks():
chunk = {"session_id": "s1", "chunk": 3, "text": "words"}
sources, context = ask.build_sources([SESSION], [ALICE, BOB], [chunk], {"s1": "Cheap GPUs"})
assert [s["n"] for s in sources] == [1, 2, 3, 4]
assert [s["kind"] for s in sources] == ["session", "person", "person", "transcript"]
assert sources[0]["session_kind"] == "talk" and sources[0]["room"] == "Hall A"
assert sources[1] == {"n": 2, "kind": "person", "id": "alice", "name": "Alice Moreno"} | {
"title": "ML Engineer",
"company": "Redwood Labs",
"sample": True,
"starts_at": None,
"room": None,
}
assert sources[2]["sample"] is False
assert sources[3]["chunk"] == 3 and sources[3]["title"] == "Sample transcript: Cheap GPUs"
assert context[0].startswith("[1] Cheap GPUs | Mon 9 Nov 10:00-10:30 | Hall A")
assert context[1].startswith("[2] Person: Alice Moreno") and context[3].startswith("[4] Sample transcript")


def test_system_prompt_lets_claude_recommend_people_but_not_invent_contacts():
text = ask.system_prompt({"name": "Emma Carter", "interests": ["AI inference"], "schools": ["University of Utah"]})
assert "recommend people to meet" in text and "sample attendee" in text and "Never invent contact" in text
assert "interests: AI inference" in text and "school: University of Utah" in text


def test_run_retrieval_falls_back_to_client_rrf_without_a_licence(monkeypatch):
calls = []

def fake_msearch(reqs):
calls.append(len(reqs))
if len(reqs) == 2:
raise ask.search.SearchFailed(
{"type": "security_exception", "reason": "current license is non-compliant for [rrf]"}
)
return [resp("s1"), resp("s2"), resp("alice"), resp("bob")]

monkeypatch.setattr(ask.search, "msearch", fake_msearch)
monkeypatch.setattr(ask.search, "_native_rrf", None)
mode, sessions, people, chunks = ask.run_retrieval("gpu", "emma", MONDAY, VEC, False)
assert mode == "hybrid-client" and calls == [2, 4]
assert [s["id"] for s in sessions] == ["s1", "s2"] and [p["id"] for p in people] == ["alice", "bob"]
assert not ask.search.native_rrf_ok()
monkeypatch.setattr(ask.search, "_native_rrf", None)


def test_run_retrieval_without_a_key_is_bm25(monkeypatch):
monkeypatch.setattr(ask.search, "msearch", lambda reqs: [resp("s1"), resp("alice")])
assert ask.run_retrieval("gpu", "emma", MONDAY, None, False)[0] == "bm25"


def test_query_vector_is_none_without_a_key(monkeypatch):
monkeypatch.setattr(ask.embeddings.settings, "openai_api_key", "")
assert ask.query_vector("gpu") is None
14 changes: 8 additions & 6 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ Kinds fold into five groups for the timeline (talks, keynotes, co-located, break

## Ask (pull request 8)

`POST /api/ask` answers a question from retrieved sessions and streams the answer as Server-Sent Events.
`POST /api/ask` answers a question from retrieved sessions, people and transcript chunks, and can recommend people to meet. It streams the answer as Server-Sent Events.

```mermaid
sequenceDiagram
Expand All @@ -125,7 +125,9 @@ sequenceDiagram
participant E as Elasticsearch
participant C as Claude
B->>A: POST /api/ask {messages, user_id}
A->>E: retrieve: BM25 over sessions (top 8), transcript chunks (top 4), user profile
A->>A: embed the question once
A->>E: one msearch: hybrid sessions (top 8), hybrid people (top 5), transcript chunks (top 4)
A->>E: user profile
A-->>B: data: {type: sources}
A->>C: chat claude-opus-5-5 (stream)
C-->>A: text deltas
Expand All @@ -135,10 +137,10 @@ sequenceDiagram

| Piece | Where | Notes |
|---|---|---|
| Retrieval | `routers/ask.py`, span `retrieve` | `multi_match` over title^3, speaker_names^2, projects^2, track, description; breaks and registration excluded. A day named in the question ("today", "tomorrow", "Wednesday") filters to that day; otherwise today gets a small boost |
| Prompt | system: role, `clock.now()` spoken ("Monday 9 November, 08:40"), the user's interests and school; latest user turn: numbered sources then the question | Earlier turns are sent back as plain text |
| Answer | Claude cites `[n]`; the browser shows chips only for the sources the answer cites, with day, time and room | Says so when the sources do not answer |
| Events | `sources`, `delta`, `done` (tokens, cost, duration, stop reason) or `error` | Counter `confox.chat.requests` (attribute `feature`) |
| Retrieval | `routers/ask.py`, span `retrieve` | The latest question is embedded once (`embeddings.embed`). One `msearch` runs: **sessions** (BM25 `multi_match` over title^3, speaker_names^2, projects^2, track, description, plus kNN on `embedding`), **people** (BM25 over name^3, title^2, company^2, interests_text^2, bio, plus kNN on the people `embedding`; only kinds `speaker` and `attendee`, never the asking user) and **transcript chunks** (BM25, as before). Each hybrid pair is fused by reciprocal rank fusion (constant 60, window 30, kNN k 20): the native `rrf` retriever, or on a basic licence the same BM25 and kNN lists fetched in the msearch and fused in Python with `search.rrf_fuse` (the licence fallback and its memory are shared with Search). Breaks and registration are excluded; a day named in the question is a filter on both sides, otherwise today gets a small BM25 boost. No `OPENAI_API_KEY`, or a failed embedding call: BM25 only. Span attributes `confox.retrieve.mode` (`hybrid`, `hybrid-client`, `bm25`), `.sessions`, `.people`, `.transcript_chunks` |
| Prompt | system: role, `clock.now()` spoken ("Monday 9 November, 08:40"), the user's interests and school, rules for people; latest user turn: numbered sources then the question | Sources are numbered sessions, then people, then transcript chunks: `[7] Person: Alice Moreno, ML Engineer at Redwood Labs; interests: ...; sample attendee (generated, not a real person)`. Claude may recommend people, must cite them, must call sample people sample attendees and must not invent contact details. Earlier turns are sent back as plain text |
| Answer | Claude cites `[n]`; the browser shows chips only for the sources the answer cites | Session chips: day, time and room. Person chips: initials, name, "title · company", a Sample chip for generated attendees, linking to `/people?q=<name>`. Says so when the sources do not answer |
| Events | `sources`, `delta`, `done` (tokens, cost, duration, stop reason) or `error`. Each source has `n`, `kind` (`session`, `person` or `chunk`), `id`, `title`, `starts_at`, `room`; sessions add `session_kind`, people add `name`, `title` (job title), `company`, `sample`, chunks add `chunk` | Counter `confox.chat.requests` (attribute `feature`) |

### LLM calls (`app/llm.py`)

Expand Down
35 changes: 34 additions & 1 deletion frontend/src/components/ask/SourceChips.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { FileText, MapPin } from 'lucide-react'
import { citedNumbers, formatWhen, placeName, type Source } from './chat.ts'
import { Link } from 'react-router'
import { citedNumbers, formatWhen, initials, placeName, roleLine, type Source } from './chat.ts'

type Props = {
text: string
Expand All @@ -19,6 +20,13 @@ export default function SourceChips({ text, sources, onSelect }: Props) {
return (
<ul className="chat-sources" aria-label="Sources">
{cited.map((s) => {
if (s.kind === 'person') {
return (
<li key={s.n}>
<PersonChip s={s} />
</li>
)
}
const body = (
<>
<span className="chat-source-n">{s.n}</span>
Expand Down Expand Up @@ -58,3 +66,28 @@ export default function SourceChips({ text, sources, onSelect }: Props) {
</ul>
)
}

/** A person source: initials, name, "title · company", a Sample chip for generated attendees, a link to People. */
function PersonChip({ s }: { s: Source }) {
const name = s.name ?? s.title
const role = roleLine(s)
return (
<Link className="chat-source chat-source-person" to={`/people?q=${encodeURIComponent(name)}`}>
<span className="chat-source-n">{s.n}</span>
<span className="avatar chat-source-avatar" aria-hidden="true">
{initials(name)}
</span>
<span className="chat-source-body">
<span className="chat-source-title">
{name}
{s.sample && (
<span className="chip chip-warn chat-source-sample" title="Generated sample attendee, not a real person">
Sample
</span>
)}
</span>
{role && <span className="chat-source-meta">{role}</span>}
</span>
</Link>
)
}
18 changes: 18 additions & 0 deletions frontend/src/components/ask/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,15 @@ export type Source = {
title: string
starts_at: string | null
room: string | null
/** Ask: "session" | "person" | "chunk". Catch up still sends "transcript" for its parts. */
kind: string | null
chunk?: number
/** Sessions: talk, keynote, ... */
session_kind?: string | null
/** People. `title` is then the job title. */
name?: string
company?: string | null
sample?: boolean
}

export type Usage = {
Expand Down Expand Up @@ -108,3 +115,14 @@ export function citedNumbers(text: string): number[] {
}
return seen
}

/** "AM" from "Alice Moreno". */
export function initials(name: string): string {
const parts = name.trim().split(/\s+/).filter(Boolean)
return ((parts[0]?.[0] ?? '') + (parts.length > 1 ? parts[parts.length - 1][0] : '')).toUpperCase()
}

/** "ML Engineer · Redwood Labs", whichever parts exist. */
export function roleLine(s: Pick<Source, 'title' | 'company'>): string {
return [s.title, s.company].filter(Boolean).join(' \u00b7 ')
}
5 changes: 3 additions & 2 deletions frontend/src/pages/Ask.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import '../styles/ask.css'
const STARTERS = [
'Which talks today are about running LLM inference cheaply on GPUs?',
'Where should I go this week to learn about GPU scheduling with Kubeflow or KServe?',
'Who should I meet about eBPF and GPU scheduling?',
'What did the Tuesday keynotes say about running AI agents safely?',
]

Expand All @@ -13,13 +14,13 @@ export default function Ask() {
<section className="page ask-page" aria-labelledby="page-title">
<h1 id="page-title">Ask Confox</h1>
<p className="page-lead">
Ask about the schedule. Answers come from the sessions Confox finds, with numbered sources you can check.
Ask about the schedule or who to meet. Answers come from the sessions and people Confox finds, with numbered sources you can check.
</p>
<ChatThread
endpoint="ask"
extraBody={{ user_id: DEMO_USER }}
label="Ask Confox conversation"
placeholder="Ask about talks, speakers, rooms or times"
placeholder="Ask about talks, people, rooms or times"
starters={STARTERS}
/>
</section>
Expand Down
4 changes: 4 additions & 0 deletions frontend/src/styles/ask.css
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ button.chat-source:hover { background: var(--panel-3); color: var(--text); }
.chat-source-body { display: flex; flex-direction: column; min-width: 0; }
.chat-source-title { color: var(--text); font-weight: 500; overflow-wrap: anywhere; }
.chat-source-meta { display: inline-flex; align-items: center; flex-wrap: wrap; gap: 3px; color: var(--muted); }
.chat-source-person { align-items: center; text-decoration: none; }
a.chat-source:hover { background: var(--panel-3); color: var(--text); }
.chat-source-avatar { flex: none; width: 26px; height: 26px; font-size: 11px; }
.chat-source-sample { margin-left: 6px; padding: 0 7px; font-size: 11px; vertical-align: 1px; }
.chat-usage { margin: 10px 0 0; color: var(--muted); font-size: 11px; }

.chat-form {
Expand Down
Loading