Nested Workflow with Loop

Inner workflow with a `Loop` step that iteratively refines research until a quality threshold is met.

1from typing import List
2
3from kern.agent import Agent
4from kern.models.openai import OpenAIChat
5from kern.workflow import Loop
6from kern.workflow.step import Step
7from kern.workflow.types import StepOutput
8from kern.workflow.workflow import Workflow
9
10
11def 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 False
15 last = outputs[-1]
16 return last.content is not None and len(str(last.content)) > 200
17
18
19# Inner workflow: iterative research
20researcher = 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)
28
29inner_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)
41
42# Outer workflow
43writer = Agent(
44 name="Writer",
45 model=OpenAIChat(id="gpt-4o-mini"),
46 instructions="Write a polished summary from the detailed research provided.",
47)
48
49outer_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)
57
58
59if __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.git
2cd kern/cookbook/04_workflows/06_advanced_concepts/workflow_as_a_step
3
4pip install kern-ai openai
5
6python nested_workflow_with_loop.py