-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathiterate.ts
65 lines (58 loc) · 1.71 KB
/
iterate.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { childState, finish, response, WorkflowState } from './state.js'
import { runTools } from './tool_calls.js'
import { Message } from './types.js'
import { Workflow } from './workflow.js'
// tbd: finalize workflow
export async function run(
state: WorkflowState,
context: Message[] = [],
workflow: Workflow
): Promise<WorkflowState> {
if (state.messages.length > workflow.maxIterations) {
return childState({
...state,
agent: 'finalBoss',
})
}
if (state.children.length > 0) {
const children = await Promise.all(
state.children.map((child) => run(child, context.concat(state.messages), workflow))
)
if (children.every((child) => child.status === 'finished')) {
return {
...state,
messages: state.messages.concat(children.flatMap((child) => child.messages)),
children: [],
}
}
return {
...state,
children,
}
}
const agent = workflow.team[state.agent]
if (state.status === 'paused') {
const toolsResponse = await runTools(state, context, workflow)
return {
...state,
status: 'running',
messages: state.messages.concat(toolsResponse),
}
}
if (state.status === 'running' || state.status === 'idle') {
try {
return agent.run(state, context, workflow)
} catch (error) {
return finish(state, response(error instanceof Error ? error.message : 'Unknown error'))
}
}
return state
}
/**
* Iterates over the workflow and takes a snapshot of the state after each iteration.
*/
export async function iterate(workflow: Workflow, state: WorkflowState) {
const nextState = await run(state, [], workflow)
workflow.snapshot({ prevState: state, nextState })
return nextState
}