From 9ab743d4134f4812ec14e99904b5e368d58d7818 Mon Sep 17 00:00:00 2001 From: riponcm <86886711+riponcm@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:49:34 -0700 Subject: [PATCH 1/2] Ask: hybrid retrieval over sessions and people, people as cited sources - One embedding and one msearch: sessions and people each BM25 + kNN fused with RRF (native retriever, client-side fallback shared with Search), plus transcript chunks; BM25 only without an embedding key - Claude may recommend people to meet, must cite them, labels sample attendees and never invents contact details - Person source chips (initials, title, company, Sample) link to People - 11 new tests --- backend/app/routers/ask.py | 296 +++++++++++++++----- backend/app/routers/search.py | 23 +- backend/tests/test_ask.py | 139 +++++++++ docs/architecture.md | 14 +- frontend/src/components/ask/SourceChips.tsx | 37 ++- frontend/src/components/ask/chat.ts | 18 ++ frontend/src/pages/Ask.tsx | 5 +- frontend/src/styles/ask.css | 4 + 8 files changed, 457 insertions(+), 79 deletions(-) diff --git a/backend/app/routers/ask.py b/backend/app/routers/ask.py index 628977b..8906c7b 100644 --- a/backend/app/routers/ask.py +++ b/backend/app/routers/ask.py @@ -1,27 +1,34 @@ -"""Ask Confox: a question answered by Claude from sessions (and sample transcripts) retrieved from Elasticsearch. +"""Ask Confox: a question answered by Claude from retrieved sessions, people and sample transcripts. POST /api/ask streams Server-Sent Events: `sources`, then `delta` text chunks, then `done` with tokens and cost. """ +import logging import re from datetime import date, datetime, timedelta from typing import Literal -from elasticsearch import NotFoundError +from elasticsearch import ApiError, NotFoundError from fastapi import APIRouter from fastapi.responses import StreamingResponse from opentelemetry import trace from pydantic import BaseModel, Field, field_validator -from .. import activity, clock, llm +from .. import activity, clock, embeddings, llm from ..config import settings from ..es import es +from . import people, search router = APIRouter(prefix="/api/ask", tags=["ask"]) +log = logging.getLogger(__name__) tracer = trace.get_tracer("confox.ask") SESSION_HITS = 8 +PEOPLE_HITS = 5 TRANSCRIPT_HITS = 4 +KNN_K = 20 +RANK_WINDOW = 30 +PEOPLE_KINDS = ["speaker", "attendee"] NOT_SESSIONS = ["break", "registration"] @@ -90,84 +97,239 @@ def asked_day(question: str, today: date) -> date | None: return None -def search_sessions(question: str, today: date) -> list[dict]: - day = asked_day(question, today) - # A named day is a filter; otherwise today gets a small nudge, since questions usually mean "soon". - by_day = ( - {"filter": {"term": {"day": day.isoformat()}}} - if day - else {"should": {"term": {"day": {"value": today.isoformat(), "boost": 1.5}}}} - ) - r = es.search( - index=settings.idx_sessions, - size=SESSION_HITS, - source_excludes=["embedding"], - query={ - "bool": { - "must": { - "multi_match": { - "query": question, - "fields": ["title^3", "speaker_names^2", "projects^2", "track", "description"], - } - }, - "must_not": {"terms": {"kind": NOT_SESSIONS}}, +def day_scope(day: date | None, today: date) -> tuple[list[dict], list[dict]]: + """Filters and optional boosts for sessions. A named day is a filter; otherwise today gets a small nudge.""" + flt: list[dict] = [{"bool": {"must_not": {"terms": {"kind": NOT_SESSIONS}}}}] + if day: + return flt + [{"term": {"day": day.isoformat()}}], [] + return flt, [{"term": {"day": {"value": today.isoformat(), "boost": 1.5}}}] + + +def sessions_lexical(question: str, flt: list[dict], should: list[dict]) -> dict: + query: dict = { + "must": {"multi_match": {"query": question, "fields": search.TEXT_FIELDS}}, + "filter": flt, + } + if should: + query["should"] = should + return {"bool": query} + + +def people_scope(user_id: str) -> list[dict]: + """Speakers and sample attendees, never the person asking.""" + return [{"terms": {"kind": PEOPLE_KINDS}}, {"bool": {"must_not": {"ids": {"values": [user_id]}}}}] + + +def people_lexical(question: str, flt: list[dict]) -> dict: + return {"bool": {"must": {"multi_match": {"query": question, "fields": people.TEXT_FIELDS}}, "filter": flt}} + + +def plain_body(query: dict, size: int) -> dict: + return {"size": size, "query": query, "_source": {"excludes": ["embedding"]}} + + +def hybrid_body(lexical: dict, vector: list[float], flt: list[dict], size: int) -> dict: + """BM25 and kNN fused by the native rrf retriever; the same filters go into both sides.""" + return { + "size": size, + "_source": {"excludes": ["embedding"]}, + "retriever": { + "rrf": { + "retrievers": [ + {"standard": {"query": lexical}}, + {"knn": search.knn(vector, KNN_K, flt)}, + ], + "rank_window_size": RANK_WINDOW, + "rank_constant": search.RRF_K, } - | by_day }, - ) - return [{"id": h["_id"], **h["_source"]} for h in r["hits"]["hits"]] + } -def search_transcripts(question: str) -> list[dict]: - if not es.indices.exists(index=settings.idx_transcripts): - return [] - r = es.search( - index=settings.idx_transcripts, - size=TRANSCRIPT_HITS, - query={"bool": {"must": {"match": {"text": question}}, "filter": {"term": {"doc_type": "chunk"}}}}, - ) - return [h["_source"] for h in r["hits"]["hits"]] +def knn_only_body(vector: list[float], flt: list[dict]) -> dict: + return {"size": KNN_K, "knn": search.knn(vector, KNN_K, flt), "_source": {"excludes": ["embedding"]}} -def retrieve(question: str, user_id: str) -> tuple[list[dict], list[str], dict]: - """Sources for the answer: numbered entries for the browser and the matching context lines for Claude.""" - with tracer.start_as_current_span("retrieve") as span: - sessions = search_sessions(question, clock.now().date()) - chunks = search_transcripts(question) - titles = {} - if chunks: - ids = list({c["session_id"] for c in chunks}) - docs = es.mget(index=settings.idx_sessions, ids=ids, source_includes=["title"])["docs"] - titles = {d["_id"]: d["_source"]["title"] for d in docs if d.get("found")} - user = profile(user_id) - span.set_attribute("confox.retrieve.sessions", len(sessions)) - span.set_attribute("confox.retrieve.transcript_chunks", len(chunks)) +def transcripts_body(question: str) -> dict: + return { + "size": TRANSCRIPT_HITS, + "query": {"bool": {"must": {"match": {"text": question}}, "filter": {"term": {"doc_type": "chunk"}}}}, + } + + +Mode = Literal["hybrid", "hybrid-client", "bm25"] + - sources, context = [], [] +def plan( + question: str, user_id: str, today: date, vector: list[float] | None, mode: Mode, with_transcripts: bool +) -> list[tuple[str, dict]]: + """The (index, body) pairs of the one msearch. Order matters: `collect` reads the answers back in this order. + + native: sessions, people. client: sessions BM25, sessions kNN, people BM25, people kNN (fused in Python). + bm25: sessions, people. Transcript chunks, when that index exists, always come last. + """ + s_flt, s_should = day_scope(asked_day(question, today), today) + p_flt = people_scope(user_id) + s_lex = sessions_lexical(question, s_flt, s_should) + p_lex = people_lexical(question, p_flt) + if vector is not None and mode == "hybrid": + out = [ + (settings.idx_sessions, hybrid_body(s_lex, vector, s_flt, SESSION_HITS)), + (settings.idx_people, hybrid_body(p_lex, vector, p_flt, PEOPLE_HITS)), + ] + elif vector is not None: + out = [ + (settings.idx_sessions, plain_body(s_lex, RANK_WINDOW)), + (settings.idx_sessions, knn_only_body(vector, s_flt)), + (settings.idx_people, plain_body(p_lex, RANK_WINDOW)), + (settings.idx_people, knn_only_body(vector, p_flt)), + ] + else: + out = [ + (settings.idx_sessions, plain_body(s_lex, SESSION_HITS)), + (settings.idx_people, plain_body(p_lex, PEOPLE_HITS)), + ] + if with_transcripts: + out.append((settings.idx_transcripts, transcripts_body(question))) + return out + + +def _hits(response: dict) -> list[dict]: + return response["hits"]["hits"] + + +def _doc(hit: dict) -> dict: + return {"id": hit["_id"], **hit["_source"]} + + +def collect(responses: list[dict], mode: Mode, vector_used: bool, with_transcripts: bool) -> tuple[list, list, list]: + """Sessions, people and transcript chunks from the msearch responses laid out by `plan`.""" + chunks = [h["_source"] for h in _hits(responses[-1])] if with_transcripts else [] + if vector_used and mode == "hybrid-client": + sessions = search.rrf_fuse([_hits(responses[0]), _hits(responses[1])], SESSION_HITS) + found = search.rrf_fuse([_hits(responses[2]), _hits(responses[3])], PEOPLE_HITS) + else: + sessions, found = _hits(responses[0]), _hits(responses[1]) + return [_doc(h) for h in sessions], [_doc(h) for h in found], chunks + + +def run_retrieval( + question: str, user_id: str, today: date, vector: list[float] | None, with_transcripts: bool +) -> tuple[Mode, list[dict], list[dict], list[dict]]: + """Hybrid (native rrf), else client-side rrf when the cluster has no licence for it, else BM25 only.""" + if vector is not None and search.native_rrf_ok(): + try: + reqs = plan(question, user_id, today, vector, "hybrid", with_transcripts) + out = collect(search.msearch(reqs), "hybrid", True, with_transcripts) + search.remember_native_rrf(True) + return ("hybrid", *out) + except (ApiError, search.SearchFailed) as exc: + if not search.native_failed(exc): + raise + search.remember_native_rrf(False) + log.warning("native rrf retriever not licensed on this cluster; using client-side RRF: %s", exc) + span = trace.get_current_span() + span.record_exception(exc) + span.add_event("confox.search.rrf_fallback", {"reason": str(exc)[:500]}) + mode: Mode = "hybrid-client" if vector is not None else "bm25" + reqs = plan(question, user_id, today, vector, mode, with_transcripts) + return (mode, *collect(search.msearch(reqs), mode, vector is not None, with_transcripts)) + + +def query_vector(question: str) -> list[float] | None: + """The question embedded once, or None (no key, or the call failed: keyword search only).""" + if not embeddings.enabled(): + return None + try: + return embeddings.embed([question])[0] + except Exception as exc: + log.warning("question embedding failed, using keyword search: %s", exc, exc_info=exc) + trace.get_current_span().record_exception(exc) + return None + + +def session_context(n: int, s: dict) -> str: + details = [ + when(s.get("starts_at"), s.get("ends_at")), + s.get("room") or "room not set", + s.get("kind") or "", + "Speakers: " + ", ".join(s.get("speaker_names") or []) if s.get("speaker_names") else "", + f"Track: {s['track']}" if s.get("track") else "", + "Projects: " + ", ".join(s["projects"]) if s.get("projects") else "", + ] + desc = (s.get("description") or "").replace("\n", " ")[:600] + return f"[{n}] {s['title']} | " + " | ".join(d for d in details if d) + (f"\n{desc}" if desc else "") + + +def person_context(n: int, p: dict) -> str: + """ "[7] Person: Alice Moreno, ML Engineer at Redwood Labs; interests: a, b; sample attendee".""" + role = ", ".join(x for x in [p.get("title")] if x) + if p.get("company"): + role = f"{role} at {p['company']}" if role else p["company"] + parts = [f"[{n}] Person: {p['name']}" + (f", {role}" if role else "")] + if p.get("interests"): + parts.append("interests: " + ", ".join(p["interests"][:8])) + parts.append("sample attendee (generated, not a real person)" if p.get("sample") else "speaker") + line = "; ".join(parts) + bio = (p.get("bio") or "").replace("\n", " ")[:300] + return line + (f"\n{bio}" if bio else "") + + +def build_sources( + sessions: list[dict], people_found: list[dict], chunks: list[dict], titles: dict[str, str] +) -> tuple[list[dict], list[str]]: + """Numbered sources (sessions, then people, then transcript chunks): browser entries and Claude's context lines.""" + sources: list[dict] = [] + context: list[str] = [] for s in sessions: n = len(sources) + 1 sources.append( - {"n": n, "id": s["id"], "title": s["title"], "starts_at": s.get("starts_at"), "room": s.get("room")} - | {"kind": s.get("kind")} + {"n": n, "kind": "session", "id": s["id"], "title": s["title"]} + | {"starts_at": s.get("starts_at"), "room": s.get("room"), "session_kind": s.get("kind")} ) - details = [ - when(s.get("starts_at"), s.get("ends_at")), - s.get("room") or "room not set", - s.get("kind") or "", - "Speakers: " + ", ".join(s.get("speaker_names") or []) if s.get("speaker_names") else "", - f"Track: {s['track']}" if s.get("track") else "", - "Projects: " + ", ".join(s["projects"]) if s.get("projects") else "", - ] - desc = (s.get("description") or "").replace("\n", " ")[:600] - context.append(f"[{n}] {s['title']} | " + " | ".join(d for d in details if d) + (f"\n{desc}" if desc else "")) + context.append(session_context(n, s)) + for p in people_found: + n = len(sources) + 1 + sources.append( + { + "n": n, + "kind": "person", + "id": p["id"], + "name": p["name"], + "title": p.get("title"), + "company": p.get("company"), + } + | {"sample": bool(p.get("sample")), "starts_at": None, "room": None} + ) + context.append(person_context(n, p)) for c in chunks: n = len(sources) + 1 title = titles.get(c["session_id"], "a keynote") sources.append( - {"n": n, "id": c["session_id"], "title": f"Sample transcript: {title}", "starts_at": None, "room": None} - | {"kind": "transcript", "chunk": c["chunk"]} + {"n": n, "kind": "chunk", "id": c["session_id"], "title": f"Sample transcript: {title}"} + | {"starts_at": None, "room": None, "chunk": c["chunk"]} ) context.append(f"[{n}] Sample transcript (generated) of '{title}', part {c['chunk']}:\n{c['text']}") + return sources, context + + +def retrieve(question: str, user_id: str) -> tuple[list[dict], list[str], dict]: + """Sources for the answer: numbered entries for the browser and the matching context lines for Claude.""" + with tracer.start_as_current_span("retrieve") as span: + vector = query_vector(question) + with_transcripts = bool(es.indices.exists(index=settings.idx_transcripts)) + mode, sessions, found, chunks = run_retrieval(question, user_id, clock.now().date(), vector, with_transcripts) + titles = {} + if chunks: + ids = list({c["session_id"] for c in chunks}) + docs = es.mget(index=settings.idx_sessions, ids=ids, source_includes=["title"])["docs"] + titles = {d["_id"]: d["_source"]["title"] for d in docs if d.get("found")} + user = profile(user_id) + span.set_attribute("confox.retrieve.mode", mode) + span.set_attribute("confox.retrieve.sessions", len(sessions)) + span.set_attribute("confox.retrieve.people", len(found)) + span.set_attribute("confox.retrieve.transcript_chunks", len(chunks)) + sources, context = build_sources(sessions, found, chunks, titles) return sources, context, user @@ -186,7 +348,11 @@ def system_prompt(user: dict) -> str: "Answer only from the numbered sources in the latest message. Cite them inline like [1] or [2][4]. " "Be concise: a short paragraph or a short list. Give day, time and room for sessions you suggest, and " "prefer ones that have not started yet. Sources marked 'Sample transcript (generated)' are fictional " - "stand-ins, not the speaker's actual words; say so if you use one. " + "stand-ins, not the speaker's actual words; say so if you use one.\n" + "Sources starting 'Person:' are people. You may recommend people to meet when it helps, say why they fit " + "(shared interests, their talks, their work) and cite them like any source. People marked 'sample attendee' " + "are generated demo profiles: always call them a sample attendee when you mention one. Never invent contact " + "details, emails, handles or availability; offer only what the source states.\n" "If the sources do not answer the question, say that plainly instead " "of guessing. Plain text only, no headings." ) diff --git a/backend/app/routers/search.py b/backend/app/routers/search.py index bcc51bb..a29c90b 100644 --- a/backend/app/routers/search.py +++ b/backend/app/routers/search.py @@ -186,8 +186,9 @@ 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: @@ -195,7 +196,21 @@ def _msearch(bodies: list[dict]) -> list[dict]: 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) @@ -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) diff --git a/backend/tests/test_ask.py b/backend/tests/test_ask.py index 74672a3..72e14d0 100644 --- a/backend/tests/test_ask.py +++ b/backend/tests/test_ask.py @@ -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", "chunk"] + 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 diff --git a/docs/architecture.md b/docs/architecture.md index b1427f8..4d70848 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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 @@ -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 @@ -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=`. 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`) diff --git a/frontend/src/components/ask/SourceChips.tsx b/frontend/src/components/ask/SourceChips.tsx index 51135f4..38f1285 100644 --- a/frontend/src/components/ask/SourceChips.tsx +++ b/frontend/src/components/ask/SourceChips.tsx @@ -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 @@ -19,12 +20,19 @@ export default function SourceChips({ text, sources, onSelect }: Props) { return ( ) } + +/** 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 ( + + {s.n} + + + + {name} + {s.sample && ( + + Sample + + )} + + {role && {role}} + + + ) +} diff --git a/frontend/src/components/ask/chat.ts b/frontend/src/components/ask/chat.ts index f88d4f9..f606ed5 100644 --- a/frontend/src/components/ask/chat.ts +++ b/frontend/src/components/ask/chat.ts @@ -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 = { @@ -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): string { + return [s.title, s.company].filter(Boolean).join(' \u00b7 ') +} diff --git a/frontend/src/pages/Ask.tsx b/frontend/src/pages/Ask.tsx index 022624e..cf1b089 100644 --- a/frontend/src/pages/Ask.tsx +++ b/frontend/src/pages/Ask.tsx @@ -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?', ] @@ -13,13 +14,13 @@ export default function Ask() {

Ask Confox

- 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.

diff --git a/frontend/src/styles/ask.css b/frontend/src/styles/ask.css index 35e1bd2..cf461be 100644 --- a/frontend/src/styles/ask.css +++ b/frontend/src/styles/ask.css @@ -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 { From da9ac2cc9830a61eb12d8a76b9b9dbb30a8f7d01 Mon Sep 17 00:00:00 2001 From: riponcm <86886711+riponcm@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:59:59 -0700 Subject: [PATCH 2/2] Ask: transcript sources use their own kind, so Catch-up part chips are unchanged --- backend/app/routers/ask.py | 2 +- backend/tests/test_ask.py | 2 +- frontend/src/components/ask/SourceChips.tsx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/app/routers/ask.py b/backend/app/routers/ask.py index 8906c7b..694d7fc 100644 --- a/backend/app/routers/ask.py +++ b/backend/app/routers/ask.py @@ -306,7 +306,7 @@ def build_sources( n = len(sources) + 1 title = titles.get(c["session_id"], "a keynote") sources.append( - {"n": n, "kind": "chunk", "id": c["session_id"], "title": f"Sample transcript: {title}"} + {"n": n, "kind": "transcript", "id": c["session_id"], "title": f"Sample transcript: {title}"} | {"starts_at": None, "room": None, "chunk": c["chunk"]} ) context.append(f"[{n}] Sample transcript (generated) of '{title}', part {c['chunk']}:\n{c['text']}") diff --git a/backend/tests/test_ask.py b/backend/tests/test_ask.py index 72e14d0..c7b998a 100644 --- a/backend/tests/test_ask.py +++ b/backend/tests/test_ask.py @@ -150,7 +150,7 @@ 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", "chunk"] + 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", diff --git a/frontend/src/components/ask/SourceChips.tsx b/frontend/src/components/ask/SourceChips.tsx index 38f1285..820e332 100644 --- a/frontend/src/components/ask/SourceChips.tsx +++ b/frontend/src/components/ask/SourceChips.tsx @@ -32,7 +32,7 @@ export default function SourceChips({ text, sources, onSelect }: Props) { {s.n} {s.title} - {(s.kind === 'chunk' || s.kind === 'transcript') && ( + {s.kind === 'transcript' && (