> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mellea.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# mellea.stdlib.components.chat

> Chat primitives: the `Message` and `ToolMessage` components.

export const SidebarFix = () => <script dangerouslySetInnerHTML={{
  __html: `
        (function () {
          const INTERVAL_MS = 500;

          const upgradeSidebar = () => {
            const links = document.querySelectorAll('a[href^="#"]');

            links.forEach((link) => {
              if (link.dataset.badged === "true") return;

              const rawText = (link.textContent || "").trim();

              // ========== FUNC ==========
              if (rawText.startsWith("FUNC ")) {
                const label = rawText.replace(/^FUNC\\s+/, "").trim();

                while (link.firstChild) link.removeChild(link.firstChild);

                // 👉 Make the whole link a single flex row & prevent wrapping
                link.style.display = "flex";
                link.style.alignItems = "center";
                link.style.whiteSpace = "nowrap";
                link.style.columnGap = "0.5rem";

                const badge = document.createElement("span");
                badge.style.marginRight = "0.5rem";
                badge.style.display = "inline-flex";
                badge.style.alignItems = "center";
                badge.style.borderRadius = "9999px";
                badge.style.padding = "0rem 0.6rem";
                badge.style.fontSize = "0.5rem";
                badge.style.fontWeight = "700";
                badge.style.letterSpacing = "0.05em";
                badge.style.backgroundColor = "rgba(48, 100, 227, 0.20)";
                badge.style.color = "#1D4ED8";

                badge.textContent = "FUNC";

                link.appendChild(badge);
                link.appendChild(document.createTextNode(label));
                link.dataset.badged = "true";
                return;
              }

              // ========== CLASS ==========
              if (rawText.startsWith("CLASS ")) {
                const label = rawText.replace(/^CLASS\\s+/, "").trim();

                while (link.firstChild) link.removeChild(link.firstChild);

                // 👉 Same flex / nowrap treatment for class links
                link.style.display = "flex";
                link.style.alignItems = "center";
                link.style.whiteSpace = "nowrap";
                link.style.columnGap = "0.5rem";

                const badge = document.createElement("span");
                badge.style.marginRight = "0.5rem";
                badge.style.display = "inline-flex";
                badge.style.alignItems = "center";
                badge.style.borderRadius = "9999px";
                badge.style.padding = "0rem 0.6rem";
                badge.style.fontSize = "0.5rem";
                badge.style.fontWeight = "700";
                badge.style.letterSpacing = "0.05em";
                badge.style.backgroundColor = "rgba(74, 222, 128, 0.20)";
                badge.style.color = "#15803D";

                badge.textContent = "CLASS";

                link.appendChild(badge);
                link.appendChild(document.createTextNode(label));
                link.dataset.badged = "true";
                return;
              }
            });
          };

          upgradeSidebar();
          setInterval(upgradeSidebar, INTERVAL_MS);
        })();
      `
}} />;

<SidebarFix />

Chat primitives: the `Message` and `ToolMessage` components.

Defines `Message`, the [`Component`](../../core/base#class-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`](../../core/base#class-context) into a flat list of `Message` objects:
`as_chat_history` (strict typing) and `as_generic_chat_history` (flexible with
configurable formatter).

## Functions

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `as_chat_history` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/stdlib/components/chat.py#L226" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
as_chat_history(ctx: Context) -> list[Message]
```

Returns a list of Messages corresponding to a Context.

**Args:**

* `ctx`: A linear [`Context`](../../core/base#class-context) whose entries are `Message` or [`ModelOutputThunk`](../../core/base#class-modeloutputthunk)
  objects with `Message` parsed representations.

**Returns:**

* List of `Message` objects 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 a
  `Message`.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `as_generic_chat_history` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/stdlib/components/chat.py#L277" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
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:

* [`ModelOutputThunk`](../../core/base#class-modeloutputthunk) with non-Message `parsed_repr`
* [`CBlock`](../../core/base#class-cblock) subclasses (subclasses only; plain [`CBlock`](../../core/base#class-cblock) is 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 linear [`Context`](../../core/base#class-context) that may contain `Message`, [`ModelOutputThunk`](../../core/base#class-modeloutputthunk),
  or other [`Component`](../../core/base#class-component) types.
* `formatter`: Optional callable that converts unknown types to strings.
  Defaults to `_default_formatter` which logs a warning and stringifies.

**Returns:**

* List of `Message` objects in conversation order.

**Raises:**

* `ValueError`: If the context history is non-linear and cannot be cast to a
  flat list.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

## Classes

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#4ADE8033]/20 text-[#15803D]">CLASS</span> `Message` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/stdlib/components/chat.py#L30" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

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.
* `documents`: Optional documents associated with
  the message.

**Attributes:**

* `Role`: Type alias for the allowed role literals: `"system"`,
  `"user"`, `"assistant"`, or `"tool"`.

<div className="h-8" />

**Methods:**

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `images` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/stdlib/components/chat.py#L65" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
images(self) -> None | list[str]
```

Returns the images associated with this message as list of base 64 strings.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `parts` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/stdlib/components/chat.py#L71" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
parts(self) -> list[Component | CBlock]
```

Return the constituent parts of this message, including content, documents, and images.

**Returns:**

* list\[Component | CBlock]: A list beginning with the content block,
* followed by any attached documents and image blocks.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `format_for_llm` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/stdlib/components/chat.py#L85" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
format_for_llm(self) -> TemplateRepresentation
```

Formats the content for a Language Model.

**Returns:**

* The formatted output suitable for language models.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#4ADE8033]/20 text-[#15803D]">CLASS</span> `ToolMessage` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/stdlib/components/chat.py#L188" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

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 of `tool_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`: The [`ModelToolCall`](../../core/base#class-modeltoolcall) representation.

**Attributes:**

* `arguments`: The arguments that were passed to the
  tool; stored from the `args` constructor parameter.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />
