Skip to content

pi_llm_agent.agent_loop

agent_loop

Agent loop — the core execution engine.

Implements the multi-turn loop: prompt → LLM → tool calls → repeat.

agent_loop(prompts, context, config, cancellation=None, stream_fn=None)

Start the agent loop and return an event stream.

Runs in a background asyncio task. Use async for event in stream to consume events.

Parameters:

Name Type Description Default
prompts list[Any]

Initial prompt messages.

required
context AgentContext

Agent context snapshot.

required
config AgentLoopConfig

Loop configuration.

required
cancellation CancellationToken | None

Optional cancellation token.

None
stream_fn StreamFn | None

Optional custom stream function.

None

Returns:

Type Description
EventStream[AgentEvent, list[Any]]

An async iterable EventStream of AgentEvent.

agent_loop_continue(context, config, cancellation=None, stream_fn=None)

Continue the agent loop from existing context. Returns an event stream.

The last message in context must be user or toolResult.

run_agent_loop(prompts, context, config, emit, cancellation=None, stream_fn=None) async

Start the agent loop with prompt messages.

This is the direct async entry point (no background task). Used by the Agent class internally.

Returns:

Type Description
list[Any]

List of all new messages added during the run.

run_agent_loop_continue(context, config, emit, cancellation=None, stream_fn=None) async

Continue the agent loop from existing context (direct async).

Returns:

Type Description
list[Any]

List of all new messages added during the run.