Annotate a class method with @task (Functional API) #4417
Replies: 2 comments 3 replies
-
Hello! I did a quick research and I found that you can't directly decorate class methods with Instead, create your tasks and workflows inside the constructor like this: def __init__(self):
# The key insight: create tasks by passing methods to the decorator functions
self.call_llm_task = task(self.call_llm)
self.workflow_entry = entrypoint()(self.simple_workflow) This way, the instance methods are already bound to Here's a full working example:from langgraph.func import entrypoint, task
class MockLLM:
def generate(self, prompt: str) -> str:
return f"[MOCKED] Response for: {prompt}"
class Workflow:
def __init__(self, param: int = 0):
self.llm = MockLLM()
self.param = param
# Create tasks by passing methods directly to task() function
self.call_llm_task = task(self.call_llm, name="call_llm")
# Create entrypoint by passing method directly
self.simple_workflow_entry = entrypoint()(self.simple_workflow)
def call_llm(self, prompt: str) -> str:
return self.llm.generate(prompt)
def simple_workflow(self, topic: str) -> dict:
if self.param == 0:
prompt = f"Explain the significance of {topic} in one sentence."
else:
prompt = f"Don't do anything"
result = self.call_llm_task(prompt).result()
return {"topic": topic, "explanation": result}
def invoke(self, topic: str) -> dict:
return self.simple_workflow_entry.invoke(topic)
if __name__ == "__main__":
workflow = Workflow()
output = workflow.invoke("LangGraph")
print(output) Please correct me if I'm wrong! |
Beta Was this translation helpful? Give feedback.
-
Thanks for the request! We'll try to add support |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Is there a way to annotate a method with @task or @workflow? I'd like to encapsulate the whole workflow in a class for better modularity of my code base but could not find a way to annotate methods. Example code:
doesn't work because of
Beta Was this translation helpful? Give feedback.
All reactions