Example demonstrating background execution with a Team.

Background execution allows you to start a team run that returns immediately with a PENDING status, while the actual work continues in the background.

Background execution allows you to start a team run that returns immediately with a PENDING status, while the actual work continues in the background. You can then poll for completion or cancel the run.

1"""
2Example demonstrating background execution with a Team.
3
4Background execution allows you to start a team run that returns immediately
5with a PENDING status, while the actual work continues in the background.
6You can then poll for completion or cancel the run.
7
8Requirements:
9- PostgreSQL running (./cookbook/scripts/run_pgvector.sh)
10- OPENAI_API_KEY set
11
12Usage:
13 .venvs/demo/bin/python cookbook/03_teams/other/background_execution.py
14"""
15
16import asyncio
17
18from kern.agent import Agent
19from kern.db.postgres import PostgresDb
20from kern.models.openai import OpenAIResponses
21from kern.run.base import RunStatus
22from kern.team import Team
23
24# ---------------------------------------------------------------------------
25# Setup
26# ---------------------------------------------------------------------------
27db = PostgresDb(
28 db_url="postgresql+psycopg://ai:ai@localhost:5532/ai",
29 session_table="team_bg_exec_sessions",
30)
31
32
33# ---------------------------------------------------------------------------
34# Create and Run Examples
35# ---------------------------------------------------------------------------
36async def example_team_background_run():
37 """Start a team background run and poll until complete."""
38 print("=" * 60)
39 print("Team Background Run with Polling")
40 print("=" * 60)
41
42 researcher = Agent(
43 name="Researcher",
44 model=OpenAIResponses(id="gpt-5.2-mini"),
45 role="Research topics and provide factual information.",
46 )
47
48 writer = Agent(
49 name="Writer",
50 model=OpenAIResponses(id="gpt-5.2-mini"),
51 role="Write clear and concise summaries.",
52 )
53
54 team = Team(
55 name="ResearchTeam",
56 model=OpenAIResponses(id="gpt-5.2-mini"),
57 members=[researcher, writer],
58 instructions=[
59 "First, have the researcher gather key facts.",
60 "Then, have the writer create a concise summary.",
61 ],
62 db=db,
63 )
64
65 # Start a background run -- returns immediately with PENDING status
66 run_output = await team.arun(
67 "What are the three laws of thermodynamics? Summarize each in one sentence.",
68 background=True,
69 )
70
71 print(f"Run ID: {run_output.run_id}")
72 print(f"Session ID: {run_output.session_id}")
73 print(f"Status: {run_output.status}")
74 assert run_output.status == RunStatus.pending, (
75 f"Expected PENDING, got {run_output.status}"
76 )
77
78 # Poll for completion
79 print("\nPolling for completion...")
80 for i in range(60):
81 await asyncio.sleep(1)
82 result = await team.aget_run_output(
83 run_id=run_output.run_id,
84 session_id=run_output.session_id,
85 )
86 if result is None:
87 print(f" [{i + 1}s] Run not found in DB yet")
88 continue
89
90 print(f" [{i + 1}s] Status: {result.status}")
91
92 if result.status == RunStatus.completed:
93 print(f"\nCompleted! Content:\n{result.content}")
94 break
95 elif result.status == RunStatus.error:
96 print(f"\nFailed! Content: {result.content}")
97 break
98 else:
99 print("\nTimed out waiting for completion")
100
101
102async def example_cancel_team_background_run():
103 """Start a team background run and cancel it."""
104 print()
105 print("=" * 60)
106 print("Cancel a Team Background Run")
107 print("=" * 60)
108
109 researcher = Agent(
110 name="Researcher",
111 model=OpenAIResponses(id="gpt-5.2-mini"),
112 role="Research topics thoroughly.",
113 )
114
115 writer = Agent(
116 name="Writer",
117 model=OpenAIResponses(id="gpt-5.2-mini"),
118 role="Write detailed essays.",
119 )
120
121 team = Team(
122 name="EssayTeam",
123 model=OpenAIResponses(id="gpt-5.2-mini"),
124 members=[researcher, writer],
125 instructions=[
126 "Have the researcher gather comprehensive information.",
127 "Then have the writer create a detailed essay.",
128 ],
129 db=db,
130 )
131
132 # Start a long background run
133 run_output = await team.arun(
134 "Write a detailed essay about the history of artificial intelligence. "
135 "Make it at least 3000 words.",
136 background=True,
137 )
138
139 print(f"Run ID: {run_output.run_id}")
140 print(f"Status: {run_output.status}")
141
142 # Wait a moment, then cancel
143 await asyncio.sleep(3)
144 print("Cancelling run...")
145 cancelled = await team.acancel_run(run_id=run_output.run_id)
146 print(f"Cancel result: {cancelled}")
147
148 # Check final state
149 await asyncio.sleep(1)
150 result = await team.aget_run_output(
151 run_id=run_output.run_id,
152 session_id=run_output.session_id,
153 )
154 if result:
155 print(f"Final status: {result.status}")
156
157
158# ---------------------------------------------------------------------------
159# Run Demo
160# ---------------------------------------------------------------------------
161async def main():
162 await example_team_background_run()
163 await example_cancel_team_background_run()
164 print("\nAll examples completed!")
165
166
167if __name__ == "__main__":
168 asyncio.run(main())

Run the Example

1# Clone and setup repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/03_teams/other
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9# Optiona: Run PgVector (needs docker)
10./cookbook/scripts/run_pgvector.sh
11
12# Export relevant API keys
13export OPENAI_API_KEY="***"
14
15python background_execution.py