mellea.stdlib.components.chat
Chat primitives: the Message and ToolMessage components.
Defines Message, the Component subtype used to represent a single turn in a
chat history with a role (user, assistant, system, or tool),
text content, and optional images and documents attachments. Also provides
ToolMessage (a Message subclass that carries the tool name and arguments), and
utilities for converting a Context into a flat list of Message objects:
as_chat_history (strict typing) and as_generic_chat_history (flexible with
configurable formatter).
Functions
FUNC message_from_template_representation
message_from_template_representation(tr: TemplateRepresentation) -> Message
Build a Message from a component's TemplateRepresentation.
Shared by ChatFormatter.to_chat_messages and as_generic_chat_history so a
component's declared role and tool metadata are honored consistently across both
conversion paths. The representation's role overrides default_role when set;
role validation is deferred to Message, which raises ValueError for anything
outside Message.Role. thinking, tool_calls, and (for role="tool")
tool_call_id are carried onto the resulting message.
Args:
tr: The template representation returned by the component'sformat_for_llm.default_role: The positional role guess to use whentr.roleisNone.content: The already-rendered text content for the message.
Returns:
- A
Messagewith the resolved role, content, attachments, and tool metadata.
FUNC as_chat_history
as_chat_history(ctx: Context) -> list[Message]
Returns a list of Messages corresponding to a Context.
Args:
ctx: A linearContextwhose entries areMessageorModelOutputThunkobjects withMessageparsed representations.
Returns:
- List of
Messageobjects in conversation order.
Raises:
ValueError: If the context history is non-linear and cannot be cast to a flat list.AssertionError: If any entry in the context cannot be converted to aMessage.
FUNC as_generic_chat_history
as_generic_chat_history(ctx: Context, formatter: Callable[[object], str] | None = None) -> list[Message]
Returns a list of Messages corresponding to a Context, with flexible type handling.
This function is more permissive than as_chat_history(), allowing arbitrary
component types. Unknown types are converted to strings using a configurable
formatter, making it suitable for general-purpose use where context composition
may be heterogeneous.
The formatter is applied to:
ModelOutputThunkwith non-Messageparsed_reprCBlocksubclasses (subclasses only; plainCBlockis stringified)- Other unknown component types
Existing Message objects are preserved as-is; their content is not formatted.
This design preserves Message fidelity while providing an escape hatch for unknown types.
Args:
ctx: A linearContextthat may containMessage,ModelOutputThunk, or otherComponenttypes.formatter: Optional callable that converts unknown types to strings. Defaults to_default_formatterwhich logs a warning and stringifies.
Returns:
- List of
Messageobjects in conversation order.
Raises:
ValueError: If the context history is non-linear and cannot be cast to a flat list.
Classes
CLASS Message
A single Message in a Chat history.
Args:
role: The role that this message came from (e.g.,"user","assistant").content: The content of the message.images: Optional images associated with the message. UseImageBlockfor base64-encoded images (supported by all vision backends) orImageUrlBlockfor URL-referenced images (passed directly to OpenAI-compatible backends; backends that require base64, such as Ollama, download and encode the image automatically).audio: Optional audio associated with the message.documents: Optional documents associated with the message.tool_calls: Optional OpenAI-compatible assistant tool calls associated with the message.tool_call_id: Optional provider-supplied tool-call id that arole="tool"message references, so a tool-result turn can be linked back to the assistant tool call that produced it (issue #1389).ToolMessagesources this from itsModelToolCallinstead; set it directly only when constructing a barerole="tool"Message.thinking: Optional reasoning trace produced by a thinking model on the turn that generated this message. Populated by_parsefromModelOutputThunk.thinking; carried throughas_chat_historyso backends can round-trip it on subsequent turns per their replay policy.Noneor empty for messages that carry no reasoning (e.g. user turns, or assistant turns from non-thinking models); the replay policy and serializers treat both falsy cases identically.
Attributes:
Role: Type alias for the allowed role literals:"system","user","assistant", or"tool".
Methods:
FUNC images
images(self) -> None | list[ImageBlock | ImageUrlBlock]
Returns the images associated with this message.
FUNC audio
audio(self) -> None | list[AudioBlock | AudioUrlBlock]
Returns the audio associated with this message.
FUNC tool_calls
tool_calls(self) -> list[dict[str, Any]] | None
Returns the OpenAI-compatible tool calls associated with this message.
FUNC tool_call_id
tool_call_id(self) -> str | None
Returns the tool-call id this role="tool" message references, if any.
FUNC parts
parts(self) -> list[Span]
Return the constituent parts of this message, including content, documents, images, and audio.
Returns:
- list[Span]: A list beginning with the content block,
- followed by any attached documents, image blocks, and audio blocks.
FUNC format_for_llm
format_for_llm(self) -> TemplateRepresentation
Formats the content for a Language Model.
Declares this message's role and carries its thinking, tool_calls,
and tool_call_id so the representation is a faithful, self-describing
view of the message (see message_from_template_representation).
Returns:
- The formatted output suitable for language models.
CLASS ToolMessage
Adds the name field for function name.
Args:
role: The role of this message; most backends use"tool".content: The content of the message; should be a stringified version oftool_output.tool_output: The output of the tool or function call.name: The name of the tool or function that was called.args: The arguments passed to the tool.tool: TheModelToolCallrepresentation.
Attributes:
arguments: The arguments that were passed to the tool; stored from theargsconstructor parameter.