/ examples / background / basic_background.py
basic_background.py
 1  #!/usr/bin/env python3
 2  """
 3  Basic Background Tasks Example for PraisonAI Agents.
 4  
 5  This example demonstrates how to use the background task system with Agent:
 6  1. Create an Agent with background task support
 7  2. Run agent tasks asynchronously
 8  3. Track task progress
 9  4. Handle task completion
10  
11  Usage:
12      python basic_background.py
13  """
14  
15  import asyncio
16  from praisonaiagents import Agent
17  from praisonaiagents.background import BackgroundRunner, BackgroundConfig, TaskStatus
18  
19  
20  async def main():
21      print("=" * 60)
22      print("Agent-Centric Background Tasks Demo")
23      print("=" * 60)
24      
25      # Create a background runner with config (used standalone, not passed to Agent)
26      runner = BackgroundRunner(config=BackgroundConfig(max_concurrent_tasks=3))
27      
28      # Create an Agent
29      agent = Agent(
30          name="AsyncAssistant",
31          instructions="You are a helpful research assistant.",
32      )
33      
34      print("\n--- Agent with Background Support Created ---")
35      print(f"Agent: {agent.name}")
36      print(f"Background runner: {runner is not None}")
37      
38      # Define some example tasks
39      async def research_task(topic: str) -> str:
40          """Simulate a research task."""
41          print(f"  šŸ”„ Researching '{topic}'...")
42          await asyncio.sleep(1.5)
43          return f"Research on '{topic}' completed with 5 key findings"
44      
45      async def analysis_task(data: str) -> str:
46          """Simulate an analysis task."""
47          print(f"  šŸ”„ Analyzing data...")
48          await asyncio.sleep(1.0)
49          return f"Analysis complete: {data}"
50      
51      # Submit tasks via background runner
52      print("\n--- Submitting Background Tasks ---")
53      
54      task1 = await runner.submit(
55          research_task, 
56          args=("AI trends 2025",), 
57          name="research_ai"
58      )
59      print(f"āœ… Submitted research task: {task1.id[:8]}")
60      
61      task2 = await runner.submit(
62          analysis_task, 
63          args=("market data",), 
64          name="analyze_market"
65      )
66      print(f"āœ… Submitted analysis task: {task2.id[:8]}")
67      
68      # List all tasks
69      print("\n--- Task Status ---")
70      for task in runner.tasks:
71          print(f"  [{task.id[:8]}] {task.status.value}")
72      
73      # Wait for tasks to complete
74      print("\n--- Waiting for Tasks ---")
75      await task1.wait(timeout=10.0)
76      await task2.wait(timeout=10.0)
77      
78      # Final results
79      print("\n--- Results ---")
80      for task in [task1, task2]:
81          status = "āœ…" if task.status == TaskStatus.COMPLETED else "āŒ"
82          print(f"  {status} {task.result}")
83      
84      # Cleanup
85      runner.clear_completed()
86      print("\nāœ… Cleared completed tasks")
87      
88      print("\n" + "=" * 60)
89      print("Demo Complete!")
90      print("=" * 60)
91  
92  
93  if __name__ == "__main__":
94      asyncio.run(main())