> ## 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.helpers.openai_compatible_helpers

> A file for helper functions that deal with OpenAI API compatible helpers.

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 />

A file for helper functions that deal with OpenAI API compatible helpers.

## 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> `extract_model_tool_requests` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/helpers/openai_compatible_helpers.py#L43" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
extract_model_tool_requests(tools: dict[str, AbstractMelleaTool], response: dict[str, Any]) -> dict[str, ModelToolCall] | None
```

Extract tool calls from the dict representation of an OpenAI-like chat response object.

**Args:**

* `tools`: Mapping of tool name to `AbstractMelleaTool` for lookup.
* `response`: Dict representation of an OpenAI-compatible chat completion message
  (must contain a `"message"` key).

**Returns:**

* Mapping of tool name to [`ModelToolCall`](../core/base#class-modeltoolcall) for each requested tool call, or
* `None` if no tool calls were found.

<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> `chat_completion_delta_merge` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/helpers/openai_compatible_helpers.py#L85" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
chat_completion_delta_merge(chunks: list[dict], force_all_tool_calls_separate: bool = False) -> dict
```

Merge a list of deltas from `ChatCompletionChunk`s into a single dict representing the `ChatCompletion` choice.

**Args:**

* `chunks`: The list of dicts that represent the message deltas.
* `force_all_tool_calls_separate`: If `True`, tool calls in separate message
  deltas will not be merged even if their index values are the same. Use
  when providers do not return the correct index value for tool calls; all
  tool calls must then be fully populated in a single delta.

**Returns:**

* A single merged dict representing the assembled `ChatCompletion` choice,
* with `finish_reason`, `index`, and a `message` sub-dict containing
* `content`, `role`, and `tool_calls`.

<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> `message_to_openai_message` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/helpers/openai_compatible_helpers.py#L173" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
message_to_openai_message(msg: Message, formatter: Formatter | None = None) -> dict
```

Serialise a Mellea `Message` to the format required by OpenAI-compatible API providers.

**Args:**

* `msg`: The `Message` object to serialise.
* `formatter`: Optional formatter used to render the message content (including
  documents) through the template system. When `None`, uses the raw
  `msg.content` string without document rendering.

**Returns:**

* A dict with `"role"` and `"content"` fields. When the message carries
* images, `"content"` is a list of text and image-URL dicts; otherwise it
* is a plain string.

<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> `messages_to_docs` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/helpers/openai_compatible_helpers.py#L220" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
messages_to_docs(msgs: list[Message]) -> list[dict[str, str]]
```

Extract all `Document` objects from a list of `Message` objects.

**Args:**

* `msgs`: List of `Message` objects whose `_docs` attributes are inspected.

**Returns:**

* A list of dicts, each with a `"text"` key and optional `"title"` and
* `"doc_id"` keys, suitable for passing to an OpenAI-compatible RAG API.

<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> `build_completion_usage` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/helpers/openai_compatible_helpers.py#L246" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
build_completion_usage(output: ModelOutputThunk) -> CompletionUsage | None
```

Build a normalized usage object from a model output, if available.

**Args:**

* `output`: Model output object whose `generation.usage` mapping contains
  token counts.

**Returns:**

* A `CompletionUsage` object when usage metadata is present on the
* output, otherwise `None`.

<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> `has_tool_calls` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/helpers/openai_compatible_helpers.py#L272" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
has_tool_calls(output: ModelOutputThunk) -> bool
```

Check if a model output has tool calls.

**Args:**

* `output`: Model output thunk that may expose a `tool_calls` mapping.

**Returns:**

* `True` if the output has non-empty tool calls, `False` otherwise.

<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> `build_tool_calls` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/helpers/openai_compatible_helpers.py#L289" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
build_tool_calls(output: ModelOutputThunk) -> list[ToolCallDict] | None
```

Build OpenAI-compatible tool calls from a model output, if available.

**Args:**

* `output`: Model output thunk that may expose a `tool_calls` mapping.

**Returns:**

* List of `ToolCallDict` objects when tool calls are present,
* otherwise `None`.

<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> `ToolCallFunction` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/helpers/openai_compatible_helpers.py#L15" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

Function details in a tool call.

<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> `ToolCallDict` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/helpers/openai_compatible_helpers.py#L22" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

OpenAI-compatible tool call dictionary with ID and function.

<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> `CompletionUsage` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/helpers/openai_compatible_helpers.py#L30" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

Token usage statistics for a completion request.

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