from unittest.mock import patch import pytest from app.pipeline.nodes.generate import make_generate_node def _chunk(title: str, url: str, text: str) -> dict: return { "text": text, "metadata": {"source_title": title, "source_url": url, "section": "Overview", "source_type": "github_readme", "doc_id": title.lower(), "chunk_index": 0}, } class _StreamingLLM: suggests_follow_ups = True def __init__(self) -> None: self.prompt = "" async def complete_with_complexity(self, prompt, system, stream, complexity): self.prompt = prompt yield "Cortex maps a codebase into a graph [2]." @pytest.mark.asyncio async def test_streamed_citations_count_in_the_sources_sent_before_the_answer(): # Two chunks of one document share a number in the prompt, so Cortex is [2], not [3]. chunks = [ _chunk("AimBuddy", "https://github.com/1337Xcode/AimBuddy", "AimBuddy tracks targets on Android in real time."), _chunk("AimBuddy", "https://github.com/1337Xcode/AimBuddy", "It runs a YOLO model on the phone's GPU through NCNN."), _chunk("Cortex", "https://github.com/1337Xcode/Cortex", "Cortex maps a codebase into a SQLite graph for coding agents."), ] events: list[dict] = [] llm = _StreamingLLM() with patch("app.pipeline.nodes.generate.get_stream_writer", return_value=events.append): await make_generate_node(llm)({"query": "What is Cortex?", "reranked_chunks": chunks, "query_complexity": "simple"}) kinds = [event["type"] for event in events] [sources] = [event["sources"] for event in events if event["type"] == "sources"] assert [source["title"] for source in sources] == ["AimBuddy", "Cortex"] assert "[2] Cortex" in llm.prompt assert kinds.index("sources") < kinds.index("token") @pytest.mark.asyncio async def test_an_answer_without_a_think_block_streams_before_the_model_finishes(): events: list[dict] = [] streamed_before_last_chunk: list[str] = [] class _WordByWordLLM: suggests_follow_ups = True async def complete_with_complexity(self, prompt, system, stream, complexity): words = ["Cortex ", "maps ", "a codebase into a graph of symbols and calls, ", "for agents [1]."] for word in words[:-1]: yield word streamed_before_last_chunk.extend(event["text"] for event in events if event["type"] == "token") yield words[-1] chunks = [_chunk("Cortex", "https://github.com/1337Xcode/Cortex", "Cortex maps a codebase into a SQLite graph for coding agents.")] with patch("app.pipeline.nodes.generate.get_stream_writer", return_value=events.append): await make_generate_node(_WordByWordLLM())({"query": "What is Cortex?", "reranked_chunks": chunks, "query_complexity": "simple"}) assert "".join(streamed_before_last_chunk).startswith("Cortex maps")