ADK using Vertex AI RAG

Using RAG with ADK engine, we need to setup our RAG engine corpus and tell our agent to use that as a point of reference. As you can see here RAG_CORPUS contains details of this endpoint.  

Then we use a tool called VertexAiRagRetrieval 


from google.adk.tools.retrieval.vertex_ai_rag_retrieval import (
    VertexAiRagRetrieval,
)

Then we hook it up to our agent and make these knowledge accessible 


# Initialize tools list
tools = []

# Only add RAG retrieval tool if RAG_CORPUS is configured
rag_corpus = os.environ.get("RAG_CORPUS")
if rag_corpus:
    ask_vertex_retrieval = VertexAiRagRetrieval(
        name="retrieve_rag_documentation",
        description=(
            "Use this tool to retrieve documentation and reference materials for the question from the RAG corpus,"
        ),
        rag_resources=[
            rag.RagResource(
                # please fill in your own rag corpus
                # here is a sample rag corpus for testing purpose
                # e.g. projects/123/locations/us-central1/ragCorpora/456
                rag_corpus=rag_corpus
            )
        ],
        similarity_top_k=10,
        vector_distance_threshold=0.6,
    )
    tools.append(ask_vertex_retrieval)

with using_session(session_id=uuid.uuid4()):
    root_agent = Agent(
        model="gemini-2.5-flash",
        name="ask_rag_agent",
        instruction=return_instructions_root(),
        tools=tools,
    )

from google.adk.apps import App

app = App(root_agent=root_agent, name="rag")


Newer full code would look something like this 

client_genai_multicorpus.py


import agentplatform
from agentplatform import types
from google.genai import types as genai_types
from google.adk.agents import Agent
from google.adk.tools import ToolContext

PROJECT_ID = "project-xxxxxxxxxxxxxxxx"
LOCATION = "us-central1"
MODEL_ID = "gemini-3.5-flash"
MAX_SEARCHES = 6  # per question

client = agentplatform.Client(project=PROJECT_ID, location=LOCATION)

def _corpus(corpus_id: str) -> str:
    return f"projects/{PROJECT_ID}/locations/{LOCATION}/ragCorpora/{corpus_id}"

# The descriptions are what the agent uses to decide where to search.
CORPORA = {
    "mortgages": {
        "resource": _corpus("4870330735698903040"),
        "description": "Mortgage documents: mortgagors, lenders, property and dealing numbers.",
    },
    "contracts": {
        "resource": _corpus("4870330735698903040"),
        "description": "Contracts and agreements: parties, terms, dates, obligations.",
    },
}

rag_retrieval_config = genai_types.RagRetrievalConfig(
    top_k=5,
    filter=genai_types.RagRetrievalConfigFilter(vector_distance_threshold=0.5),
)

def _retrieve(corpus_resource: str, query: str):
    return client.rag.retrieve_contexts(
        vertex_rag_store=genai_types.VertexRagStore(
            rag_resources=[
                genai_types.VertexRagStoreRagResource(rag_corpus=corpus_resource)
            ],
        ),
        query=types.RagQuery(text=query, rag_retrieval_config=rag_retrieval_config),
    )

def _to_passages(response):
    """Turn the response into compact passages. Field names are my best guess:
    print one raw response and adjust if they differ."""
    contexts = getattr(getattr(response, "contexts", None), "contexts", None)
    if contexts is None:
        return {"raw": str(response)}  # unexpected shape, hand back as-is
    return [
        {
            "text": getattr(c, "text", ""),
            "source": getattr(c, "source_display_name", None) or getattr(c, "source_uri", None),
            "score": getattr(c, "score", None) or getattr(c, "distance", None),
        }
        for c in contexts
    ]

def search_documents(query: str, corpus: str, tool_context: ToolContext) -> dict:
    """Search one corpus, or all, and return the most relevant passages.

    Args:
        query: A focused search query. Keep identifiers and names exactly as written.
        corpus: A corpus name from the instructions, or "all" to search every corpus.
    """
    used = tool_context.state.get("temp:search_count", 0)
    if used >= MAX_SEARCHES:
        return {
            "status": "search_limit_reached",
            "message": "No more searches allowed. Answer from what you have and say what is missing.",
        }
    tool_context.state["temp:search_count"] = used + 1

    names = list(CORPORA) if corpus == "all" else [corpus]
    results = {}
    for name in names:
        if name not in CORPORA:
            return {"error": f"Unknown corpus '{name}'. Use one of {list(CORPORA)} or 'all'."}
        try:
            results[name] = _to_passages(_retrieve(CORPORA[name]["resource"], query))
        except Exception as e:
            results[name] = {"error": str(e)}
    return {"searches_used": used + 1, "searches_left": MAX_SEARCHES - used - 1, "results": results}

_corpus_help = "\n".join(f'- "{k}": {v["description"]}' for k, v in CORPORA.items())

INSTRUCTION = f"""You are a research agent that answers questions from private documents.

Corpora:
{_corpus_help}

Work like this:
1. PLAN: decide which corpus (or "all") most likely holds the answer. Split multi-part
   questions into separate searches.
2. SEARCH with search_documents. Keep identifiers, names, numbers and reference codes exactly
   as written, and rewrite the rest into a focused query.
3. CHECK: do the passages state the specific fact asked for? Related text is not enough.
4. If not, rewrite and search again. Try alternate formats of identifiers (spacing, slashes,
   prefixes), synonyms, or another language, or try a different corpus.
5. STOP when you have the answer or after repeated misses. Never guess.
6. ANSWER concisely and cite the source for each fact. If you can't find it, say what you
   searched and what is missing.
"""

root_agent = Agent(
    name="agentic_rag_agent",
    model=MODEL_ID,
    instruction=INSTRUCTION,
    tools=[search_documents],
)

And here we have the runner:



import asyncio
import uuid
import os
from dotenv import load_dotenv

from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types

from client_genai_multicorpus import root_agent

APP_NAME = "grounded_app"
USER_ID = "user1"

os.environ.setdefault("GOOGLE_GENAI_USE_VERTEXAI", "TRUE")
os.environ.setdefault("GOOGLE_CLOUD_PROJECT", "project-f54eacb9-b4e5-40b9-b0c")
os.environ.setdefault("GOOGLE_CLOUD_LOCATION", "global")

async def ask(runner: Runner, session_id: str, question: str) -> str:
    """Send one question to the agent, print each search, return the final answer."""
    message = types.Content(role="user", parts=[types.Part(text=question)])
    answer = ""

    async for event in runner.run_async(
        user_id=USER_ID, session_id=session_id, new_message=message
    ):
        if event.content and event.content.parts:
            for part in event.content.parts:
                # Show each search the agent makes
                if part.function_call:
                    args = dict(part.function_call.args or {})
                    print(f"  [search] corpus={args.get('corpus')!r} query={args.get('query')!r}")
                # Show search budget and any errors coming back
                if part.function_response:
                    resp = part.function_response.response or {}
                    if "searches_left" in resp:
                        print(f"  [result] searches left: {resp['searches_left']}")
                    if "error" in resp:
                        print(f"  [error] {resp['error']}")

        if event.is_final_response() and event.content and event.content.parts:
            answer = "".join(p.text or "" for p in event.content.parts)

    return answer


async def main():
    session_service = InMemorySessionService()
    session_id = str(uuid.uuid4())
    await session_service.create_session(
        app_name=APP_NAME, user_id=USER_ID, session_id=session_id
    )

    runner = Runner(
        agent=root_agent,
        app_name=APP_NAME,
        session_service=session_service,
    )

    print("Ask about your documents. Type 'exit' to quit.")
    while True:
        try:
            question = input("\nYou: ").strip()
        except (EOFError, KeyboardInterrupt):
            break
        if not question:
            continue
        if question.lower() in {"exit", "quit"}:
            break

        try:
            answer = await ask(runner, session_id, question)
            print(f"\nAgent: {answer}")
        except Exception as e:
            print(f"\n[error] {type(e).__name__}: {e}")


if __name__ == "__main__":
    asyncio.run(main())










Comments

Popular posts from this blog

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20

llama cpp running it in google colab