agentLoop function
AgentEventStream
agentLoop({
- required List<
Message> prompts, - required Context context,
- required AgentLoopConfig config,
- required StreamFunction streamFunction,
- required ToolExecutor toolExecutor,
- CancelToken? cancelToken,
Starts an agent loop with new prompt messages.
The prompts are appended to context and announced with
MessageStartEvent/MessageEndEvent; the loop then streams the model,
executes tool calls via toolExecutor, and re-invokes the model until it
stops calling tools, fails, or cancelToken is cancelled. Provider
failures never throw (errors-as-events): they end the loop with an
assistant message whose AssistantMessage.stopReason is
StopReason.error or StopReason.aborted.
The returned AgentEventStream replays all events to a late listener and its EventStream.result resolves with the messages produced by the run.
context is copied defensively; the loop mutates only its own copy.
Implementation
AgentEventStream agentLoop({
required List<Message> prompts,
required Context context,
required AgentLoopConfig config,
required StreamFunction streamFunction,
required ToolExecutor toolExecutor,
CancelToken? cancelToken,
}) {
final stream = AgentEventStream();
_drive(
stream,
runAgentLoop(
prompts: prompts,
context: context,
config: config,
emit: stream.push,
streamFunction: streamFunction,
toolExecutor: toolExecutor,
cancelToken: cancelToken,
),
);
return stream;
}