MelleaSession: the primary entry point for running generative programs.
MelleaSession wraps a [Backend](../core/backend#class-backend) and a [Context](../core/base#class-context) and exposes high-level methods
(act, instruct, sample) that drive the generate-validate-repair loop. It
also manages a global context variable (accessible via get_session()) so that
nested components can reach the current session without explicit threading. Use
start_session(...) as a context manager to create and automatically clean up a
session.
Functions
FUNC get_session
- The currently active
MelleaSession.
RuntimeError: If no session is currently active.
FUNC backend_name_to_class
name: Short backend name, e.g."ollama","hf","openai","watsonx", or"litellm".
- The corresponding
[Backend](../core/backend#class-backend)class, orNoneif the name is unrecognised.
ImportError: If the requested backend has optional dependencies that are not installed (e.g.mellea[hf],mellea[watsonx], ormellea[litellm]).
FUNC start_session
with statement), it automatically
sets the session as the current active session for use with convenience functions
like instruct(), chat(), query(), and transform(). When called directly,
it returns a session object that can be used directly.
Args:
backend_name: The backend to use. Options are:- “ollama”: Use Ollama backend for local models
- “hf” or “huggingface”: Use HuggingFace transformers backend
- “openai”: Use OpenAI API backend
- “watsonx”: Use IBM WatsonX backend
- “litellm”: Use the LiteLLM backend
model_id: Model identifier or name. Can be aModelIdentifierfrom mellea.backends.model_ids or a string model name.ctx: Context manager for conversation history. Defaults to SimpleContext(). Use ChatContext() for chat-style conversations.model_options: Additional model configuration options that will be passed to the backend (e.g., temperature, max_tokens, etc.).plugins: Optional list of plugins scoped to this session. Accepts@hook-decorated functions,@plugin-decorated class instances,MelleaPlugininstances, or[PluginSet](../plugins/pluginset#class-pluginset)instances.**backend_kwargs: Additional keyword arguments passed to the backend constructor.
- A session object that can be used as a context manager
- or called directly with session methods.
Exception: Ifbackend_nameis not one of the recognised backend identifiers.ImportError: If the requested backend requires optional dependencies that are not installed.
Classes
CLASS MelleaSession
Mellea sessions are a THIN wrapper around m convenience functions with NO special semantics.
Using a Mellea session is not required, but it does represent the “happy path” of Mellea programming. Some nice things about ussing a MelleaSession:
- In most cases you want to keep a Context together with the Backend from which it came.
- You can directly run an instruction or a send a chat, instead of first creating the
InstructionorChatobject and then later calling backend.generate on the object. - The context is “threaded-through” for you, which allows you to issue a sequence of commands instead of first calling backend.generate on something and then appending it to your context.
MelleaSessions and managing your Context and Backend directly.
Note: we put the instruct, validate, and other convenience functions here instead of in Context or Backend to avoid import resolution issues.
Args:
backend: The backend to use for all model inference in this session.ctx: The conversation context. Defaults to a newSimpleContextifNone.
ctx: The active conversation context; neverNone(defaults to a freshSimpleContextwhenNoneis passed). Updated after every call that produces model output.id: Unique session UUID assigned at construction.
FUNC clone
- a copy of the current session. Keeps the context, backend, and session logger.
FUNC reset
SESSION_RESET plugin hook if any plugins are registered, then
replaces self.ctx with the result of ctx.reset_to_new(), discarding
all accumulated conversation history.
FUNC cleanup
FUNC act
FUNC act
FUNC act
action: the Component from which to generate.requirements: used as additional requirements when a sampling strategy is providedstrategy: a SamplingStrategy that describes the strategy for validating and repairing/retrying for the instruct-validate-repair pattern. None means that no particular sampling strategy is used.return_sampling_results: attach the (successful and failed) sampling attempts to the results.format: if set, the BaseModel to use for constrained decoding.model_options: additional model options, which will upsert into the model/backend’s defaults.tool_calls: if true, tool calling is enabled.
- A ModelOutputThunk if
return_sampling_resultsisFalse, else returns aSamplingResult.
FUNC instruct
FUNC instruct
FUNC instruct
description: The description of the instruction.requirements: A list of requirements that the instruction can be validated against.icl_examples: A list of in-context-learning examples that the instruction can be validated against.grounding_context: A list of grounding contexts that the instruction can use. They can bind as variables using a (key: str, value: str | ContentBlock) tuple.user_variables: A dict of user-defined variables used to fill in Jinja placeholders in other parameters. This requires that all other provided parameters are provided as strings.prefix: A prefix string or ContentBlock to use when generating the instruction.output_prefix: A string or ContentBlock that defines a prefix for the output generation. Usually you do not need this.strategy: A SamplingStrategy that describes the strategy for validating and repairing/retrying for the instruct-validate-repair pattern. None means that no particular sampling strategy is used.return_sampling_results: attach the (successful and failed) sampling attempts to the results.format: If set, the BaseModel to use for constrained decoding.model_options: Additional model options, which will upsert into the model/backend’s defaults.tool_calls: If true, tool calling is enabled.images: A list of images to be used in the instruction or None if none.
- A
[ModelOutputThunk](../core/base#class-modeloutputthunk)ifreturn_sampling_resultsisFalse, - else a
[SamplingResult](../core/sampling#class-samplingresult).
FUNC chat
content: The message text to send.role: The role for the outgoing message (default"user").images: Optional list of images to include in the message.user_variables: Optional Jinja variable substitutions applied tocontent.format: Optional Pydantic model for constrained decoding of the response.model_options: Additional model options to merge with backend defaults.tool_calls: If true, tool calling is enabled.
- The assistant
Messageresponse.
FUNC validate
reqs: A single[Requirement](../core/requirement#class-requirement)or a list of them to validate.output: Optional model output[CBlock](../core/base#class-cblock)to validate against instead of the context.format: Optional Pydantic model for constrained decoding.model_options: Additional model options to merge with backend defaults.generate_logs: Optional list to append generation logs to.input: Optional input[CBlock](../core/base#class-cblock)to include alongsideoutputwhen validating.
- List of
[ValidationResult](../core/requirement#class-validationresult)objects, one per requirement.
FUNC query
obj: The object to be queried. It should be an instance of MObject or can be converted to one if necessary.query: The string representing the query to be executed against the object.format: format for output parsing.model_options: Model options to pass to the backend.tool_calls: If true, the model may make tool calls. Defaults to False.
- The result of the query as processed by the backend.
FUNC transform
obj: The object to be queried. It should be an instance of MObject or can be converted to one if necessary.transformation: The string representing the query to be executed against the object.format: format for output parsing; usually not needed with transform.model_options: Model options to pass to the backend.
- ModelOutputThunk|Any: The result of the transformation as processed by the backend. If no tools were called,
- the return type will be always be ModelOutputThunk. If a tool was called, the return type will be the return type
- of the function called, usually the type of the object passed in.
FUNC aact
FUNC aact
FUNC aact
action: the Component from which to generate.requirements: used as additional requirements when a sampling strategy is providedstrategy: a SamplingStrategy that describes the strategy for validating and repairing/retrying for the instruct-validate-repair pattern. None means that no particular sampling strategy is used.return_sampling_results: attach the (successful and failed) sampling attempts to the results.format: if set, the BaseModel to use for constrained decoding.model_options: additional model options, which will upsert into the model/backend’s defaults.tool_calls: if true, tool calling is enabled.
- A ModelOutputThunk if
return_sampling_resultsisFalse, else returns aSamplingResult.
FUNC ainstruct
FUNC ainstruct
FUNC ainstruct
description: The description of the instruction.requirements: A list of requirements that the instruction can be validated against.icl_examples: A list of in-context-learning examples that the instruction can be validated against.grounding_context: A list of grounding contexts that the instruction can use. They can bind as variables using a (key: str, value: str | ContentBlock) tuple.user_variables: A dict of user-defined variables used to fill in Jinja placeholders in other parameters. This requires that all other provided parameters are provided as strings.prefix: A prefix string or ContentBlock to use when generating the instruction.output_prefix: A string or ContentBlock that defines a prefix for the output generation. Usually you do not need this.strategy: A SamplingStrategy that describes the strategy for validating and repairing/retrying for the instruct-validate-repair pattern. None means that no particular sampling strategy is used.return_sampling_results: attach the (successful and failed) sampling attempts to the results.format: If set, the BaseModel to use for constrained decoding.model_options: Additional model options, which will upsert into the model/backend’s defaults.tool_calls: If true, tool calling is enabled.images: A list of images to be used in the instruction or None if none.
- A
[ModelOutputThunk](../core/base#class-modeloutputthunk)ifreturn_sampling_resultsisFalse, - else a
[SamplingResult](../core/sampling#class-samplingresult).
FUNC achat
content: The message text to send.role: The role for the outgoing message (default"user").images: Optional list of images to include in the message.user_variables: Optional Jinja variable substitutions applied tocontent.format: Optional Pydantic model for constrained decoding of the response.model_options: Additional model options to merge with backend defaults.tool_calls: If true, tool calling is enabled.
- The assistant
Messageresponse.
FUNC avalidate
reqs: A single[Requirement](../core/requirement#class-requirement)or a list of them to validate.output: Optional model output[CBlock](../core/base#class-cblock)to validate against instead of the context.format: Optional Pydantic model for constrained decoding.model_options: Additional model options to merge with backend defaults.generate_logs: Optional list to append generation logs to.input: Optional input[CBlock](../core/base#class-cblock)to include alongsideoutputwhen validating.
- List of
[ValidationResult](../core/requirement#class-validationresult)objects, one per requirement.
FUNC aquery
obj: The object to be queried. It should be an instance of MObject or can be converted to one if necessary.query: The string representing the query to be executed against the object.format: format for output parsing.model_options: Model options to pass to the backend.tool_calls: If true, the model may make tool calls. Defaults to False.
- The result of the query as processed by the backend.
FUNC atransform
obj: The object to be queried. It should be an instance of MObject or can be converted to one if necessary.transformation: The string representing the query to be executed against the object.format: format for output parsing; usually not needed with transform.model_options: Model options to pass to the backend.
- ModelOutputThunk|Any: The result of the transformation as processed by the backend. If no tools were called,
- the return type will be always be ModelOutputThunk. If a tool was called, the return type will be the return type
- of the function called, usually the type of the object passed in.
FUNC powerup
powerup_cls to MelleaSession.
Iterates over all functions defined on powerup_cls and attaches each
one as a method on the MelleaSession class, effectively extending
the session with domain-specific helpers at runtime.
Args:
powerup_cls: A class whose functions should be added toMelleaSessionas instance methods.
FUNC last_prompt
- A string if the last prompt was a raw call to the model OR a list of messages (as role-msg-dicts). Is None if none could be found.