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

如何在Haystack中串联多个PromptNode?现有实现遇错误求解决方案

Haystack串联基础问答与细化PromptNode的正确方案及错误修正

错误原因分析

触发name 'results' is not defined异常,是因为你在Shaper组件的处理函数中引用了未在Haystack上下文里定义的变量results。Haystack组件间的数据传递依赖标准字段(如documents、answers、query),自定义变量名无法被框架识别。

正确实现思路

无需额外Shaper组件即可完成串联,直接利用Haystack管道的自动数据传递机制:

  1. 第一个PromptNode生成的简洁回答会存入answers字段
  2. 第二个PromptNode通过模板引用answers字段的内容,实现扩展细化

完整代码示例

1. 导入依赖模块

from haystack.nodes import PromptNode, PromptTemplate
from haystack.pipelines import Pipeline

2. 定义Prompt模板

  • 基础问答模板(生成简洁回答):
basic_qa_template = PromptTemplate(
    prompt="基于以下文档生成简洁回答:\n\n{documents}\n\n问题:{query}\n\n简洁回答:"
)
  • 细化扩展模板(基于简洁回答生成详细内容):
refine_template = PromptTemplate(
    prompt="将以下回答扩展为详细内容,保持原意且补充相关细节:\n\n{answers[0].answer}\n\n详细回答:"
)

3. 创建PromptNode实例

以OpenAI模型为例(替换为你使用的模型及密钥):

basic_qa_node = PromptNode(
    model_name_or_path="gpt-3.5-turbo",
    api_key="YOUR_OPENAI_API_KEY",
    default_prompt_template=basic_qa_template
)
refine_node = PromptNode(
    model_name_or_path="gpt-3.5-turbo",
    api_key="YOUR_OPENAI_API_KEY",
    default_prompt_template=refine_template
)

4. 构建并运行管道

# 初始化管道
pipeline = Pipeline()
# 添加基础问答节点,接收Query输入
pipeline.add_node(component=basic_qa_node, name="basic_qa", inputs=["Query"])
# 添加细化节点,接收基础问答节点的输出答案
pipeline.add_node(component=refine_node, name="refine_answer", inputs=["basic_qa.output_answers"])

# 测试运行
test_documents = [{"content": "Haystack是deepset开发的开源LLM应用框架,支持检索增强生成(RAG)、问答、摘要等场景,提供模块化组件便于快速搭建AI应用。"}]
result = pipeline.run(query="Haystack是什么?", documents=test_documents)

# 输出结果
print("简洁回答:", result["answers"][0].answer)
print("详细回答:", result["answers"][1].answer)

需用Shaper时的修正方案

如果必须用Shaper调整输入格式,需确保函数接收Haystack上下文的标准字段参数:

from haystack.nodes import Shaper

# 正确定义Shaper处理函数,接收框架传递的answers和query参数
def format_refine_input(answers, query):
    return {"refine_input": answers[0].answer, "original_query": query}

shaper = Shaper(func=format_refine_input)

# 调整管道结构
pipeline = Pipeline()
pipeline.add_node(component=basic_qa_node, name="basic_qa", inputs=["Query"])
pipeline.add_node(component=shaper, name="answer_shaper", inputs=["basic_qa.output_answers"])
# 细化节点接收Shaper的输出
pipeline.add_node(component=refine_node, name="refine_answer", inputs=["answer_shaper.output"])

此时细化模板需对应调整为引用refine_input:

refine_template = PromptTemplate(
    prompt="针对问题「{original_query}」,将以下回答扩展为详细内容:\n\n{refine_input}\n\n详细回答:"
)

内容的提问来源于stack exchange,提问作者Josh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 22:52:47