流式输出和事件#
在实际应用中,代理可能需要很长时间才能运行。向用户提供关于代理进度的反馈至关重要,而流式传输可以实现这一点。
AgentWorkflow
提供了一系列预构建的事件,你可以使用它们向用户流式传输输出。让我们看看如何做到这一点。
首先,我们将介绍一个需要一些时间执行的新工具。在这种情况下,我们将使用一个名为 Tavily 的网络搜索工具,它在 LlamaHub 中可用。
pip install llama-index-tools-tavily-research
它需要一个 API 密钥,我们将在 .env
文件中将其设置为 TAVILY_API_KEY
,并使用 os.getenv
方法检索。让我们引入我们的导入
from llama_index.tools.tavily_research import TavilyToolSpec
import os
并初始化工具
tavily_tool = TavilyToolSpec(api_key=os.getenv("TAVILY_API_KEY"))
现在,我们将使用该工具和一个我们之前初始化过的 LLM 来创建一个代理。
workflow = FunctionAgent(
tools=tavily_tool.to_tool_list(),
llm=llm,
system_prompt="You're a helpful assistant that can search the web for information.",
)
在之前的示例中,我们使用 await
在 workflow.run
方法上获取代理的最终响应。然而,如果我们不对响应进行等待,我们将获得一个异步迭代器,我们可以迭代该迭代器来获取传入的事件。这个迭代器将返回各种事件。我们将从一个 AgentStream
事件开始,它包含输出传入时的“增量”(最新的变化)。我们需要导入该事件类型
from llama_index.core.agent.workflow import AgentStream
现在我们可以运行工作流并查找该类型的事件进行输出
handler = workflow.run(user_msg="What's the weather like in San Francisco?")
async for event in handler.stream_events():
if isinstance(event, AgentStream):
print(event.delta, end="", flush=True)
如果你自己运行这段代码,你会看到输出在代理运行时分块到达,返回类似这样的内容
The current weather in San Francisco is as follows:
- **Temperature**: 17.2°C (63°F)
- **Condition**: Sunny
- **Wind**: 6.3 mph (10.1 kph) from the NNW
- **Humidity**: 54%
- **Pressure**: 1021 mb (30.16 in)
- **Visibility**: 16 km (9 miles)
For more details, you can check the full report [here](https://www.weatherapi.com/).
AgentStream
只是 AgentWorkflow
运行时发出的众多事件之一。其他的事件包括:
AgentInput
: 开始代理执行的完整消息对象AgentOutput
: 来自代理的响应ToolCall
: 调用了哪些工具以及使用了哪些参数ToolCallResult
: 工具调用的结果
你可以在此示例的完整代码中看到我们如何过滤这些事件。
接下来,你将学习如何让人类参与循环,以便为你的代理提供反馈。