如何提取LlamaIndex中生成响应时所用的context_str?
提取LlamaIndex查询中的context_str
以下是几种可行的提取方法:
- 使用回调函数捕获完整Prompt
通过添加调试回调,LlamaIndex会打印出发送给LLM的完整Prompt,你可以从中提取分隔符---------------------之间的context_str内容:
from llama_index.core.callbacks import CallbackManager, LlamaDebugHandler from llama_index.core import ServiceContext # 创建调试回调处理器 llama_debug_handler = LlamaDebugHandler(print_trace_on_end=True) callback_manager = CallbackManager([llama_debug_handler]) # 配置包含回调的服务上下文 service_context = ServiceContext.from_defaults(callback_manager=callback_manager) # 重新初始化索引和查询引擎 index = VectorStoreIndex.from_documents(documents, service_context=service_context) query_engine = index.as_query_engine() # 执行查询,回调会打印完整Prompt response = query_engine.query("was July 2023 recorded as the hottest day on Earth?")
- 从检索阶段直接获取Context
跳过LLM调用,直接获取查询引擎检索到的节点内容,拼接后就是context_str:
# 获取检索到的相关节点 nodes = query_engine.retrieve("was July 2023 recorded as the hottest day on Earth?") # 拼接节点内容得到context_str context_str = "\n\n".join([node.get_content() for node in nodes]) print("提取的context_str:") print(context_str)
- 从响应对象的源节点提取
查询返回的response对象包含所有用于生成回答的源节点,直接提取这些节点的内容即可:
response = query_engine.query("was July 2023 recorded as the hottest day on Earth?") # 提取源节点内容并拼接 context_str = "\n\n".join([node.node.get_content() for node in response.source_nodes]) print("提取的context_str:") print(context_str)
内容的提问来源于stack exchange,提问作者Yousif Abdalla
相关产品推荐
相关产品推荐

