Skip to main content

Function: loopWithState()

loopWithState<TBot, TCustomState, TResult>(bot, config): Processable<unknown, { history: TResult[]; result: TResult; state: TCustomState; }>

Defined in: core/dist/types/graph/loop-with-state.d.ts:82

Repeat a body until a condition stops it, threading custom state.

repeat() is the same iteration without the state: this adds the mutable bag a condition and its handlers read and write through LoopContext, and returns it alongside the result.

The state starts as a shallow copy of the input when the input is a plain object, which is what lets a caller seed it.

history comes back with the result rather than living on the loop. The class exposed it through getHistory() / getIterationCount(), which read whatever the last .process() call left behind — so two concurrent runs of one loop overwrote each other's. Returning it makes it per-invocation.

Type Parameters

TBot

TBot extends Processable<unknown, unknown>

TCustomState

TCustomState extends Record<string, unknown> = Record<string, unknown>

TResult

TResult = unknown

Parameters

bot

TBot

config

LoopConfig<TResult, TCustomState>

Returns

Processable<unknown, { history: TResult[]; result: TResult; state: TCustomState; }>

Example

const refine = loopWithState(draftBot, {
condition: (draft, ctx) => ctx.iteration < 5 && !draft.approved,
maxIterations: 5,
});
const { result, state } = await refine.process(brief);