Frame · dsa / ai-algorithms / 20-agent-workflow-dag-scheduler.jsJavaScript
Agent Workflow DAG Scheduler With Parallel Levels
Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.
Same file as in the repo · ~20s timeout
From file header (JSDoc)
Agent Workflow DAG Scheduler With Parallel Levels
Problem: An agent workflow is a set of steps (tool calls, LLM calls,
retrieval) where some steps depend on the outputs of others. Given
`steps` as an object mapping step id to the list of ids it depends on,
return the execution plan as levels: every step in a level has all its
dependencies in earlier levels, so a level's steps can run in parallel.
Each step must appear in the earliest possible level, and ids inside a
level are sorted for determinism. Throw an Error mentioning "cycle" if the
graph has a cycle, and one mentioning "unknown" if a dependency is not a
step. Also implement `runWorkflow(steps, handlers)` which executes levels
in order, running each level with Promise.all, and passes every handler an
object of its dependencies' results; it resolves to all results.
Constraints:
- 1 <= number of steps <= 10^4, total dependencies <= 10^5
Example:
{ plan: [], search: ["plan"], fetch: ["plan"], summarize: ["search", "fetch"] }
-> [["plan"], ["fetch", "search"], ["summarize"]]
Approach: Kahn's algorithm processed level by level: compute in-degrees,
start with all zero in-degree steps, and when finishing a level decrement
the in-degree of each dependent, collecting the ones that hit zero into
the next level. If fewer steps are emitted than exist, the rest are on a
cycle. Time O(V + E + V log V) for the sorting, space O(V + E).
@param {Record<string, string[]>} steps
@returns {string[][]}