Feature: Multi-hop document-RAG for cross-document questions
Summary
Document-RAG currently performs a single retrieval pass: extract concepts → embed → fetch matching chunks → synthesise answer. This works well when the answer lives in one or two chunks, but falls short for questions that span multiple documents or require connecting information across sections.
A multi-hop retrieval loop would let the LLM read initial chunks, identify what information is still missing, and issue follow-up queries — iterating until it has enough context to answer.
Motivation
Example questions that need multi-hop:
- "How does the data retention policy interact with the GDPR compliance requirements?" — retention policy is in one document, GDPR requirements in another
- "Compare the authentication mechanisms described in the v2 and v3 architecture documents" — needs chunks from two different documents
- "What are all the prerequisites for deploying the production pipeline?" — prerequisites may be scattered across setup guide, infrastructure doc, and runbook
Today these queries retrieve chunks biased toward one aspect of the question and miss the rest.
Proposed design
Please PR against the latest release/vX.Y branch.
Iterative retrieval loop
1. Extract concepts from query (existing step)
2. Retrieve initial chunks (existing step)
3. Loop (max N iterations):
a. Present query + retrieved chunks to LLM with a "reflection" prompt
b. LLM outputs either:
- SUFFICIENT: enough context to answer → break
- FOLLOW_UP: one or more follow-up queries for missing info
c. For each follow-up query: extract concepts → embed → retrieve chunks
d. Deduplicate and append to chunk set
4. Synthesise answer from full chunk set (existing step)
Where it fits in the codebase
This would be a new retrieval module alongside the existing ones:
trustgraph-flow/trustgraph/retrieval/
├── document_rag/ # existing single-hop
│ ├── document_rag.py
│ └── rag.py
├── graph_rag/ # existing graph-based
│ ├── graph_rag.py
│ └── rag.py
└── multihop_rag/ # new
├── multihop_rag.py # MultiHopRag class with iterative loop
└── rag.py # Processor wiring
The MultiHopRag class would reuse the existing Query helper from document_rag.py for the retrieval steps (concept extraction, embedding, chunk fetching). The new part is the reflection/follow-up loop.
New prompt template
A multihop-reflection prompt that takes:
query: the original questiondocuments: chunks retrieved so far- Output: JSON with
status("sufficient" or "follow_up") and optionalfollow_up_querieslist
Configuration
--max-hops: maximum retrieval iterations (default 3)--doc-limit-per-hop: chunks to fetch per follow-up query (default 5)--total-doc-limit: overall cap on accumulated chunks (default 30)
Explainability
Each hop would emit its own exploration provenance event, so the explainability trace shows the full retrieval chain: question → hop 1 (N chunks) → hop 2 (M chunks) → synthesis.
What you'll learn
- How TrustGraph's document-RAG and prompt systems work
- How to create a new retrieval module and wire it into the processor framework
- How to add prompt templates to the config system
- How the explainability/provenance system tracks retrieval steps
References
- Single-hop retrieval:
trustgraph-flow/trustgraph/retrieval/document_rag/document_rag.py - Processor wiring:
trustgraph-flow/trustgraph/retrieval/document_rag/rag.py - Prompt client interface:
trustgraph-base/trustgraph/base/prompt_client.py - Provenance helpers:
trustgraph-flow/trustgraph/provenance/
Hi can i try working on this?
@Luffy2208 sure! Let me know if there's anything you need.
Jump on Discord: https://discord.gg/sQMwkRz5GX to chat if that's useful
Hi @Luffy2208 ,checking in, are you still working on this? Happy to help collaborate or pick it up if it's stalled, just don't want to duplicate effort.
Hi @01AtharvR , i havent started working on it yet , but i wish to , its just that im engaged in somethings right now will give it a try in these 2 days
hey @cybermaggedon looks like there is no activity on this issue for sometime, you mind i take a look on this? could you assign it to me if possible? :bowtie: i am new to these ai stuffs, want to give it a try, looks like there is so much to learn in this single issue, also joined discord for discussion...
@iks1 thanks for the offer! Please do, you would be very welcome.
Reach out if you want guidance, help or just to kick ideas around if you need. @cybermaggedon on our Discord.
@cybermaggedon had some questions on this task.
how do you want me to test the implementation?
- are unit tests enough? (this is done)
- do you want me to wire it to some frontend? perhaps the trustgraph ui? not sure how complex that would be tho.
- or do you want me to make a pr and you would review it.
@iks1 in terms of feature-complete, we like, at a minimum, the ability to run with a command line end-to-end. So would be good if your change could include a CLI command in trustgraph-cli (e.g. tg-invoke-multigop-rag) and have the pass-through in the Python API (in trustgraph-base).
If you could smoke test that would be good, but I'm happy for you to PR with unit tests in place and I can smoke test.
To get it to properly work there's a little bit of wiring needed in trustgraph-templates to add to the flows (I can take care of that). Once it's in place it should be straightforward to add to trustgraph-ui, and I can give you some points for that.
Appreciate your work on this!
@cybermaggedon thanks! I had some more questions 😅
-
--doc-limit-per-hopvs existingQuery(fetch_limit=...)are they same?- or is it supposed to be strict cap on chunks appended per follow-up query, MultiHopRag should trim results after
Query.get_docs()returns?
- or is it supposed to be strict cap on chunks appended per follow-up query, MultiHopRag should trim results after
-
Multiple follow-up queries from reflection: If the LLM returns multiple follow-up queries in one reflection response, should those all be treated as part of the next hop/iteration, or should each follow-up query count as its own hop? i am also thinking about explainability/provenance shape of it. 🤔
-
Prompt template location: i am not sure where this should live, right now i managed to do something with some scripts. 😅
Feel free to play with the parameters to get it to work.
-
To my mind, I can't see a reason to differentiate docs per hop vs a sort of 'total' docs. You can treat them the same.
-
I think I would treat as separate queries, exactly for explainability as you suggest. It will be easier to understand in explainability as separate queries.
-
I think this looks like a new service so needs to be added a) to container launch and b) to the flows so that the messaging is plumbed in. The templates live in the trustgraph-templates repo, I'll post the updates that would be needed on this ticket.
Wiring into templates... If you can't make sense of the templates, I'm happy to run the change, I'm making notes to help other people run a template change. trustgraph/trustgraph-templates is the repo.
Adding a new processing service to the templates
This uses multihop-rag as a worked example — a retrieval
service that sits alongside document-rag in the same container and
uses the same stores. When putting services into flows, things are basically
organised around the data. Document RAG uses the doc chunk embeddings,
which is what multihop-rag does so we may as well put it into the same
bit of template.
Overview
Two files need to change:
- Flow wiring — declare the pub/sub topics the service reads and writes so that the runtime config connects it to the rest of the system.
- Processor launch config — add the service to a container's
launch.yamlso the process group actually executes the code.
1. Flow wiring (flows/document-store.jsonnet)
Every service that communicates over pub/sub needs an entry in the
flows system. Flows are grouped by the stores they depend on.
Because multihop-rag uses the same document embeddings, reranker,
keyword index, and LLM services as document-rag, it belongs in the
same flow file: flows/document-store.jsonnet.
Add the interface
In the interfaces block, register the new service's
request/response interface:
"interfaces" +: {
...
"document-rag": request_response_if("document-rag:{workspace}:{id}"),
"multihop-rag": request_response_if("multihop-rag:{workspace}:{id}"), // new
...
},
This declares the topic pair so the runtime config knows the service exists.
Add the flow processor
In the flow block, add a processor entry listing every topic the
service reads or writes. Model it on whichever existing processor is
closest — here that's document-rag:
"flow" +: {
...
"multihop-rag:{id}": {
topics: {
request: request("multihop-rag:{workspace}:{id}"),
response: response("multihop-rag:{workspace}:{id}"),
"embeddings-request": request("embeddings:{workspace}:{id}"),
"embeddings-response": response("embeddings:{workspace}:{id}"),
"prompt-request": request("prompt-rag:{workspace}:{id}"),
"prompt-response": response("prompt-rag:{workspace}:{id}"),
"document-embeddings-request": request("document-embeddings:{workspace}:{id}"),
"document-embeddings-response": response("document-embeddings:{workspace}:{id}"),
"reranker-request": request("reranker:{workspace}:{id}"),
"reranker-response": response("reranker:{workspace}:{id}"),
"keyword-index-request": request("keyword-index:{workspace}:{id}"),
"keyword-index-response": response("keyword-index:{workspace}:{id}"),
explainability: flow("triples-store:{workspace}:{id}"),
"librarian-request": librarian_request,
"librarian-response": librarian_response,
},
},
...
},
The {id} and {workspace} placeholders are substituted at runtime
for multi-tenant/multi-instance deployments.
Where does the flow file get included?
Flow files are composed in flows/flow-blueprints.jsonnet. The
document-store block is already pulled into every blueprint that
uses document RAG (e.g. everything). Because multihop-rag lives
inside document-store.jsonnet, it is automatically included
wherever document RAG is — no blueprint changes needed.
2. Processor launch config (core/rag.jsonnet)
The flow wiring tells the runtime config about the topics. The processor launch config tells the container to actually start the service.
core/rag.jsonnet defines the rag container, which runs a
processor-group command that reads a launch.yaml listing all the
processors to start.
Add default parameters
At the top of the file, in the parameters block, add defaults for
any tunable parameters the new service needs:
parameters +:: {
...
"document-rag-concurrency": 1,
"document-rag-doc-limit": 20,
"multihop-rag-concurrency": 1, // new
"multihop-rag-doc-limit": 20, // new
...
},
Add local bindings
Further down, extract the parameters into local variables:
local multihopRagConc = pars["multihop-rag-concurrency"],
local multihopDocLimit = pars["multihop-rag-doc-limit"],
Add the Python class reference
local multihopRag = "%s.multihop_rag.Processor" % retrieval,
This resolves to trustgraph.retrieval.multihop_rag.Processor — the
Python class that implements the service.
Add the processor entry
In the processors array inside the launch.yaml config volume, add
an entry for the new service:
{
class: multihopRag,
params: {
id: "multihop-rag",
concurrency: multihopRagConc,
doc_limit: multihopDocLimit,
retrieval_mode: retrievalMode,
} + $["pub-sub-params"],
},
The id must match the flow processor name (without the :{id}
suffix). $["pub-sub-params"] injects the messaging connection
parameters.
Summary
| What | Where | Why |
|---|---|---|
| Interface declaration | flows/document-store.jsonnet → interfaces |
Runtime config knows the service exists |
| Topic wiring | flows/document-store.jsonnet → flow |
Runtime config can route messages |
| Default parameters | core/rag.jsonnet → parameters |
Tunables with sensible defaults |
| Processor entry | core/rag.jsonnet → launch.yaml |
Container actually starts the service |
If your new service needs different stores or a different container, follow the same pattern but in the appropriate flow file and core component file.
Thanks, that helps! @cybermaggedon
For the first point, I think I explained it poorly. The confusing bit is not only per-hop vs total docs, but how doc_limit_per_hop maps onto the existing document-RAG Query(fetch_limit=...).
Because Query first extracts concepts, then queries document embeddings per concept, fetch_limit=1 does not necessarily mean 1 chunk total. For example:
- query extracts 4 concepts
fetch_limit=1Querydoesper_concept_limit = max(1, fetch_limit // len(vectors))- so it can retrieve up to 1 chunk per concept, i.e. up to 4 chunks
So I’m wondering whether MultiHopRag should preserve that existing Query(fetch_limit=...) behavior, or whether it should trim after Query.get_docs() so the requested limit is a strict cap on the number of chunks appended.
Ok, preserving the 2 limits makes sense, thankyou for the explanation.
Feel free to go with what you think is best, you've spent more time thinking about this. We're happy to work with increments and see what works.