import { SearchMode } from "../constants/search-mode.js"; import { CategoryWeightCalculator } from "../document/category-weight-calculator.js"; import { IntegrationMethodWeightCalculator } from "../document/integration-method-weight-calculator.js"; import { Result, TossPaymentsBM25Calculator, } from "../document/toss-payments-bm25-calculator.js"; import { TossPaymentsDocument } from "../document/toss-payments-document.js"; import { SynonymDictionary } from "../document/synonym-dictionary.js"; import { TokenEstimator } from "../document/token-estimator.js"; import { DocumentChunk } from "../document/types.js"; export class TossPaymentDocsRepository { private static readonly GLOSSARY_PATH_SEGMENT = "/resources/glossary/"; // 문서 단위 점수에 합산할 상위 청크 수. groupResultsByDocId 참고. // 골든셋 스윕(1/2/3/5/8)에서 3~5가 최적이었고 더 보수적인 3을 택했다 // (k=1 hit@1 38 → k=3 42, MRR 0.863 → 0.911. k=8 은 41로 다시 하락). static readonly DOCUMENT_SCORE_TOP_CHUNKS = 3; private readonly documentV1BM25Calculator: TossPaymentsBM25Calculator; private readonly documentV2BM25Calculator: TossPaymentsBM25Calculator; private readonly documentGlossaryBM25Calculator: TossPaymentsBM25Calculator; private readonly allV1Keywords: Set; private readonly allV2Keywords: Set; private readonly allGlossaryKeywords: Set; private readonly documentsById: Map; private static readonly TRUNCATION_WARNING = "\n\n... (내용이 더 있습니다...)"; constructor( private readonly documents: TossPaymentsDocument[], private readonly categoryWeightCalculator: CategoryWeightCalculator, private readonly integrationMethodWeightCalculator: IntegrationMethodWeightCalculator, private readonly synonymDictionary: SynonymDictionary ) { // 버전 무관 공통 문서(/reference, /codes, /blog, /legacy, /en 등)는 // parseVersionFromUrl 이 version 을 못 잡아 undefined 로 남는다. 이들을 제외하면 // v1/v2 색인 어디에도 들어가지 않아 검색 자체가 불가능해진다. // CATEGORY_WEIGHTS 가 이미 blog/codes/legacy/reference 가중치를 정의하고 있으므로 // 원래 검색 대상이었고, 랭킹은 카테고리 가중치가 조정한다. const isVersionless = (document: TossPaymentsDocument) => document.version === undefined && !document.link.includes(TossPaymentDocsRepository.GLOSSARY_PATH_SEGMENT); const v1Documents = documents.filter( (document) => document.version === "v1" || isVersionless(document) ); const v2Documents = documents.filter( (document) => document.version === "v2" || isVersionless(document) ); const glossaryDocuments = documents.filter((document) => document.link.includes(TossPaymentDocsRepository.GLOSSARY_PATH_SEGMENT) ); this.documentV1BM25Calculator = new TossPaymentsBM25Calculator(v1Documents); this.documentV2BM25Calculator = new TossPaymentsBM25Calculator(v2Documents); this.documentGlossaryBM25Calculator = new TossPaymentsBM25Calculator( glossaryDocuments ); this.allV1Keywords = new Set(v1Documents.map((doc) => doc.keywords).flat()); this.allV2Keywords = new Set(v2Documents.map((doc) => doc.keywords).flat()); this.allGlossaryKeywords = new Set( glossaryDocuments.map((doc) => doc.keywords).flat() ); this.documentsById = new Map( documents.map((document) => [document.id, document]) ); } getAllV1Keywords(): string[] { return Array.from(this.allV1Keywords); } getAllV2Keywords(): string[] { return Array.from(this.allV2Keywords); } getAllGlossaryKeywords(): string[] { return Array.from(this.allGlossaryKeywords); } async findV1DocumentsByKeyword( keywords: string[], searchMode: SearchMode = SearchMode.BALANCED, maxTokens: number ): Promise { const converted = this.synonymDictionary.convertToSynonyms(keywords); const results = this.documentV1BM25Calculator.calculate( converted, searchMode ); // Category별 가중치 적용 const weightedResults = this.categoryWeightCalculator.apply( results, this.documents ); // 연동방식별 가중치 적용 (payment-widget 부스트 / payment-window 중립) const methodWeightedResults = this.integrationMethodWeightCalculator.apply(weightedResults); return this.normalize(methodWeightedResults, maxTokens); } async findV2DocumentsByKeyword( keywords: string[], searchMode: SearchMode = SearchMode.BALANCED, maxTokens: number ): Promise { const converted = this.synonymDictionary.convertToSynonyms(keywords); const results = this.documentV2BM25Calculator.calculate( converted, searchMode ); // Category별 가중치 적용 const weightedResults = this.categoryWeightCalculator.apply( results, this.documents ); // 연동방식별 가중치 적용 (payment-widget 부스트 / payment-window 중립) const methodWeightedResults = this.integrationMethodWeightCalculator.apply(weightedResults); return this.normalize(methodWeightedResults, maxTokens); } async findGlossaryDocumentsByKeyword( keywords: string[], searchMode: SearchMode = SearchMode.BALANCED, maxTokens: number ): Promise { const converted = this.synonymDictionary.convertToSynonyms(keywords); const results = this.documentGlossaryBM25Calculator.calculate( converted, searchMode ); // Category별 가중치 적용 (glossary는 모두 동일 카테고리라 순위 변화 없음 — 일관성 목적) const weightedResults = this.categoryWeightCalculator.apply( results, this.documents ); return this.normalize(weightedResults, maxTokens); } /** * `documents` 의 배열 위치는 ID 와 무관하다. * * 로더가 전 문서를 병렬 fetch 하고 **완료된 순서대로** Map 에 담기 때문에 배열은 * 응답 도착 순서로 늘어서는데, ID 는 llms.txt 에서의 위치다. 그래서 * `documents[id]` 는 엣지 케이스가 아니라 평상시에 어긋난다 * (247건 실측: ID 에 구멍이 하나도 없는데도 85.8%가 다른 문서를 가리켰다). * * fetch 가 실패한 문서가 있으면 여기에 ID 구멍까지 더해진다. */ findOneById(id: number): TossPaymentsDocument | undefined { return this.documentsById.get(id); } private normalize(results: Result[], maxTokens: number): string { const groupedByDocId = this.groupResultsByDocId(results); const docs: string[] = []; let currentTokens = 0; // 각 문서별로 chunk 조회 for (const [docId, chunkIds] of groupedByDocId.entries()) { const document = this.findOneById(docId); if (!document) { continue; } const documentChunks = document.findByChunkIds(chunkIds, { windowSize: 1, }); if (documentChunks.length > 0) { const processedChunk = this.smartTruncateChunks( documentChunks, maxTokens - currentTokens ); if (processedChunk) { const header = document.toResponseHeader(); const headerTokens = TokenEstimator.estimate(header); maxTokens -= headerTokens; docs.push(header); docs.push(processedChunk.text); currentTokens += processedChunk.tokens; if (currentTokens >= maxTokens) { break; } } } } return docs.join("\n\n"); } /** * Result 배열을 문서 ID별로 그룹핑하고, 문서 단위 점수로 재정렬한다. * * 점수는 청크 단위로 매겨지는데 그대로 두면 **최고점 청크 하나가 문서를 대표**한다. * 그러면 주제를 넓게 다루는 레퍼런스 문서가 불리하다 — 한 term 이 여러 청크에 * 흩어져 청크당 tf 가 낮아지기 때문이다. 길이 정규화 탓이 아니다(실측: reference.md * 는 청크 76개에 평균 wordCount 119 로 전체 평균 126 보다 오히려 짧다. "결제 승인"이 * 14개 청크에 분산돼 있는데 랭킹에는 1개만 반영됐다). * * 상위 몇 개 청크의 점수를 합해 "문서 전체가 이 주제를 얼마나 다루는가"를 반영한다. * 전부 합하지 않는 것은 청크 수가 많다는 이유만으로 상위를 독식하지 않게 하기 위함이다. */ private groupResultsByDocId(results: Result[]): Map { const resultsByDocId = new Map(); for (const result of results) { if (!resultsByDocId.has(result.id)) { resultsByDocId.set(result.id, []); } resultsByDocId.get(result.id)!.push(result); } const rankedDocuments = Array.from(resultsByDocId.entries()) .map(([docId, chunkResults]) => ({ docId, score: TossPaymentDocsRepository.documentScore(chunkResults), chunkIds: [...new Set(chunkResults.map((result) => result.chunkId))].sort( (a, b) => a - b ), })) .sort((a, b) => b.score - a.score); return new Map( rankedDocuments.map(({ docId, chunkIds }) => [docId, chunkIds]) ); } /** * 문서 단위 점수 = 상위 N개 청크 점수의 합. * N 은 골든셋으로 스윕해 정한 값이다(docs/SEARCH_QUALITY_HARDENING_PLAN.md). */ static documentScore(chunkResults: Result[]): number { return [...chunkResults] .sort((a, b) => b.score - a.score) .slice(0, TossPaymentDocsRepository.DOCUMENT_SCORE_TOP_CHUNKS) .reduce((sum, result) => sum + result.score, 0); } /** * 토큰 제한 하에서 chunks를 스마트하게 절단합니다. * @param chunks 처리할 DocumentChunk 배열 * @param remainingTokens 남은 토큰 수 * @returns 처리된 텍스트와 사용된 토큰 수 */ private smartTruncateChunks( chunks: DocumentChunk[], remainingTokens: number ): { text: string; tokens: number } | null { if (chunks.length === 0) return null; let availableTokens = remainingTokens; if (availableTokens <= 0) return null; let selectedChunks: DocumentChunk[] = []; let usedTokens = 0; // chunk별 토큰 수를 확인하면서 선택 for (const chunk of chunks) { const chunkTokens = chunk.estimatedTokens; if (availableTokens >= chunkTokens) { selectedChunks.push(chunk); availableTokens -= chunkTokens; usedTokens += chunkTokens; } else { // 부분 선택 가능한지 확인 const partialChunk = this.tryPartialChunk(chunk, availableTokens); if (partialChunk) { selectedChunks.push(partialChunk.chunk); usedTokens += partialChunk.tokens; } break; } } if (selectedChunks.length === 0) { return null; } const needsTruncation = selectedChunks.length < chunks.length; const content = selectedChunks.map((chunk) => chunk.rawText).join("\n\n"); const fullText = content + (needsTruncation ? TossPaymentDocsRepository.TRUNCATION_WARNING : ""); const finalTokens = usedTokens + (needsTruncation ? TokenEstimator.estimate(TossPaymentDocsRepository.TRUNCATION_WARNING) : 0); return { text: fullText, tokens: finalTokens, }; } /** * 토큰 제한 하에서 chunk를 부분적으로 절단을 시도합니다. * @param chunk 절단할 DocumentChunk * @param availableTokens 사용 가능한 토큰 수 * @returns 부분 절단된 chunk와 토큰 수 */ private tryPartialChunk( chunk: DocumentChunk, availableTokens: number ): { chunk: DocumentChunk; tokens: number } | null { if (availableTokens < 100) return null; // 최소한의 토큰은 필요 // 의미 단위로 자르기 시도 (문장, 단락, 리스트 아이템 등) const semanticBoundaries = this.findSemanticBoundaries(chunk.text); for (let i = semanticBoundaries.length - 1; i >= 0; i--) { const truncatedText = chunk.text.substring(0, semanticBoundaries[i]); const estimatedTokens = TokenEstimator.estimate(truncatedText); if (estimatedTokens <= availableTokens) { return { chunk: { ...chunk, text: truncatedText }, tokens: estimatedTokens, }; } } return null; } /** * 텍스트에서 의미 있는 경계점들을 찾습니다. * @param text 분석할 텍스트 * @returns 경계점 위치 배열 (문자 인덱스) */ private findSemanticBoundaries(text: string): number[] { const boundaries: number[] = []; // 1. 문단 경계 (더블 개행) let match; const paragraphRegex = /\n\n/g; while ((match = paragraphRegex.exec(text)) !== null) { boundaries.push(match.index); } // 2. 문장 경계 (마침표, 느낌표, 물음표 + 공백) const sentenceRegex = /[.!?]\s+/g; while ((match = sentenceRegex.exec(text)) !== null) { boundaries.push(match.index + match[0].length); } // 3. 리스트 아이템 경계 const listRegex = /\n-\s+/g; while ((match = listRegex.exec(text)) !== null) { boundaries.push(match.index); } // 4. 코드 블록 경계 const codeBlockRegex = /```[\s\S]*?```/g; while ((match = codeBlockRegex.exec(text)) !== null) { boundaries.push(match.index + match[0].length); } // 정렬 및 중복 제거 return [...new Set(boundaries)].sort((a, b) => a - b); } }