llama-agents 的resource对象

llama-agents 的resource对象从定位来说就是可以注入外部依赖可以方便在step中复用共享,为了方便处理,同时还提供了一个基于json 配置的resource配置,而且resource 以及resourceconfig 可以组合使用

参考玩法

  • resource
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")
  • 基于配置的
class ClassifierConfig(BaseModel):
    categories: list[str]
    threshold: float


class DocumentClassifier(Workflow):
    @step
    async def classify(
        self,
        ev: StartEvent,
        config: Annotated[
            ClassifierConfig,
            ResourceConfig(config_file="classifier.json"),
        ],
    ) -> StopEvent:
        # config is loaded from classifier.json and validated as ClassifierConfig
        return StopEvent(result=f"Using threshold: {config.threshold}")

说明

resource 实际可以作为存储以及配置管理的一些依赖,效果上相比默认的状态管理,灵活性更方便一些

参考资料

https://developers.llamaindex.ai/python/llamaagents/workflows/resources/

posted on 2026-05-14 08:00  荣锋亮  阅读(18)  评论(0)    收藏  举报

导航