跳到正文
DEV Community· FinneganBlake3578·· 9 小時前AI 評分60

Node.js PDF 助手建置紀錄:為何向量搜尋本身無法回答問題

Node.js PDF Assistant Build Log — Why Vector Search Cannot Answer Questions

AI 導讀

Node.js PDF 助手的建置紀錄指出,向量搜尋只會按嵌入向量相似度排序候選片段,不能單獨生成有文件依據的答案。作者主張以 RAG 串接片段選擇、生成、引用驗證及證據不足時拒答,並讓每個片段保留文件識別碼、頁碼和片段識別碼。他建議分開測試檢索是否找齊所需證據,以及答案和引用是否受證據支持,再按實際失誤增加重排等檢索機制。

正文

A one-person developer-tools business cannot afford to treat every plausible PDF passage as an answer. Vector search cannot answer questions on its own: the operational constraint is grounding, because a user needs a response tied to the document and the system needs a defensible way to abstain when retrieval comes up short.

TL;DR: Vector search returns items whose embeddings are close to a query embedding. Those items are evidence candidates, not answers. Retrieval-augmented generation (RAG) adds the missing work: select usable passages, give them to a generator with the question, require citations, and refuse unsupported claims. For a folder of PDFs, I would ship the smallest pipeline that preserves page-level provenance before adding clever retrieval features.

That distinction affects the whole build. Search optimizes which text to inspect. Question answering has to interpret that text, reconcile it with the question, express a response, and show where the response came from.

Why can't vector search answer questions from PDFs?

A vector index stores representations of chunks and finds nearby representations. The returned score describes the relationship used by the search algorithm. It does not certify that a passage is true, complete, current, or sufficient for the question.

Consider a folder containing API guides as PDFs. A developer asks, "Which authentication headers are required for batch uploads?" The nearest chunks might include an overview that says uploads require authentication, a table defining a header on the next page, and an older migration note. No single hit necessarily contains the complete answer. Search has done useful work, but synthesis and evidence checking remain.

This is the first boundary I would make explicit in the codebase:

Stage Input Output What it does not prove
Indexing PDF text and provenance Searchable chunks That extraction preserved every meaning
Retrieval A question Ranked candidate chunks That the candidates answer it
Context selection Ranked candidates A bounded evidence set That the evidence is mutually consistent
Generation Question plus evidence A cited response or abstention That an uncited statement is supported

RAG connects these stages. The original RAG paper describes generation conditioned on retrieved external passages, rather than treating retrieval as the final response. That separation is still the useful mental model: the retriever proposes evidence; the generator composes an answer from it.

Search can miss for mundane reasons. A chunk boundary may split a definition from its qualifier. A diagram caption may survive PDF extraction while the diagram's meaning does not. The user's term may differ from the wording in the manual. Similar passages can also describe different versions or scopes.

None of these cases is repaired by presenting the top result with more confidence.

The constraint that changes the build

Grounding and citation must survive every transformation. I want each extracted chunk to carry a stable document identifier, page number, and chunk identifier. If those fields are attached after generation, citation becomes guesswork. If they travel with the text from ingestion through retrieval, the response can point back to the actual evidence.

The unit of retrieval also needs enough local context to be intelligible. Tiny fragments may match a term but omit its conditions. Huge chunks can mix unrelated sections and consume the generator's context budget. There is no universally correct chunk size in the supplied research, so I would treat it as an application setting and test it against real questions rather than announce a magic number.

For this developer-tools scenario, the acceptance rule is simple: every substantive claim in an answer must map to at least one retrieved chunk, and each displayed citation must identify the PDF and page. If the selected context does not support an answer, the system says so. That may feel less impressive in a demo. It is far more useful in a tool someone relies on while shipping code.

This is also a revenue-per-hour decision. I would rather spend a week making provenance and abstention predictable than build a complicated reranker before I know retrieval is the bottleneck. Ship weekly. Measure the failure that users actually see.

The smallest working TypeScript pipeline

The first implementation does not need to bind the application to a particular vector database or generation API. Two narrow interfaces keep the differentiated part — evidence handling — visible and leave commodity infrastructure replaceable.

type Chunk = {
  id: string;
  documentId: string;
  fileName: string;
  page: number;
  text: string;
};

type Match = Chunk & {
  score: number;
};

type CitedAnswer = {
  answer: string;
  citations: Array<{
    chunkId: string;
    fileName: string;
    page: number;
  }>;
  abstained: boolean;
};

interface Retriever {
  search(question: string, limit: number): Promise<Match[]>;
}

interface GroundedGenerator {
  answer(input: {
    question: string;
    evidence: Chunk[];
  }): Promise<{
    answer: string;
    citedChunkIds: string[];
    abstained: boolean;
  }>;
}

The orchestration layer should distrust both sides of that interface. An empty retrieval result cannot support an answer. A generated citation that was never supplied as evidence must not reach the user. The same applies to duplicate or malformed citations.

export async function answerPdfQuestion(
  question: string,
  retriever: Retriever,
  generator: GroundedGenerator,
): Promise<CitedAnswer> {
  const matches = await retriever.search(question, 8);

  if (matches.length === 0) {
    return {
      answer: "The indexed PDFs do not provide enough evidence to answer.",
      citations: [],
      abstained: true,
    };
  }

  const evidence = matches.map(({ score: _score, ...chunk }) => chunk);
  const result = await generator.answer({ question, evidence });
  const byId = new Map(evidence.map((chunk) => [chunk.id, chunk]));
  const citedIds = [...new Set(result.citedChunkIds)];
  const citations = citedIds.map((id) => byId.get(id));

  if (result.abstained || citations.some((chunk) => chunk === undefined)) {
    return {
      answer: "The retrieved PDF passages do not support a cited answer.",
      citations: [],
      abstained: true,
    };
  }

  return {
    answer: result.answer,
    citations: citations.map((chunk) => ({
      chunkId: chunk!.id,
      fileName: chunk!.fileName,
      page: chunk!.page,
    })),
    abstained: false,
  };
}

Eight candidates in this example are an implementation choice, not a quality guarantee. The right value depends on the documents, chunking, and questions. It belongs in evaluation data and configuration, not in marketing copy.

The generator contract matters more than its brand. It should receive only the selected evidence, distinguish quoted document text from instructions, return machine-checkable citation identifiers, and abstain when the evidence is inadequate. The application then validates those identifiers before rendering fileName and page to the reader.

I would outsource PDF parsing, embedding computation, and vector storage behind interfaces until one becomes a proven constraint. The application-specific value is the trace from answer to page and the behavior when evidence is weak. That is where scarce engineering hours pay back.

What I would test before adding more retrieval machinery

A demo question is not an evaluation set. I would assemble questions that represent the actual PDF folder and record the passages needed to answer each one. The set should include direct lookups, questions whose answer spans adjacent chunks, conflicting passages, terms that appear in irrelevant sections, and questions the documents cannot answer.

Then test stages separately. Retrieval should be judged on whether the required evidence appears in the candidate set. The final response should be judged on whether its claims are supported by that evidence and whether its citations resolve to the correct pages. A system can retrieve the right passage and still generate an unsupported detail. It can also produce careful prose from the wrong passage. One end-to-end score hides those two different repair jobs.

Failure records need enough context to act on:

  • the original question;
  • the retrieved chunk identifiers and scores;
  • the evidence actually sent for generation;
  • the returned citation identifiers; and
  • whether the application abstained.

Do not log full document text by default if those PDFs may contain sensitive material. Identifiers and controlled samples can make many failures diagnosable without copying the corpus into another system. Retention and access should follow the application's data policy.

Latency and cost deserve measurement, but neither is the main claim here. Record time spent in extraction, retrieval, and generation separately. That tells you which stage is worth optimizing. A faster nearest-neighbor lookup does little for revenue per hour if PDF ingestion or answer validation dominates the user wait.

What changes when the corpus grows

At larger scale, I would consider lexical plus vector retrieval, metadata filters, reranking, and more deliberate context selection. Each addition must fix an observed miss in the evaluation set. Otherwise it creates another component to operate without proving better grounded answers.

Versioning becomes more important too. When two PDFs describe different releases, document metadata should let retrieval narrow the scope or let the answer expose the conflict. Silently blending them produces polished ambiguity. Citation does not cure that; it merely makes the conflict inspectable.

The core contract stays small: retrieve candidates, select evidence, generate within that evidence, validate citations, and abstain when support is missing. Vector search is valuable because it reduces the material the answerer must inspect. It cannot answer questions on its own because ranking related text is a different job from producing a supported response.

For a solo SaaS, that boundary is useful discipline. Build the evidence path first. Add sophistication only when a named failure earns its maintenance cost.

Sources

References:

來源:DEV Community · dev.to