Howwise RSS
AI & Automation6 min read

LangChain QA with Sources: Cite URL Section Anchors

Short answer

To get langchain qa with sources url section citations, split the page by headings, store the heading and anchor in each chunk's metadata, and set metadata['source'] to URL#anchor. The chain only echoes the metadata it is shown.

Key takeaways
  • The source in a citation is just metadata['source'] on the retrieved chunk, set by the loader and copied by the splitter.
  • A single-page URL gives one source because the loader returns one Document and every chunk inherits its metadata.
  • Split by headings, then store heading, anchor and a deep link in metadata before embedding.
  • Set metadata['source'] to the deep link (or point the document prompt at a new key) so the sources chain shows it.
  • If the page has no id anchors, fall back to a #:~:text= fragment link, which works mainly in Chromium browsers.

Where does a LangChain source citation actually come from?

The source shown in a RAG answer is not generated by the model or chosen by the retriever. It is the value of metadata['source'] on each retrieved Document. WebBaseLoader sets it to the page URL when it loads the page.

The path is: loader sets metadata, the splitter copies it to every chunk, the vector store saves it next to the embedding, the retriever returns it, and the chain prints it. Nothing in that path knows about headings unless you put them in metadata.

That is why a long single page always cites the same URL. WebBaseLoader (and UnstructuredURLLoader in its default mode) returns one Document for the whole page, and RecursiveCharacterTextSplitter gives every chunk a copy of that one metadata dict.

StageWhat happens to metadataTypical result for one long page
LoaderSets source (and often title, language)One Document, source = page URL
SplitterCopies parent metadata to each chunk100 chunks, all with the same source
Vector storeStores metadata beside the vectorSame URL on every hit
ChainReads the 'source' key into the prompt and outputAnswer cites only the base URL
docs = loader.load()
print(len(docs), docs[0].metadata)   # 1 {'source': 'https://...', 'title': ...}
chunks = splitter.split_documents(docs)
print({c.metadata['source'] for c in chunks})  # a single URL
Tip: Always print doc.metadata after loading and after splitting. Loader defaults differ between versions and loaders, and this one habit finds most citation bugs.

How do I split a web page by headings and keep the heading in metadata?

Split by structure first, then by size. HTMLHeaderTextSplitter reads h1, h2 and h3 tags and attaches the active headings to each chunk's metadata, for example {'h2': 'Installation'}. If you prefer, convert the HTML to Markdown and use MarkdownHeaderTextSplitter with '#', '##' and '###'.

If a section is still too long, run RecursiveCharacterTextSplitter on the header-split chunks with split_documents. It preserves the header metadata on each smaller piece.

from langchain_text_splitters import (
    HTMLHeaderTextSplitter, RecursiveCharacterTextSplitter)

headers = [("h1", "h1"), ("h2", "h2"), ("h3", "h3")]
html_splitter = HTMLHeaderTextSplitter(headers_to_split_on=headers)
sections = html_splitter.split_text_from_url("https://example.com/guide")

sizer = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
chunks = sizer.split_documents(sections)
print(chunks[3].metadata)   # {'h1': 'Guide', 'h2': 'Installation'}
Warning: HTMLHeaderTextSplitter gives you heading text only. It does not record the id attribute, and the splitter output has no 'source' key, so you must add the URL and anchor yourself.

How do I build LangChain QA with sources URL section links (URL#anchor)?

A deep link needs the fragment the browser will scroll to. Many documentation sites put an id on each heading, such as <h2 id="installation">, and some put it on a child <a> or a wrapping <section>. Open the page source and confirm this before writing code, because a made-up fragment simply scrolls nowhere.

The most reliable approach is to parse the HTML yourself and create one Document per section. You read the real id, so the link matches the page, and you control the metadata fields: source, page_url, heading and anchor.

import re, requests
from bs4 import BeautifulSoup
from langchain_core.documents import Document

URL = "https://example.com/guide"
soup = BeautifulSoup(requests.get(URL, timeout=30).text, "html.parser")
root = soup.find("main") or soup.body

def slugify(t):
    return re.sub(r"[^a-z0-9]+", "-", t.lower()).strip("-")

sections, cur = [], None
for el in root.find_all(["h1", "h2", "h3", "p", "li", "pre"]):
    if el.name in ("h1", "h2", "h3"):
        anchor = el.get("id")
        if not anchor:
            a = el.find("a", id=True) or el.find_parent("section", id=True)
            anchor = a.get("id") if a else None
        cur = {"heading": el.get_text(" ", strip=True),
               "anchor": anchor, "text": []}
        sections.append(cur)
    elif cur is not None:
        cur["text"].append(el.get_text(" ", strip=True))

docs = []
for s in sections:
    body = "\n".join(s["text"]).strip()
    if not body:
        continue
    link = f"{URL}#{s['anchor']}" if s["anchor"] else URL
    docs.append(Document(
        page_content=body,
        metadata={"source": link, "page_url": URL,
                  "heading": s["heading"], "anchor": s["anchor"] or ""}))
Tip: Slugifying the heading text only works when the site generates ids the same way (GitHub-style slugs, for instance). Treat it as a guess and compare a few links against the real page.

How do I embed the sections and return heading plus link?

Split long sections by size, but put the heading back at the top of every chunk so each piece still says what it is about. Then embed into a fresh vector store.

The chain import below uses the langchain_classic package, where the legacy chain classes live in LangChain 1.x. Install it with pip install langchain-classic. If you pin langchain<1.0 instead, the old path from langchain.chains import RetrievalQAWithSourcesChain still works.

Two Chroma details matter. Metadata values must be str, int, float or bool, so None (a missing anchor) fails and lists or dicts need flattening, which is why the code above uses an empty string. And re-running the script on a persisted collection adds duplicates, so delete the old collection or use stable ids.

# LangChain 1.x: pip install langchain-classic
# (on langchain<1.0 use: from langchain.chains import RetrievalQAWithSourcesChain)
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_classic.chains import RetrievalQAWithSourcesChain

sizer = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=80)
chunks = []
for d in docs:
    for piece in sizer.split_text(d.page_content):
        chunks.append(Document(
            page_content=f"{d.metadata['heading']}\n\n{piece}",
            metadata=d.metadata))

store = Chroma(collection_name="guide", embedding_function=OpenAIEmbeddings(),
               persist_directory="./db")
store.delete_collection()            # clears old, stale chunks
store = Chroma.from_documents(chunks, OpenAIEmbeddings(),
                              collection_name="guide", persist_directory="./db")

chain = RetrievalQAWithSourcesChain.from_chain_type(
    llm=ChatOpenAI(temperature=0),
    retriever=store.as_retriever(search_kwargs={"k": 4}),
    return_source_documents=True)

out = chain.invoke({"question": "How do I install it?"})
print(out["answer"])
print(out["sources"])                # deep links, since source = URL#anchor
for d in out["source_documents"]:
    print(d.metadata["heading"], "->", d.metadata["source"])
Warning: delete_collection() permanently removes the stored vectors. Only run it when you intend to rebuild the index from the source page.

Why does the sources chain still show only the base URL?

RetrievalQAWithSourcesChain formats each retrieved document with a document prompt that reads page_content and the 'source' key, and the model is asked to list the sources it used. The 'sources' string in the output is the model copying values it was shown.

So if the prompt contains the bare URL, the answer cites the bare URL. The simplest fix is what the example does: overwrite metadata['source'] with the deep link and keep the plain page URL in a separate key like page_url.

The alternative is to leave source alone and change the chain's document prompt so it prints your own key, for example a template of 'Content: {page_content}\nSource: {source_url}'. The prompt variables must match metadata keys, or formatting fails.

Do not rely on the model to compose anchors from heading text. It will occasionally invent or mangle them. Show it ready-made links, and for the user-facing citation list, read d.metadata from source_documents instead of parsing the model's text.

How do I do this with create_retrieval_chain or LCEL?

In LangChain 1.x, create_retrieval_chain and create_stuff_documents_chain are legacy helpers that now live in langchain_classic, alongside RetrievalQAWithSourcesChain. They still work and are a good fit for a fixed retrieve-then-answer flow. For new projects, LCEL or an agent with a retriever tool is the maintained direction.

create_retrieval_chain returns a dict with input, context (the retrieved Documents) and answer, so the sources come back with the answer. Format the context yourself so the model sees heading and link.

# LangChain 1.x: pip install langchain-classic
# (on langchain<1.0 use langchain.chains and langchain.chains.combine_documents)
from langchain_classic.chains import create_retrieval_chain
from langchain_classic.chains.combine_documents import create_stuff_documents_chain
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(temperature=0)
doc_prompt = PromptTemplate.from_template(
    "[{heading}] ({source})\n{page_content}")
prompt = ChatPromptTemplate.from_messages([
    ("system", "Answer only from the context. Cite the bracketed headings.\n\n{context}"),
    ("human", "{input}")])

qa = create_stuff_documents_chain(llm, prompt, document_prompt=doc_prompt)
rag = create_retrieval_chain(store.as_retriever(search_kwargs={"k": 4}), qa)

res = rag.invoke({"input": "How do I install it?"})
print(res["answer"])
for d in res["context"]:
    print(f"- {d.metadata['heading']}: {d.metadata['source']}")
Tip: Run pip list | grep -i langchain to see which major version you have. An ImportError on langchain.chains usually means you are on 1.x and need langchain_classic.

What if the page has no anchors, and how small should chunks be?

When headings have no ids, use a text fragment link: URL#:~:text=<url-encoded first words of the chunk>. Chromium browsers (Chrome, Edge) scroll to and highlight the match. Support elsewhere is uneven, and the link does nothing if the text is split across elements or the page renders it with JavaScript later. Use 5 to 8 words from the start of the section and quote with urllib.parse.quote(text, safe="").

Chunk size is a precision tradeoff. Chunks that align to one section give exact citations, while larger chunks that span headings blur them and the link points to only one of them. Around 500 to 1000 characters per chunk is a sensible start, with small overlap (10 percent) applied only inside a section so an overlap never pulls in text from another heading.

SituationCitation to useCaveat
Headings have id attributesURL#idCheck the real HTML
No ids, stable heading textURL#:~:text=first%20wordsChromium mainly
Content built by JavaScriptRender first, or cite page onlyFragment may not match
from urllib.parse import quote
words = " ".join(chunk_text.split()[:6])
link = f"{URL}#:~:text={quote(words, safe='')}"

Common questions

Why does WebBaseLoader metadata only contain the URL?

WebBaseLoader records source and, when it finds them, title, description and language. It does not understand page structure, so there is no heading or anchor data to record. You add that by splitting or parsing the HTML yourself.

Can I use UnstructuredURLLoader to get sections?

Yes, with mode='elements' it returns one Document per element, and the metadata can include the category (such as Title). That gives structure but not id anchors, so you would still need to look up the real ids or use text fragments.

Why did my metadata disappear or raise an error in Chroma?

Chroma accepts only str, int, float and bool values, so lists, dicts and None fail. Flatten them to strings, or run langchain_community.vectorstores.utils.filter_complex_metadata, which drops unsupported fields.

Why do I get duplicate or old citations after re-running my script?

Persisted stores keep earlier chunks, so rebuilding adds a second copy with the old metadata. Delete the collection before re-indexing, or assign deterministic ids so the same chunk overwrites itself.

Can the retriever filter by section?

Yes. Because heading is metadata, you can pass search_kwargs={'k': 4, 'filter': {'heading': 'Installation'}} to a Chroma retriever. This is useful when the user's question names a specific section.

Related topics:langchainragretrievalcitationsweb scraping