You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改LlamaIndex RAG示例代码以显示检索上下文?

最简实现LlamaIndex RAG上下文+答案输出

直接利用LlamaIndex返回的response对象内置的source_nodes属性即可获取检索到的上下文片段,修改后的代码如下:

from llama_index import VectorStoreIndex, SimpleDirectoryReader

documents = SimpleDirectoryReader("data").load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()
response = query_engine.query("What did the author do growing up?")

# 输出检索到的上下文
print("Here's my retrieved context:")
for node in response.source_nodes:
    print(f"- {node.text}")

# 输出答案
print("\nAnd here's my answer:")
print(response)

关键说明

  • response.source_nodes存储了检索阶段匹配到的所有相关文档节点,每个节点的text字段就是对应的上下文片段
  • 通过循环遍历该列表,即可逐个输出所有检索到的上下文内容
  • 后续直接输出原response对象即可得到问答结果,完全匹配你期望的输出格式

内容的提问来源于stack exchange,提问作者Jeremy K.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 05:05:58