Spaces:
Runtime error
Runtime error
GitHub Actions commited on
Commit ·
5af4b9d
1
Parent(s): d91b95f
Deploy 97556b1
Browse files- app/main.py +1 -0
- app/pipeline/nodes/generate.py +7 -13
- app/pipeline/nodes/retrieve.py +32 -4
- app/services/llm_client.py +4 -1
- app/services/reranker.py +18 -13
- app/services/vector_store.py +48 -0
- tests/test_generate_numbered_sources.py +22 -0
- tests/test_resume_chunker_sections.py +36 -0
- tests/test_retrieve_contact_filter.py +19 -0
- tests/test_site_profile.py +4 -4
- tests/test_vector_store_fetch_by_doc_ids.py +56 -0
app/main.py
CHANGED
|
@@ -276,6 +276,7 @@ async def lifespan(app: FastAPI):
|
|
| 276 |
app.state.tts_keepalive_task.cancel()
|
| 277 |
except Exception:
|
| 278 |
pass
|
|
|
|
| 279 |
app.state.semantic_cache = None
|
| 280 |
app.state.qdrant.close()
|
| 281 |
if app.state.tts_client:
|
|
|
|
| 276 |
app.state.tts_keepalive_task.cancel()
|
| 277 |
except Exception:
|
| 278 |
pass
|
| 279 |
+
await reranker.aclose()
|
| 280 |
app.state.semantic_cache = None
|
| 281 |
app.state.qdrant.close()
|
| 282 |
if app.state.tts_client:
|
app/pipeline/nodes/generate.py
CHANGED
|
@@ -418,11 +418,6 @@ def _build_low_trust_fallback(query: str, source_refs: list[SourceRef]) -> str:
|
|
| 418 |
|
| 419 |
|
| 420 |
def make_generate_node(llm_client: LLMClient, gemini_client=None) -> Callable[[PipelineState], dict]: # noqa: ANN001
|
| 421 |
-
# Number of token chunks to buffer before deciding there is no CoT block.
|
| 422 |
-
# Llama 3.1 8B may omit <think> entirely; Llama 3.3 70B always starts with one.
|
| 423 |
-
# 50 chunks is enough to cover the opening tag without delaying short answers.
|
| 424 |
-
_THINK_LOOKAHEAD: int = 50
|
| 425 |
-
|
| 426 |
async def generate_node(state: PipelineState) -> dict:
|
| 427 |
writer = get_stream_writer()
|
| 428 |
query = state["query"]
|
|
@@ -518,11 +513,12 @@ def make_generate_node(llm_client: LLMClient, gemini_client=None) -> Callable[[P
|
|
| 518 |
)
|
| 519 |
prompt = f"{criticism_note}{history_prefix}Passages:\n{context_block}\n\nVisitor question: {query}"
|
| 520 |
|
| 521 |
-
#
|
| 522 |
# Phase 1 — detect and buffer the <think> block, emitting thinking events.
|
| 523 |
# Phase 2 — emit answer tokens in real time after </think>.
|
| 524 |
-
#
|
| 525 |
-
#
|
|
|
|
| 526 |
stream = llm_client.complete_with_complexity(
|
| 527 |
prompt=prompt,
|
| 528 |
system=_VOICE_SYSTEM_PROMPT if is_audio_mode else build_system_prompt(),
|
|
@@ -535,14 +531,12 @@ def make_generate_node(llm_client: LLMClient, gemini_client=None) -> Callable[[P
|
|
| 535 |
phase2_buf = "" # tail buffer — holds last _TAG_BOUNDARY_WINDOW chars
|
| 536 |
in_think = False # currently inside <think> block
|
| 537 |
think_done = False # </think> was found; switched to direct streaming
|
| 538 |
-
no_cot = False #
|
| 539 |
-
token_chunk_count = 0 # number of token chunks received
|
| 540 |
think_first_emitted = False # CoT first-sentence status already sent
|
| 541 |
|
| 542 |
try:
|
| 543 |
async for token in stream:
|
| 544 |
raw_answer += token
|
| 545 |
-
token_chunk_count += 1
|
| 546 |
|
| 547 |
if think_done or no_cot:
|
| 548 |
# Phase 2: emit all but the last _TAG_BOUNDARY_WINDOW chars so that
|
|
@@ -565,8 +559,8 @@ def make_generate_node(llm_client: LLMClient, gemini_client=None) -> Callable[[P
|
|
| 565 |
# Text before the think tag is part of the answer.
|
| 566 |
writer({"type": "token", "text": pre})
|
| 567 |
buf = buf[buf.index("<think>") + 7:] # 7 = len("<think>")
|
| 568 |
-
elif
|
| 569 |
-
#
|
| 570 |
no_cot = True
|
| 571 |
writer({"type": "token", "text": buf})
|
| 572 |
buf = ""
|
|
|
|
| 418 |
|
| 419 |
|
| 420 |
def make_generate_node(llm_client: LLMClient, gemini_client=None) -> Callable[[PipelineState], dict]: # noqa: ANN001
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 421 |
async def generate_node(state: PipelineState) -> dict:
|
| 422 |
writer = get_stream_writer()
|
| 423 |
query = state["query"]
|
|
|
|
| 513 |
)
|
| 514 |
prompt = f"{criticism_note}{history_prefix}Passages:\n{context_block}\n\nVisitor question: {query}"
|
| 515 |
|
| 516 |
+
# The model streams tokens one chunk at a time. We intercept them to:
|
| 517 |
# Phase 1 — detect and buffer the <think> block, emitting thinking events.
|
| 518 |
# Phase 2 — emit answer tokens in real time after </think>.
|
| 519 |
+
# A model that thinks aloud opens its reply with <think>, so the first characters
|
| 520 |
+
# decide: anything else first means there is no block, and the answer streams at
|
| 521 |
+
# once. (Waiting for 50 chunks held back most of every short answer.)
|
| 522 |
stream = llm_client.complete_with_complexity(
|
| 523 |
prompt=prompt,
|
| 524 |
system=_VOICE_SYSTEM_PROMPT if is_audio_mode else build_system_prompt(),
|
|
|
|
| 531 |
phase2_buf = "" # tail buffer — holds last _TAG_BOUNDARY_WINDOW chars
|
| 532 |
in_think = False # currently inside <think> block
|
| 533 |
think_done = False # </think> was found; switched to direct streaming
|
| 534 |
+
no_cot = False # the reply did not open with <think>
|
|
|
|
| 535 |
think_first_emitted = False # CoT first-sentence status already sent
|
| 536 |
|
| 537 |
try:
|
| 538 |
async for token in stream:
|
| 539 |
raw_answer += token
|
|
|
|
| 540 |
|
| 541 |
if think_done or no_cot:
|
| 542 |
# Phase 2: emit all but the last _TAG_BOUNDARY_WINDOW chars so that
|
|
|
|
| 559 |
# Text before the think tag is part of the answer.
|
| 560 |
writer({"type": "token", "text": pre})
|
| 561 |
buf = buf[buf.index("<think>") + 7:] # 7 = len("<think>")
|
| 562 |
+
elif buf.lstrip() and not "<think>".startswith(buf.lstrip()[:7]):
|
| 563 |
+
# The reply opened with something other than <think>: go direct.
|
| 564 |
no_cot = True
|
| 565 |
writer({"type": "token", "text": buf})
|
| 566 |
buf = ""
|
app/pipeline/nodes/retrieve.py
CHANGED
|
@@ -64,7 +64,8 @@ _FOCUS_KEYWORDS: dict[frozenset[str], str] = {
|
|
| 64 |
frozenset({"experience", "work", "job", "role", "career", "internship",
|
| 65 |
"skills", "skill", "education", "degree", "university",
|
| 66 |
"certification", "certifications", "qualified", "resume", "cv",
|
| 67 |
-
"employment", "professional", "placement", "history"
|
|
|
|
| 68 |
frozenset({"project", "built", "build", "developed", "architecture",
|
| 69 |
"system", "platform", "app", "application"}): "project",
|
| 70 |
frozenset({"blog", "post", "article", "wrote", "writing", "published"}): "blog",
|
|
@@ -116,6 +117,25 @@ _NORMALISATION_STOPWORDS: frozenset[str] = frozenset(
|
|
| 116 |
)
|
| 117 |
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
def _focused_source_type(query: str) -> str | None:
|
| 120 |
"""
|
| 121 |
Return the source_type that the query is focused on, or None for broad queries.
|
|
@@ -446,7 +466,7 @@ def make_retrieve_node(
|
|
| 446 |
"top_rerank_score": None,
|
| 447 |
}
|
| 448 |
|
| 449 |
-
fused: list[Chunk] = _rrf_merge(all_ranked_lists)
|
| 450 |
|
| 451 |
# ── Reading events — one per unique source document ────────────────────
|
| 452 |
# Emitted BEFORE deduplication so the user sees sources appear in
|
|
@@ -492,7 +512,13 @@ def make_retrieve_node(
|
|
| 492 |
sibling_count = 0
|
| 493 |
if unique_chunks:
|
| 494 |
sibling_fps: set[str] = {f"{c['metadata']['doc_id']}::{c['metadata']['section']}" for c in unique_chunks}
|
| 495 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 496 |
if sibling_count >= _SIBLING_TOTAL_CAP:
|
| 497 |
break
|
| 498 |
doc_id = seed["metadata"]["doc_id"]
|
|
@@ -500,7 +526,7 @@ def make_retrieve_node(
|
|
| 500 |
if seed_idx is None:
|
| 501 |
seed_idx = -1
|
| 502 |
|
| 503 |
-
siblings =
|
| 504 |
# RC-2 fix: sort by chunk_index so we can prefer adjacent chunks.
|
| 505 |
# Guard against chunk_index being actual None in Qdrant payloads.
|
| 506 |
siblings.sort(key=lambda c: c["metadata"].get("chunk_index") or 0)
|
|
@@ -605,6 +631,8 @@ def make_retrieve_node(
|
|
| 605 |
_FOCUS_TYPE_ALIASES: dict[str, frozenset[str]] = {
|
| 606 |
"cv": frozenset({"cv", "resume", "bio"}),
|
| 607 |
"github_readme": frozenset({"github_readme", "github"}),
|
|
|
|
|
|
|
| 608 |
}
|
| 609 |
for chunk in reranked:
|
| 610 |
doc_id = chunk["metadata"]["doc_id"]
|
|
|
|
| 64 |
frozenset({"experience", "work", "job", "role", "career", "internship",
|
| 65 |
"skills", "skill", "education", "degree", "university",
|
| 66 |
"certification", "certifications", "qualified", "resume", "cv",
|
| 67 |
+
"employment", "professional", "placement", "history",
|
| 68 |
+
"languages", "language", "current", "currently", "company", "employer"}): "cv",
|
| 69 |
frozenset({"project", "built", "build", "developed", "architecture",
|
| 70 |
"system", "platform", "app", "application"}): "project",
|
| 71 |
frozenset({"blog", "post", "article", "wrote", "writing", "published"}): "blog",
|
|
|
|
| 117 |
)
|
| 118 |
|
| 119 |
|
| 120 |
+
# A contact chunk only points at one of his profiles. Each names him, so for any question
|
| 121 |
+
# that is not about reaching or following him it outranks what was actually asked about.
|
| 122 |
+
_CONTACT_INTENT: frozenset[str] = frozenset({
|
| 123 |
+
"contact", "reach", "touch", "email", "mail", "hire", "connect", "message",
|
| 124 |
+
"linkedin", "github", "twitter", "youtube", "profile", "profiles", "social", "socials", "follow",
|
| 125 |
+
})
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _wants_contact(query: str) -> bool:
|
| 129 |
+
return bool(frozenset(re.findall(r"[a-z]+", query.lower())) & _CONTACT_INTENT)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _without_contact_chunks(chunks: list[Chunk], query: str) -> list[Chunk]:
|
| 133 |
+
"""The chunks a question should be answered from: profile pointers only when it asks for them."""
|
| 134 |
+
if _wants_contact(query):
|
| 135 |
+
return chunks
|
| 136 |
+
return [chunk for chunk in chunks if chunk["metadata"].get("source_type") != "contact"]
|
| 137 |
+
|
| 138 |
+
|
| 139 |
def _focused_source_type(query: str) -> str | None:
|
| 140 |
"""
|
| 141 |
Return the source_type that the query is focused on, or None for broad queries.
|
|
|
|
| 466 |
"top_rerank_score": None,
|
| 467 |
}
|
| 468 |
|
| 469 |
+
fused: list[Chunk] = _without_contact_chunks(_rrf_merge(all_ranked_lists), retrieval_query)
|
| 470 |
|
| 471 |
# ── Reading events — one per unique source document ────────────────────
|
| 472 |
# Emitted BEFORE deduplication so the user sees sources appear in
|
|
|
|
| 512 |
sibling_count = 0
|
| 513 |
if unique_chunks:
|
| 514 |
sibling_fps: set[str] = {f"{c['metadata']['doc_id']}::{c['metadata']['section']}" for c in unique_chunks}
|
| 515 |
+
seeds = unique_chunks[:_SIBLING_EXPAND_TOP_N]
|
| 516 |
+
# Every seed's document in one query, not one round trip each.
|
| 517 |
+
siblings_by_doc = vector_store.fetch_by_doc_ids(
|
| 518 |
+
list(dict.fromkeys(seed["metadata"]["doc_id"] for seed in seeds)),
|
| 519 |
+
limit_per_doc=_SIBLING_FETCH_LIMIT,
|
| 520 |
+
)
|
| 521 |
+
for seed in seeds:
|
| 522 |
if sibling_count >= _SIBLING_TOTAL_CAP:
|
| 523 |
break
|
| 524 |
doc_id = seed["metadata"]["doc_id"]
|
|
|
|
| 526 |
if seed_idx is None:
|
| 527 |
seed_idx = -1
|
| 528 |
|
| 529 |
+
siblings = list(siblings_by_doc.get(doc_id, []))
|
| 530 |
# RC-2 fix: sort by chunk_index so we can prefer adjacent chunks.
|
| 531 |
# Guard against chunk_index being actual None in Qdrant payloads.
|
| 532 |
siblings.sort(key=lambda c: c["metadata"].get("chunk_index") or 0)
|
|
|
|
| 631 |
_FOCUS_TYPE_ALIASES: dict[str, frozenset[str]] = {
|
| 632 |
"cv": frozenset({"cv", "resume", "bio"}),
|
| 633 |
"github_readme": frozenset({"github_readme", "github"}),
|
| 634 |
+
# There are no project pages any more: projects live in their READMEs and the CV.
|
| 635 |
+
"project": frozenset({"project", "github_readme", "resume"}),
|
| 636 |
}
|
| 637 |
for chunk in reranked:
|
| 638 |
doc_id = chunk["metadata"]["doc_id"]
|
app/services/llm_client.py
CHANGED
|
@@ -211,6 +211,9 @@ class OpenAIClient:
|
|
| 211 |
|
| 212 |
# About 500 words: longer than any answer the prompts ask for.
|
| 213 |
_MAX_COMPLETION_TOKENS = 700
|
|
|
|
|
|
|
|
|
|
| 214 |
_CLASSIFY_MAX_TOKENS = 16
|
| 215 |
|
| 216 |
def __init__(self, api_key: str, model: str, budget: DailyBudget, client: Optional[AsyncOpenAI] = None):
|
|
@@ -252,7 +255,7 @@ class OpenAIClient:
|
|
| 252 |
stream=stream,
|
| 253 |
reasoning_effort="minimal",
|
| 254 |
max_completion_tokens=self._MAX_COMPLETION_TOKENS,
|
| 255 |
-
timeout=
|
| 256 |
)
|
| 257 |
if not stream:
|
| 258 |
yield response.choices[0].message.content or ""
|
|
|
|
| 211 |
|
| 212 |
# About 500 words: longer than any answer the prompts ask for.
|
| 213 |
_MAX_COMPLETION_TOKENS = 700
|
| 214 |
+
# A stalled stream is retried after 6 s without a chunk rather than waiting out the
|
| 215 |
+
# whole 15 s (an answer once took 14.6 s); the first token normally comes within 2 s.
|
| 216 |
+
_TIMEOUT = httpx.Timeout(15.0, read=6.0)
|
| 217 |
_CLASSIFY_MAX_TOKENS = 16
|
| 218 |
|
| 219 |
def __init__(self, api_key: str, model: str, budget: DailyBudget, client: Optional[AsyncOpenAI] = None):
|
|
|
|
| 255 |
stream=stream,
|
| 256 |
reasoning_effort="minimal",
|
| 257 |
max_completion_tokens=self._MAX_COMPLETION_TOKENS,
|
| 258 |
+
timeout=self._TIMEOUT,
|
| 259 |
)
|
| 260 |
if not stream:
|
| 261 |
yield response.choices[0].message.content or ""
|
app/services/reranker.py
CHANGED
|
@@ -27,6 +27,12 @@ class Reranker:
|
|
| 27 |
self._remote = environment == "prod" and bool(remote_url)
|
| 28 |
self._url = remote_url.rstrip("/") if self._remote else ""
|
| 29 |
self._min_score: float = 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
async def rerank(self, query: str, chunks: list[Chunk], top_k: int = 5) -> list[Chunk]:
|
| 32 |
"""
|
|
@@ -51,19 +57,18 @@ class Reranker:
|
|
| 51 |
reraise=True,
|
| 52 |
)
|
| 53 |
async def _remote_call() -> tuple[list[int], list[float]]:
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
return [int(i) for i in indices], [float(s) for s in scores]
|
| 67 |
|
| 68 |
indices, scores = await _remote_call()
|
| 69 |
result = []
|
|
|
|
| 27 |
self._remote = environment == "prod" and bool(remote_url)
|
| 28 |
self._url = remote_url.rstrip("/") if self._remote else ""
|
| 29 |
self._min_score: float = 0.0
|
| 30 |
+
# One connection for the process: a client per call paid a TLS handshake every question.
|
| 31 |
+
self._client = httpx.AsyncClient(timeout=60.0) if self._remote else None
|
| 32 |
+
|
| 33 |
+
async def aclose(self) -> None:
|
| 34 |
+
if self._client is not None:
|
| 35 |
+
await self._client.aclose()
|
| 36 |
|
| 37 |
async def rerank(self, query: str, chunks: list[Chunk], top_k: int = 5) -> list[Chunk]:
|
| 38 |
"""
|
|
|
|
| 57 |
reraise=True,
|
| 58 |
)
|
| 59 |
async def _remote_call() -> tuple[list[int], list[float]]:
|
| 60 |
+
truncated = [t[:1500] for t in texts]
|
| 61 |
+
resp = await self._client.post(
|
| 62 |
+
f"{self._url}/rerank",
|
| 63 |
+
json={"query": query[:512], "texts": truncated, "top_k": top_k},
|
| 64 |
+
)
|
| 65 |
+
resp.raise_for_status()
|
| 66 |
+
data = resp.json()
|
| 67 |
+
indices = data.get("indices")
|
| 68 |
+
scores = data.get("scores")
|
| 69 |
+
if not isinstance(indices, list) or not isinstance(scores, list):
|
| 70 |
+
raise httpx.HTTPError("Invalid reranker response schema")
|
| 71 |
+
return [int(i) for i in indices], [float(s) for s in scores]
|
|
|
|
| 72 |
|
| 73 |
indices, scores = await _remote_call()
|
| 74 |
result = []
|
app/services/vector_store.py
CHANGED
|
@@ -28,6 +28,10 @@ logger = logging.getLogger(__name__)
|
|
| 28 |
_DENSE_VEC = "dense"
|
| 29 |
_SPARSE_VEC = "sparse"
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
class VectorStore:
|
| 33 |
def __init__(self, client: QdrantClient, collection: str):
|
|
@@ -329,6 +333,50 @@ class VectorStore:
|
|
| 329 |
logger.warning("fetch_by_doc_id failed for %r: %s", doc_id, exc)
|
| 330 |
return []
|
| 331 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
def search_by_raptor_level(
|
| 333 |
self,
|
| 334 |
query_vector: list[float],
|
|
|
|
| 28 |
_DENSE_VEC = "dense"
|
| 29 |
_SPARSE_VEC = "sparse"
|
| 30 |
|
| 31 |
+
# fetch_by_doc_ids reads pages of this size, and stops at the ceiling whatever is left.
|
| 32 |
+
_SIBLING_SCROLL_PAGE = 256
|
| 33 |
+
_SIBLING_SCROLL_CEILING = 1024
|
| 34 |
+
|
| 35 |
|
| 36 |
class VectorStore:
|
| 37 |
def __init__(self, client: QdrantClient, collection: str):
|
|
|
|
| 333 |
logger.warning("fetch_by_doc_id failed for %r: %s", doc_id, exc)
|
| 334 |
return []
|
| 335 |
|
| 336 |
+
def fetch_by_doc_ids(self, doc_ids: list[str], limit_per_doc: int) -> dict[str, list[Chunk]]:
|
| 337 |
+
"""
|
| 338 |
+
The leaf chunks of several documents in one round trip, grouped by doc_id, at most
|
| 339 |
+
`limit_per_doc` each. Sibling expansion asked once per document before, and each
|
| 340 |
+
call to Qdrant costs a network round trip from the API Space.
|
| 341 |
+
"""
|
| 342 |
+
if not doc_ids:
|
| 343 |
+
return {}
|
| 344 |
+
scroll_filter = Filter(
|
| 345 |
+
must=[
|
| 346 |
+
FieldCondition(key="metadata.doc_id", match=MatchAny(any=list(doc_ids))),
|
| 347 |
+
FieldCondition(key="metadata.chunk_type", match=MatchValue(value="leaf")),
|
| 348 |
+
]
|
| 349 |
+
)
|
| 350 |
+
# Every chunk of these documents, so one long document cannot crowd out the rest;
|
| 351 |
+
# documents here run to a few dozen chunks, so this is one page in practice.
|
| 352 |
+
records: list = []
|
| 353 |
+
offset = None
|
| 354 |
+
try:
|
| 355 |
+
while len(records) < _SIBLING_SCROLL_CEILING:
|
| 356 |
+
page, offset = self.client.scroll(
|
| 357 |
+
collection_name=self.collection,
|
| 358 |
+
scroll_filter=scroll_filter,
|
| 359 |
+
limit=_SIBLING_SCROLL_PAGE,
|
| 360 |
+
offset=offset,
|
| 361 |
+
with_payload=True,
|
| 362 |
+
with_vectors=False,
|
| 363 |
+
)
|
| 364 |
+
records.extend(page)
|
| 365 |
+
if offset is None:
|
| 366 |
+
break
|
| 367 |
+
except Exception as exc:
|
| 368 |
+
logger.warning("fetch_by_doc_ids failed for %d documents: %s", len(doc_ids), exc)
|
| 369 |
+
return {}
|
| 370 |
+
grouped: dict[str, list[Chunk]] = {}
|
| 371 |
+
for record in records:
|
| 372 |
+
if not record.payload:
|
| 373 |
+
continue
|
| 374 |
+
chunk = Chunk(**record.payload)
|
| 375 |
+
siblings = grouped.setdefault(chunk["metadata"]["doc_id"], [])
|
| 376 |
+
if len(siblings) < limit_per_doc:
|
| 377 |
+
siblings.append(chunk)
|
| 378 |
+
return grouped
|
| 379 |
+
|
| 380 |
def search_by_raptor_level(
|
| 381 |
self,
|
| 382 |
query_vector: list[float],
|
tests/test_generate_numbered_sources.py
CHANGED
|
@@ -42,3 +42,25 @@ async def test_streamed_citations_count_in_the_sources_sent_before_the_answer():
|
|
| 42 |
assert [source["title"] for source in sources] == ["AimBuddy", "Cortex"]
|
| 43 |
assert "[2] Cortex" in llm.prompt
|
| 44 |
assert kinds.index("sources") < kinds.index("token")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
assert [source["title"] for source in sources] == ["AimBuddy", "Cortex"]
|
| 43 |
assert "[2] Cortex" in llm.prompt
|
| 44 |
assert kinds.index("sources") < kinds.index("token")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@pytest.mark.asyncio
|
| 48 |
+
async def test_an_answer_without_a_think_block_streams_before_the_model_finishes():
|
| 49 |
+
events: list[dict] = []
|
| 50 |
+
streamed_before_last_chunk: list[str] = []
|
| 51 |
+
|
| 52 |
+
class _WordByWordLLM:
|
| 53 |
+
suggests_follow_ups = True
|
| 54 |
+
|
| 55 |
+
async def complete_with_complexity(self, prompt, system, stream, complexity):
|
| 56 |
+
words = ["Cortex ", "maps ", "a codebase into a graph of symbols and calls, ", "for agents [1]."]
|
| 57 |
+
for word in words[:-1]:
|
| 58 |
+
yield word
|
| 59 |
+
streamed_before_last_chunk.extend(event["text"] for event in events if event["type"] == "token")
|
| 60 |
+
yield words[-1]
|
| 61 |
+
|
| 62 |
+
chunks = [_chunk("Cortex", "https://github.com/1337Xcode/Cortex", "Cortex maps a codebase into a SQLite graph for coding agents.")]
|
| 63 |
+
with patch("app.pipeline.nodes.generate.get_stream_writer", return_value=events.append):
|
| 64 |
+
await make_generate_node(_WordByWordLLM())({"query": "What is Cortex?", "reranked_chunks": chunks, "query_complexity": "simple"})
|
| 65 |
+
|
| 66 |
+
assert "".join(streamed_before_last_chunk).startswith("Cortex maps")
|
tests/test_resume_chunker_sections.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 5 |
+
if str(ROOT) not in sys.path:
|
| 6 |
+
sys.path.insert(0, str(ROOT))
|
| 7 |
+
|
| 8 |
+
from ingestion.chunkers.resume_chunker import chunk_resume
|
| 9 |
+
|
| 10 |
+
CV = """Darshan Chheda
|
| 11 |
+
Software Engineer
|
| 12 |
+
|
| 13 |
+
EXPERIENCE
|
| 14 |
+
|
| 15 |
+
Founding Engineer, Alfrd | London, UK | Sep 2026 – Present
|
| 16 |
+
- Built the product as its main engineer.
|
| 17 |
+
|
| 18 |
+
Quality Assurance Tester Intern, Xsilica Software Solutions | Hyderabad, India | Apr 2023 – Oct 2023
|
| 19 |
+
- Caught 30+ defects before release.
|
| 20 |
+
|
| 21 |
+
PROJECTS
|
| 22 |
+
|
| 23 |
+
Cortex | Rust, SQLite, MCP | github.com/1337XCode/Cortex | May 2026
|
| 24 |
+
- Built an MCP server in Rust.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_each_role_and_project_is_a_passage_named_for_it() -> None:
|
| 29 |
+
chunks = chunk_resume(CV, doc_id="cv", title="Darshan Chheda's CV", source_url="https://x/cv.pdf", source_type="resume")
|
| 30 |
+
sections = [chunk["metadata"]["section"] for chunk in chunks]
|
| 31 |
+
|
| 32 |
+
assert "Experience: Founding Engineer, Alfrd" in sections
|
| 33 |
+
assert "Experience: Quality Assurance Tester Intern, Xsilica Software Solutions" in sections
|
| 34 |
+
assert "Projects: Cortex" in sections
|
| 35 |
+
alfrd = next(chunk for chunk in chunks if chunk["metadata"]["section"] == "Experience: Founding Engineer, Alfrd")
|
| 36 |
+
assert alfrd["text"].startswith("Darshan Chheda's CV — Experience: Founding Engineer, Alfrd:")
|
tests/test_retrieve_contact_filter.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.pipeline.nodes.retrieve import _without_contact_chunks
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def _chunk(title: str, source_type: str) -> dict:
|
| 5 |
+
return {"text": title, "metadata": {"source_title": title, "source_type": source_type, "doc_id": title.lower(), "section": "s"}}
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
CHUNKS = [_chunk("LinkedIn", "contact"), _chunk("Resume", "resume"), _chunk("Cortex", "github_readme")]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_profile_pointers_are_dropped_from_questions_about_anything_else() -> None:
|
| 12 |
+
kept = _without_contact_chunks(CHUNKS, "Where does Darshan work now?")
|
| 13 |
+
|
| 14 |
+
assert [chunk["metadata"]["source_title"] for chunk in kept] == ["Resume", "Cortex"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_profile_pointers_answer_questions_about_reaching_him() -> None:
|
| 18 |
+
for question in ("How do I get in touch with Darshan?", "What's Darshan's LinkedIn?", "Can I email him?"):
|
| 19 |
+
assert _without_contact_chunks(CHUNKS, question) == CHUNKS
|
tests/test_site_profile.py
CHANGED
|
@@ -28,10 +28,10 @@ Open to software engineering roles in the UK
|
|
| 28 |
def test_the_page_is_one_profile_and_each_off_site_profile_its_own_document() -> None:
|
| 29 |
documents = profile_documents(LLMS_TXT)
|
| 30 |
|
| 31 |
-
assert [(d["title"], d["url"], d["slug"]) for d in documents] == [
|
| 32 |
-
("darshanchheda.com", "https://www.darshanchheda.com/", "site-profile"),
|
| 33 |
-
("GitHub", "https://github.com/1337XCode", "profile-github"),
|
| 34 |
-
("LinkedIn", "https://linkedin.com/in/darshchheda", "profile-linkedin"),
|
| 35 |
]
|
| 36 |
assert "Open to software engineering roles in the UK" in documents[0]["clean_content"]
|
| 37 |
assert documents[2]["clean_content"].endswith("https://linkedin.com/in/darshchheda")
|
|
|
|
| 28 |
def test_the_page_is_one_profile_and_each_off_site_profile_its_own_document() -> None:
|
| 29 |
documents = profile_documents(LLMS_TXT)
|
| 30 |
|
| 31 |
+
assert [(d["title"], d["url"], d["slug"], d["source_type"]) for d in documents] == [
|
| 32 |
+
("darshanchheda.com", "https://www.darshanchheda.com/", "site-profile", "profile"),
|
| 33 |
+
("GitHub", "https://github.com/1337XCode", "profile-github", "contact"),
|
| 34 |
+
("LinkedIn", "https://linkedin.com/in/darshchheda", "profile-linkedin", "contact"),
|
| 35 |
]
|
| 36 |
assert "Open to software engineering roles in the UK" in documents[0]["clean_content"]
|
| 37 |
assert documents[2]["clean_content"].endswith("https://linkedin.com/in/darshchheda")
|
tests/test_vector_store_fetch_by_doc_ids.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from types import SimpleNamespace
|
| 2 |
+
|
| 3 |
+
from app.services import vector_store
|
| 4 |
+
from app.services.vector_store import VectorStore
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _record(doc_id: str, index: int) -> SimpleNamespace:
|
| 8 |
+
return SimpleNamespace(payload={"text": f"{doc_id} {index}", "metadata": {"doc_id": doc_id, "section": str(index), "chunk_index": index}})
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class _FakeQdrant:
|
| 12 |
+
"""Qdrant's scroll: a page of records, and where the next page starts (None at the end)."""
|
| 13 |
+
|
| 14 |
+
def __init__(self, records: list[SimpleNamespace]) -> None:
|
| 15 |
+
self.records = records
|
| 16 |
+
self.calls = 0
|
| 17 |
+
|
| 18 |
+
def scroll(self, **kwargs):
|
| 19 |
+
self.calls += 1
|
| 20 |
+
start = kwargs.get("offset") or 0
|
| 21 |
+
end = start + kwargs["limit"]
|
| 22 |
+
return self.records[start:end], (end if end < len(self.records) else None)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# A long document first, as Qdrant's id order can put it: it must not crowd out the other.
|
| 26 |
+
RECORDS = [_record("cortex", 0), _record("cortex", 1), _record("cortex", 2), _record("cv", 0), _record("cv", 1)]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _indices(grouped: dict) -> dict:
|
| 30 |
+
return {doc_id: [chunk["metadata"]["chunk_index"] for chunk in chunks] for doc_id, chunks in grouped.items()}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_siblings_of_several_documents_come_from_one_query_grouped_and_capped() -> None:
|
| 34 |
+
client = _FakeQdrant(RECORDS)
|
| 35 |
+
|
| 36 |
+
grouped = VectorStore(client, "knowledge_base").fetch_by_doc_ids(["cortex", "cv"], limit_per_doc=2)
|
| 37 |
+
|
| 38 |
+
assert client.calls == 1
|
| 39 |
+
assert _indices(grouped) == {"cortex": [0, 1], "cv": [0, 1]}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_documents_longer_than_a_page_are_read_to_the_end(monkeypatch) -> None:
|
| 43 |
+
monkeypatch.setattr(vector_store, "_SIBLING_SCROLL_PAGE", 2)
|
| 44 |
+
client = _FakeQdrant(RECORDS)
|
| 45 |
+
|
| 46 |
+
grouped = VectorStore(client, "knowledge_base").fetch_by_doc_ids(["cortex", "cv"], limit_per_doc=2)
|
| 47 |
+
|
| 48 |
+
assert client.calls == 3
|
| 49 |
+
assert _indices(grouped) == {"cortex": [0, 1], "cv": [0, 1]}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_no_documents_asks_nothing() -> None:
|
| 53 |
+
client = _FakeQdrant([])
|
| 54 |
+
|
| 55 |
+
assert VectorStore(client, "knowledge_base").fetch_by_doc_ids([], limit_per_doc=2) == {}
|
| 56 |
+
assert client.calls == 0
|