Skip to main content
Prerequisites: Quick Start complete, pip install mellea, Ollama running locally.
Concept overview: Context and Sessions explains the architecture and design.
MelleaSession is a regular Python class. You can subclass it to add custom behavior to any session method — input filtering, output validation, logging, rate limiting, or anything else you need to inject consistently across all calls.

Context types

Before customizing a session, it helps to understand the two built-in context types:
  • SimpleContext (default) — resets the chat history on each model call. The model sees only the current instruction and its requirements. This is the right default for most instruct() use cases.
  • ChatContext — preserves the message history across calls. The model sees all previous turns. Use this for multi-turn conversations and for chat().

Inspecting context

The ctx object exposes helpers for reading the current session state:

Branching context with clone()

clone() creates a copy of the session at its current context state. Both clones start from the same history and then diverge independently. This is useful for exploring multiple continuations of the same conversation:
Both m1 and m2 have the Multiply 2x2 exchange in their history when they start. They each produce independent answers to their respective follow-up questions.

Resetting a session

To clear a session’s context without creating a new session object:
This calls ctx.reset_to_new() on the current context, discarding all prior history while keeping the session’s backend and other configuration intact.

Extending MelleaSession

Subclass MelleaSession and override any method to inject custom behavior. The example below gates all incoming chat messages through Guardian Intrinsics safety checks:
A few things to note:
  • LocalHFBackend loads the Guardian model weights on instantiation — create one instance and pass it in to avoid reloading on every session.
  • guardian_check() returns a float score from 0.0 (safe) to 1.0 (risk). Values at or above 0.5 indicate risk detected.
  • scoring_schema="user_prompt" tells Guardian to evaluate the last user message rather than the assistant response (the default, "assistant_response").
  • Neither the blocked message nor the rejection reply is added to the chat context, so the conversation history stays clean.

What you can override

You can override any public method on MelleaSession. The most commonly overridden methods are:
Note: When you override a method, call super() unless you intentionally want to replace the default behaviour entirely. The base methods handle context management and telemetry instrumentation. Full example: docs/examples/sessions/creating_a_new_type_of_session.py