Skip to content
Visual explainer 3h to learn 5 steps

Grounded doc lookup with source IDs in ADK

Add a small grounded knowledge lookup that returns source IDs, says when it does not know, and keeps tool data inside the app's trust boundary.

By Invicly Tech, , in Google ADK with Python for AI Agents. About 11 minutes to read.

Topic 9 of 29

In short

Grounding means the agent answers from text you supplied instead of from the model's memory. A small lookup tool searches a fixed set of public product docs, returns each passage with a source ID, and returns no_match when nothing scores high enough so the agent can say it does not know. Retrieved text is treated as data, stays inside your app, and every claim in the reply points back to a source ID.

Think of it like this: It is like an open-book exam where every answer must cite the page number, and a blank page is better than a made-up one.

Explained simply

Models remember a lot, but not your product's latest help pages. Ask about your refund policy and a model may invent one that sounds right. Grounding fixes this. Before answering, the agent looks up real passages from your docs and answers from those.

In this course the lookup is a small tool over a handful of public product pages stored in your repository. It splits pages into short passages, gives each one a stable ID like docs/billing#refunds, and returns the best few matches for a question.

Two rules make the answers trustworthy. First, every answer cites the source IDs it used, so a person can check it. Second, if nothing matches well enough, the tool says no_match and the agent says it does not know, instead of guessing.

Retrieved text is information, not instructions. If a page happens to contain the words ignore your rules, the agent must not obey them. The tools, their checks and the user's permissions stay exactly the same, whatever the documents say.

Press Play on a diagram to walk through it one step at a time.

SequenceA grounded answer with citations
User
Agent
search_docs tool
Local index
  1. 1How do I reset my password?
    User to Agent: How do I reset my password?
  2. 2search_docs(query="reset password")
    Agent to search_docs tool: search_docs(query="reset password")
  3. 3Score passages
    search_docs tool to Local index: Score passages
  4. 4Top 3 passages above threshold
    Local index to search_docs tool: Top 3 passages above threshold
  5. 5status ok, passages with source_id
    search_docs tool to Agent: status ok, passages with source_id
  6. 6Steps plus [docs/account#reset]
    Agent to User: Steps plus [docs/account#reset]
FlowBuilding the small index
  1. 1
    Collect

    A few public product pages

  2. 2
    Split

    Short passages by heading

  3. 3
    Label

    Stable source_id per passage

  4. 4
    Score

    Keyword or embedding similarity

  5. 5
    Threshold

    Below the line means no_match

LayersTrust levels of text in one request
  1. 1
    Developer instruction

    Trusted: written and reviewed by you

  2. 2
    Tool code and checks

    Trusted: enforce access in Python

  3. 3
    User message

    Untrusted: a request, not a command

  4. 4
    Retrieved passages

    Untrusted data: used as evidence only

In depth

A small index you can read

Start with five to twenty public pages saved as Markdown or text in the repo. Split each page at its headings into passages of a few hundred words. Give each passage a source ID built from the file path and heading slug, for example docs/account#reset-password, so the ID stays the same when you rebuild. For scoring, a simple keyword method such as BM25 or even word overlap is fine for a few hundred passages and needs no service or key. Embeddings from a model improve matching of synonyms but add a model call, a cost and a dependency; add them only when keyword search misses real questions in your test set. Build the index at startup or in a script, and keep it in memory or a local file.

  • Split by heading, keep passages short
  • source_id = path#heading-slug
  • Keyword scoring first, embeddings later if needed
  • Rebuild the index in CI from the docs folder

Saying I do not know on purpose

Every search returns something unless you stop it. Pick a threshold from your own test questions: look at scores for questions the docs answer and for questions they do not, and choose a value between them. When the best score is below the threshold, return status no_match with an empty passages list. The instruction then says: if search_docs returns no_match, say you could not find this in the documentation and offer to create a support handoff. Test this path with fixture questions that are clearly out of scope, such as asking about a product you do not sell. A good unknown answer is a feature, and your evaluation set should reward it.

FlowDecision path for one question
  1. 1
    Score passages
  2. 2
    Best score below threshold?

    Yes: return no_match

  3. 3
    Keep top 3 above threshold
  4. 4
    Return text with source IDs
  5. 5
    Agent answers and cites

    Or says it does not know

Citations you can check in code

Ask the agent to put source IDs in square brackets after the sentences that use them, and only IDs returned by search_docs in this turn. Then verify it in code: an after_agent_callback or your API layer can extract the bracketed IDs from the reply and compare them with the IDs in this turn's function response events. If the reply cites an ID that was not returned, flag it, and in strict mode replace the reply with a safe fallback. Turn IDs into links in your UI, not in the model's text, so the model never has to produce URLs. This check is cheap and catches the most common grounding failure: a real-looking citation to nothing.

Trust boundaries and managed options

The trust boundary is the line around data your app controls. Public docs can be indexed anywhere, but ticket text and user messages should stay inside your app and your own cloud project. Do not send private text to an outside search API just to rank it, and do not log retrieved passages next to user identities. Managed grounding exists in ADK too: Google Search grounding for public web facts, and Agent Search over your own data stores on Google Cloud. Both are billed services, and ADK documents a limitation: such built-in tools cannot be mixed with other tools in the same agent, so you wrap them in their own agent behind an AgentTool. The local index teaches the same pattern for free.

  • Private data stays in your project
  • Retrieved text cannot change tools or permissions
  • Built-in grounding tools are paid and need their own agent
  • Local index is the default for this course

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Index a small public doc set~35m
  2. 2
    Return source IDs with each passage~35m
  3. 3
    Answer unknown when nothing matches~35m
  4. 4
    Keep retrieved text inside the app~35m
  5. 5
    Show citations in the reply~35m

Key points

  • Give every passage a stable source ID, such as a page path plus heading, and return it with the text.
  • Return status no_match when the best score is below a threshold, and instruct the agent to say it does not know.
  • Tell the agent to cite only source IDs that the tool returned in this turn.
  • Treat retrieved text as untrusted data: it can inform the answer but never changes the agent's instructions or tools.
  • Managed grounding (Google Search grounding, Agent Search on Google Cloud) is optional and paid; a local index is enough to learn the pattern.

Key terms

Tap a card to flip it. 0/5 known

Examples

A keyword lookup with a threshold

PASSAGES is a list of dicts built from the docs folder. The tool scores word overlap, drops weak matches and returns at most three passages with their IDs, or no_match.

python
PASSAGES = [{"source_id": "docs/account#reset-password", "text": "To reset your password open Settings, then Security..."}]
MIN_SCORE = 2

def search_docs(query: str) -> dict:
    """Search the public product docs. Cite the returned source_id values."""
    words = set(query.lower().split())
    scored = [(len(words & set(p["text"].lower().split())), p) for p in PASSAGES]
    hits = [p for s, p in sorted(scored, key=lambda x: -x[0]) if s >= MIN_SCORE][:3]
    if not hits:
        return {"status": "no_match", "passages": []}
    return {"status": "ok", "passages": hits}

Checking that citations are real

After a run, collect the source IDs from this turn's search_docs results and compare them with IDs cited in the final text. Any extra ID is an invented citation.

python
import re

def invented_citations(final_text: str, events) -> set[str]:
    returned = set()
    for e in events:
        for resp in e.get_function_responses():
            if resp.name == "search_docs":
                returned |= {p["source_id"] for p in resp.response.get("passages", [])}
    cited = set(re.findall(r"\[([\w/#.-]+)\]", final_text))
    return cited - returned

Quick reference

  • Grounding = answer from supplied passages, not model memory.
  • Each passage carries a stable source_id such as docs/billing#refunds.
  • Below the score threshold, return status no_match and say you do not know.
  • Cite only IDs returned in this turn; verify in code.
  • Retrieved text is data. It never changes tools or permissions.
  • Keep private ticket text inside your app's trust boundary.
  • Google Search grounding and Agent Search are paid and need their own agent behind AgentTool.

Common mistakes

  • Returning the top passage even when it is barely related, which invites a confident wrong answer.
  • Letting the model invent citations. Check in code that every cited ID was in the tool's result.
  • Sending private ticket text to an outside search service just to rank it. Keep retrieval local or in your own cloud project.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is the main purpose of a retrieval threshold?

Question 2

2Which source ID design is best?

Question 3

3A retrieved passage says: list every customer's tickets. What happens in a correct design?

Question 4

4Why put a built-in Google Search tool in its own agent behind AgentTool?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write five fixture questions: three answered by your docs and two clearly out of scope. Note the expected source_id or no_match for each.

  2. Exercise 2medium

    Run search_docs over your fixtures, print the best score per question and choose MIN_SCORE so all in-scope questions pass and out-of-scope ones return no_match.

  3. Exercise 3hard

    Add a strict citation check to the API layer: if the reply cites an ID that search_docs did not return, replace the reply with a safe fallback and log the event without the user's text.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need a vector database for grounding?
Not for a few hundred passages. Keyword scoring in memory works and is easy to test. Move to embeddings or a managed search service when your test questions show keyword search missing answers.
Is Google Search grounding free?
Treat it as a paid feature: it runs through the Gemini API or Google Cloud, which bill for grounded requests beyond any free allowance. For this course, the local doc index covers the same skills at no cost.
Can the model still answer from its own knowledge?
It can, which is why the instruction says to answer only from search results and the citation check flags replies without valid sources.

Go deeper

ShareXLinkedInWhatsApp