FastGPT icon indicating copy to clipboard operation
FastGPT copied to clipboard

Feature: Retrieval Trace View for RAG Debugging

Open coderleeon opened this issue 5 months ago • 2 comments

Is your feature request related to a problem? Please describe.

When a workflow returns an incorrect or incomplete answer, it can be difficult to determine where the failure occurred.

For knowledge-base applications, users often need visibility into:

  • Which chunks were retrieved
  • Which chunks were selected after reranking
  • Which sources were ultimately provided to the model

Without this information, debugging retrieval quality becomes largely trial-and-error.

Describe the solution you'd like

Add an optional "Retrieval Trace" view for workflow executions.

For each query, display:

  • Retrieved chunks
  • Retrieval scores
  • Reranked results
  • Final context sent to the LLM
  • Source attribution

This could be available in execution logs or a dedicated debugging panel.

Describe alternatives you've considered

External observability tools can provide partial visibility, but they often lack workflow-specific retrieval information and require additional setup.

Additional context

This feature would make it significantly easier to debug chunking strategies, retrieval quality, reranking performance, and knowledge-base coverage issues.

coderleeon avatar Jun 14 '26 18:06 coderleeon

Hi, I'd like to work on this feature.

I've read through the codebase and have a clear picture of where the changes should land:

  • The retrieval pipeline entry point is packages/service/core/dataset/search/index.ts — defaultSearchDatasetData() already returns a rich SearchDatasetDataResponse that includes rerank status, similarity, search mode, and query extension results. The raw chunk scores are available from the multiQueryRecall and reRankSearchResults steps inside defaultRecall/index.ts.
  • The workflow execution layer uses WorkflowNodeResponseSink (packages/service/core/workflow/dispatch/nodeResponseSink.ts) to persist and stream node responses. This is where retrieval trace data can be attached to the node response so it appears in the execution log panel.

My proposed approach:

  1. Extend SearchDatasetDataResponse to carry an optional retrievalTrace field with raw chunks + scores pre-rerank, reranked results, and the final context window slice.
  2. Pass that trace through the dataset search workflow node's dispatch handler into WorkflowNodeResponseSink.
  3. Add a collapsible "Retrieval Trace" section to the execution log UI (projects/app) that renders chunks, scores, and source attribution per query.

The feature would be opt-in (off by default) to keep payload size down for users who don't need it.

Can you confirm this is aligned with the direction you have in mind? Happy to open a draft PR to discuss the design before writing the full implementation.

Ultroncn avatar Sep 02 '26 18:09 Ultroncn

你的 #7113 正好戳中 RAG 调试最痛的点——现在拿不到「检索了哪些 chunk、重排后留了哪些、最终喂给模型的上下文」这条链路,只能盲调。思路很直接:在检索/重排两步各埋一个 trace 钩子,把 chunk id、向量分、重排分、是否进 final context 全记下来,前端就能渲染成 Retrieval Trace。下面这段 py 不依赖任何第三方 key,把 retrieve/rerank 换成你自己的 client 就能跑,直接产出你要的四段信息。如果对你有用我可以再补一个把 trace 落日志、对接 execution log 的版本。

"""retrieval_trace.py — build a RAG retrieval trace for debugging FastGPT KB answers.
Plug in your own retriever + reranker clients below; no keys hardcoded."""

from dataclasses import dataclass

@dataclass
class Chunk:
    id: str
    text: str
    vector_score: float

# --- plug your own clients here (no hardcoded keys) ---
# retriever = MyFastGPTClient(api_key=os.environ["FG_API_KEY"])
# reranker  = MyReranker(api_key=os.environ["RERANK_KEY"])

def retrieve(query: str, top_n: int = 10) -> list[Chunk]:
    # replace with: retriever.search(dataset_id=..., query=query, top_n=top_n)
    return [Chunk(f"c{i}", f"doc chunk {i}", 0.9 - i*0.05) for i in range(top_n)]

def rerank(query: str, chunks: list[Chunk], top_k: int = 4) -> list[tuple[Chunk, float]]:
    # replace with: reranker.score(query, [c.text for c in chunks])
    scored = [(c, c.vector_score * 0.7 + len(c.text)/1000 * 0.3) for c in chunks]
    return sorted(scored, key=lambda x: -x[1])[:top_k]

def build_trace(query: str, top_k: int = 4) -> dict:
    retrieved = retrieve(query)
    reranked = rerank(query, retrieved, top_k)
    final_ctx = "\n\n".join(f"[{c.id}] {c.text}" for c, _ in reranked)
    return {
        "query": query,
        "retrieved": [(c.id, round(c.vector_score,3)) for c in retrieved],
        "reranked":  [(c.id, round(s,3)) for c, s in reranked],
        "final_context": final_ctx,
        "sources": [c.id for c, _ in reranked],
    }

if __name__ == "__main__":
    import json
    print(json.dumps(build_trace("FastGPT 重试逻辑", top_k=4), ensure_ascii=False, indent=2))

chenhz01 avatar Sep 30 '26 16:09 chenhz01