liveBook · Manning

Session

As explained in Build an AI Agent (From Scratch)

A session is a persistent stateful container that associates conversation history, events, and execution state with a particular conversation identifier across agent runs.

A session holds conversation history and execution state across multiple agent run() calls. Reusing a session_id lets a later call continue the same conversation instead of starting without earlier context. A session outlives the ExecutionContext for any single run; long-term memory, by contrast, retains selected knowledge across sessions. section 6.3.1 section 6.1.2

A Session contains:

  • session_id and an optional user_id, identifying the conversation and user. section 6.3.1
  • events, accumulated across runs, including conversation history and execution events. section 6.3.1 section 6.1.2
  • state, a flexible dictionary for intermediate execution data, such as a pending tool call or task progress. section 6.3.1
  • created_at and updated_at timestamps. section 6.3.1
Listing 6.8 Session class design
class Session(BaseModel):
    """Container for persistent conversation state across multiple run() calls."""

    session_id: str
    user_id: str | None = None
    events: list[Event] = Field(default_factory=list)
    state: dict[str, Any] = Field(default_factory=dict)
    created_at: datetime = Field(default_factory=datetime.now)
    updated_at: datetime = Field(default_factory=datetime.now)

The Session model defines the persistent container and its default fields. section 6.3.1

SessionManager separates the container from storage. Its asynchronous interface creates, retrieves, and saves sessions; get_or_create() combines retrieval and creation. InMemorySessionManager uses a Python dictionary, rejects duplicate IDs on creation, and returns None for missing IDs. It is useful for testing and single-process applications, but its sessions disappear when the program terminates. A database-backed implementation can provide persistent storage instead. section 6.3.2 section 6.3.4

To integrate sessions, run() accepts a session_id and loads or creates the corresponding session. ExecutionContext holds references to the session and manager; its events and state properties expose the session’s fields so existing code can keep using context.events and context.state. After execution, the manager saves the session. section 6.3.3

Listing 6.13 run() method with session support
async def run(
    self, 
    user_input: str,
    session_id: str | None = None,
    context: ExecutionContext | None = None,
) -> AgentResult:
    """Execute the agent with optional session support."""

    # Load or create session if session_id is provided
    session = None
    if session_id:
        session = await self.session_manager.get_or_create(session_id)

    # Create context with session support
    if context is None:
        context = ExecutionContext(
            session=session,
            session_manager=self.session_manager,
        )

    # Existing run() logic...

    # Save session if available
    if session:
        await self.session_manager.save(session)

    return AgentResult(output=context.final_result, context=context)

The run() flow shows where the session is loaded, attached to a new execution context, and saved. section 6.3.3

Continuing a conversation

A first call stores Alice’s name and occupation under alice_session. A second call with the same ID retrieves the earlier events, so the agent can answer a question about both. Without an ID, or with different IDs, the calls do not share that conversation. section 6.3.4

Sessions also support asynchronous human approval. When a tool requires confirmation, the agent can save pending execution state and return; once approval arrives, it restores the state and resumes. For database or JSON storage, pending models can be converted with model_dump() and reconstructed with model_validate(). section 6.3 section 6.3.5

# Saving: when pending occurs in act()
pending_calls = [PendingToolCall(tool_call=tc, confirmation_message=msg)]
context.state["pending_tool_calls"] = [p.model_dump() for p in pending_calls]

# Restoring: when resuming run()
raw_pending = context.state.get("pending_tool_calls", [])
pending_calls = [PendingToolCall.model_validate(d) for d in raw_pending]

Pending tool calls are stored as dictionaries in session state and reconstructed when execution resumes. section 6.3.5

A session preserves history, but accumulated events can still make model context too large. Sliding windows, compaction, and summarization can reduce the context presented to the model as conversations grow. section 6.1.3

How Build an AI Agent (From Scratch) covers it

How deep it goes
Implements the container, manager, and agent integration, while suggesting rather than implementing database-backed storage.
Examples
Uses a name-and-occupation conversation and a pending tool-confirmation workflow to illustrate shared history and resumable state.
What it assumes
Builds on an existing agent and ExecutionContext while defining Session and SessionManager explicitly.
What you can do after
Build sessions and an in-memory manager from scratch, then integrate them into an agent’s run flow.
How it connects
Connects sessions to execution context, short-term memory, long-term memory, and human-in-the-loop approval.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build an AI Agent (From Scratch). The section links point to the parts of the book it draws on.