Nested Workflow with Loop
Inner workflow with a `Loop` step that iteratively refines research until a quality threshold is met.
1from typing import List23from kern.agent import Agent4from kern.models.openai import OpenAIChat5from kern.workflow import Loop6from kern.workflow.step import Step7from kern.workflow.types import StepOutput8from kern.workflow.workflow import Workflow91011def is_detailed_enough(outputs: List[StepOutput]) -> bool:12 """End the loop when the output is sufficiently detailed (> 200 chars)."""13 if not outputs:14 return False15 last = outputs[-1]16 return last.content is not None and len(str(last.content)) > 200171819# Inner workflow: iterative research20researcher = Agent(21 name="Iterative Researcher",22 model=OpenAIChat(id="gpt-4o-mini"),23 instructions=(24 "You are a researcher. Each iteration, expand on the previous research "25 "with more detail and specifics. Build on what was already written."26 ),27)2829inner_workflow = Workflow(30 name="Iterative Research",31 description="Researches a topic in iterative passes until sufficiently detailed",32 steps=[33 Loop(34 name="research_loop",35 steps=[Step(name="research_pass", agent=researcher)],36 end_condition=is_detailed_enough,37 max_iterations=3,38 ),39 ],40)4142# Outer workflow43writer = Agent(44 name="Writer",45 model=OpenAIChat(id="gpt-4o-mini"),46 instructions="Write a polished summary from the detailed research provided.",47)4849outer_workflow = Workflow(50 name="Iterative Research and Write",51 description="Iteratively researches until detailed, then writes a summary",52 steps=[53 Step(name="research_phase", workflow=inner_workflow),54 Step(name="writing_phase", agent=writer),55 ],56)575859if __name__ == "__main__":60 outer_workflow.print_response(61 input="Explain how neural networks learn",62 stream=True,63 )Run the Example
1git clone https://github.com/kern-ai/kern.git2cd kern/cookbook/04_workflows/06_advanced_concepts/workflow_as_a_step34pip install kern-ai openai56python nested_workflow_with_loop.py