跳转到内容
Hugging Face 智能体课程
1. 课程运作方式及问答环节
单元2. 智能体框架

在 LlamaIndex 中创建智能体工作流程

LlamaIndex中的工作流程提供了一种结构化的方式,将代码组织成有序且易于管理的步骤。

这样的工作流程是通过定义来创建的 Steps 由...触发 Events,并且它们自身也会发出信号 Events 触发进一步的步骤。让我们看看 Alfred 展示的用于 RAG 任务的 LlamaIndex 工作流程。

工作流程示意图

Workflows 提供了几个关键的优势:

  • 将代码组织成独立的步骤
  • 事件驱动架构以实现灵活的控制流程
  • 步骤间的安全类型通信
  • 内置状态管理
  • 支持简单和复杂的智能体交互

正如你可能已经猜到的, 工作流程在智能体的自主性与对整体工作流程的控制之间实现了良好的平衡。

那么,让我们自己学习如何创建一个工作流程吧!

创建工作流程

[!TIP] 您可以按照代码进行操作。 这个笔记本 您可以使用 Google Colab来运行它。

基础工作流程创建

安装 Workflow 包 如文中所述 LlamaHub的相关章节我们可以使用以下命令安装Workflow包:
pip install llama-index-utils-workflow

我们可以通过定义一个继承自…的类来创建一个一步到位的工作流程。 Workflow 并用智能体装饰你的函数。 @step我们还需要添加 StartEvent 和 StopEvent这些是特殊事件,用于指示工作流的开始和结束。

from llama_index.core.workflow import StartEvent, StopEvent, Workflow, step

class MyWorkflow(Workflow):
    @step
    async def my_step(self, ev: StartEvent) -> StopEvent:
        # do something here
        return StopEvent(result="Hello, world!")


w = MyWorkflow(timeout=10, verbose=False)
result = await w.run()

如您所见,我们现在可以通过调用工具调用来运行工作流程。 w.run().

连接多个步骤

为了连接多个步骤,我们 创建携带数据在智能体之间传递的自定义事件。 为此,我们需要添加一个 Event 这是在两个智能体之间传递的,它将第一步的输出传递给第二步。

from llama_index.core.workflow import Event

class ProcessingEvent(Event):
    intermediate_result: str

class MultiStepWorkflow(Workflow):
    @step
    async def step_one(self, ev: StartEvent) -> ProcessingEvent:
        # Process initial data
        return ProcessingEvent(intermediate_result="Step 1 complete")

    @step
    async def step_two(self, ev: ProcessingEvent) -> StopEvent:
        # Use the intermediate result
        final_result = f"Finished processing: {ev.intermediate_result}"
        return StopEvent(result=final_result)

w = MultiStepWorkflow(timeout=10, verbose=False)
result = await w.run()
result

类型提示在这里非常重要,因为它确保了工作流程能够正确执行。让我们让事情变得更复杂一些吧!

循环与分支

类型提示是工作流程中最强大的功能,因为它允许我们创建分支、循环和连接,从而实现更复杂的工作流程。

让我们来看一个例子 创建循环 通过使用联合运算符 |在下面的例子中,我们看到 LoopEvent 被作为该步骤的输入,也可以作为输出返回。

from llama_index.core.workflow import Event
import random


class ProcessingEvent(Event):
    intermediate_result: str


class LoopEvent(Event):
    loop_output: str


class MultiStepWorkflow(Workflow):
    @step
    async def step_one(self, ev: StartEvent | LoopEvent) -> ProcessingEvent | LoopEvent:
        if random.randint(0, 1) == 0:
            print("Bad thing happened")
            return LoopEvent(loop_output="Back to step one.")
        else:
            print("Good thing happened")
            return ProcessingEvent(intermediate_result="First step complete.")

    @step
    async def step_two(self, ev: ProcessingEvent) -> StopEvent:
        # Use the intermediate result
        final_result = f"Finished processing: {ev.intermediate_result}"
        return StopEvent(result=final_result)


w = MultiStepWorkflow(verbose=False)
result = await w.run()
result

绘制工作流程

我们还可以绘制工作流程。让我们使用 draw_all_possible_flows 用于绘制工作流的函数。该函数将工作流存储在一个HTML文件中。

from llama_index.utils.workflow import draw_all_possible_flows

w = ... # as defined in the previous section
draw_all_possible_flows(w, "flow.html")

工作流程图绘制

在课程中,还有最后一个有趣的小技巧,那就是能够在工作流程中添加状态。

状态管理

状态管理在您需要跟踪工作流程的状态时非常有用,这样每个步骤都可以访问相同的状态。我们可以通过使用 Context 在步骤函数中对参数进行类型提示。

from llama_index.core.workflow import Context, StartEvent, StopEvent


@step
async def query(self, ctx: Context, ev: StartEvent) -> StopEvent:
    # store query in the context
    await ctx.store.set("query", "What is the capital of France?")

    # do something with context and event
    val = ...

    # retrieve query from the context
    query = await ctx.store.get("query")

    return StopEvent(result=val)

太好了!现在您已经知道如何在 LlamaIndex 中创建基本的工作流程了!

[!TIP] 工作流程中存在一些更复杂的细节,你可以了解这些细节。 LlamaIndex文档.

然而,还有另一种创建工作流程的方法,该方法依赖于 AgentWorkflow 那么,让我们来看看如何利用这一点来创建一个多智能体工作流程。

使用多智能体工作流实现工作流自动化

我们可以不使用手动工作流程创建,而是使用 AgentWorkflow 创建多智能体工作流的类这个 AgentWorkflow 使用智能体来创建一个由一个或多个智能体组成的系统,这些智能体可以根据各自的专长能力进行协作,并将任务相互移交。 这使得可以构建复杂的智能体系统,其中不同的智能体负责任务的各个方面。 而不是从 llama_index.core.agent,我们将从智能体类导入 llama_index.core.agent.workflow必须指定一个智能体作为根智能体。 AgentWorkflow 智能体。 当接收到用户消息时,首先将其路由到根智能体。

每个智能体然后可以:

  • 直接使用智能体进行请求处理
  • 切换到更适合该任务的另一个智能体
  • 返回用户响应

让我们来看看如何创建一个多智能体工作流程。

from llama_index.core.agent.workflow import AgentWorkflow, ReActAgent
from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI

# Define some tools
def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

def multiply(a: int, b: int) -> int:
    """Multiply two numbers."""
    return a * b

llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct")

# we can pass functions directly without FunctionTool -- the fn/docstring are parsed for the name/description
multiply_agent = ReActAgent(
    name="multiply_agent",
    description="Is able to multiply two integers",
    system_prompt="A helpful assistant that can use a tool to multiply numbers.",
    tools=[multiply],
    llm=llm,
)

addition_agent = ReActAgent(
    name="add_agent",
    description="Is able to add two integers",
    system_prompt="A helpful assistant that can use a tool to add numbers.",
    tools=[add],
    llm=llm,
)

# Create the workflow
workflow = AgentWorkflow(
    agents=[multiply_agent, addition_agent],
    root_agent="multiply_agent",
)

# Run the system
response = await workflow.run(user_msg="Can you add 5 and 3?")

智能体工具还可以修改我们之前提到的工作流状态。在开始工作流之前,我们可以提供一个初始状态字典,该字典将对所有智能体可用。 该状态存储在工作流上下文的状态键中。它会被注入到状态提示中,从而增强每个新的用户消息。

让我们通过修改前面的示例来添加一个计数器,以统计函数调用次数:

from llama_index.core.workflow import Context

# Define some tools
async def add(ctx: Context, a: int, b: int) -> int:
    """Add two numbers."""
    # update our count
    cur_state = await ctx.store.get("state")
    cur_state["num_fn_calls"] += 1
    await ctx.store.set("state", cur_state)

    return a + b

async def multiply(ctx: Context, a: int, b: int) -> int:
    """Multiply two numbers."""
    # update our count
    cur_state = await ctx.store.get("state")
    cur_state["num_fn_calls"] += 1
    await ctx.store.set("state", cur_state)

    return a * b

...

workflow = AgentWorkflow(
    agents=[multiply_agent, addition_agent],
    root_agent="multiply_agent",
    initial_state={"num_fn_calls": 0},
    state_prompt="Current state: {state}. User message: {msg}",
)

# run the workflow with context
ctx = Context(workflow)
response = await workflow.run(user_msg="Can you add 5 and 3?", ctx=ctx)

# pull out and inspect the state
state = await ctx.store.get("state")
print(state["num_fn_calls"])

恭喜!你现在已经掌握了在 LlamaIndex 中使用智能体的基础知识了!🎉

让我们继续进行最后一个小测验,以巩固你的知识!🚀