主题
在真实场景里,agent 可能运行相当长的时间。把进展反馈给用户非常关键,而流式输出正是做到这一点的方式。
AgentWorkflow 提供了一组预置事件,你可以用它们把输出流式地呈现给用户。我们来看看怎么做。
提示
有些模型可能不支持流式 LLM 输出。流式默认是开启的,如果遇到报错,你随时可以用 FunctionAgent(..., streaming=False) 把它关掉。
首先引入一个执行起来需要一些时间的新工具。这里用名为 Tavily 的网页搜索工具,它作为 llama-index-tools-tavily-research 包提供。
终端窗口
pip install llama-index-tools-tavily-research它需要 API key,我们把它写进 .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 来创建 agent。
workflow = FunctionAgent(
tools=tavily_tool.to_tool_list(),
llm=llm,
system_prompt="You're a helpful assistant that can search the web for information.",
)在之前的示例里,我们对 workflow.run 使用 await,拿到 agent 的最终回答。但如果不 await 这个返回值,我们会拿到一个异步迭代器,可以边产生边遍历这些事件。这个迭代器会返回各种各样的事件。我们先从 AgentStream 事件开始,它携带输出的“delta”(最新增量的那部分)。需要先导入这个事件类型:
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)如果你自己运行它,会看到输出是一块一块随着 agent 的运行到达的,大致像这样:
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:开启 agent 本次执行的完整消息对象AgentOutput:agent 的回答ToolCall:调用了哪些工具、用了什么参数ToolCallResult:一次工具调用的结果
在这个示例的完整代码里可以看到我们对更多这类事件的过滤处理。
接下来你会了解如何让人在回路来为你的 agent 提供反馈。