diff --git a/backend/app/chat/service.py b/backend/app/chat/service.py index 03ae794..2938988 100644 --- a/backend/app/chat/service.py +++ b/backend/app/chat/service.py @@ -1,3 +1,4 @@ +import re from typing import Protocol from backend.app.audit.models import AuditCitation, ChatAuditEvent @@ -119,7 +120,13 @@ def answer( response = ChatResponse( answer=llm_response.content, model=llm_response.model, - citations=_build_citations(supported_chunks), + citations=_build_citations( + supported_chunks, + citation_ids=_extract_citation_ids( + llm_response.content, + max_id=len(supported_chunks), + ), + ), usage=ChatUsage( prompt_tokens=llm_response.prompt_tokens, completion_tokens=llm_response.completion_tokens, @@ -212,19 +219,41 @@ def _build_user_prompt(*, question: str, chunks: list[RetrievedChunk]) -> str: ) -def _build_citations(chunks: list[RerankedChunk]) -> list[ChatCitation]: - return [ - ChatCitation( - citation_id=index, - document_id=item.chunk.document_id, - filename=item.chunk.filename, - chunk_index=item.chunk.chunk_index, - score=item.chunk.score, - rerank_score=item.rerank_score, - snippet=_build_snippet(item.chunk.chunk_text), +def _build_citations( + chunks: list[RerankedChunk], + *, + citation_ids: list[int] | None = None, +) -> list[ChatCitation]: + if citation_ids is None: + citation_ids = list(range(1, len(chunks) + 1)) + + citations: list[ChatCitation] = [] + for citation_id in citation_ids: + item = chunks[citation_id - 1] + citations.append( + ChatCitation( + citation_id=citation_id, + document_id=item.chunk.document_id, + filename=item.chunk.filename, + chunk_index=item.chunk.chunk_index, + score=item.chunk.score, + rerank_score=item.rerank_score, + snippet=_build_snippet(item.chunk.chunk_text), + ) ) - for index, item in enumerate(chunks, start=1) - ] + return citations + + +def _extract_citation_ids(answer: str, *, max_id: int) -> list[int]: + citation_ids: list[int] = [] + seen: set[int] = set() + for match in re.finditer(r"\[(\d+)\]", answer): + citation_id = int(match.group(1)) + if citation_id < 1 or citation_id > max_id or citation_id in seen: + continue + citation_ids.append(citation_id) + seen.add(citation_id) + return citation_ids def _filter_supported_chunks( diff --git a/backend/tests/chat/test_service.py b/backend/tests/chat/test_service.py index 5271732..c7f5934 100644 --- a/backend/tests/chat/test_service.py +++ b/backend/tests/chat/test_service.py @@ -29,13 +29,18 @@ def retrieve( class FakeLLMClient: - def __init__(self) -> None: + def __init__( + self, + *, + content: str = "정책 문서 기준 답변입니다. [1]", + ) -> None: + self.content = content self.request: LLMRequest | None = None def generate(self, request: LLMRequest) -> LLMResponse: self.request = request return LLMResponse( - content="정책 문서 기준 답변입니다. [1]", + content=self.content, model="google/gemma-4-E4B-it", finish_reason="stop", prompt_tokens=20, @@ -172,7 +177,7 @@ def test_chat_service_uses_reranker_order() -> None: score=0.7, ), ] - llm_client = FakeLLMClient() + llm_client = FakeLLMClient(content="두 문서를 모두 참고했습니다. [1] [2]") service = _service( retriever=FakeRetriever(chunks), reranker=FakeReranker(["doc-b", "doc-a"]), @@ -197,6 +202,49 @@ def test_chat_service_uses_reranker_order() -> None: assert [citation.rerank_score for citation in response.citations] == [1.0, 0.9] +def test_chat_service_returns_only_answer_referenced_citations() -> None: + chunks = [ + _chunk( + document_id="doc-a", + filename="a.md", + chunk_index=0, + text="일반 보안 정책", + score=0.9, + ), + _chunk( + document_id="doc-b", + filename="b.md", + chunk_index=1, + text="API Key 권한 정책", + score=0.8, + ), + ] + audit_log = FakeAuditLog() + service = _service( + retriever=FakeRetriever(chunks), + reranker=FakeReranker(["doc-a", "doc-b"]), + llm_client=FakeLLMClient( + content="두 번째 근거만 답변에 사용합니다. [2] [2] [99] [0]" + ), + audit_log=audit_log, + retrieval_limit=5, + rerank_top_k=2, + ) + + response = service.answer( + workspace_context=_workspace_context(), + chat_request=ChatRequest(question="API Key 권한은?"), + ) + + assert response.retrieved_chunk_count == 2 + assert [citation.citation_id for citation in response.citations] == [2] + assert [citation.document_id for citation in response.citations] == ["doc-b"] + assert [citation.citation_id for citation in audit_log.events[0].citations] == [2] + assert [citation.document_id for citation in audit_log.events[0].citations] == [ + "doc-b" + ] + + def test_chat_service_filters_low_relevance_chunks() -> None: chunks = [ _chunk(