Production Workflows

Build a Small Internal Research Assistant with Source Tracking

Build a Small Internal Research Assistant with Source Tracking
Learn how to build a reliable internal research assistant featuring explicit source tracking, stable document identifiers, keyword retrieval, and forced citations. This practical guide covers deterministic retrieval, structured JSON generation, post-processing filters, and essential failure mode testing to ensure AI-generated answers remain verifiable, transparent, and trustworthy.

The first internal research assistant I built could answer almost any question about our product docs. It could not tell me where any of the answers came from. When a teammate asked “Which version of the API still supports the old authentication header?” the assistant replied with a confident paragraph and no citations. We spent the next hour hunting through the same documents the model had supposedly read. That was the moment I stopped treating “helpful answer” as the success metric and started treating “answer plus traceable sources” as the minimum bar.

This post builds the smallest useful version of that bar: a research assistant that retrieves a few relevant passages, generates an answer, and returns the exact sources it used. No vector database cluster, no multi-agent orchestration—just a clear retrieve-then-generate loop with explicit source tracking you can inspect and trust.

As always:

Build the smallest useful version, then test what breaks.

What You Will Have Working by the End

  • A tiny in-memory document store with stable source IDs

  • A simple retrieval step that returns the most relevant passages

  • A generation step that must cite those passages

  • A structured response containing the answer and the list of sources used

  • Three realistic failure modes and how to notice them early

The output will be something a teammate can verify in under a minute.

The Document Store (Intentionally Tiny)

We start with a handful of short documents. In a real system these would live in a search index or a vector store; for learning we keep them in a Python list so every step stays visible.

Python

DOCUMENTS = [
    {
        "id": "doc-001",
        "title": "Authentication Overview",
        "text": (
            "All API requests must include an x-api-key header. "
            "Keys are created in the console under Settings > API Keys. "
            "Legacy Authorization: Bearer headers were deprecated in version 3.2 "
            "and removed in version 4.0."
        )
    },
    {
        "id": "doc-002",
        "title": "Rate Limits",
        "text": (
            "The default rate limit is 60 requests per minute per API key. "
            "Enterprise plans can request higher limits. "
            "When a limit is exceeded the API returns HTTP 429."
        )
    },
    {
        "id": "doc-003",
        "title": "Error Codes",
        "text": (
            "Common error codes include 401 (invalid key), 403 (forbidden), "
            "404 (resource not found), 429 (rate limited), and 500 (internal error). "
            "All error responses include a JSON body with a type and message field."
        )
    },
    {
        "id": "doc-004",
        "title": "Versioning Policy",
        "text": (
            "Breaking changes are only introduced in major versions. "
            "Version 4.0 removed legacy authentication headers. "
            "Clients should pin to a specific major version in production."
        )
    }
]

Each document has a stable id. That ID is what we will return as a source. Never rely on the model to invent source identifiers; always pass them in and require the model to echo them back.

Simple Retrieval

A documentary close-up of a screen showing Python document store lists and keyword retrieval code.

For this minimal version we use straightforward keyword overlap. It is not state-of-the-art retrieval, but it is deterministic, easy to debug, and sufficient to demonstrate source tracking.

Python

def retrieve(query: str, top_k: int = 2) -> list[dict]:
    """Return the top_k documents with the most keyword overlap."""
    query_terms = set(query.lower().split())
    scored = []
    for doc in DOCUMENTS:
        doc_terms = set(doc["text"].lower().split())
        overlap = len(query_terms & doc_terms)
        scored.append((overlap, doc))
    scored.sort(key=lambda x: x[0], reverse=True)
    return [doc for score, doc in scored[:top_k] if score > 0]

In production you would replace this function with a call to your search or embedding index. The rest of the workflow stays the same: retrieval returns a list of documents that each carry a stable ID and the original text.

The Generation Step with Forced Citations

We give the model only the retrieved passages and require it to cite the document IDs it actually used.

Python

import json
import os
from dotenv import load_dotenv
from anthropic import Anthropic

load_dotenv()
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))

SYSTEM = """You are an internal research assistant.
You will be given a user question and a set of source passages.
Answer the question using ONLY the provided sources.
You must cite every source you use by its doc ID.
Return ONLY a valid JSON object with this shape:
{
  "answer": "string",
  "sources_used": ["doc-id", ...]
}
Do not invent document IDs. Only use IDs that appear in the provided sources.
If the sources do not contain enough information, say so in the answer and return an empty sources_used list.
Do not wrap the JSON in markdown.
"""

def generate_answer(query: str, sources: list[dict]) -> dict:
    if not sources:
        return {
            "answer": "I could not find any relevant sources for this question.",
            "sources_used": []
        }

    source_block = "\n\n".join(
        f"[{doc['id']}] {doc['title']}\n{doc['text']}" for doc in sources
    )

    user_content = (
        f"Question: {query}\n\n"
        f"Sources:\n{source_block}\n\n"
        f"Return the JSON object described in the system instructions."
    )

    response = client.messages.create(
        model="claude-sonnet-5",  # verify current ID in official docs
        max_tokens=512,
        system=SYSTEM,
        messages=[{"role": "user", "content": user_content}]
    )

    raw = response.content[0].text.strip()
    try:
        data = json.loads(raw)
    except json.JSONDecodeError as e:
        raise ValueError(f"Model returned invalid JSON: {e}\nRaw: {raw}") from e

    if "answer" not in data or "sources_used" not in data:
        raise ValueError(f"Missing required keys in model output: {data}")

    # Ensure sources_used only contains IDs we actually provided
    allowed_ids = {doc["id"] for doc in sources}
    cleaned_sources = [sid for sid in data["sources_used"] if sid in allowed_ids]
    data["sources_used"] = cleaned_sources

    return data

Two important safeguards:

  1. We only send the retrieved passages, not the entire corpus.

  2. After the model responds we filter sources_used so that any invented ID is dropped.

    A documentary photo of a developer reviewing terminal logs for forced AI citations and filtered source IDs.

The Full Research Assistant

Python

def research(query: str) -> dict:
    print(f"Query: {query}")
    sources = retrieve(query, top_k=2)
    print(f"Retrieved sources: {[s['id'] for s in sources]}")

    result = generate_answer(query, sources)

    # Attach the full source texts for the caller (optional but useful)
    source_lookup = {doc["id"]: doc for doc in sources}
    result["source_details"] = [
        {
            "id": sid,
            "title": source_lookup[sid]["title"],
            "text": source_lookup[sid]["text"]
        }
        for sid in result["sources_used"]
        if sid in source_lookup
    ]
    return result


if __name__ == "__main__":
    question = "Which version removed the legacy Authorization Bearer header?"
    output = research(question)
    print("\n=== Research Result ===")
    print(json.dumps(output, indent=2))

When you run it you should see a short answer together with the exact document IDs (and the original text) that support the claim.

Three Failure Modes Worth Testing

1. The Model Cites a Source It Was Never Given

Temporarily add a fake ID to the model’s response (or weaken the prompt) and confirm the post-processing step removes it. Never trust a source list that has not been filtered against the passages you actually supplied.

2. Retrieval Returns Nothing Useful

Ask a question that has no overlap with any document. Confirm the assistant returns a clear “I could not find any relevant sources” answer and an empty sources_used list instead of hallucinating an answer.

3. The Answer Ignores the Sources

Ask a question whose answer is present in the retrieved passages, then inspect whether the model actually used those passages or invented a different explanation. If the citations are missing or the answer contradicts the source text, the prompt or the retrieval ranking needs work. Logging both the retrieved passages and the final answer side-by-side makes this failure obvious.

I keep a small set of “known-answer” questions whose correct sources I already know. Running the assistant against that set is part of every change to the retrieval or generation step.

Practical Rules That Keep Source Tracking Honest

  • Stable document IDs are non-negotiable. Generate them when the document is ingested, never at query time.

  • Only send the model the passages it is allowed to cite.

  • Filter the model’s cited IDs against the passages you actually provided.

  • Return the original source text alongside the IDs so a human can verify the claim in seconds.

  • Prefer “I don’t know” plus an empty source list over a fluent answer with no citations.

What This Assistant Does Not Do Yet

It does not:

  • Use embeddings or a real search index

  • Handle documents longer than a few paragraphs

  • Support follow-up questions that require conversation memory

  • Re-rank passages with a cross-encoder or the model itself

  • Store query logs or evaluation sets automatically

Those capabilities belong to later posts. The goal today is a retrieve-then-generate loop that never loses the link between an answer and the passages that support it.

Verification Checklist

  1. Ask the sample versioning question and confirm the answer cites the correct document IDs.

  2. Ask a question with no matching documents and confirm the assistant returns an empty source list.

  3. Manually inspect source_details and confirm the returned text matches the original documents.

  4. Force an invented source ID in the model output and confirm it is stripped before the result is returned.

  5. Log the retrieved passages and the final answer side-by-side and confirm they are consistent.

If all five steps pass, you have a working research assistant with honest source tracking.

Update Note

Model identifiers and structured-output helpers continue to evolve. Always verify the current recommended model ID and the preferred way to request JSON in the official Anthropic documentation. The retrieve-then-generate pattern with explicit source filtering remains useful regardless of those surface changes.

Looking Ahead

The next post adds background jobs and retries so the same research (or triage, or summarization) step can run reliably as part of a larger pipeline. Once you can produce an answer that carries its sources, the remaining production concerns become ordinary engineering: queues, retries, observability, and cost control.

Keep the research script. When you later connect it to a real document store, you will already have the discipline of stable IDs, filtered citations, and human-verifiable source text.

Build the smallest useful version, then test what breaks.

— Caleb Fletcher

Boise, Idaho

Updated · 2026-10-24 14:11
Feedback

No feedback yet — submit the first.

Submit feedback
© 2026 Context & Tools. All rights reserved. data-driven, published weekly ♥