Deeply Nested Workflow (3 Levels)
Three levels of workflow nesting with parallel branches at level 2.
1from kern.agent import Agent2from kern.models.openai import OpenAIChat3from kern.workflow import Parallel4from kern.workflow.step import Step5from kern.workflow.types import StepInput, StepOutput6from kern.workflow.workflow import Workflow789def merge_results(step_input: StepInput) -> StepOutput:10 """Merge content from previous steps."""11 prev = step_input.previous_step_content or ""12 return StepOutput(content=f"Merged: {prev[:500]}")131415# Level 3: Mini-workflows for individual research tasks16data_agent = Agent(17 name="Data Agent",18 model=OpenAIChat(id="gpt-4o-mini"),19 instructions="Gather raw data and statistics on the topic. Be concise (2-3 sentences).",20)2122analysis_agent = Agent(23 name="Analysis Agent",24 model=OpenAIChat(id="gpt-4o-mini"),25 instructions="Analyze the data provided. Identify key trends. Be concise (2-3 sentences).",26)2728data_workflow = Workflow(29 name="Data Collection",30 description="Collects and analyzes raw data",31 steps=[32 Step(name="gather", agent=data_agent),33 Step(name="analyze", agent=analysis_agent),34 ],35)3637opinion_agent = Agent(38 name="Opinion Agent",39 model=OpenAIChat(id="gpt-4o-mini"),40 instructions="Provide expert opinion and perspective on the topic. Be concise (2-3 sentences).",41)4243opinion_workflow = Workflow(44 name="Expert Opinion",45 description="Gathers expert perspectives",46 steps=[Step(name="opinion", agent=opinion_agent)],47)4849# Level 2: Research workflow with parallel Level 3 workflows50level2_workflow = Workflow(51 name="Comprehensive Research",52 description="Runs data collection and expert opinion in parallel",53 steps=[54 Parallel(55 Step(name="data_branch", workflow=data_workflow),56 Step(name="opinion_branch", workflow=opinion_workflow),57 name="parallel_research",58 ),59 Step(name="merge", executor=merge_results),60 ],61)6263# Level 1: Outermost workflow64writer = Agent(65 name="Writer",66 model=OpenAIChat(id="gpt-4o-mini"),67 instructions="Write a polished short paragraph synthesizing all research provided.",68)6970outer_workflow = Workflow(71 name="Full Pipeline",72 description="3-level nested workflow: research (parallel mini-workflows) -> write",73 steps=[74 Step(name="research", workflow=level2_workflow),75 Step(name="write", agent=writer),76 ],77)787980if __name__ == "__main__":81 outer_workflow.print_response(82 input="What is the future of renewable energy?",83 stream=True,84 )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 deeply_nested_workflow.py