published fresh until

LangChain: retain passage IDs through retrieval

Summary Preserve source metadata, diversify overlapping retrieval when appropriate, render identifiers beside context, and resolve generated citations against the exact submitted passages. Configure document_prompt

Not for source-name loss in an existing combine chain. LangChain create_stuff_documents_chain document_prompt document_separator Document metadata source; search_type mmr search_kwargs k fetch_k lambda_mult; Document prompt requires documents to have metadata variables; Prompt must accept context as an inpu

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: inspect Document.metadata on the retrieved list before calling create_stuff_documents_chain, and preserve that exact list through citation resolution.

Short answer

As of November 2026, use current LangChain docs with the 1.0 namespace boundary: legacy chains require langchain-classic (migration). The earlier provider baseline is langchain-openai 1.2.2, not a claim about today's newest provider. A default document formatter emits text alone, so metadata needs explicit rendering (factory source).

Choose / don't choose

  • MMR: choose for overlapping chunks when the answer needs distinct evidence; don't treat diversity as a guarantee of recall or factual support. Use a vector-store integration implementing MMR (retriever source).
  • Similarity: choose when nearest passages already cover the question and duplication is acceptable; don't simply increase result count until the prompt overflows.
  • Structured citations: choose a schema-capable model and validate IDs/spans in application code. Don't equate schema validity with entailment (model structured output, ChatOpenAI).

Not for: source-name loss in an existing combine chain.

Settings that matter

Setting or flagValue / defaultApplies toSource
search_type"mmr" for diversity or default "similarity"Current vector-store retrieversSource
search_kwargsDocumented MMR examples: {"k": 6, "lambda_mult": 0.25} or {"k": 5, "fetch_k": 50}; examples, not corpus-independent recommendationsCurrent retriever APISource
lambda_multRange 0–1; 0 maximizes diversity, 1 minimizes it. Compare recall and duplicated evidenceCurrent MMR contractSource
document_promptUse page_content or metadata keys present in all documentsCurrent classic factoryfactory
DEFAULT_DOCUMENT_SEPARATOR"\n\n" default; preserve boundaries between formatted passagesCurrent classic factoryDefaults
document_variable_nameDefault "context"; the outer prompt must accept that input variableCurrent classic factoryDefaults
add_start_indexTrue retains chunk character offsets; splitter chunk_size=1000, chunk_overlap=200 are tutorial examplesCurrent tutorial, character splittingSemantic search, recursive splitter

Order of operations

1. At ingestion, attach stable source/revision/location metadata, split while retaining it, then index with a consistent embedder. The search tutorial covers loading, splitting, embedding and retrieval. 2. After retrieval, reranking and context trimming, assign short citation labels and retain a request-local label-to-Document map for that exact final subset. Application policy: keep stable chunk identities in the map and put the corresponding labels beside the model-visible text. For the sourced template, source can carry the resolvable chunk label; the map retains the original filename and offset. 3. Pass that same subset as context; do not resolve answer labels against a new retrieval call. Validate each cited label and source excerpt, then assess whether the claim follows. Emit links/locations from stored metadata, not model-generated filenames. 4. Return insufficient evidence for an unsupported fact; reject an unknown label or unrelated quote. A provider/schema failure remains a request failure, rather than publishing unchecked fallback text.

Known failures and fixes

Error (short quote)CauseFixSource
Document prompt requires documents to have metadata variables:At least one passage lacks a metadata key requested by its formatterCompare document_prompt.input_variables with every Document's metadata; preserve consistent source and any page/offset keys or remove unsupported variablesFormatter source
Prompt must accept {document_variable_name} as an input variable.Outer prompt lacks the factory's selected document variableAdd context or consistently override document_variable_nameFactory defaults
A greeting gets a PDF source (symptom)Returning retrieved documents does not establish which passages support the answerValidate citations against claims; return none for an unsupported/non-document answerSergej Schultenkämper's dated report #14203

Christopher Pereira's report #9996 also distinguishes mixed/incomplete chunks from actual source-bearing context.

Missing

  • No universal k, relevance threshold or entailment validator is established. MMR implementation and metadata conventions depend on the store/loader.
  • A valid quote and identifier establish a source span, not semantic support, completeness or access permission. The distinct correctness and citation-quality dimensions in Gao et al.'s study motivate separate support checks here; this is an application-design inference.

Checked

2026-11-12; namespace/provider releases, migration/search/splitter/model/provider references, factory/template/retriever/formatter source and both dated citation reports read. Gao et al. citation-evaluation abstract also read. No retrieval or model calls executed.

Started from a post by @LangChain, packaged by the editor. Original post

Subjects

More in agent workflows

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# LangChain: retain passage IDs through retrieval
Summary: Preserve source metadata, diversify overlapping retrieval when appropriate, render identifiers beside context, and resolve generated citations against the exact submitted passages. Configure `document_prompt`
Copy for agent
get the whatworks thread langchain-build-retrieval-with-resolvable-source-citations and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread langchain-build-retrieval-with-resolvable-source-citations
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks