899. Supervisor that routes tasks to worker agents
Why it matters Multi-agent systems need a router: which specialist gets which job, without overloading anyone. It is the same problem as load balancing servers.
A supervisor agent hands tasks to worker agents.
Write route_to_workers(workers, tasks).
- workers: list of dicts {"name": str, "skills": list of str, "capacity": int}.
- tasks: list of dicts {"id": str, "skill": str}, handled in order.
- For each task, the eligible workers have the skill and their current load is below their capacity. Give the task to the eligible worker with the lowest current load; ties go to the alphabetically first name. If no worker is eligible the task is unassigned.
Return a dict {"assignments": dict task id -> worker name, "unassigned": list of task ids in order, "load": dict worker name -> number of tasks, including workers with 0}.
def route_to_workers(workers, tasks)Example 1
Input: route_to_workers([{'name': 'coder', 'skills': ['code'], 'capacity': 2}, {'name': 'helper', 'skills': ['code', 'search'], 'capacity': 1}], [{'id': 't1', 'skill': 'code'}, {'id': 't2', 'skill': 'search'}, {'id': 't3', 'skill': 'code'}, {'id': 't4', 'skill': 'search'}])
Output: {'assignments': {'t1': 'coder', 't2': 'helper', 't3': 'coder'}, 'unassigned': ['t4'], 'load': {'coder': 2, 'helper': 1}}
Example 2
Input: workers = [{'name': 'b', 'skills': ['x'], 'capacity': 5}, {'name': 'a', 'skills': ['x'], 'capacity': 5}], tasks = [{'id': '1', 'skill': 'x'}, {'id': '2', 'skill': 'x'}, {'id': '3', 'skill': 'x'}]
Output: {'assignments': {'1': 'a', '2': 'b', '3': 'a'}, 'unassigned': [], 'load': {'b': 1, 'a': 2}}
Example 3
Input: workers = [{'name': 'solo', 'skills': ['math'], 'capacity': 0}], tasks = [{'id': 'q', 'skill': 'math'}]
Output: {'assignments': {}, 'unassigned': ['q'], 'load': {'solo': 0}}
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
Start every worker's load at 0.
Hint 2
Eligible: skill matches and load < capacity.
Hint 3
min with key (load, name).
Common mistakes
- Forgetting workers with no tasks in the load dict.
- Checking load <= capacity.
- Reordering tasks.
Understand the idea
Filter by skill and free capacity, then pick the least loaded worker. Least-loaded spreads work evenly; the name tie-break keeps the result reproducible, which matters when you test agent systems. Greedy in-order routing can strand later tasks, as in the example where helper is busy by the time t4 arrives.
Shapes and data flow
Lists of dicts in, dict out.