ClaudeCitationsDocument AIStructured Outputs

Keep a source citation with every field Claude extracts

Claude citations cannot be combined with strict structured output. Extract cited field lines, parse them into records, and verify missing values and source locations before use.

Keep a source citation with every field Claude extracts

Extracting contract fields and preserving evidence requires more than enabling JSON and citations together. The current Claude API rejects citations combined with output_config.format with a 400 error.

Anthropic recommends a different path: ask for one cited line per field, then parse those lines into structured records in your application. Keep each value connected to the text block and citations that produced it.

This article checks the Claude citations guide, especially “Get structured data with citations” and location rules, on November 19, 2026. No model request or contract upload was performed. The sample policy is fictional and supplies no legal or commercial advice.

Why not reuse the existing JSON workflow?

Structured output constrains fields and types. Citations identify supporting passages. The current strict-output interface cannot combine the two.

A cited answer can contain several text blocks, each with its own citations array. Joining only the text and parsing it as JSON discards the relationship between values and sources. Even without strict schema enforcement, prompting for “only JSON” can result in few or no citations, according to the guide.

Use cited field lines when source evidence matters, then validate the resulting data in code. Keep strict JSON output for tasks whose contract does not require these document citations.

What should the request contain?

A useful public fixture includes a general rule, an exception, and one deliberately missing fact:

Unopened goods may be returned within 7 days after delivery.
Custom items are excluded from that rule and require manual review.

Ask for return_window, custom_items, and review_days. The last field is absent, so the response should not invent a duration. This follows the official example's current model, claude-opus-5-5, and uses a locally configured ANTHROPIC_API_KEY. It has not been executed here.

import anthropic

client = anthropic.Anthropic()
response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "document",
                "source": {
                    "type": "text",
                    "media_type": "text/plain",
                    "data": "Unopened goods may be returned within 7 days after delivery. Custom items are excluded and require manual review.",
                },
                "title": "Public demo policy v1",
                "citations": {"enabled": True},
            },
            {
                "type": "text",
                "text": "Extract return_window, custom_items, review_days. Use one field: value line per field and cite each supported value. Use UNKNOWN for information not stated. Do not guess.",
            },
        ],
    }],
)
print(response.model_dump_json(indent=2))

Do not add output_config.format or the deprecated output_format. For multiple documents, follow the current requirement to enable citations consistently rather than mixing enabled and disabled documents.

Enable document citations, request field lines, preserve evidence during parsing, then validate business meaning

What if one field spans several text blocks?

Process blocks in response order. Start a new record at a newline and attach a block's citations to each line containing its text. One block is not necessarily one line: the official example separates a field label and its value.

This offline parser takes a complete response saved as response.json. It accepts known fields, rejects duplicates, and flags missing, UNKNOWN, or uncited values. It does not establish that a citation supports the value; source review remains necessary.

import json
from pathlib import Path

payload = json.loads(Path("response.json").read_text())
lines = [{"text": "", "citations": []}]
for block in payload.get("content", []):
    if block.get("type") != "text":
        continue
    pieces = block.get("text", "").split("\n")
    for i, piece in enumerate(pieces):
        if i:
            lines.append({"text": "", "citations": []})
        lines[-1]["text"] += piece
        if piece:
            lines[-1]["citations"].extend(block.get("citations", []))

fields = {}
expected = {"return_window", "custom_items", "review_days"}
for line in lines:
    name, separator, value = line["text"].partition(":")
    name, value = name.strip(), value.strip()
    if not separator or name not in expected:
        continue
    if name in fields:
        raise ValueError(f"Duplicate field: {name}")
    fields[name] = {
        "value": value,
        "citations": line["citations"],
        "needs_review": not value or value == "UNKNOWN" or not line["citations"],
    }
for name in expected - fields.keys():
    fields[name] = {"value": None, "citations": [], "needs_review": True}
print(json.dumps(fields, ensure_ascii=False, indent=2))

Join label and value blocks into a line while keeping the value block's citations attached

Validate meaning as well as structure. “7 days” must retain “unopened” and “after delivery.” A number alone does not preserve the policy. An invented review duration should fail source review even if the model attaches a citation.

How are citation locations numbered?

Different document types use different ranges. Do not apply a universal “add one” transformation.

SourceLocation conventionPractical consequence
PDFOne-based pages, exclusive endA range from 1 to 2 covers the first page
Plain textZero-based character offsets, exclusive endRetain the exact source version
Custom contentZero-based content-block offsets, exclusive endRetain block order and identifiers
document_indexZero-based across all document blocks in the request, spanning messagesDo not search only the final message

PDF citations reference extracted text, not images. The document's title and context are not citable source content. For scans, first check the PDF evidence chain.

Is a valid citation enough for automatic approval?

No. Anthropic guarantees valid document pointers and extracts cited_text from the source. That does not guarantee every requested field exists or that an interpretation is correct.

Verify field coverage, source location, supporting meaning, and retained conditions separately

Check that fields are complete, duplicates are flagged, the correct document version opens, and the quoted passage supports the value without dropping exceptions. Confirm that the final UI preserves the association between text and citations.

When using retrieved chunks, retain document IDs, versions, and chunk mappings; see reranking and source mapping. For Nbility, start with connection basics and separately verify that the selected channel preserves native citations. Successful ordinary chat is insufficient evidence.

Related posts

Claude's text watermark is live: which models carry it, and who can check
ClaudeText WatermarkContent Provenance

Claude's text watermark is live: which models carry it, and who can check

Since November 16, 2026, supported Claude models watermark their text output. Here is what the watermark actually encodes, which models and platforms carry it, when sampling parameters weaken it, and why only a few organizations can detect it today.

Run your Agent workflow through Nbility

Get an API key and connect OpenAI-compatible models and developer tools from one place.

Get an API key