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 mostinstruct()use cases.ChatContext— preserves the message history across calls. The model sees all previous turns. Use this for multi-turn conversations and forchat().
Inspecting context
Thectx 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:
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: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 a Guardian safety check:
reqify()normalisesstr | RequirementintoRequirementobjects, so you can pass plain strings alongsideGuardianCheckinstances.self.validate()is the same method you would call on a plainMelleaSession. Passoutput=CBlock(content)to validate against a specific text block rather than the last model output.- 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 onMelleaSession. The most commonly overridden
methods are:
| Method | Typical use |
|---|---|
chat() | Input/output filtering, logging |
instruct() | Custom default requirements or strategies |
validate() | Centralised validation reporting |
__enter__ / __exit__ | Custom session lifecycle hooks |
Note: When you override a method, callsuper()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