Retrieve and answer
Use the evidence tools in agrag.evidence when your application needs retrieved passages. Use build_agent when you want the system to search, combine evidence, and return a cited answer. The direct-search example needs no agent LLM; the agent examples do.
Prerequisites
Install the storage, embedding, and extraction extras. The agent layer needs the agents extra:
uv pip install "agentic-graphrag[neo4j,extract]"
# For the agent layer:
uv pip install "agentic-graphrag[agents]"
Each code block on this page is complete. It opens a graph with DEFAULT_SCHEMA, adds two sentences, and closes the graph at the end. The agent examples read AGENT_LLM_BASE_URL, AGENT_LLM_MODEL_ID, and AGENT_LLM_API_KEY, and fall back to LLM_BASE_URL, LLM_MODEL_ID, and LLM_API_KEY, from the environment or from .env. The default model id is gpt-4o-mini.
Search directly
The evidence tools search passages, fetch the exact text, and check citations without an agent LLM. Each tool takes a scope, the set of document keys the call may read, so the example gives its document an explicit document_key.
import asyncio
import hashlib
from agrag.common.data_models import DEFAULT_SCHEMA
from agrag.common.data_models.document import Document, DocumentFamily, SourceFormat
from agrag.embedding import build_embedder
from agrag.evidence import fetch_evidence, search_evidence
from agrag.graphdb import build_graph_store
from agrag.ingestion import Graph
from agrag.ingestion.extract import GlinerExtractor
TEXT = "Aspirin treats headaches. Ibuprofen also treats headaches."
DOCUMENT_KEY = "headache-notes"
async def main() -> None:
graph_store = build_graph_store("neo4j")
embedder = build_embedder("ibm-granite/granite-embedding-small-english-r2")
graph = await Graph.open(
schema=DEFAULT_SCHEMA,
graph_store=graph_store,
embedder=embedder,
extractor=GlinerExtractor(),
)
try:
await graph.add(documents=[Document(
text=TEXT,
title="Headache notes",
uri="notes://headache",
document_key=DOCUMENT_KEY,
source_format=SourceFormat.TXT,
family=DocumentFamily.PROSE,
content_hash=hashlib.sha256(TEXT.encode()).hexdigest(),
loader_name="manual",
char_count=len(TEXT),
)])
scope = frozenset({DOCUMENT_KEY})
found = await search_evidence(
graph_store, embedder, "What treats headaches?", scope=scope
)
for hit in found.hits:
print(f"{hit.score:.3f} {hit.snippet}")
ids = [hit.evidence_id for hit in found.hits]
fetched = await fetch_evidence(graph_store, ids, scope=scope)
for outcome in fetched.outcomes:
print(outcome.status.value, outcome.text)
finally:
await graph_store.close()
asyncio.run(main())
An empty result is not an error. Troubleshoot common errors lists its causes. Find and cite evidence covers the citation check and the other evidence tools.
Answer with an agent
import asyncio
import hashlib
from agrag.agents.build import build_agent
from agrag.agents.settings import AgentLLMSettings
from agrag.common.data_models import DEFAULT_SCHEMA
from agrag.common.data_models.document import Document, DocumentFamily, SourceFormat
from agrag.embedding import build_embedder
from agrag.graphdb import build_graph_store
from agrag.ingestion import Graph
from agrag.ingestion.extract import GlinerExtractor
TEXT = "Aspirin treats headaches. Ibuprofen also treats headaches."
DOCUMENT_KEY = "headache-notes"
async def main() -> None:
graph_store = build_graph_store("neo4j")
embedder = build_embedder("ibm-granite/granite-embedding-small-english-r2")
graph = await Graph.open(
schema=DEFAULT_SCHEMA,
graph_store=graph_store,
embedder=embedder,
extractor=GlinerExtractor(),
)
try:
await graph.add(documents=[Document(
text=TEXT,
title="Headache notes",
uri="notes://headache",
document_key=DOCUMENT_KEY,
source_format=SourceFormat.TXT,
family=DocumentFamily.PROSE,
content_hash=hashlib.sha256(TEXT.encode()).hexdigest(),
loader_name="manual",
char_count=len(TEXT),
)])
agent = build_agent(
graph_store=graph_store,
embedder=embedder,
scope=frozenset({DOCUMENT_KEY}),
project_id="headache-research",
agent_id="research-agent",
llm_settings=AgentLLMSettings.from_openai_compatible_env(),
)
result = await agent.ainvoke({
"task_name": "headache-treatment",
"question": "What treats headaches?",
})
print(result["answer"])
finally:
await graph_store.close()
asyncio.run(main())
The result has the answer, a status such as answered, insufficient_evidence, partial, budget_exhausted, recording_failed or partial_retrieval, the citations it fetched, the invalid_citations, any recording_failures, the task name with its last event number, and the messages. See Agent loop for the statuses. The agent stores task state under the supplied project_id, agent_id, and task_name.
Render result["answer"] with your application's Markdown renderer to show clickable HTTP(S) source references. The example uses an inline source URI, so its references are readable text rather than links. Keep result["citations"] for canonical evidence IDs and fetched passage text.
For a document copied from a remote source, set Document.uri to its actual user-openable HTTP(S) URL and Document.title to a readable name before passing it to graph.add(documents=[...]). Supply the document text yourself. graph.add(source=...) reads local paths, directories, and globs. Returned source URIs contain valid HTTP(S) URLs, and local documents are cited by title. An application that serves local documents can provide its own authorized document-viewer links.
See Citations in MCP clients for using readable source references in client answers.
Set the document scope
Pass the exact document keys the agent may read as a set of strings. The scope is fixed when the agent is built and applies to search, fetch, and citation checks.
import asyncio
import hashlib
from agrag.agents.build import build_agent
from agrag.agents.settings import AgentLLMSettings
from agrag.common.data_models import DEFAULT_SCHEMA
from agrag.common.data_models.document import Document, DocumentFamily, SourceFormat
from agrag.embedding import build_embedder
from agrag.graphdb import build_graph_store
from agrag.ingestion import Graph
from agrag.ingestion.extract import GlinerExtractor
TEXT = "Aspirin treats headaches. Ibuprofen also treats headaches."
DOCUMENT_KEY = "headache-notes"
async def main() -> None:
graph_store = build_graph_store("neo4j")
embedder = build_embedder("ibm-granite/granite-embedding-small-english-r2")
graph = await Graph.open(
schema=DEFAULT_SCHEMA,
graph_store=graph_store,
embedder=embedder,
extractor=GlinerExtractor(),
)
try:
await graph.add(documents=[Document(
text=TEXT,
title="Headache notes",
uri="notes://headache",
document_key=DOCUMENT_KEY,
source_format=SourceFormat.TXT,
family=DocumentFamily.PROSE,
content_hash=hashlib.sha256(TEXT.encode()).hexdigest(),
loader_name="manual",
char_count=len(TEXT),
)])
agent = build_agent(
graph_store=graph_store,
embedder=embedder,
scope=frozenset({DOCUMENT_KEY}),
project_id="headache-research",
agent_id="research-agent",
llm_settings=AgentLLMSettings.from_openai_compatible_env(),
)
finally:
await graph_store.close()
asyncio.run(main())
Set the scope when your application builds the agent. The tools enforce the scope. The model cannot see or change it. To call the evidence tools from your own code, use Find and cite evidence. The tools reference lists each agent tool and its parameters.
Search themes
search_themes answers broad questions about a corpus, such as "what do these documents cover?". It matches the query against the community report embeddings of the last detect_communities run and returns each theme with the in-scope passages that mention its member entities. Run community detection first. Documents added after that run stay out of the result until the next run.
from agrag.evidence import search_themes
themes = await search_themes(
graph_store, embedder, "What do the notes cover?", scope=scope, limit=3
)
for theme in themes.themes:
print(theme.score, theme.entities)
for passage in theme.passages:
print(" ", passage.evidence_id)
The result carries no community report text. Each passage is an evidence id that fetch_evidence reads, so its passages go through the same fetch and citation check steps as the other evidence tools.
Configuration
Hybrid search reorders its top hits with a cross-encoder when a reranker is configured. Rerank is on by default and needs the embed-local extra; a missing extra turns rerank off with a warning. The RETRIEVAL_ variables, including RETRIEVAL_RERANK_ENABLED and the agent deadline AGENT_REQUEST_DEADLINE_SECONDS, are listed in the configuration reference.