0
0
Agentic_aiml~20 mins

Async agent execution in Agentic Ai - ML Experiment: Train & Evaluate

Choose your learning style8 modes available
Experiment - Async agent execution
Problem:You have an AI agent designed to perform multiple tasks sequentially, but it takes too long to complete all tasks.
Current Metrics:Total execution time: 120 seconds; Task success rate: 95%
Issue:The agent executes tasks one after another (synchronously), causing slow overall performance despite high task success.
Your Task
Modify the agent to execute tasks asynchronously to reduce total execution time while maintaining at least 90% task success rate.
Do not change the task logic or success criteria.
Keep the agent's environment and input data unchanged.
Hint 1
Hint 2
Hint 3
Solution
Agentic_ai
import asyncio

class AsyncAgent:
    def __init__(self, tasks):
        self.tasks = tasks

    async def run_task(self, task_id, duration):
        print(f"Starting task {task_id}")
        await asyncio.sleep(duration)  # Simulate task work
        print(f"Finished task {task_id}")
        return f"Result of task {task_id}"

    async def run_all_tasks(self):
        # Create coroutine objects for all tasks
        coros = [self.run_task(i, d) for i, d in enumerate(self.tasks, 1)]
        # Run tasks concurrently and gather results
        results = await asyncio.gather(*coros)
        return results

# Example usage
async def main():
    # Simulate 5 tasks with different durations
    task_durations = [5, 10, 3, 7, 8]
    agent = AsyncAgent(task_durations)

    import time
    start_time = time.time()
    results = await agent.run_all_tasks()
    end_time = time.time()

    print("All tasks completed.")
    print("Results:", results)
    print(f"Total execution time: {end_time - start_time:.2f} seconds")

if __name__ == "__main__":
    asyncio.run(main())
Converted synchronous task execution to asynchronous using asyncio.
Used asyncio.gather to run all tasks concurrently.
Measured total execution time to verify speedup.
Results Interpretation

Before: Total execution time was 120 seconds with 95% task success rate.

After: Total execution time reduced to about 10 seconds with task success rate maintained at 95%.

Running tasks asynchronously can drastically reduce total execution time without sacrificing task success, demonstrating the power of concurrent execution in AI agents.
Bonus Experiment
Try implementing a timeout for each task so that if a task takes too long, it is cancelled and does not block other tasks.
💡 Hint
Use asyncio.wait_for to add a timeout to each task coroutine.