msg_parts

The canonical LLM message model - Msg and the Part classes - and its formatted text form

Msg and the 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 and mk_msgs to build messages from ordinary Python values. Use 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 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:

APITextImageFile
OpenAI Responses{"type":"input_text","text":"..."}{"type":"input_image","image_url":"..."}{"type":"input_file","file_data":"data:application/pdf;base64,...","filename":"..."}
OpenAI Chat{"type":"text","text":"..."}{"type":"image_url","image_url":{"url":"..."}}{"type":"file","file":{"file_data":"data:application/pdf;base64,...","filename":"..."}}
Anthropic{"type":"text","text":"..."}{"type":"image","source":{"type":"base64","media_type":"image/jpeg","data":"..."}}{"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"..."}}
Gemini{"text":"..."}{"inlineData":{"mimeType":"image/jpeg","data":"..."}}{"fileData":{"mimeType":"application/pdf","fileUri":"..."}}

These are API representations, not constructor arguments for Part. Construct Text, InputImage, InputAudio, InputVideo, or 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 requires the registered tag, not aliases such as image_url or pdf.

ClassRegistered tagContent
TexttextPlain text
InputImageinput_imageImage URL or data URL
InputAudioinput_audioAudio URL or data URL
InputVideoinput_videoVideo URL or data URL
InputFileinput_fileFile 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.

PartOpenAI ResponsesOpenAI ChatAnthropicGemini
Textinput_texttexttexttext
InputImageinput_imageimage_urlimage with sourceinlineData or fileData
InputAudioRaises ValueErrorinput_audioRaises ValueErrorinlineData or fileData
InputVideoinput_video with video_urlRaises ValueErrorRaises ValueErrorinlineData or fileData
InputFileinput_filefiledocument with sourceinlineData 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. 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/Blob/FileData (specs/gemini.json:189-387). For converter behavior, see fastllm.openai_responses, fastllm.openai_chat, fastllm.anthropic, and fastllm.gemini.

source

Part

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 and ToolResult are parts too. Their definitions appear in the tool section below.

source

Refusal

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

A provider's refusal to answer.

source

Thinking

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

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

source

Text

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 stores the URL or data URL in text and its MIME type in mime.

source

Media

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

InputVideo

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

OutputImage

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

A generated image output.

source

InputFile

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

A file input.

source

InputAudio

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

An audio input.

source

InputImage

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

An image input.

Use mk_part when reading serialized parts. It looks up the tag in Part.reg and passes the remaining fields to that class.

source

mk_part

def mk_part(
    type, **kw
):

The Part subclass registered for wire tag type, built from kw

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
InputVideo(raw=None, cache_control=None, text='https://www.youtube.com/watch?v=x', mime=None, start=600, end=1200, fps=None)
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
  • raw: {'long': '1010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010...'}
  • citations: None

Msg

Msg groups an ordered list of parts under a role such as user, assistant, or tool. Its text property joins the 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 contains the assistant's 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 roleOpenAI ChatOpenAI ResponsesAnthropicGemini
System promptrole: "system"role: "system" input or request instructionsSeparate system parametersystem_instruction
userrole: "user"role: "user"role: "user"role: "user"
assistantrole: "assistant"role: "assistant"role: "assistant"role: "model"
toolrole: "tool" with tool_call_idfunction_call_output with call_id and outputtool_result blocks in a user messagefunctionResponse 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 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

Msg

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.

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

Msg

  • role: user

<contents>

Text (text)

Hello world!

Details
  • raw: {'long': '1010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010...'}
  • citations: None

Text (text)

Hello world!

Details
  • raw: {'long': '1010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010...'}
  • citations: None

Text (text)

Hello world!

Details
  • raw: {'long': '1010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010...'}
  • citations: None

</contents>

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 reconstructs the parts through 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

dict2msg

def dict2msg(
    d
):

The Msg that msg2dict produced d from

source

msg2dict

def msg2dict(
    m
):

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

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
{'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 records a requested function call. 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.

APICall objectArgumentsStreaming
OpenAI Responses{type: "function_call", call_id, name, arguments}JSON string in argumentsresponse.function_call_arguments.delta events
OpenAI Chat{id, type: "function", function: {name, arguments}}JSON string in function.argumentstool_calls[i].function.arguments deltas
Anthropic{type: "tool_use", id, name, input}Parsed object in inputinput_json_delta events
GeminifunctionCall: {id, name, args}Parsed object in argsComplete 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

ToolResult

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

ToolUse

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 to display parts or messages together as Markdown in a notebook.

source

display_list

def display_list(
    l
):
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
  • id: oxwvx1fm
  • server: False
  • raw: {'thoughtSignature': 'EscDCsQDAQw51scPHdv+D5BX7JWdLzz3Bv8tsKFRuAJe2UkTFZ+NZKzNsLtmQBiia+/r4HJEUptq1zQB0q9HToX0qzCUqyNAbDLY...'}

Completion

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:

ValueOpenAI ResponsesOpenAI ChatAnthropicGemini
Contentoutput[], including message content and function callschoices[0].messagecontent[]candidates[0].content.parts[]
Finish statusstatuschoices[0].finish_reasonstop_reasoncandidates[0].finishReason
UsageusageusageusageusageMetadata
Tool callsfunction_call output itemsmessage.tool_calls[]tool_use blocksfunctionCall parts

Each normalizer constructs the appropriate parts in message.content. Gemini retains separate text parts. Completion.tool_calls selects the 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

Completion

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

Normalized completion response.

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
  • id: t1
  • server: False
  • raw: None

Message utilities

mk_tool_res_msg pairs calls and results by position. It returns one tool message containing a 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 parts whose content and flags are retained.

source

mk_tool_res_msg

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 returns a string unchanged or reads a part's text. It also accepts None. part_txt reads text from a Part and returns other inputs unchanged.

source

part_txt

def part_txt(
    p
):

source

sys_text

def sys_text(
    system
):

Extract text from system (str or Part).

Provider converters need a MIME type for media. data_url extracts the MIME type and encoded body from a base64 data URL. 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 imports httpx when you fetch a URL. The rest of this module doesn't require that import. 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

url_mime

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

data_url

def data_url(
    url
):

Parse data:mime;base64,data URL into (mime, b64_data), or None.

url_mime returns the default MIME type when neither the URL nor its content identifies a format. The default is application/octet-stream.

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.

_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

MediaUrl

def MediaUrl(
    url, mime=None
):

Direct URL media reference

mk_content converts a string to Text. For bytes, it detects the MIME type and creates a base64 data URL. Unrecognized bytes raise ValueError. A MediaUrl becomes a media part that retains the URL.

The MIME prefix selects InputImage, InputAudio, or InputVideo. Other MIME types use InputFile. Message builders use this conversion for lists of mixed content.

An existing Part passes through mk_content unchanged. Other unrecognized objects also pass through.

source

mk_content

def mk_content(
    o
):

Convert a content value (str, bytes, MediaUrl, or already a Part) to a canonical 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

extract_fence_call

def extract_fence_call(
    text
):

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

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.

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')
('py', 'print(1)')

source

split_fence_msgs

def split_fence_msgs(
    msgs
):

Split all assistant msgs on result fences for wire protocol

source

mk_result_fence

def mk_result_fence(
    output
):

_split_msg_on_fences separates assistant text at five-backtick result fences. It returns other messages unchanged. split_fence_msgs applies this operation to a list of messages.

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
  • raw: None
  • citations: None

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

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
[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 parts with assistant text. The example has one assistant segment before the result.

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
[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 parts in a final assistant message. Tool requests end the assistant turn before the caller supplies their results.

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
  • id: 4vy96hyd
  • server: False
  • raw: None

</contents>

hist2fmt

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 objects follows a different rule. 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 to write the reference and the reply's reader to resolve it. Neither behavior exists yet.

source

tool_text

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.

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')})
'{"path": "/tmp"}'

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; unrecognized part types raise ValueError.

Audio uses aidialog's existing serialized 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

resp_part

def resp_part(
    p
):

p as a content block for Fastllm's Responses facade

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 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 with compact media tags.

source

ToolResponse

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:

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 leaves a value untruncated when its class sets full = True. 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

MdStr

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

FullResponse

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

StopResponse

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

trunc_str

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

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

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

mk_tr_details

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 calls these methods while assembling a reply. Each subclass owns its rendering behavior.

source

Part.doc

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

source

Part.formatted

def formatted():

Thinking.formatted returns the brain glyph by default. Setting the part's showthink attribute exposes the text during streaming. 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

Thinking.doc

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

source

Thinking.formatted

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

ToolUse.doc

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

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

source

ToolUse.formatted

def formatted():

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

ToolResult.doc

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

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

source

ToolResult.formatted

def formatted():

ctext supplies content inside a tool result. Most parts use their formatted value. 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 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

Media.ctext

def ctext():

source

Part.ctext

def ctext():
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
'𝍁caption\n<media input_image image/png>𝍁'

In a kernel, a ToolResponse holding a caption and an image displays as two Responses parts, with their tool_text as the plain-text form:

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 uses tool_text to retain the caption and replace the image with a MIME-tagged placeholder. Reading this stored block won't restore the image.

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))
{
  "id": "t1",
  "name": "screenshot",
  "args": {},
  "result": "The login page.\n<media input_image image/png>"
}

Stored with msg2dict, the result keeps its parts, image included:

mtm = Msg('tool', [mtr.replace(md=True, full=True)])
test_eq(dict2msg(json.loads(json.dumps(msg2dict(mtm)))), mtm)
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 returns its <media> tag (ctext) instead of streaming raw image data. doc and _repr_markdown_ render a Markdown image when text is set.

source

OutputImage.doc

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

source

OutputImage.formatted

def formatted():
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 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/ToolResult pair into a json {.tool} block. Other message roles raise ValueError.

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

hist2fmt

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 copies each call's arguments into the block for its result.

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.

{
  "id": "t1",
  "name": "simple_add",
  "args": {
    "a": 10,
    "b": 5
  },
  "result": "15"
}
{
  "id": "t2",
  "name": "simple_add",
  "args": {
    "a": 2,
    "b": 1
  },
  "result": "3"
}

Now I multiply them.

{
  "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.

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 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 result sets the block's md flag.

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.

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

Otters are mustelids.

hist2fmt omits thinking unless you pass showthink=True. With it, the thinking goes in a collapsed block between think_start and think_end comments.

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))
Thinking

hmm, sums

The answer is 8.

Gemini code-execution results can have no ID. 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.

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

Building conversations

mk_msg accepts a string, a list of mixed content, a role/content dict, a msg2dict dict, a Msg, or a Completion. An existing Msg passes through unchanged. A Completion supplies its message. None returns None.

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

source

mk_msg

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 from content, or unwrap an existing message or completion.

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

Msg

  • role: user

<contents>

Text (text)

hey

Details
  • raw: None
  • citations: None

</contents>

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

mk_msgs

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:

msgs = mk_msgs(['Hey!',"Hi there!","How are you?","I'm doing fine and you?"])
msgs
[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)]
msgs[-2]

Msg

  • role: user

<contents>

Text (text)

How are you?

Details
  • raw: None
  • citations: None

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

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
[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 dict per message, restores exactly. fastllm's AsyncChat.dumps writes this form:

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 wraps non-list input and returns a list of Msg objects. You'll get a LiteLLM fastllm message history back.

msgs = mk_msgs("Hey")
msgs
[Msg(role='user', content=[Text(raw=None, cache_control=None, text='Hey', citations=None)], raw=None, raw_api=None)]
msgs = mk_msgs(['Hey!',"Hi there!","How are you?","I'm fine, you?"])
msgs
[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 or InputImage instead of a plain URL string to send the image itself.

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
  • raw: None
  • citations: None

Text (text)

https://example.com/puppy.jpg

Details
  • raw: None
  • citations: None

</contents>