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

开始使用

Haystack 是一个开源 AI 框架,用于构建自定义的生产级 LLM 应用,例如 AI Agent、强大的 RAG 应用和可扩展的搜索系统。

安装

使用 pip 安装 Haystack

pip install haystack-ai

更多详情,请参阅我们的文档。

文档:安装

前提条件

要运行示例,您需要

  • 用于网络搜索的 SerperDev API 密钥
  • 您选择的模型提供商(例如 OpenAI、Anthropic、Gemini、Amazon Bedrock)的凭据

🤖 Haystack 基础 Agent

您可以使用 Agent 组件,仅用几行代码就能构建一个可用的 Agent。它接收用户问题,决定是否使用工具(如网络搜索),并返回响应,无需手动路由。

下面是一个使用 SerperDevWebSearch 组件作为工具与不同模型配合的最小化示例

import os

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

os.environ["OPENAI_API_KEY"] = "<YOUR OPENAI API KEY>"
os.environ["SERPERDEV_API_KEY"] = "<YOUR SERPERDEV API KEY>"

search_tool = ComponentTool(component=SerperDevWebSearch())

basic_agent = Agent(
    chat_generator=OpenAIChatGenerator(model="gpt-4o-mini"),
    system_prompt="You are a helpful web agent.",
    tools=[search_tool],
)

result = basic_agent.run(messages=[ChatMessage.from_user("When was the first version of Haystack released?")])

print(result['last_message'].text)

安装 Antropic x Haystack 集成

pip install anthropic-haystack
import os

from haystack.components.agents import Agent
from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.tools import ComponentTool
from haystack.components.websearch import SerperDevWebSearch

os.environ["ANTHROPIC_API_KEY"] = "<YOUR ANTHROPIC API KEY>"
os.environ["SERPERDEV_API_KEY"] = "<YOUR SERPERDEV API KEY>"

search_tool = ComponentTool(component=SerperDevWebSearch())

basic_agent = Agent(
    chat_generator=AnthropicChatGenerator(model="claude-3-7-sonnet-latest"),
    system_prompt="You are a helpful web agent.",
    tools=[search_tool],
)

result = basic_agent.run(messages=[ChatMessage.from_user("When was the first version of Haystack released?")])

print(result['last_message'].text)

安装 Amazon Bedrock x Haystack 集成

pip install amazon-bedrock-haystack
import os

from haystack.components.agents import Agent
from haystack_integrations.components.generators.amazon_bedrock import AmazonBedrockChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.tools import ComponentTool
from haystack.components.websearch import SerperDevWebSearch

os.environ["AWS_ACCESS_KEY_ID"] = "<YOUR AWS ACCESS KEY>"
os.environ["AWS_SECRET_ACCESS_KEY"] = "<YOUR SECRET ACCESS KEY>"
os.environ["AWS_DEFAULT_REGION"] = "<AWS REGION>"
os.environ["SERPERDEV_API_KEY"] = "<YOUR SERPERDEV API KEY>"

search_tool = ComponentTool(component=SerperDevWebSearch())

basic_agent = Agent(
    chat_generator=AmazonBedrockChatGenerator(model="mistral.mistral-large-2402-v1:0"),
    system_prompt="You are a helpful web agent.",
    tools=[search_tool],
)

result = basic_agent.run(messages=[ChatMessage.from_user("When was the first version of Haystack released?")])

print(result['last_message'].text)

安装 Google Gen AI x Haystack 集成

pip install google-genai-haystack
import os

from haystack.components.agents import Agent
from haystack_integrations.components.generators.amazon_bedrock import AmazonBedrockChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.tools import ComponentTool
from haystack.components.websearch import SerperDevWebSearch

os.environ["GOOGLE_API_KEY"] = "<YOUR GOOGLE API KEY>"
os.environ["SERPERDEV_API_KEY"] = "<YOUR SERPERDEV API KEY>"

search_tool = ComponentTool(component=SerperDevWebSearch())

basic_agent = Agent(
    chat_generator=GoogleGenAIChatGenerator(model="gemini-2.5-flash"),
    system_prompt="You are a helpful web agent.",
    tools=[search_tool],
)

result = basic_agent.run(messages=[ChatMessage.from_user("When was the first version of Haystack released?")])

print(result['last_message'].text)

Haystack 支持来自 CohereHugging FaceMetaMistralOllama 等提供商的模型,以及本地和云托管选项,还有更多

在文档中浏览支持的模型和聊天生成器的完整列表。

⚙️ 高级 Agent 配置

一旦您构建了第一个 Agent,就可以轻松地扩展其功能以适应更高级的用例。Haystack 的设计模块化且可定制,因此您可以轻松微调 Agent 的行为方式、工具如何返回数据以及数据如何在组件之间流动。

以下是如何将基础 Agent 演变为更高级的 Agent

🛠️ 自定义工具

在基础示例中,SerperDevWebSearch 组件被转换为具有默认行为的工具。为了获得更多控制,您可以

  • 为工具添加名称和描述,以便 LLM 更好地了解何时使用它。
  • 使用 outputs_to_string 将工具的输出(例如 Document 对象)转换为字符串,以便可以直接在提示中使用。
  • 使用 outputs_to_state 将工具输出保存到 Agent 的内部状态,使其在推理过程的后续步骤中可访问。
from haystack.tools import ComponentTool
from haystack.components.websearch import SerperDevWebSearch

def doc_to_string(documents) -> str:
    result_str = ""
    for document in documents:
        result_str += f"File Content for {document.meta['link']}: {document.content}\n\n"
    return result_str

search_tool = ComponentTool(
    component=SerperDevWebSearch(top_k=5),
    name="web_search", 
    description="Search the web for up-to-date information on any topic",
    outputs_to_string={"source": "documents", "handler": doc_to_string}, # Convert Documents' content into strings before passing it back to the LLM
    outputs_to_state={"documents": {"source": "documents"}}, # Save Documents into Agent's state
)

🧠 增强 Agent 的行为

Agent 本身也可以配置为处理更高级的任务

  • 自定义 system_prompt 指导 Agent 的个性和工具使用策略。
  • exit_conditions 让您可以定义 Agent 何时应停止推理(例如,一旦它产生最终的 text 响应或调用列出的工具)。
  • state_schema 定义内部记忆的结构,例如在步骤之间存储检索到的文档。
  • streaming_callback 允许您实时流式传输部分结果、跟踪工具使用情况以及调试工具-Agent 交互。
from haystack.components.generators.utils import print_streaming_chunk
from haystack.components.agents import Agent
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage, Document

agent = Agent(
    chat_generator=OpenAIChatGenerator(model="gpt-4o-mini"),
    system_prompt="""
    You are a helpful assistant that has access to web. User's ask you questions and you provide answers.
    Use the tools that you're provided with to get information. Don't use your own knowledge.
    Make sure the information that you retrieved is enough to resolve the user query.
    """,
    tools=[search_tool],
    exit_conditions=["text"], # Stop agent execution when there's a text response
    state_schema={"documents":{"type":list[Document]}}, # Define Agent state schema for saved documents 
    streaming_callback=print_streaming_chunk # Display streaming output chunks and print tool calls and tool call results
)

agent_results = agent.run(messages=[ChatMessage.from_user("What are some popular use cases for AI agents?")])
print(agent_results["last_message"].text)

## See the Documents saved in the Agent state
agent_results["documents"]

只需几行配置,您的 Agent 就会变得更透明、更具状态感,并且更有用。这种灵活的设计使您能够构建强大的多步助手,这些助手能够智能地推理、检索和行动,而无需从头开始编写自定义编排代码。

有关如何创建可以使用组件管道作为工具的工具调用 Agent 的实践指南,请参阅我们的教程。

教程:构建一个工具调用 Agent

下一步