流式输出与事件
在实际应用中,智能体的运行可能需要很长时间。向用户提供关于智能体进度的反馈至关重要,而流式传输使您能够实现这一点。
AgentWorkflowAgentWorkflow 提供了一组预构建的事件,您可以使用这些事件将输出流式传输给用户。让我们来看看这是如何实现的。
首先,我们将介绍一个需要较长时间执行的新工具。这里我们将使用名为Tavily的网络搜索工具,该工具可在LlamaHub中获取。
pip install llama-index-tools-tavily-research它需要一个API密钥,我们将在.env文件中设置为TAVILY_API_KEY,并使用os.getenv方法进行获取。现在让我们引入所需的导入项:
from llama_index.tools.tavily_research import TavilyToolSpecimport 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.",)在之前的示例中,我们已在 workflow.run 方法上使用 await 来获取智能体的最终响应。但如果我们不等待响应,就会获得一个异步迭代器,通过遍历该迭代器可以实时获取事件流。这个迭代器将返回各类事件。我们将从 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 在运行时发出的众多事件之一。其他事件包括:
AgentInputAgentInput: 启动智能体执行的完整消息对象AgentOutputAgentOutput: 来自智能体的响应ToolCallToolCall: 调用了哪些工具及其参数ToolCallResultToolCallResult: 工具调用的结果
您可以在此示例的完整代码中查看我们如何筛选更多此类事件。
接下来你将学习如何让人类参与循环为你的智能体提供反馈。