跳转到内容

资源对象

资源是您可以注入到工作流步骤中的外部依赖项。

作为一个简单的示例,请看以下工作流程中来自llama-index的memory

from workflows.resource import Resource
from llama_index.core.llms import ChatMessage
from llama_index.core.memory import Memory
from typing import Annotated
def get_memory(*args, **kwargs):
return Memory.from_defaults("user_id_123", token_limit=60000)
class SecondEvent(Event):
msg: str
class WorkflowWithResource(Workflow):
@step
async def first_step(
self,
ev: StartEvent,
memory: Annotated[Memory, Resource(get_memory)],
) -> SecondEvent:
print("Memory before step 1", memory)
await memory.aput(
ChatMessage(role="user", content="This is the first step")
)
print("Memory after step 1", memory)
return SecondEvent(msg="This is an input for step 2")
@step
async def second_step(
self, ev: SecondEvent, memory: Annotated[Memory, Resource(get_memory)]
) -> StopEvent:
print("Memory before step 2", memory)
await memory.aput(ChatMessage(role="user", content=ev.msg))
print("Memory after step 2", memory)
return StopEvent(result="Messages put into memory")

要将资源注入工作流步骤,您需要在步骤签名中添加参数并定义其类型, 使用 Annotated 并调用 Resource() 包装器,传入返回实际资源对象的函数或可调用对象。 被包装函数的返回类型必须与声明的类型匹配,确保执行时期望值与提供值之间的一致性。在上面的示例中,memory: Annotated[Memory, Resource(get_memory) 定义了类型为 Memory 的资源,该资源将由 get_memory() 函数提供,并在工作流运行时通过 memory 参数传递给步骤。

资源在工作流的各个步骤之间共享,Resource()包装器将仅调用工厂函数一次。 如果这不是期望的行为,将cache=False传递给Resource()将在不同步骤中注入不同的资源对象, 从而多次调用工厂函数。