---
title: msg_parts
description: The canonical LLM message model - `Msg` and the `Part` classes - and
  its formatted text form
---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

[`Msg`](msg_parts.md#msg) and the [`Part`](msg_parts.md#part) subclasses describe LLM conversations without tying them to a provider. `fastllm` uses these types for its chat clients. Dialog libraries, transcript tools, and compaction code can use them without importing an LLM client. This module depends on `fastcore`.

Use [`mk_msg`](msg_parts.md#mk_msg) and [`mk_msgs`](msg_parts.md#mk_msgs) to build messages from ordinary Python values. Use [`hist2fmt`](msg_parts.md#hist2fmt) to write messages as an editable Markdown reply, and aihist's `fmt2hist` to read one back. The Markdown format stores tool calls, results, and usage in fenced JSON blocks.

## Part

A message can contain text, images, reasoning, and tool calls. Each item in `Msg.content` is a [`Part`](msg_parts.md#part) subclass. Provider converters translate between these objects and their API's content blocks. Changing providers doesn't require a different way to construct messages, although each provider has its own capability limits.

Subclasses register a serialization tag such as `text` or `input_image`. The tag is available as `.type`. Each subclass defines its own fields and display methods. Renderers call those methods without checking the tag.

Every part accepts `raw` and `cache_control`. `raw` retains provider details that the shared fields don't represent, such as an Anthropic thinking signature. `cache_control` holds a prompt-cache directive for providers that support one. `fastllm` uses these parts in input coercion, response normalization, and provider serialization.

The provider APIs use different names and nesting for the same content:

| API | Text | Image | File |
|--- |--- |--- |--- |
| [OpenAI Responses](https://developers.openai.com/api/reference/resources/responses/methods/create) | `{"type":"input_text","text":"..."}` | `{"type":"input_image","image_url":"..."}` | `{"type":"input_file","file_data":"data:application/pdf;base64,...","filename":"..."}` |
| [OpenAI Chat](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create) | `{"type":"text","text":"..."}` | `{"type":"image_url","image_url":{"url":"..."}}` | `{"type":"file","file":{"file_data":"data:application/pdf;base64,...","filename":"..."}}` |
| [Anthropic](https://docs.anthropic.com/en/api/messages) | `{"type":"text","text":"..."}` | `{"type":"image","source":{"type":"base64","media_type":"image/jpeg","data":"..."}}` | `{"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"..."}}` |
| [Gemini](https://ai.google.dev/api/generate-content) | `{"text":"..."}` | `{"inlineData":{"mimeType":"image/jpeg","data":"..."}}` | `{"fileData":{"mimeType":"application/pdf","fileUri":"..."}}` |

These are API representations, not constructor arguments for [`Part`](msg_parts.md#part). Construct [`Text`](msg_parts.md#text), [`InputImage`](msg_parts.md#inputimage), [`InputAudio`](msg_parts.md#inputaudio), [`InputVideo`](msg_parts.md#inputvideo), or [`InputFile`](msg_parts.md#inputfile) instead. Media subclasses store a URL or data URL in `text` and a MIME type in `mime`. There is no `Part.data` field or provider-name override. [`mk_part`](msg_parts.md#mk_part) requires the registered tag, not aliases such as `image_url` or `pdf`.

| Class | Registered tag | Content |
|--- |--- |--- |
| [`Text`](msg_parts.md#text) | `text` | Plain text |
| [`InputImage`](msg_parts.md#inputimage) | `input_image` | Image URL or data URL |
| [`InputAudio`](msg_parts.md#inputaudio) | `input_audio` | Audio URL or data URL |
| [`InputVideo`](msg_parts.md#inputvideo) | `input_video` | Video URL or data URL |
| [`InputFile`](msg_parts.md#inputfile) | `input_file` | File URL or data URL |

The following table describes the current `fastllm` user-message converters. It doesn't promise that every model accepts every format its API can represent.

| Part | OpenAI Responses | OpenAI Chat | Anthropic | Gemini |
|--- |--- |--- |--- |--- |
| [`Text`](msg_parts.md#text) | `input_text` | `text` | `text` | `text` |
| [`InputImage`](msg_parts.md#inputimage) | `input_image` | `image_url` | `image` with `source` | `inlineData` or `fileData` |
| [`InputAudio`](msg_parts.md#inputaudio) | Raises `ValueError` | `input_audio` | Raises `ValueError` | `inlineData` or `fileData` |
| [`InputVideo`](msg_parts.md#inputvideo) | `input_video` with `video_url` | Raises `ValueError` | Raises `ValueError` | `inlineData` or `fileData` |
| [`InputFile`](msg_parts.md#inputfile) | `input_file` | `file` | `document` with `source` | `inlineData` or `fileData` |

OpenAI Chat audio requires a base64 data URL. Its converter extracts the encoded data and a `wav` or `mp3` format into `input_audio`. The Chat file converter also requires a base64 data URL. It doesn't accept a URL or a file ID through [`InputFile`](msg_parts.md#inputfile). Responses accepts file URLs and data URLs. Anthropic uses a `url` or `base64` source. Gemini uses `fileData` for URLs and `inlineData` for data URLs.

The original API comparison used these specification locations: OpenAI Responses `Input{Text,Image,File}Content` (`specs/openai.with-code-samples.yml:68093-68444`), OpenAI Chat `ChatCompletionRequestMessageContentPart*` (`specs/openai.with-code-samples.yml:35185-35321`), Anthropic `Request{Text,Image,Document}Block` (`specs/anthropic.yml:12159-12458`), and Gemini [`Part`](msg_parts.md#part)/`Blob`/`FileData` (`specs/gemini.json:189-387`). For converter behavior, see `fastllm.openai_responses`, `fastllm.openai_chat`, `fastllm.anthropic`, and `fastllm.gemini`.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L21)

### Part

```python
def Part(
    *, raw=None, # The vendor's original block, kept for lossless round-trips
    cache_control=None, # Prompt-cache directive for providers that take one
):
```

*Base class for content parts; subclasses register under the wire tag they serialize as.*

`PartType` lists the registered tags. [`ToolUse`](msg_parts.md#tooluse) and [`ToolResult`](msg_parts.md#toolresult) are parts too. Their definitions appear in the tool section below.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L59)

### Refusal

```python
def Refusal(
    text=None, **kw
):
```

*A provider's refusal to answer.*

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L53)

### Thinking

```python
def Thinking(
    text=None, showthink:bool=False, **kw
):
```

*A reasoning block; `showthink` asks renderers to show the thought rather than a 🧠 glyph.*

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L47)

### Text

```python
def Text(
    text=None, citations=None, **kw
):
```

*Plain text content; `citations` lists the sources it rests on as `url_citation` dicts (`url`, `title`, optional `start_index`/`end_index`)*

[`Media`](msg_parts.md#media) stores the URL or data URL in `text` and its MIME type in `mime`.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L66)

### Media

```python
def Media(
    text=None, mime=None, **kw
):
```

*Media content: `text` is a URL or data URL.*

Choose the subclass for the media you send or receive:

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L79)

### InputVideo

```python
def InputVideo(
    text=None, # URL or data URL
    mime=None, # Media type
    start=None, # Clip start, in seconds
    end=None, # Clip end, in seconds
    fps=None, # Frames per second sampled from the video
    **kw
):
```

*A video input; `start`/`end` clip it to a range and `fps` sets the sampled frame rate, for providers that support them*

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L77)

### OutputImage

```python
def OutputImage(
    text=None, mime=None, **kw
):
```

*A generated image output.*

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L76)

### InputFile

```python
def InputFile(
    text=None, mime=None, **kw
):
```

*A file input.*

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L75)

### InputAudio

```python
def InputAudio(
    text=None, mime=None, **kw
):
```

*An audio input.*

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L74)

### InputImage

```python
def InputImage(
    text=None, mime=None, **kw
):
```

*An image input.*

Use [`mk_part`](msg_parts.md#mk_part) when reading serialized parts. It looks up the tag in `Part.reg` and passes the remaining fields to that class.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L93)

### mk\_part

```python
def mk_part(
    type, **kw
):
```

*The [`Part`](msg_parts.md#part) subclass registered for wire tag `type`, built from `kw`*

```python
v = InputVideo('https://www.youtube.com/watch?v=x', start=600, end=1200)
test_eq(mk_part(**{k:v for k,v in v.__dict__.items() if k[0] != '_'}, type=v.type), v)
v
```

```output
InputVideo(raw=None, cache_control=None, text='https://www.youtube.com/watch?v=x', mime=None, start=600, end=1200, fps=None)
```

```python
Text('Hello world!'*30, raw={'long':"10"*150})
```

**Text** (`text`)

Hello world!Hello world!Hello world!Hello world!Hello world!Hello world!Hello world!Hello world!Hell...

<details>
<summary>Details</summary>

- raw: `{'long': '1010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010...'}`
- citations: `None`

</details>

## Msg

[`Msg`](msg_parts.md#msg) groups an ordered list of parts under a role such as `user`, `assistant`, or `tool`. Its `text` property joins the [`Text`](msg_parts.md#text) parts without separators. Other parts remain in `content`.

`fastllm` accepts these messages in completion requests and uses them to replay tool conversations. A [`Completion`](msg_parts.md#completion) contains the assistant's [`Msg`](msg_parts.md#msg). Provider converters handle the differences in message roles and layout.

OpenAI Chat uses `{role, content}` messages. Its roles include `system`, `developer`, `user`, `assistant`, and `tool`. Content can be a string or typed blocks. Responses accepts message input items but represents tool calls and results as separate items.

Anthropic accepts `user` and `assistant` messages. It takes the system prompt in a separate `system` parameter. Gemini uses `{role, parts}` with `user` and `model` roles. Its system prompt goes in `system_instruction`.

| Conversation role | OpenAI Chat | OpenAI Responses | Anthropic | Gemini |
|--- |--- |--- |--- |--- |
| System prompt | `role: "system"` | `role: "system"` input or request instructions | Separate `system` parameter | `system_instruction` |
| `user` | `role: "user"` | `role: "user"` | `role: "user"` | `role: "user"` |
| `assistant` | `role: "assistant"` | `role: "assistant"` | `role: "assistant"` | `role: "model"` |
| `tool` | `role: "tool"` with `tool_call_id` | `function_call_output` with `call_id` and `output` | `tool_result` blocks in a `user` message | `functionResponse` parts in a `user` message |

Responses uses `input_text` for user text and `output_text` for assistant text. The shared model stores both as [`Text`](msg_parts.md#text).

[`Msg`](msg_parts.md#msg) has `role`, `content`, `raw`, and `raw_api` fields. Tool identifiers, names, and arguments belong to the tool parts in `content`. There is no `Msg.data` metadata dict. Provider-specific fields, including error information, belong in `raw` rather than extra message fields. This module doesn't interpret them.

`raw` retains the original provider message. `raw_api` names the API whose wire format it is in, such as `openai_chat` or `anthropic`. A `fastllm` converter replays `raw` only when `raw_api` names the converter's API. It rebuilds other messages from their parts. The shape of `raw` doesn't identify its API: an OpenAI Chat message whose content is a list of blocks looks like an Anthropic message.

The original API comparison used OpenAI `ChatCompletionRequest*Message` (`specs/openai.with-code-samples.yml:35022-35444`), Anthropic `InputMessage` and `RequestToolResultBlock` (`specs/anthropic.yml:11140-11159,12595-12652`), and Gemini `Content` (`specs/gemini.json:171-188`).

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L119)

### Msg

```python
def Msg(
    role, # 'user', 'assistant', or 'tool'
    content, # list of `Part`
    raw=None, # The provider's message as received, replayed verbatim to the API that `raw_api` names
    raw_api=None, # The API whose wire format `raw` is in, such as `openai_chat` or `anthropic`
):
```

*A normalized message; `raw` is the wire form it was parsed from, when a provider produced it.*

```python
Msg('user', content=[Text('Hello world!', raw={'long':"10"*150})]*3)
```

**Msg**

- role: `user`

\<contents\>

**Text** (`text`)

Hello world!

<details>
<summary>Details</summary>

- raw: `{'long': '1010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010...'}`
- citations: `None`

</details>

**Text** (`text`)

Hello world!

<details>
<summary>Details</summary>

- raw: `{'long': '1010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010...'}`
- citations: `None`

</details>

**Text** (`text`)

Hello world!

<details>
<summary>Details</summary>

- raw: `{'long': '1010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010...'}`
- citations: `None`

</details>

\</contents\>

[`msg2dict`](msg_parts.md#msg2dict) writes the role, content, raw provider message, and `raw_api` to a dict. Each part includes its registered `type` and public instance attributes. Underscore-prefixed attributes don't enter the dict.

[`dict2msg`](msg_parts.md#dict2msg) reconstructs the parts through [`mk_part`](msg_parts.md#mk_part). A dict without `raw_api` gives a message whose `raw_api` is `None`. The example retains the provider's thinking signature and `raw_api` through JSON serialization. A list of parts inside a part, such as a tool result's text and image, becomes a list of part dicts and comes back as parts. Other attribute values must themselves support JSON serialization.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L163)

### dict2msg

```python
def dict2msg(
    d
):
```

*The [`Msg`](msg_parts.md#msg) that [`msg2dict`](msg_parts.md#msg2dict) produced `d` from*

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L159)

### msg2dict

```python
def msg2dict(
    m
):
```

*`m` as a JSON-ready dict, each part tagged with its wire `type`*

```python
m = Msg('assistant', [Thinking('hmm', raw={'type':'thinking', 'signature':'sig'}), Text('Hi')], raw={'role':'assistant'}, raw_api='anthropic')
d = msg2dict(m)
test_eq(dict2msg(json.loads(json.dumps(d))), m)
d
```

```output
{'role': 'assistant',
 'content': [{'type': <PartType.thinking: 'thinking'>,
   'raw': {'type': 'thinking', 'signature': 'sig'},
   'cache_control': None,
   'text': 'hmm',
   'showthink': False},
  {'type': <PartType.text: 'text'>,
   'raw': None,
   'cache_control': None,
   'text': 'Hi',
   'citations': None}],
 'raw': {'role': 'assistant'},
 'raw_api': 'anthropic'}
```

## Tool parts

[`ToolUse`](msg_parts.md#tooluse) records a requested function call. [`ToolResult`](msg_parts.md#toolresult) records its output. Both have `id`, `name`, `arguments`, `server`, `text`, `md`, and `full` fields. `arguments` defaults to an empty dict. `server=True` identifies a tool the provider ran itself. `md=True` renders a result as Markdown; `full=True` bypasses ordinary saved-result shortening.

Assistant messages can mix tool calls with text. Client tool results normally follow in a `tool` message. Provider responses can also include results from server tools. The formatted text representation combines each call with its result.

| API | Call object | Arguments | Streaming |
|--- |--- |--- |--- |
| [OpenAI Responses](https://developers.openai.com/api/reference/resources/responses/methods/create) | `{type: "function_call", call_id, name, arguments}` | JSON string in `arguments` | `response.function_call_arguments.delta` events |
| [OpenAI Chat](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create) | `{id, type: "function", function: {name, arguments}}` | JSON string in `function.arguments` | `tool_calls[i].function.arguments` deltas |
| [Anthropic](https://docs.anthropic.com/en/api/messages) | `{type: "tool_use", id, name, input}` | Parsed object in `input` | `input_json_delta` events |
| [Gemini](https://ai.google.dev/api/generate-content) | `functionCall: {id, name, args}` | Parsed object in `args` | Complete argument objects rather than JSON-text fragments |

`fastllm` converts these fields to `ToolUse.id`, `ToolUse.name`, and a parsed `ToolUse.arguments` dict. Responses supplies `call_id` for the ID. Chat supplies the function name from `function.name`. Anthropic and Gemini use `name` directly.

The original API comparison used OpenAI Responses `FunctionToolCall` (`specs/openai.with-code-samples.yml:44347-44389`), OpenAI Chat `ChatCompletionMessageToolCall` (`specs/openai.with-code-samples.yml:34869-34894`), Anthropic `ResponseToolUseBlock` (`specs/anthropic.yml:13563-13588`), and Gemini `FunctionCall` (`specs/gemini.json:273-293`).

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L176)

### ToolResult

```python
def ToolResult(
    id=None, name=None, arguments=None, server:bool=False, text=None, md:bool=False, full:bool=False, **kw
):
```

*A tool call's result, `text` holding the output.*

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L175)

### ToolUse

```python
def ToolUse(
    id=None, name=None, arguments=None, server:bool=False, text=None, md:bool=False, full:bool=False, **kw
):
```

*A tool invocation; `server` marks one the provider ran itself.*

Use [`display_list`](msg_parts.md#display_list) to display parts or messages together as Markdown in a notebook.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L192)

### display\_list

```python
def display_list(
    l
):
```

```python
ToolUse(id='oxwvx1fm', name='simple_add', arguments={'b': 547982745, 'a': 5478954793}, raw={'thoughtSignature': 'EscDCsQDAQw51scPHdv+D5BX7JWdLzz3Bv8tsKFRuAJe2UkTFZ+NZKzNsLtmQBiia+/r4HJEUptq1zQB0q9HToX0qzCUqyNAbDLY76KxMeW9jpsnUvh6ZjPM5sDD7fAafF7cjdApNMsihPqIZBAZjAlFPcp1c/50MObH5f1q7hO7fgDS4iSJ3Q3FfbAYWnJ4nlA2peVMu/6WFcKZh1wcZCIuN6iFCj6nhH+6RKkaFRaM0b6XCmpti6qldSeZx+qtHmo+lzr1tct4Gz/CITDI7gRJ3qfLYV2u45jOhKzdd1t6gQ39XLJ93j0xd0AwpzcdZLbHWqwWJCQ43nNzhJ7IQTAWOSyPgKDnlAMHq2PTEoXBYkMBApCZ1x+HncBzt77kQrTTe7sWGVmD5boVnYAIFPFGXOULP5tDZ+nog+Fg8NV10vaFKlHVf+VDzFnVWxT259LN12ykGtBilfpTXiKCV12RAZwhuL7vXXHrsBGg5HNVImcXqgMvwf/rtQlJeop+9bEcAiU48hMFMzumOrCmmHD3HgxpYLW7T3vtDmbNdKCDqVtIwO4Rp5HE6GudRWmq8iC2UnyQglUXoXVnxIZW7eYYDsGAYrYgZ1A='})
```

🔧 **simple\_add**(`{'b': 547982745, 'a': 5478954793}`)

<details>
<summary>Details</summary>

- id: `oxwvx1fm`
- server: `False`
- raw: `{'thoughtSignature': 'EscDCsQDAQw51scPHdv+D5BX7JWdLzz3Bv8tsKFRuAJe2UkTFZ+NZKzNsLtmQBiia+/r4HJEUptq1zQB0q9HToX0qzCUqyNAbDLY...'}`

</details>

## Completion

[`Completion`](msg_parts.md#completion) contains an assistant message plus response metadata. `fastllm.types.mk_completion` constructs it from a non-streaming API response. It records the requested `model`, `api_name`, and `vendor_name`. `raw` holds the complete response dict.

The provider normalizers read different response fields:

| Value | OpenAI Responses | OpenAI Chat | Anthropic | Gemini |
|--- |--- |--- |--- |--- |
| Content | `output[]`, including message content and function calls | `choices[0].message` | `content[]` | `candidates[0].content.parts[]` |
| Finish status | `status` | `choices[0].finish_reason` | `stop_reason` | `candidates[0].finishReason` |
| Usage | `usage` | `usage` | `usage` | `usageMetadata` |
| Tool calls | `function_call` output items | `message.tool_calls[]` | `tool_use` blocks | `functionCall` parts |

Each normalizer constructs the appropriate parts in `message.content`. Gemini retains separate text parts. [`Completion.tool_calls`](msg_parts.md#completion.tool_calls) selects the [`ToolUse`](msg_parts.md#tooluse) parts from that content rather than storing a second copy.

`finish_reason` uses normalized values such as `stop`, `tool_calls`, `length`, and `content_filter`. For example, Responses `completed`, Anthropic `end_turn`, and Gemini `STOP` normally become `stop`. A pending client tool call changes a successful finish to `tool_calls`. Usage normalization belongs to the provider modules.

The constructor uses the model name supplied by the caller for all providers. Gemini's `modelVersion` remains in `raw`; it doesn't replace the requested model name.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L197)

### Completion

```python
def Completion(
    model, message, finish_reason=None, usage=None, api_name=None, vendor_name=None, raw=None
):
```

*Normalized completion response.*

```python
comp = Completion('claude-sonnet-4-20250514', Msg('assistant', [Text('The sum is 8. '), ToolUse(id='t1', name='add', arguments={'a':3,'b':5})]), finish_reason='tool_use')
test_eq(len(comp.tool_calls), 1)
comp.tool_calls[0]
```

🔧 **add**(`{'a': 3, 'b': 5}`)

<details>
<summary>Details</summary>

- id: `t1`
- server: `False`
- raw: `None`

</details>

## Message utilities

[`mk_tool_res_msg`](msg_parts.md#mk_tool_res_msg) pairs calls and results by position. It returns one `tool` message containing a [`ToolResult`](msg_parts.md#toolresult) per pair. Each result copies the call's ID, name, arguments, and server flag. Results can be strings, lists of media parts, or existing [`ToolResult`](msg_parts.md#toolresult) parts whose content and flags are retained.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L211)

### mk\_tool\_res\_msg

```python
def mk_tool_res_msg(
    tool_calls:list[__main__.ToolUse], results:list[str | list | __main__.ToolResult]
):
```

*Pair calls with text, media parts, or canonical results, retaining their flags*

[`sys_text`](msg_parts.md#sys_text) returns a string unchanged or reads a part's `text`. It also accepts `None`. [`part_txt`](msg_parts.md#part_txt) reads `text` from a [`Part`](msg_parts.md#part) and returns other inputs unchanged.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L224)

### part\_txt

```python
def part_txt(
    p
):
```

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L219)

### sys\_text

```python
def sys_text(
    system
):
```

*Extract text from system (str or Part).*

Provider converters need a MIME type for media. [`data_url`](msg_parts.md#data_url) extracts the MIME type and encoded body from a base64 data URL. [`url_mime`](msg_parts.md#url_mime) first checks the URL extension. For an unknown extension, it fetches the resource and examines its `Content-Type` header. A missing or generic header triggers byte detection with `detect_mime`.

[`_fetch_url_partial`](msg_parts.md#_fetch_url_partial) imports `httpx` when you fetch a URL. The rest of this module doesn't require that import. [`MediaUrl`](msg_parts.md#mediaurl) stores a URL with an explicit or inferred MIME type. Constructing it without `mime` can therefore make a network request. It retains the URL rather than storing downloaded content.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L250)

### url\_mime

```python
def url_mime(
    url, default:str='application/octet-stream'
):
```

*Guess mime from URL extension, then the server's Content-Type, then sniffed bytes; never None.*

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L246)

### data\_url

```python
def data_url(
    url
):
```

*Parse data:mime;base64,data URL into (mime, b64\_data), or None.*

[`url_mime`](msg_parts.md#url_mime) returns the default MIME type when neither the URL nor its content identifies a format. The default is `application/octet-stream`.

```python
test_eq(url_mime('https://example.com/badge.svg'), 'image/svg+xml')
test_eq(url_mime('nonsense.xyz123'), 'application/octet-stream')
```

These tests replace the fetch with local responses. A specific `Content-Type` takes priority after stripping parameters such as `charset`. For a generic header, recognizable PNG bytes determine the MIME type. Plain text with a generic header falls back to the default.

```python
_real = _fetch_url_partial
def _fetch_url_partial(url, nbytes=512): return 'image/svg+xml; charset=utf-8', b'<svg xmlns="http://www.w3.org/2000/svg"/>'
test_eq(url_mime('https://example.com/chart'), 'image/svg+xml')
def _fetch_url_partial(url, nbytes=512): return 'application/octet-stream', b'\x89PNG\r\n\x1a\n' + b'\0'*16
test_eq(url_mime('https://example.com/pic'), 'image/png')
def _fetch_url_partial(url, nbytes=512): return 'text/plain', b'some text'
test_eq(url_mime('https://example.com/thing'), 'application/octet-stream')
_fetch_url_partial = _real
```

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L261)

### MediaUrl

```python
def MediaUrl(
    url, mime=None
):
```

*Direct URL media reference*

[`mk_content`](msg_parts.md#mk_content) converts a string to [`Text`](msg_parts.md#text). For bytes, it detects the MIME type and creates a base64 data URL. Unrecognized bytes raise `ValueError`. A [`MediaUrl`](msg_parts.md#mediaurl) becomes a media part that retains the URL.

The MIME prefix selects [`InputImage`](msg_parts.md#inputimage), [`InputAudio`](msg_parts.md#inputaudio), or [`InputVideo`](msg_parts.md#inputvideo). Other MIME types use [`InputFile`](msg_parts.md#inputfile). Message builders use this conversion for lists of mixed content.

An existing [`Part`](msg_parts.md#part) passes through [`mk_content`](msg_parts.md#mk_content) unchanged. Other unrecognized objects also pass through.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L285)

### mk\_content

```python
def mk_content(
    o
):
```

*Convert a content value (str, bytes, [`MediaUrl`](msg_parts.md#mediaurl), or already a [`Part`](msg_parts.md#part)) to a canonical [`Part`](msg_parts.md#part)*

## The formatted text form

The editable reply format combines prose with fenced JSON. A `json {.tool}` block records a call and its result. Tool blocks contain `id`, `name`, `args`, and `result`, with optional `server` and `md` flags. The `error` field is reserved.

### Result fences

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L304)

### extract\_fence\_call

```python
def extract_fence_call(
    text
):
```

*Return (lang, code) if text ends with terminated py/bash fence, else None*

[`extract_fence_call`](msg_parts.md#extract_fence_call) recognizes `py` and `bash` calls between five-backtick fences. Both fences must occupy their own lines. The closing fence must end the text apart from whitespace. It returns `(language, code)`, or `None` if no final call matches.

``````python
for bad in ['\n`````py\nprint(1)', '\n```py\nprint(1)\n```\n', 'some text `````py\nprint(1)\n`````\n', '\n`````python\nprint(1)\n`````\n']:
    test_eq(bool(fence_call_re.search(bad)), False)
test_eq(extract_fence_call('prose\n`````bash\nls -la\n`````\n'), ('bash', 'ls -la'))
test_eq(extract_fence_call('\n`````py\nprint(1)\n`````\nmore text'), None)
test_eq(extract_fence_call('hello world'), None)
test_eq(extract_fence_call('\n`````py\nx = 1 | 2\n`````\n'), ('py', 'x = 1 | 2'))
extract_fence_call('\n`````py\nprint(1)\n`````\n')
``````

```output
('py', 'print(1)')
```

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L330)

### split\_fence\_msgs

```python
def split_fence_msgs(
    msgs
):
```

*Split all assistant msgs on result fences for wire protocol*

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L312)

### mk\_result\_fence

```python
def mk_result_fence(
    output
):
```

[`_split_msg_on_fences`](msg_parts.md#_split_msg_on_fences) separates assistant text at five-backtick `result` fences. It returns other messages unchanged. [`split_fence_msgs`](msg_parts.md#split_fence_msgs) applies this operation to a list of messages.

``````python
msg = Msg(role='assistant', content=[Text('Hello world')])
test_eq(_split_msg_on_fences(msg), [msg])
usr = Msg(role='user', content=[Text('`````result\n2\n`````')])
test_eq(_split_msg_on_fences(usr), [usr])
msg
``````

**Msg**

- role: `assistant`

\<contents\>

**Text** (`text`)

Hello world

<details>
<summary>Details</summary>

- raw: `None`
- citations: `None`

</details>

\</contents\>

The model's code stays in an assistant message. The result becomes a `user` message containing its result fence, as required for code-result replay. Any following assistant text starts another message.

``````python
msg = Msg(role='assistant', content=[Text('Let me calculate.\n`````py\n1+1\n`````\n\n`````result\n2\n`````\n\nDone.')])
res = _split_msg_on_fences(msg)
test_eq([m.role for m in res], ['assistant', 'user', 'assistant'])
test_eq(['`````py\n1+1' in res[0].text, '`````result\n2\n`````' in res[1].text, 'Done.' in res[2].text], [True]*3)
res
``````

``````output
[Msg(role='assistant', content=[Text(raw=None, cache_control=None, text='Let me calculate.\n`````py\n1+1\n`````', citations=None)], raw=None, raw_api=None),
 Msg(role='user', content=[Text(raw=None, cache_control=None, text='\n`````result\n2\n`````\n', citations=None)], raw=None, raw_api=None),
 Msg(role='assistant', content=[Text(raw=None, cache_control=None, text='Done.', citations=None)], raw=None, raw_api=None)]
``````

The split retains preceding [`Thinking`](msg_parts.md#thinking) parts with assistant text. The example has one assistant segment before the result.

``````python
code_txt = '`````py\nimport random\nprint(random.random())\n`````\n`````result\n42\n`````\n'
msg = Msg(role='assistant', content=[Thinking('The user wants an RNG function...'), Text(code_txt)])
res = split_fence_msgs([msg])
test_eq([[type(p).__name__ for p in m.content] for m in res], [['Thinking','Text'], ['Text']])
res
``````

``````output
[Msg(role='assistant', content=[Thinking(raw=None, cache_control=None, text='The user wants an RNG function...', showthink=False), Text(raw=None, cache_control=None, text='`````py\nimport random\nprint(random.random())\n`````', citations=None)], raw=None, raw_api=None),
 Msg(role='user', content=[Text(raw=None, cache_control=None, text='\n`````result\n42\n`````\n', citations=None)], raw=None, raw_api=None)]
``````

The split places all [`ToolUse`](msg_parts.md#tooluse) parts in a final assistant message. Tool requests end the assistant turn before the caller supplies their results.

```python
msg = Msg(role='assistant', content=[Text(code_txt),
    ToolUse(id='4vy96hyd', name='python', arguments={'code': 'print(random.randint(1, 100))'})])
res = _split_msg_on_fences(msg)
test_eq([m.role for m in res], ['assistant', 'user', 'assistant'])
test_eq([m.content[0].type for m in res], ['text', 'text', 'tool_use'])
res[-1]
```

**Msg**

- role: `assistant`

\<contents\>

🔧 **python**(`{'code': 'print(random.randint(1, 100))'}`)

<details>
<summary>Details</summary>

- id: `4vy96hyd`
- server: `False`
- raw: `None`

</details>

\</contents\>

### hist2fmt

[`tool_text`](msg_parts.md#tool_text) converts a tool's return value to text for storage and provider requests. Strings pass through unchanged. Dicts and ordinary lists become JSON, not Python reprs. `default=str` converts values that JSON can't encode on their own. Other objects use `str`.

A list containing only [`Part`](msg_parts.md#part) objects follows a different rule. [`tool_text`](msg_parts.md#tool_text) joins their `ctext` values with newlines. Text remains text. Media becomes a tag such as `<media input_image image/png>`, matching clikernel's kernel-image convention. `fastllm` uses this policy in its chat layer and provider serializers.

A stored tool block doesn't retain media bytes or URLs. Provider converters send the media during the live turn. Reading the block later recovers the placeholder text, not the media.

Two possible lossless formats remain deferred. Embedding media in the block would enlarge stored replies with base64. Display truncation could also corrupt it. Alternatively, a `ref` attribute on each `<media>` tag could identify content in a separate store, as Solveit's image attachments do. That would require [`_media_tag`](msg_parts.md#_media_tag) to write the reference and the reply's reader to resolve it. Neither behavior exists yet.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L341)

### tool\_text

```python
def tool_text(
    res, # A tool function's return value
):
```

*Convert a tool result to text, using compact media tags and JSON for structured values.*

```python
test_eq(tool_text('hi'), 'hi')
test_eq(tool_text({'a': 1, 'ok': True}), '{"a": 1, "ok": true}')
test_eq(tool_text([1, 'x']), '[1, "x"]')
test_eq(tool_text(42), '42')
tool_text({'path': Path('/tmp')})
```

```output
'{"path": "/tmp"}'
```

[`resp_part`](msg_parts.md#resp_part) encodes content for Fastllm's Responses facade. Text, images, videos and files use Responses-shaped blocks. File data URLs use standard filename extensions, with `.bin` for an unknown MIME type. File URLs use `file_url`. Other values become `input_text` holding their [`tool_text`](msg_parts.md#tool_text); unrecognized part types raise `ValueError`.

Audio uses aidialog's existing serialized [`InputAudio`](msg_parts.md#inputaudio) fields, including its URL or data URL and MIME type. The facade restores the part before the selected backend converts it. This is a facade extension, not native OpenAI Responses audio input.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L356)

### resp\_part

```python
def resp_part(
    p
):
```

*`p` as a content block for Fastllm's Responses facade*

```python
test_eq(resp_part(Text('hi')), dict(type='input_text', text='hi'))
test_eq(resp_part(InputFile('data:application/pdf;base64,JVBE')), dict(type='input_file', file_data='data:application/pdf;base64,JVBE', filename='upload.pdf'))
test_eq(resp_part(InputFile('https://x.co/a.pdf')), dict(type='input_file', file_url='https://x.co/a.pdf'))
test_eq(resp_part({'a': 1}), dict(type='input_text', text='{"a": 1}'))
office = InputFile('data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,eA==')
test_eq(resp_part(office)['filename'], 'upload.docx')
test_eq(resp_part(InputFile('data:application/vnd.unknown;base64,eA=='))['filename'], 'upload.bin')
```

[`ToolResponse`](msg_parts.md#toolresponse) keeps a tool's returned content as parts, such as a caption, image or audio. Fastllm unwraps it before provider conversion. In a kernel, its MIME bundle carries facade content blocks under `TOOL_RESPONSE_MIME`. Aihist restores canonical parts for Python clients or passes the blocks to a Responses facade. The plain-text form uses [`tool_text`](msg_parts.md#tool_text) with compact media tags.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L371)

### ToolResponse

```python
def ToolResponse(
    content, # A value, or a list of values such as parts, strings or bytes
):
```

*Base class for objects needing a basic `__repr__`*

These string subclasses request special handling downstream:

- [`StopResponse`](msg_parts.md#stopresponse) ends the tool loop after that tool result.
- [`FullResponse`](msg_parts.md#fullresponse) opts out of display truncation.
- [`MdStr`](msg_parts.md#mdstr) allows the renderer to treat a tool result as Markdown rather than fenced text.

A tool must opt in to Markdown rendering. Untrusted Markdown can mislead readers. The formatted tool block records this choice in its `md` flag.

[`trunc_str`](msg_parts.md#trunc_str) leaves a value untruncated when its class sets `full = True`. [`FullResponse`](msg_parts.md#fullresponse) sets it, as do fastcore's `Safe` and `FullString`. A host's own string type can set it too. Ordinary strings can use `𝍁...𝍁` markers to request the same exemption after serialization.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L383)

### MdStr

```python
def MdStr():
```

*str(object\='') -\> str str(bytes\_or\_buffer\[, encoding\[, errors\]\]) -\> str*

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.**str**() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L382)

### FullResponse

```python
def FullResponse():
```

*str(object\='') -\> str str(bytes\_or\_buffer\[, encoding\[, errors\]\]) -\> str*

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.**str**() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L381)

### StopResponse

```python
def StopResponse():
```

*str(object\='') -\> str str(bytes\_or\_buffer\[, encoding\[, errors\]\]) -\> str*

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.**str**() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

[`trunc_str`](msg_parts.md#trunc_str) limits ordinary display strings and marks truncation with ellipses and a `TRUNCATED` wrapper. With the default `skip=10`, it drops the first ten characters as well as the tail. It does not preserve both ends. `mx=None` disables truncation.

Values whose class sets `full` pass through unchanged. With the default `replace`, `𝍁...𝍁` protects its contents from truncation and removes the markers. Setting `replace=None` disables that marker exemption.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L386)

### trunc\_str

```python
def trunc_str(
    s, mx:int=2000, skip:int=10, replace:str='TRUNCATED'
):
```

*Shorten ordinary display strings using `mx` and mark truncation with `replace`.*

```python
test_eq(trunc_str('𝍁xxxxxxxxxx𝍁', mx=5), 'xxxxxxxxxx')
test_eq(trunc_str(Safe('xxxxxxxxxx'), mx=5), 'xxxxxxxxxx')
test_eq(trunc_str(FullResponse('xxxxxxxxxx'), mx=5), 'xxxxxxxxxx')
test_eq(trunc_str('xxxxxxxxxx', mx=5, skip=0), '<TRUNCATED>xxxxx…</TRUNCATED>')
test_eq(trunc_str('xxxxxxxxxx', mx=5, skip=1), '<TRUNCATED>…xxx…</TRUNCATED>')
test_eq(trunc_str('xxxxxxxxxx', mx=None), 'xxxxxxxxxx')
```

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L405)

### mk\_tr\_details

```python
def mk_tr_details(
    tr, mx:int=2000
):
```

*Create the `{.tool}` wire block for a tool call; `mx=None` disables truncation*

Parts implement two rendering interfaces. `formatted` supplies fragments for a streaming display. Text returns its current fragment without stripping whitespace. Thinking has its own compact display. A tool call has none.

`doc(showthink=False, mx=2000)` renders finished content. It strips text, optionally includes thinking, and writes completed tool calls as fenced JSON. [`hist2fmt`](msg_parts.md#hist2fmt) calls these methods while assembling a reply. Each subclass owns its rendering behavior.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L417)

### Part.doc

```python
def doc(
    showthink:bool=False, mx:int=2000
):
```

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L415)

### Part.formatted

```python
def formatted():
```

[`Thinking.formatted`](msg_parts.md#thinking.formatted) returns the brain glyph by default. Setting the part's `showthink` attribute exposes the text during streaming. [`Thinking.doc`](msg_parts.md#thinking.doc) instead uses its `showthink` argument. It puts the text in a collapsed details block between `think_start` and `think_end` comments. The comments let a reader of the reply remove the block.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L423)

### Thinking.doc

```python
def doc(
    showthink:bool=False, mx:int=2000
):
```

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L421)

### Thinking.formatted

```python
def formatted():
```

A tool call has no streaming fragment. A server call's document form is a completed tool block. A client call has an empty document form. Its result's block shows the call and its arguments.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L431)

### ToolUse.doc

```python
def doc(
    showthink:bool=False, mx:int=2000
):
```

*Render a server call as a completed tool block, and a client call as nothing.*

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L429)

### ToolUse.formatted

```python
def formatted():
```

[`ToolResult.doc`](msg_parts.md#toolresult.doc) writes a tool block when the result has an ID. It returns an empty string without one. A reader of the reply needs the ID to rebuild the call and its result.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L440)

### ToolResult.doc

```python
def doc(
    showthink:bool=False, mx:int=2000
):
```

*Render an identified result as a tool block. Omit results without an ID.*

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L438)

### ToolResult.formatted

```python
def formatted():
```

`ctext` supplies content inside a tool result. Most parts use their `formatted` value. [`Media.ctext`](msg_parts.md#media.ctext) uses a `<media>` tag instead of exposing a URL or a potentially large data URL.

Joining parts retains a text part's `full` exemption. [`tool_text`](msg_parts.md#tool_text) encloses the combined text and media tags in `𝍁...𝍁`. An existing marker pair around a text part has the same effect and moves to the outside:

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L449)

### Media.ctext

```python
def ctext():
```

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L446)

### Part.ctext

```python
def ctext():
```

```python
test_eq(Text('caption').ctext, 'caption')
test_eq(Thinking('secret').ctext, '🧠')
image = InputImage('data:image/png;base64,xxx', mime='image/png')
test_eq(tool_text([Text('caption'), image]), 'caption\n<media input_image image/png>')
test_eq(tool_text([InputFile('https://x.co/a.pdf')]), '<media input_file>')
protected = tool_text([Text(Safe('caption')), image])
test_eq(tool_text([Text('𝍁caption𝍁'), image]), protected)
test_eq(protected, '𝍁caption\n<media input_image image/png>𝍁')
protected
```

```output
'𝍁caption\n<media input_image image/png>𝍁'
```

In a kernel, a [`ToolResponse`](msg_parts.md#toolresponse) holding a caption and an image displays as two Responses parts, with their [`tool_text`](msg_parts.md#tool_text) as the plain-text form:

```python
tr = ToolResponse([Text('The login page.'), InputImage('data:image/png;base64,iVBORw0K', mime='image/png')])
b = tr._repr_mimebundle_()
test_eq([p['type'] for p in b[TOOL_RESPONSE_MIME]], ['input_text', 'input_image'])
test_eq(b['text/plain'], 'The login page.\n<media input_image image/png>')
audio = InputAudio('data:audio/wav;base64,UklGRg==', mime='audio/wav')
ab = ToolResponse([Text('The clip.'), audio])._repr_mimebundle_()
test_eq(mk_part(**ab[TOOL_RESPONSE_MIME][1]), audio)
test_eq(ab['text/plain'], 'The clip.\n<media input_audio audio/wav>')
```

This result contains a caption and an image. [`mk_tr_details`](msg_parts.md#mk_tr_details) uses [`tool_text`](msg_parts.md#tool_text) to retain the caption and replace the image with a MIME-tagged placeholder. Reading this stored block won't restore the image.

```python
mtr = ToolResult(id='t1', name='screenshot', text=[Text('The login page.'), InputImage('data:image/png;base64,iVBORw0K', mime='image/png')])
assert '<media input_image image/png>' in mk_tr_details(mtr)
Markdown(mk_tr_details(mtr))
```

```json
{
  "id": "t1",
  "name": "screenshot",
  "args": {},
  "result": "The login page.\n<media input_image image/png>"
}
```

Stored with [`msg2dict`](msg_parts.md#msg2dict), the result keeps its parts, image included:

```python
mtm = Msg('tool', [mtr.replace(md=True, full=True)])
test_eq(dict2msg(json.loads(json.dumps(msg2dict(mtm)))), mtm)
```

```python
test_eq(ToolUse(id='tc1', name='simple_add', arguments={'a':3,'b':5}).formatted, '')
test_eq(ToolUse(id='s1', name='web_search', server=True).formatted, '')
test_eq(Thinking('deep thought').formatted, '🧠')
test_eq(Thinking('deep thought', showthink=True).formatted, 'deep thought')
test_eq(Text('hi').formatted, 'hi')
```

[`OutputImage.formatted`](msg_parts.md#outputimage.formatted) returns its `<media>` tag (`ctext`) instead of streaming raw image data. `doc` and `_repr_markdown_` render a Markdown image when `text` is set.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L455)

### OutputImage.doc

```python
def doc(
    showthink:bool=False, mx:int=2000
):
```

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L453)

### OutputImage.formatted

```python
def formatted():
```

```python
out_img = OutputImage('data:image/png;base64,xxx', mime='image/png')
test_eq(out_img.formatted, '<media output_image image/png>')
test_eq(out_img.doc(), '![](data:image/png;base64,xxx)')
test_eq(out_img._repr_markdown_(), '![](data:image/png;base64,xxx)')
test_eq(OutputImage(mime='image/png').doc(), '')
test_eq(OutputImage(mime='image/png')._repr_markdown_(), '<media output_image image/png>')
test_eq(mk_part(**_part2dict(out_img)), out_img)
```

Use [`hist2fmt`](msg_parts.md#hist2fmt) to turn captured assistant and tool messages into an editable reply, such as a Solveit prompt output or an llmsurgery dialog. It retains text and combines each matching [`ToolUse`](msg_parts.md#tooluse)/[`ToolResult`](msg_parts.md#toolresult) pair into a `json {.tool}` block. Other message roles raise `ValueError`.

[`mk_tr_details`](msg_parts.md#mk_tr_details) truncates long results using `mx`, which defaults to 2000. It allows string arguments up to five times that limit. Pass `mx=None` to disable those limits. The text format also discards raw provider data and media. It isn't a lossless serialization of arbitrary messages.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L460)

### hist2fmt

```python
def hist2fmt(
    msgs:list[__main__.Msg], mx:int=2000, showthink:bool=False
)->str:
```

*Render assistant and tool messages as one editable Markdown reply.*

This conversation has two rounds of tool calls. [`hist2fmt`](msg_parts.md#hist2fmt) copies each call's arguments into the block for its result.

```python
h = [Msg('assistant', [Text("I'll add these in parallel."), ToolUse(id='t1', name='simple_add', arguments={'a':10, 'b':5}),
        ToolUse(id='t2', name='simple_add', arguments={'a':2, 'b':1})]),
     Msg('tool', [ToolResult(id='t1', name='simple_add', text='15'), ToolResult(id='t2', name='simple_add', text='3')]),
     Msg('assistant', [Text('Now I multiply them.'), ToolUse(id='t3', name='multiply', arguments={'a':15, 'b':3})]),
     Msg('tool', [ToolResult(id='t3', name='multiply', text='45')])]
s = hist2fmt(h)
test_eq(s.count(tool_info), 3)
assert '"a": 10' in s
Markdown(s)
```

I'll add these in parallel.

```json
{
  "id": "t1",
  "name": "simple_add",
  "args": {
    "a": 10,
    "b": 5
  },
  "result": "15"
}
```

```json
{
  "id": "t2",
  "name": "simple_add",
  "args": {
    "a": 2,
    "b": 1
  },
  "result": "3"
}
```

Now I multiply them.

```json
{
  "id": "t3",
  "name": "multiply",
  "args": {
    "a": 15,
    "b": 3
  },
  "result": "45"
}
```

A client call without a result, such as one from an interrupted turn, is left out of the reply.

```python
pend = Msg('assistant', [Text('Calling...'), ToolUse(id='p1', name='f', arguments={'x':1})])
test_eq(hist2fmt([pend]), 'Calling...')
```

A server call represents work the provider has already done. It doesn't need a separate result message. [`hist2fmt`](msg_parts.md#hist2fmt) writes its `text` as the result in a completed tool block, where the call happened in the turn. Text the model wrote after the call follows the block. If the text is empty, it uses `Server tool call executed.`.

An [`MdStr`](msg_parts.md#mdstr) result sets the block's `md` flag.

```python
srv = Msg('assistant', [Text('Let me check.'), ToolUse(id='s1', name='web_search', arguments={'query': 'otters'}, server=True, text=MdStr('Otter: https://example.com/otter')),
    Text('Otters are mustelids.')])
s = hist2fmt([srv])
assert s.index('web_search') < s.index('Otters are mustelids.')
assert '"md": true' in s
Markdown(s)
```

Let me check.

```json
{
  "id": "s1",
  "name": "web_search",
  "args": {
    "query": "otters"
  },
  "result": "Otter: https://example.com/otter",
  "server": true,
  "md": true
}
```

Otters are mustelids.

[`hist2fmt`](msg_parts.md#hist2fmt) omits thinking unless you pass `showthink=True`. With it, the thinking goes in a collapsed block between `think_start` and `think_end` comments.

```python
tm = Msg('assistant', [Thinking('hmm, sums'), Text('The answer is 8.')])
test_eq(hist2fmt([tm]), 'The answer is 8.')
test_eq('hmm, sums' in hist2fmt([tm], showthink=True), True)
Markdown(hist2fmt([tm], showthink=True))
```

<!--think_start-->

<details>
<summary>Thinking</summary>

hmm, sums

</details>

<!--think_end-->

The answer is 8.

Gemini code-execution results can have no ID. [`ToolResult.doc`](msg_parts.md#toolresult.doc) omits them because it can't associate them with a call. The example retains the assistant text but loses the ID-less result.

```python
gm = Msg('assistant', [Text('Ran it.'), ToolResult(text='42', raw={'codeExecutionResult': {}})])
test_eq(hist2fmt([gm]), 'Ran it.')
```

## Building conversations

[`mk_msg`](msg_parts.md#mk_msg) accepts a string, a list of mixed content, a role/content dict, a [`msg2dict`](msg_parts.md#msg2dict) dict, a [`Msg`](msg_parts.md#msg), or a [`Completion`](msg_parts.md#completion). An existing [`Msg`](msg_parts.md#msg) passes through unchanged. A [`Completion`](msg_parts.md#completion) supplies its `message`. `None` returns `None`.

Strings become [`Text`](msg_parts.md#text). A role/content dict supplies its own role and wraps its `content` in [`Text`](msg_parts.md#text). A [`msg2dict`](msg_parts.md#msg2dict) dict, whose `content` is a list of part dicts, becomes the [`Msg`](msg_parts.md#msg) it was made from. A list converts each item with [`mk_content`](msg_parts.md#mk_content). To convert bytes or a [`MediaUrl`](msg_parts.md#mediaurl) into media, put it in that list. A bare value takes the [`Text`](msg_parts.md#text) path. The default role is `user`.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L478)

### mk\_msg

```python
def mk_msg(
    content, # Content: str, bytes (image), list of mixed content, role/content dict, or `msg2dict` dict
    role:str='user', # Message role if content isn't already a dict/Message
):
```

*Build a [`Msg`](msg_parts.md#msg) from content, or unwrap an existing message or completion.*

```python
m = mk_msg('hey')
test_eq(m, mk_msg(['hey']))
m
```

**Msg**

- role: `user`

\<contents\>

**Text** (`text`)

hey

<details>
<summary>Details</summary>

- raw: `None`
- citations: `None`

</details>

\</contents\>

[`mk_msgs`](msg_parts.md#mk_msgs) builds a conversation. It starts with the `user` role for content without an explicit role. After a user or tool message, the next inferred role is `assistant`. After any other role, it is `user`.

Existing messages and dicts retain their roles. A string is plain text, even when it contains tool blocks. Empty input returns an empty list.

[source](https://github.com/AnswerDotAI/aidialog/blob/main/aidialog/msg_parts.py#L495)

### mk\_msgs

```python
def mk_msgs(
    msgs, # List of messages (each: str, bytes, list, dict, Msg, or Completion)
):
```

*Create a list of fastllm canonical Msgs.*

Here's a conversation made from plain strings:

```python
msgs = mk_msgs(['Hey!',"Hi there!","How are you?","I'm doing fine and you?"])
msgs
```

```output
[Msg(role='user', content=[Text(raw=None, cache_control=None, text='Hey!', citations=None)], raw=None, raw_api=None),
 Msg(role='assistant', content=[Text(raw=None, cache_control=None, text='Hi there!', citations=None)], raw=None, raw_api=None),
 Msg(role='user', content=[Text(raw=None, cache_control=None, text='How are you?', citations=None)], raw=None, raw_api=None),
 Msg(role='assistant', content=[Text(raw=None, cache_control=None, text="I'm doing fine and you?", citations=None)], raw=None, raw_api=None)]
```

```python
msgs[-2]
```

**Msg**

- role: `user`

\<contents\>

**Text** (`text`)

How are you?

<details>
<summary>Details</summary>

- raw: `None`
- citations: `None`

</details>

\</contents\>

Explicit tool roles also work for parallel calls. Both results below keep their `tool` role. The following plain string becomes the assistant's reply.

```python
msgs = mk_msgs(['Tell me the weather in Paris and Rome', 'Assistant calls weather tool two times',
    {'role': 'tool', 'content': 'Weather in Paris is ...'}, {'role': 'tool', 'content': 'Weather in Rome is ...'},
    'Assistant returns weather', 'Thanks!'])
msgs
```

```output
[Msg(role='user', content=[Text(raw=None, cache_control=None, text='Tell me the weather in Paris and Rome', citations=None)], raw=None, raw_api=None),
 Msg(role='assistant', content=[Text(raw=None, cache_control=None, text='Assistant calls weather tool two times', citations=None)], raw=None, raw_api=None),
 Msg(role='tool', content=[Text(raw=None, cache_control=None, text='Weather in Paris is ...', citations=None)], raw=None, raw_api=None),
 Msg(role='tool', content=[Text(raw=None, cache_control=None, text='Weather in Rome is ...', citations=None)], raw=None, raw_api=None),
 Msg(role='assistant', content=[Text(raw=None, cache_control=None, text='Assistant returns weather', citations=None)], raw=None, raw_api=None),
 Msg(role='user', content=[Text(raw=None, cache_control=None, text='Thanks!', citations=None)], raw=None, raw_api=None)]
```

A stored conversation, one [`msg2dict`](msg_parts.md#msg2dict) dict per message, restores exactly. fastllm's `AsyncChat.dumps` writes this form:

```python
stored = json.dumps([msg2dict(m) for m in msgs])
test_eq(mk_msgs(json.loads(stored)), msgs)
```

You can pass a single prompt without a list. [`mk_msgs`](msg_parts.md#mk_msgs) wraps non-list input and returns a list of [`Msg`](msg_parts.md#msg) objects. You'll get a ~~LiteLLM~~ fastllm message history back.

```python
msgs = mk_msgs("Hey")
msgs
```

```output
[Msg(role='user', content=[Text(raw=None, cache_control=None, text='Hey', citations=None)], raw=None, raw_api=None)]
```

```python
msgs = mk_msgs(['Hey!',"Hi there!","How are you?","I'm fine, you?"])
msgs
```

```output
[Msg(role='user', content=[Text(raw=None, cache_control=None, text='Hey!', citations=None)], raw=None, raw_api=None),
 Msg(role='assistant', content=[Text(raw=None, cache_control=None, text='Hi there!', citations=None)], raw=None, raw_api=None),
 Msg(role='user', content=[Text(raw=None, cache_control=None, text='How are you?', citations=None)], raw=None, raw_api=None),
 Msg(role='assistant', content=[Text(raw=None, cache_control=None, text="I'm fine, you?", citations=None)], raw=None, raw_api=None)]
```

For one message with multiple parts, use two lists. The outer list contains messages. The inner list contains that message's parts.

This is useful for a question with an image. The example below contains two text parts: a question and a URL string. Use a [`MediaUrl`](msg_parts.md#mediaurl) or [`InputImage`](msg_parts.md#inputimage) instead of a plain URL string to send the image itself.

```python
msgs = mk_msgs([['Whats in this image?', 'https://example.com/puppy.jpg']])
test_eq(len(msgs), 1)
test_eq(len(msgs[0].content), 2)
msgs[0]
```

**Msg**

- role: `user`

\<contents\>

**Text** (`text`)

Whats in this image?

<details>
<summary>Details</summary>

- raw: `None`
- citations: `None`

</details>

**Text** (`text`)

[https://example.com/puppy.jpg](https://example.com/puppy.jpg)

<details>
<summary>Details</summary>

- raw: `None`
- citations: `None`

</details>

\</contents\>
