概述

可以通过一个全局状态,来保留任意数据或函数以供所有事件处理程序使用。

实现逻辑

通过Context来维护一个全局状态变量,可以保存值的列表,这样可以供后续的执行步骤使用。

代码实现

from llama_index.core.workflow import (
    Event,
    StartEvent,
    StopEvent,
    Workflow,
    step,
)
​
from llama_index.core.memory import VectorMemory
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, Settings
from llama_index.llms.ollama import Ollama
from llama_index.core.workflow import Context
​
import asyncio
import random
​
Settings.llm = Ollama(model="llama3.2", request_timeout=360)
​
class QueryEvent(Event):
    query: str
​
class GlobalExampleFlow(Workflow):
    @step
    async def setup(self, ctx: Context, ev: StartEvent) -> QueryEvent:
        # 设置key的值
        await ctx.set("key", ["value1", "value2", "value3"])
​
        return QueryEvent(query=ev.query)
​
    @step
    async def query(self, ctx: Context, ev: QueryEvent) -> StopEvent:
        # 获取上下文的key
        data = await ctx.get("key")
​
        result = f"The answer to your query is {data[1]}"
        return StopEvent(result=result)
​
# 画流程图
from llama_index.utils.workflow import draw_all_possible_flows
draw_all_possible_flows(GlobalExampleFlow, filename="GlobalExampleFlow.html")
​
# main
async def main():
    g = GlobalExampleFlow(timeout=10, verbose=True)
    result = await g.run(query="What's LlamaIndex?")
    print(result)
    
# run main
if __name__ == '__main__':
    asyncio.run(main())

执行结果

Running step setup
Step setup produced event QueryEvent
Running step query
Step query produced event StopEvent
The answer to your query is value2

从执行结果可以看出,获取到了设置的列表值中的第2个位置的值。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐