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.34Background execution allows you to start a team run that returns immediately5with a PENDING status, while the actual work continues in the background.6You can then poll for completion or cancel the run.78Requirements:9- PostgreSQL running (./cookbook/scripts/run_pgvector.sh)10- OPENAI_API_KEY set1112Usage:13 .venvs/demo/bin/python cookbook/03_teams/other/background_execution.py14"""1516import asyncio1718from kern.agent import Agent19from kern.db.postgres import PostgresDb20from kern.models.openai import OpenAIResponses21from kern.run.base import RunStatus22from kern.team import Team2324# ---------------------------------------------------------------------------25# Setup26# ---------------------------------------------------------------------------27db = PostgresDb(28 db_url="postgresql+psycopg://ai:ai@localhost:5532/ai",29 session_table="team_bg_exec_sessions",30)313233# ---------------------------------------------------------------------------34# Create and Run Examples35# ---------------------------------------------------------------------------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)4142 researcher = Agent(43 name="Researcher",44 model=OpenAIResponses(id="gpt-5.2-mini"),45 role="Research topics and provide factual information.",46 )4748 writer = Agent(49 name="Writer",50 model=OpenAIResponses(id="gpt-5.2-mini"),51 role="Write clear and concise summaries.",52 )5354 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 )6465 # Start a background run -- returns immediately with PENDING status66 run_output = await team.arun(67 "What are the three laws of thermodynamics? Summarize each in one sentence.",68 background=True,69 )7071 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 )7778 # Poll for completion79 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 continue8990 print(f" [{i + 1}s] Status: {result.status}")9192 if result.status == RunStatus.completed:93 print(f"\nCompleted! Content:\n{result.content}")94 break95 elif result.status == RunStatus.error:96 print(f"\nFailed! Content: {result.content}")97 break98 else:99 print("\nTimed out waiting for completion")100101102async 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)108109 researcher = Agent(110 name="Researcher",111 model=OpenAIResponses(id="gpt-5.2-mini"),112 role="Research topics thoroughly.",113 )114115 writer = Agent(116 name="Writer",117 model=OpenAIResponses(id="gpt-5.2-mini"),118 role="Write detailed essays.",119 )120121 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 )131132 # Start a long background run133 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 )138139 print(f"Run ID: {run_output.run_id}")140 print(f"Status: {run_output.status}")141142 # Wait a moment, then cancel143 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}")147148 # Check final state149 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}")156157158# ---------------------------------------------------------------------------159# Run Demo160# ---------------------------------------------------------------------------161async def main():162 await example_team_background_run()163 await example_cancel_team_background_run()164 print("\nAll examples completed!")165166167if __name__ == "__main__":168 asyncio.run(main())Run the Example
1# Clone and setup repo2git clone https://github.com/kern-ai/kern.git3cd kern/cookbook/03_teams/other45# Create and activate virtual environment6./scripts/demo_setup.sh7source .venvs/demo/bin/activate89# Optiona: Run PgVector (needs docker)10./cookbook/scripts/run_pgvector.sh1112# Export relevant API keys13export OPENAI_API_KEY="***"1415python background_execution.py