Generate contextual tags with a model
Your pages carry too little metadata for projected tags to separate them, and the search still returns passages from the wrong document or the wrong section. A language model can read each page once, offline, and write for each section a short context that situates it in its page. This is Anthropic's Contextual Retrieval, moved upstream of indexing: the contexts are written once into sidematter files, and no model runs while you index or search. This procedure writes the contexts with duckdb-vectors annotate, keeps them fresh when pages change, and moves them between the front matter and the sidematter files. It is the third and fourth layer of the troubleshooting procedure. Measure each step on your own questions with the evaluation procedure, because a context costs model calls, and a longer text to embed.
What does the model write?
For each section, the model reads the whole page and writes the short context that situates the section in it. The prompt is the one of Anthropic, word for word. The page is sent once as a cached prompt prefix, and read from the cache for its other sections. The result is a sentence of about 50 words, for example "The backoff settings of the Cedar deployment runbook, which ...". The command writes it to a sidematter file next to the page, named after it with .sidematter.yaml added. The tags reference defines sidematter once, with its merge rules. Here is what the command adds:
pages/
retry-policy.md
retry-policy.md.sidematter.yaml# retry-policy.md.sidematter.yaml
crc: 3f9a1c02 # fingerprint of the page text, written by the command
sections: # per-section metadata, keyed by section path
retry-policy/backoff:
retrieval:
context: The backoff settings of the Cedar deployment runbook, which ...Values that a model derives go under the key retrieval, which says what they are for. They never mix with tags that people wrote. The command never commits: review the diff before you do.
What do you need?
pip install "duckdb-vectors[anthropic]", or the extra of the provider that you choose in step 1:bedrock,anthropicoropenai. A local model needs theopenaiextra and anopenai_base_url.- The credentials of that provider. Pages are sent to the model. If they are private, check that the provider and its region fit your obligations.
- A copy of the pages to work on. The command writes a sidematter file next to each page, or with
--write-to frontmatterrewrites the front matter in place, so run it on a working copy or a branch. - To try the path first with no provider, set
annotation.model: fake. A deterministic stand-in answers in the expected shape, and its contexts are not meaningful. On the eight pages offixtures/tagged/, it completes in seconds. Every model answer is cached on disk by content, in theworkfolder of the manifest, so a re-run costs nothing and an edited page costs only that page.
Step 1: choose the generation model
Run duckdb-vectors init in the folder of your pages, then uncomment the annotation block of .duckdb-vectors.yaml and set model. The prefix selects the provider, and the attributes with the same prefix configure it:
| Model | Provider | Notes |
|---|---|---|
bedrock:eu.anthropic.claude-haiku-4-5-20251001-v1:0 | Amazon Bedrock | Supports batch jobs. |
anthropic:<model> | Anthropic Messages API | The key comes from ${ANTHROPIC_API_KEY}. |
openai:<model> | OpenAI Chat Completions | With openai_base_url, any OpenAI-compatible server, local ones included. |
fake | none | Tests only. |
The manifest reference lists the attributes. A key is never written in the file, only as a ${VAR} reference. Without annotation.model, annotate stops and tells you what to set.
Step 2: write the section contexts
Start with a dry run. It writes the contexts to work/contexts.json only, so that you can read them and count the calls:
$ duckdb-vectors annotate --dry-run
$ duckdb-vectors annotateWithout --dry-run, the contexts go into the sections key of the sidematter file of each page. With --write-to frontmatter, they go into the front matter of the page instead. Pages whose crc is current are skipped, and --force writes every page again. The command prints a usage report with the tokens and, for models with a known price, the cost. A page much longer than the model needs, such as a 300-page filing, can be bounded with annotation.max_document_chars or --max-document-chars 12000. The model then sees the opening of the page and the neighbourhood of the section, instead of the whole page. Read a sample before you go on. Pick ten sections, and check that each context names what its section loses when it is cut from its page.
Step 3: index with the contexts
The context is a tag like any other. Index it in the embedding and in the keyword index, by setting tags in the manifest:
tags:
fields:
- "context: $.retrieval.context"
bm25: true$ duckdb-vectors indexIn our runs the keyword index carried a large share of the gain, so we recommend bm25: true. Keep the prefix short: the context is about 50 words, so add few other tags next to it. The tags report of the projection procedure warns when prefix and chunk probably exceed the input window of the model. Note that it always calls a context decorative, since a context differs on every section. Ignore that verdict, and judge the context on your questions.
How to tag PDF files?
annotate writes the contexts of Markdown pages and PDF files in the same run, so a mixed folder needs no separate command. A PDF has no front matter and the command never modifies it, so everything goes to its sidematter file, whatever --write-to says:
reports/
annual-report.pdf
annual-report.pdf.sidematter.yaml# annual-report.pdf.sidematter.yaml
crc: 333db27a # CRC32 of the bytes of the PDF file
pages: # per-page metadata, keyed by the 1-based page number
1:
retrieval:
context: The opening page of the Beacon annual report 2024, which ...Contexts. annotate writes one context per page under pages.<n>.retrieval.context. The model reads the text of the whole document, cached as a prompt prefix, and the page to situate, so a page cut from a 300-page report still names its company and period. A page with no text gets no context. --max-document-chars bounds the document the same way as for Markdown. --from-pack applies a pack to PDF files with the same page keys, and refuses a page that the PDF does not have. Text and OCR. The command reads pages through the same code as the indexer: the embedded text layer, or a local OCR for a scanned page. The OCR therefore runs again at annotation time on scanned pages, on top of the run at indexing time. A cached answer saves the model calls on a second run, and it does not save the OCR. Tags. The document information that the PDF declares (title, author, subject, keywords) stays native, and wins over a sidematter key on a collision, as for front matter.
How to keep tags fresh?
Pages change, and a context written for an old text misleads the search. annotate also writes a top-level crc: the CRC32 of the page body, as 8 hex digits. The front matter is left out, so that writing contexts or the crc never changes it. Line endings and trailing spaces are normalized first, so formatting noise is not an edit. The crc is written to the same file as the contexts, and read from it. On the next run, annotate skips a page when the stored crc matches the current body and the page holds a context for every section. A page with no crc is annotated and gains one. If you change max_document_chars or the model, then use --force, because the crc covers the text and not the settings. The crc covers the whole body, so a typo fix annotates the whole page again, and an edit to front matter values does not. For a PDF file, the crc is the CRC32 of the bytes of the file. A re-saved PDF with the same text is a different file. To find the stale pages, with no model call:
$ duckdb-vectors annotate --checkIt lists the pages whose crc is missing or differs from the text, and exits with status 1 if there are any. On a copy of fixtures/tagged/, it reports "0 pages without a current crc" after annotate with the fake model, and after an edit of one page it lists that page and fails. Use it to gate a pull request. The following GitHub Actions workflow installs the package and fails when a page changed without new contexts. It is an example that you adapt:
name: check-contexts
on:
pull_request:
paths: ["pages/**"]
jobs:
crc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: astral-sh/setup-uv@v7
- name: Install duckdb-vectors
run: pip install duckdb-vectors
- name: List the pages without a current crc
run: duckdb-vectors --manifest pages annotate --checkIf the check fails, then the author runs duckdb-vectors annotate on the branch, reads the diff, and pushes the sidematter files.
How to use batch inference?
Bedrock batch inference has its own quotas, far above the daily token quota of on-demand calls, and it costs half as much. It needs at least 100 requests per job and can take up to a day, though jobs of a few thousand requests usually finish within an hour. It needs an S3 bucket in the region of the job, and a service role that lets bedrock.amazonaws.com read and write that bucket and invoke the model.
- Set the
batchsection of the manifest, withbedrock_bucketandbedrock_role_arn, and abedrock:model inannotation. - Run
duckdb-vectors annotate. It answers what it can from earlier answers, submits the rest as jobs, and exits with status 3. - Run the same command again later, by hand or from a scheduler. Each run fetches the jobs that completed and submits what is still missing. When nothing is pending, it writes the contexts and exits with status 0.
duckdb-vectors statuslists the jobs with their state. With fewer than 100 missing requests, the command sends them online and says so, and--no-batchsends all the requests online for one run.
How to move tags between the front matter and the sidematter?
A knowledge base tagged before sidematter files existed holds retrieval, sections and crc in the front matter of its pages. While they stay there, they win over any new value in a sidematter file. Move them once:
$ duckdb-vectors move-tags-to-sidematter --dry-run
$ duckdb-vectors move-tags-to-sidematterFor each page, the three keys go into its sidematter file and leave the front matter. Every other key and the body stay as written, and a page that holds no such key is not touched. If a sidematter file already exists, then the keys are merged into it. A key path that holds a different value in both files is a collision: the command reports it, leaves that page unchanged, and exits with status 1. duckdb-vectors move-tags-to-frontmatter moves the keys back into the front matter. When you move or rename a page, move its sidematter file with it, for example with git mv on both. Pages curated before the key was renamed keep their values under llm.
Next steps
- Evaluate retrieval on your own queries: measure each step before you keep it.
- Project tags in embeddings: the first layer, and the
tagsreport. - Inspect a knowledge base: check the tags, their values and the prefix.
- Manifest reference: the
annotationandbatchsections. - Tags reference: the concepts and the published work.
- Performance workbook: the measured gains and costs.
- Reproduce the tagged benchmark: the same results on public corpora.
- Issue #65: the method and its pre-registration.