Lesson 5: Session lifecycle & engine loop
What happens per turn
From internal-docs/picoflow-engine.md, every /ai/run turn looks like:
FlowEngineloads the session byCHAT_SESSION_ID(or creates one).- The active step is hydrated with its own memory slice.
- The step prompt + tools are sent to the model.
- Tool calls are executed; handlers may change state or request a step transition.
- State, memory,
sequence, and logs are persisted to the document DB. - The response is streamed back to the caller.
Because state is persisted, any container can serve the next turn.
Why this flow is simple to trace
- Deterministic ordering:
medical-flow.tslists steps in one array, so transitions are predictable. - Tool-directed transitions: handlers return
{ step, state, tool }, making control changes explicit. - Memory scoping: each step uses its own memory key (see
.useMemory('end')onEndStep). This keeps prompts clean and debuggable. - Retry guardrails:
FlowEnginewill retry empty/invalid model outputs (as described in the engine doc), so you rarely need custom retry code.
Session document quick check
When you run the bot with Mongo/Cosmos enabled, each turn appends to the session doc:
messagesgrouped by stepstateblobs per step (symptoms, doctors, booking confirmation)sequencearray showing step transitions
Use this to audit what the model saw and what tools returned before shipping changes.