Find and cite evidence
Use the functions in agrag.evidence to search the passages of your documents, fetch the exact text behind a result, and check that a citation points to text you fetched. The built-in agent and the MCP server call the same functions.
Before you start
- A graph that already holds your documents. See Ingest documents.
- The
neo4jextra. The functions need no LLM. - The key of each document you want to read. A file document's key is its resolved absolute path.
Search, fetch, and check
Evidence search and read functions take a scope, a frozenset of the document keys that the caller may read. Search returns current document text. Fetch can also return retained text from a superseded version while the source remains live.
import asyncio
from pathlib import Path
from agrag.common.data_models.evidence import EvidenceSearchMode, FetchStatus
from agrag.embedding import build_embedder
from agrag.evidence import check_citations, fetch_evidence, search_evidence
from agrag.graphdb import build_graph_store
async def main() -> None:
store = build_graph_store("neo4j")
embedder = build_embedder("ibm-granite/granite-embedding-small-english-r2")
scope = frozenset({str(Path("your-document.md").resolve())})
try:
await store.connect()
found = await search_evidence(
store,
embedder,
"What does the document require?",
mode=EvidenceSearchMode.HYBRID,
limit=5,
scope=scope,
)
for hit in found.hits:
print(hit.evidence_id, hit.snippet)
ids = [hit.evidence_id for hit in found.hits[:2]]
fetched = await fetch_evidence(store, ids, scope=scope)
for outcome in fetched.outcomes:
print(outcome.status, outcome.status_of_version, outcome.text)
ok_ids = [o.evidence_id for o in fetched.outcomes if o.status is FetchStatus.OK]
checks = await check_citations(ids, ok_ids, scope=scope)
print([(c.cited_id, c.verdict) for c in checks.checks])
finally:
await store.close()
asyncio.run(main())
search_evidence returns an EvidenceSearchResult. Its status is ok, partial, no_match, empty_scope, index_not_ready, or failed. partial means that one search leg failed and the other returned hits, and truncated is true when the candidate list was cut. Each hit has an evidence_id, a title, a location, a snippet of up to 240 characters, and a score.
search_evidence takes three modes. EvidenceSearchMode.LEXICAL runs a lexical search, EvidenceSearchMode.SEMANTIC runs a semantic (vector) search, and EvidenceSearchMode.HYBRID runs both and combines them. Use the embedder that you used for ingestion.
fetch_evidence returns a FetchResult whose outcomes list holds one FetchOutcome per id, in order. Its text is the exact stored text, cut to max_chars, which defaults to 4000 characters. The status is ok, partial, truncated, unavailable, malformed, index_not_ready, or failed, and status_of_version is current or superseded. An id from an earlier version of an updated document still returns its text and is labeled superseded.
check_citations returns a CitationResult whose checks list holds one verdict for each cited id. A verdict is valid when you fetched the id in scope. The other verdicts are not_fetched, unavailable, and malformed.
Move around a passage
navigate_document_tree takes an evidence id and a relation, and returns the neighboring text. Add the snippets in this and the next two sections inside the try block of the example above.
from agrag.common.data_models.navigation import NavigationRelation
from agrag.evidence import navigate_document_tree
if ids:
result = await navigate_document_tree(
store,
ids[0],
NavigationRelation.PARENT,
scope=scope,
limit=5,
max_chars=4000,
)
for item in result.items:
print(item.heading_path, item.text)
else:
print("No passages matched the search.")
The relations are parent, children, siblings, previous, next, and table_context. The last one returns the rows around a table cell. The result lists up to limit items and marks the first item that the max_chars budget cuts.
Search entities and explore relations
entity_search searches entity names lexically and entity embeddings semantically. Each hit carries up to support_limit passages that mention the entity. explore_relationships follows the relations of an entity outward.
from agrag.evidence import entity_search, explore_relationships
entities = await entity_search(
store, embedder, "Charles Babbage", scope=scope, limit=5
)
if entities.hits:
hit = entities.hits[0]
for passage in hit.support:
print(passage)
graph_view = await explore_relationships(store, hit.entity_id, scope=scope, depth=1)
for edge in graph_view.edges:
print(edge)
else:
print("No entities matched the search.")
explore_relationships walks at most two steps from the entity. An edge is an assertion when a passage in scope supports it, and a path when the relation has no source passage. The result lists the bounds that cut the walk in truncated_by.
Render numbered references
render_citations replaces the valid ids in an answer with numbered references and adds a Sources list.
from agrag.common.data_models.evidence import CitationVerdict
from agrag.evidence import render_citations
valid_ids = [check.cited_id for check in checks.checks if check.verdict is CitationVerdict.VALID]
if valid_ids:
answer = f"The document sets a deadline. [{valid_ids[0]}]"
rendered, sources = render_citations(answer, valid_ids, fetched.outcomes)
print(rendered)
else:
print("No fetched citation passed validation.")
Pass only ids that check_citations marked valid, together with the fetch outcomes of the same run.
Related
- Retrieval compares the strategies and shows which tool fits a question.
- Passage search, Entity search, Explore relationships, Document tree navigation, Fetch evidence, and Check citations list the inputs, the result fields, and the statuses of each call.
- Evidence ids and citations describes id formats, fetch statuses, and citation verdicts.
- Explanation: Agent loop describes how one task-scoped agent turns a question into a cited answer with these functions.
- How-to: Run the MCP server gives an MCP client tools to search, read passages, and check citations.
- Reference: Tools for parameters and limits, Evidence API for signatures.