Agent
该Agent 组件是一个工具使用代理,它与聊天型 LLM 和工具进行交互,以迭代方式解决复杂查询。它可以执行外部工具,管理多次 LLM 调用之间的状态,并基于可配置的exit_conditions.
| pipeline 中的最常见位置 | 在 ChatPromptBuilder 或用户输入之后 |
| 必需的初始化变量 | chat_generator:一个支持工具的聊天生成器实例 |
| 强制运行变量 | messages:一个 ChatMessage 列表 |
| 输出变量 | messages:包含工具和模型响应的聊天历史 |
| API 参考 | Agent |
| GitHub 链接 | https://github.com/deepset-ai/haystack/blob/main/haystack/components/agents/agent.py |
概述
该Agent 组件是一个基于循环的系统,它使用聊天型大型语言模型(LLM)和外部工具来解决复杂的用户查询。它以迭代方式工作——调用工具、更新状态和生成提示——直到满足以下可配置的exit_conditions 之一。
它可以
- 根据用户输入动态选择工具,
- 使用模式(schema)维护和验证运行时状态,
- 从 LLM 流式传输 token 级别的输出。
该Agent 返回一个包含以下内容的字典:
messages:完整的对话历史,- 其他动态键,基于
state_schema.
参数
要初始化Agent 组件,您需要为其提供一个支持工具的聊天生成器实例。您可以传递一个 tools 或 ComponentTool 实例列表,或者将它们包装在 Toolset 中进行分组管理。
您还可以配置
- 一个
system_prompt为您的 Agent, - 一个包含字符串的列表
exit_conditions,这些条件将导致代理返回。可以是- “text”,这意味着当 LLM 只回复文本响应时,Agent 将退出,
- 或者特定的工具名称。
- 一个
state_schema,用于一次 Agent 调用运行。它定义了工具在执行过程中可以读取或写入的额外信息,例如文档或上下文。您可以使用此模式传递工具可以生成和消费的参数。 streaming_callback,用于直接将 LLM 的 token 流式传输到输出中。
有关可用参数的完整列表,请参阅 Agents API 文档。
流式传输
您可以随着输出的生成而流式传输。将回调函数传递给streaming_callback。使用内置的print_streaming_chunk 来打印文本 token 和工具事件(工具调用和工具结果)。
from haystack.components.generators.utils import print_streaming_chunk
# Configure any `Generator` or `ChatGenerator` with a streaming callback
component = SomeGeneratorOrChatGenerator(streaming_callback=print_streaming_chunk)
# If this is a `ChatGenerator`, pass a list of messages:
# from haystack.dataclasses import ChatMessage
# component.run([ChatMessage.from_user("Your question here")])
# If this is a (non-chat) `Generator`, pass a prompt:
# component.run({"prompt": "Your prompt here"})
流式输出仅适用于单个响应。如果提供程序支持多个候选,请将
n=1.
设置为 1。有关流式输出如何工作以及如何编写自定义回调函数,请参阅我们的流式输出支持文档。StreamingChunk 工作原理以及如何编写自定义回调。
默认首选print_streaming_chunk。仅当您需要特定的传输(例如 SSE/WebSocket)或自定义 UI 格式时,才编写自定义回调。
用法
单独使用
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.tools.tool import Tool
from haystack.components.agents import Agent
from typing import List
# Tool Function
def calculate(expression: str) -> dict:
try:
result = eval(expression, {"__builtins__": {}})
return {"result": result}
except Exception as e:
return {"error": str(e)}
# Tool Definition
calculator_tool = Tool(
name="calculator",
description="Evaluate basic math expressions.",
parameters={
"type": "object",
"properties": {
"expression": {"type": "string", "description": "Math expression to evaluate"}
},
"required": ["expression"]
},
function=calculate,
outputs_to_state={"calc_result": {"source": "result"}}
)
# Agent Setup
agent = Agent(
chat_generator=OpenAIChatGenerator(),
tools=[calculator_tool],
exit_conditions=["calculator"],
state_schema={
"calc_result": {"type": int},
}
)
# Run the Agent
agent.warm_up()
response = agent.run(messages=[ChatMessage.from_user("What is 7 * (4 + 2)?")])
# Output
print(response["messages"])
print("Calc Result:", response.get("calc_result"))
在 pipeline 中
下面的示例管道创建了一个数据库助手,使用了OpenAIChatGenerator, LinkContentFetcher 和自定义数据库工具。它读取给定的 URL 并处理页面内容,然后为 AI 构建提示。助手使用此信息将给定页面上的人名和头衔写入数据库。
from haystack.components.agents import Agent
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.components.builders.chat_prompt_builder import ChatPromptBuilder
from haystack.components.converters.html import HTMLToDocument
from haystack.components.fetchers.link_content import LinkContentFetcher
from haystack.core.pipeline import Pipeline
from haystack.tools import tool
from haystack.document_stores.in_memory import InMemoryDocumentStore
from typing import Optional
from haystack.dataclasses import ChatMessage, Document
document_store = InMemoryDocumentStore() # create a document store or an SQL database
@tool
def add_database_tool(name: str, surname: str, job_title: Optional[str], other: Optional[str]):
"""Use this tool to add names to the database with information about them"""
document_store.write_documents([Document(content=name + " " + surname + " " + (job_title or ""), meta={"other":other})])
return
database_asistant = Agent(
chat_generator=OpenAIChatGenerator(model="gpt-4o-mini"),
tools=[add_database_tool],
system_prompt="""
You are a database assistant.
Your task is to extract the names of people mentioned in the given context and add them to a knowledge base, along with additional relevant information about them that can be extracted from the context.
Do not use you own knowledge, stay grounded to the given context.
Do not ask the user for confirmation. Instead, automatically update the knowledge base and return a brief summary of the people added, including the information stored for each.
""",
exit_conditions=["text"],
max_agent_steps=100,
raise_on_tool_invocation_failure=False
)
extraction_agent = Pipeline()
extraction_agent.add_component("fetcher", LinkContentFetcher())
extraction_agent.add_component("converter", HTMLToDocument())
extraction_agent.add_component("builder", ChatPromptBuilder(
template=[ChatMessage.from_user("""
{% for doc in docs %}
{{ doc.content|default|truncate(25000) }}
{% endfor %}
""")],
required_variables=["docs"]
))
extraction_agent.add_component("database_agent", database_asistant)
extraction_agent.connect("fetcher.streams", "converter.sources")
extraction_agent.connect("converter.documents", "builder.docs")
extraction_agent.connect("builder", "database_agent")
agent_output = extraction_agent.run({"fetcher":{"urls":["https://en.wikipedia.org/wiki/Deepset"]}})
print(agent_output["database_agent"]["messages"][-1].text)
其他参考资料
🧑🍳 食谱:构建一个 GitHub Issue 解析器 Agent
📓 教程:构建一个工具调用 Agent
更新于 2 个月前
