📘 **TELUS Agriculture & Consumer Goods** 如何通过 **Haystack Agents** 转变促销交易

Haystack 2.12.0

在 Github 上查看

⭐️ Highlights

Agent 组件支持状态管理

The Agent 组件支持提供商无关的聊天模型,并允许工具调用功能,既可以作为独立组件使用,也可以在 pipeline 中使用。如果定义了 SERPERDEV_API_KEYOPENAI_API_KEY,那么 Web 搜索 Agent 的构建将非常简单。

from haystack.components.agents import Agent 
from haystack.components.generators.chat import OpenAIChatGenerator 
from haystack.components.websearch import SerperDevWebSearch 
from haystack.dataclasses import ChatMessage 
from haystack.tools.component_tool import ComponentTool 

web_tool = ComponentTool(     
    component=SerperDevWebSearch(), 
) 

agent = Agent(     
    chat_generator=OpenAIChatGenerator(),
    tools=[web_tool],
) 

result = agent.run(
    messages=[ChatMessage.from_user("Find information about Haystack by deepset")]
) 

Agent 支持响应流式传输、可自定义的退出条件以及灵活的状态管理系统,该系统允许工具在执行过程中共享和修改数据。

agent = Agent(
    chat_generator=OpenAIChatGenerator(),
    tools=[web_tool, weather_tool],
    exit_conditions=["text", "weather_tool"],
    state_schema = {...},
    streaming_callback=streaming_callback,
)

SuperComponent 用于可重用 pipeline

SuperComponent 允许您将复杂的 pipeline 包装成可重用的组件。这使得在您的应用程序中轻松重用它们。只需使用 pipeline 初始化 SuperComponent 即可。

from haystack import Pipeline, SuperComponent

with open("pipeline.yaml", "r") as file:
  pipeline = Pipeline.load(file)

super_component = SuperComponent(pipeline)

这还不是全部!为了展示其优势,haystack-experimental 中有三个现成的 SuperComponent。例如,有一个 MultiFileConverter,它包装了一个支持 CSV、DOCX、HTML、JSON、MD、PPTX、PDF、TXT 和 XSLX 转换器的 pipeline。安装集成依赖项 pip install pypdf markdown-it-py mdit_plain trafilatura python-pptx python-docx jq openpyxl tabulate 后,您就可以使用任何支持的文件类型作为输入运行了。

from haystack_experimental.super_components.converters import MultiFileConverter

converter = MultiFileConverter()
converter.run(sources=["test.txt", "test.pdf"], meta={})

这是一个从任何 Haystack pipeline 创建自定义 SuperComponent 的示例。

from haystack import Pipeline, SuperComponent
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.components.builders import ChatPromptBuilder
from haystack.components.retrievers import InMemoryBM25Retriever
from haystack.dataclasses.chat_message import ChatMessage
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.dataclasses import Document

document_store = InMemoryDocumentStore()
documents = [
    Document(content="Paris is the capital of France."),
    Document(content="London is the capital of England."),
]
document_store.write_documents(documents)

prompt_template = [
    ChatMessage.from_user(
    '''
    According to the following documents:
    {% for document in documents %}
    {{document.content}}
    {% endfor %}
    Answer the given question: {{query}}
    Answer:
    '''
    )
]
prompt_builder = ChatPromptBuilder(template=prompt_template, required_variables="*")

pipeline = Pipeline()
pipeline.add_component("retriever", InMemoryBM25Retriever(document_store=document_store))
pipeline.add_component("prompt_builder", prompt_builder)
pipeline.add_component("llm", OpenAIChatGenerator())
pipeline.connect("retriever.documents", "prompt_builder.documents")
pipeline.connect("prompt_builder.prompt", "llm.messages")

# Create a super component with simplified input/output mapping
wrapper = SuperComponent(
    pipeline=pipeline,
    input_mapping={
        "query": ["retriever.query", "prompt_builder.query"],
    },
    output_mapping={"llm.replies": "replies"}
)

# Run the pipeline with simplified interface
result = wrapper.run(query="What is the capital of France?")
print(result)
# {'replies': [ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>,
#  _content=[TextContent(text='The capital of France is Paris.')],...)

⬆️ 升级说明

  • 更新了 ChatMessage 的序列化和反序列化。ChatMessage.to_dict() 现在返回一个包含键:role、content、meta 和 name 的字典。ChatMessage.from_dict() 支持此格式,并与旧格式保持兼容。

    如果您的应用程序使用了 ChatMessage.to_dict() 的结果,请更新您的代码以处理新格式。如果您在 Pipeline 中使用 ChatPromptBuilder,则无需进行更改。

  • LLMEvaluatorContextRelevanceEvaluatorFaithfulnessEvaluator 现在内部使用 ChatGenerator 实例而不是 Generator 实例。公共属性 generator 已被 _chat_generator 替换。

  • to_pandascomparative_individual_scores_reportscore_report 已从 EvaluationRunResult 中移除,请改用 detailed_reportcomparative_detailed_reportaggregated_report

🚀 新功能

  • 在类型兼容性检查期间,将裸类型(例如,List、Dict)视为带有 Any 参数的通用类型。
  • 添加了对 Callable 类型的兼容性。
  • ToolComponentTool 添加了 outputs_to_string,允许用户自定义 Tool 的输出如何转换为字符串,以便可以将其提供回 ChatGenerator 的 ChatMessage 中。如果未提供 outputs_to_string,则 ToolInvoker 中会使用默认的转换器。默认处理程序使用当前默认行为。
  • CSVDocumentSplitter 组件添加了一个新参数 split_mode 来控制拆分模式。新参数可以设置为 row-wise 以按行拆分 CSV 文件。默认值为 threshold,这是之前的行为。
  • 我们添加了一种新的检索技术,AutoMergingRetriever,它与 HierarchicalDocumentSplitter 一起实现了自动合并检索技术。
  • HuggingFaceLocalChatGenerator 添加了 run_async 方法。此方法内部使用 ThreadPoolExecutor 返回可以 await 的协程。
  • LinkContentFetcher 组件中引入了异步功能和 HTTP/2 支持,从而在多个方面改进了内容获取。
  • 现在,DOCXToDocument 组件可以选择将提取的超链接地址包含在输出 Documents 中。它接受一个可以设置为“markdown”或“plain”的 link_format 参数。默认情况下,如前所述,不会提取超链接地址。
  • 向所有 Azure OpenAI 组件添加了一个新参数 azure_ad_token_providerAzureOpenAIGeneratorAzureOpenAIChatGeneratorAzureOpenAITextEmbedderAzureOpenAIDocumentEmbedder。此参数可以选择接受一个返回 bearer token 的可调用对象,从而实现通过 Azure AD 进行身份验证。
    • 在 haystack/utils/azure.py 中引入了实用函数 default_azure_token_provider。此函数提供了一个可由 Haystack 序列化的默认 token 提供程序。用户现在可以将 default_azure_token_provider 作为 azure_ad_token_provider 传递,或者实现自定义 token 提供程序。
  • 用户现在可以在 ChatPromptBuilder 中使用日期和时间。与 PromptBuilder 类似,ChatPromptBuilder 现在支持 arrow 来处理 datetime。
  • 引入新的 State dataclass,其模式可自定义,用于管理 Agent 状态。增强了 Tool 的错误日志记录,并扩展了 ToolInvoker 组件以使用新引入的 State。
  • 现在 RecursiveDocumentSplitter 支持按 token 数量进行拆分。将“split_unit”设置为“token”将使用硬编码的 tiktoken 分词器(o200k_base),并需要安装 tiktoken。

⚡️ 增强说明

⚠️ 弃用说明

  • LLMEvaluatorContextRelevanceEvaluatorFaithfulnessEvaluatorapiapi_keyapi_params 参数现在已弃用,将在 Haystack 2.13.0 中移除。默认情况下,这些组件将继续在 JSON 模式下使用 OpenAI。要配置特定的 LLM,请使用 chat_generator 参数。
  • LLMMetadataExtractor 的 generator_api 和 generator_api_params 初始化参数以及 LLMProvider 枚举已弃用,将在 Haystack 2.13.0 中移除。请改用 chat_generator 来配置底层 LLM。例如,将 generator_api=LLMProvider.OPENAI 更改为 chat_generator=OpenAIChatGenerator()

🐛 Bug 修复