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

如何从Haystack的print_answers输出中提取指定子字符串?

解决Haystack中print_answers输出无法索引提取文本的问题
  • 放弃直接使用print_answers的字符串输出,先获取Pipeline执行后的结构化返回结果:

    # 执行pipeline并保存原始结果
    query_result = pipeline.run(query="你的问题内容")
    
  • 从结构化结果中直接提取所需文本:

    • 提取核心答案文本:query_result['answers'][0].answer
    • 提取答案关联的元数据(如来源文档信息):query_result['answers'][0].meta
  • 按需自定义输出逻辑,替代print_answers:

    def custom_extract_answer(result, max_length=500):
        # 提取答案文本并按需求切片
        raw_answer = result['answers'][0].answer
        trimmed_answer = raw_answer[:max_length] + "..." if len(raw_answer) > max_length else raw_answer
        print(f"整理后的答案:\n{trimmed_answer}")
    
    # 调用自定义函数
    custom_extract_answer(query_result)
    

原理说明

print_answers是Haystack提供的格式化展示工具,它会把结构化的结果对象转换成纯字符串输出,导致无法进行索引、切片等操作。直接操作Pipeline返回的结构化字典(包含Answer对象),就能灵活获取任意需要的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 04:39:57