Model input and dialog conversion
aidialog notebooks and convert between dialogs, chats, and Markdown.
aihist.hist turns aidialog.dialog.Dialog notebooks into model input items, canonical chat messages, and Markdown documents, and converts chat messages or sub-dialogs back. Invalid histories (such as a dialog not ending in a prompt, duplicate tool call IDs, unsupported user part types, or non-keyword tool calls) raise ValueError.
from aidialog.dialog import Dialog
dlg = Dialog(name='demo')
dlg.mk_message('Distances are in metres.', msg_type='note')
p = dlg.mk_message('How far is 3 km?', msg_type='prompt')
assert build(dlg, p.id, dict(input_modalities=['text', 'image'], max_input_tokens=200_000))
assert len(chat2dlg(dlg2chat(dlg), name='demo').messages) == 1
assert '3 km' in dlg2md(dlg)Building model input
build prepares the Responses input items for a prompt cell, including messages above the prompt and each earlier prompt’s saved reply fitted to 80% of the model’s input window. Pinned messages stay, and older unpinned messages drop first at ten-message boundaries and around messages larger than 20,000 characters.
build
def build(
nb, # `Dialog` or ipynb notebook dict
prompt:str, # ID of the prompt cell to build input for
aim_info:dict=None, # Model capabilities dict (every media modality enabled when `None`)
**kw
)->list[dict]: # Extra context fields accepted by `aihist::input::Prompt` (e.g. `path`, `vars`, `crafts`)Build Responses API input items for prompt cell prompt of nb.
references
def references(
nb, # `Dialog` or ipynb notebook dict
prompt:str, # ID of the target prompt cell
crafts:tuple=(), # Craft/system prompt texts to scan alongside dialog cells
)->dict: # Dict of sorted unique `'vars'`, `'cmds'`, and `'tools'` referencesReturn sorted unique $ vars, commands, and & tool references from the prompt’s prefit context.
count_tokens
def count_tokens(
text:str
)->int:Return an approximate token count for text calibrated against OpenAI’s o200k tokenizer.
dlg2hist
def dlg2hist(
dlg, # `Dialog` or iterable of messages ending with a prompt
aim_info:dict, # Model capabilities dict (such as `fastllm` model info)
plain:bool=False, # Render prompts as bare content without the serving envelope?
)->list: # Alternating `[user_parts, reply_str, ...]` turnsConvert dlg into alternating user parts and saved reply strings.
Dialogs, chats, and Markdown
Use dlg2chat and chat2dlg to round-trip between an aidialog.dialog.Dialog and canonical chat messages whose tool calls are structured parts. Use reply2dlg and dlg2reply to explode a single AI reply into editable note and code cells and collapse it back.
dlg2chat
def dlg2chat(
dlg, # `Dialog` or iterable of messages ending with a prompt
aim_info:dict=None, # Model capabilities dict (every media modality when `None`)
plain:bool=False, # Render prompts as bare content without the serving envelope?
)->list[aidialog.msg_parts.Msg]:Convert dlg into canonical chat Msg objects with each reply’s tool calls recovered as structured parts.
chat2dlg
def chat2dlg(
msgs:list[aidialog.msg_parts.Msg], # Canonical chat messages, e.g. from `dlg2chat`
name:str, # Dialog name
cls:type=Dialog, # `Dialog` class to instantiate
mx:int=2000, # Max characters per rendered tool input/output string (`None` disables truncation)
)->aidialog.dialog.Dialog:Convert canonical chat messages into a Dialog with one prompt message per user turn.
reply2chat
def reply2chat(
outp:str
)->list[aidialog.msg_parts.Msg]:Parse stored reply outp into canonical chat Msg objects in strict call/result alternation.
reply2dlg
def reply2dlg(
pmsg
)->aidialog.dialog.Dialog:Explode pmsg’s AI reply into a Dialog of editable note and code messages.
dlg2reply
def dlg2reply(
sub:aidialog.dialog.Dialog
)->str:Implode a sub-dialog of note and code messages back into saved reply Markdown.
dlg2md
def dlg2md(
d, # `Dialog` or iterable of messages
exportfilter:bool=False, # Keep only messages selected by `export_filter`?
weave:bool=False, # Code messages contribute only `render_text` over their outputs as prose?
*, language:str='python', # Kernel language for code fences
)->str:Render dialog d as one Markdown document.
msg2md
def msg2md(
m, # Single `Message`
weave:bool=False, # Code messages contribute only `render_text` over their outputs as prose?
*, language:str='python', # Kernel language for code fences
)->str | None: # Markdown string, or `None` for empty codeRender one message as Markdown with stored attachments inlined, language fences, and output/prompt divs.
msg2text
def msg2text(
m, part:str='input'
)->str:Extract 'input' source or plain-text 'output' for copying one message part.
msgs2py
def msgs2py(
msgs, # `Dialog` or iterable of messages
full:bool=False, # Include commented non-code cells and outputs?
)->str:Export marked code cells, or a full Python transcript with non-code cells and outputs commented.
Message parts and media
Convert individual messages and cell outputs into the XML and media parts that a model reads, resizing raster images when needed and substituting unavailable-media tags when the target model does not support a modality.
cell_turn
def cell_turn(
m, aim_info:dict=None
)->dict:Return canonical model parts and normalized saved reply for one message without fitting or shortening call IDs.
cell_media
def cell_media(
m, aim_info:dict=None
)->list[dict]:Return canonical Responses media parts for one message.
cell_reply
def cell_reply(
m
)->str | None:Return a prompt message’s normalized saved reply, or None for other message types.
hist_xml
def hist_xml(
m
)->str:Render message m as the XML string a model reads.
to_parts
def to_parts(
m, aim_info:dict=None
)->list:Convert message m to history parts: its media followed by its XML.
to_media
def to_media(
m, aim_info:dict=None
)->list:Return the media message m shows a model: referenced attachments, marked links, then code output images.
tool_result
def tool_result(
outputs:list, # Jupyter-style cell output dicts
aim_info:dict=None, # Model capabilities dict
code:bool=False, # `True` when the tool ran code
)->aidialog.msg_parts.ToolResult:Build a canonical ToolResult from notebook outputs, retaining Markdown and full-output flags.
output_parts
def output_parts(
m, aim_info:dict=None
)->list:Return message m’s output images as Parts (each <media> tag and image, or an unavailable note).
merge_media
def merge_media(
text:str, parts:list
):Combine output text and media parts into one tool result: a string when no media remains, else parts then text.
media_item
def media_item(
media_type:str, # Media kind (e.g. `'image'`, `'pdf'`, `'audio'`, `'video'`)
media_id, # Identifier string or callable `media_id(bytes) -> str`
data, # Media bytes or zero-arg loader callable
aim_info:dict, # Model capabilities dict
mime:str=None, # Optional MIME type override
)->list:Format media data as [xml_tag, data], or [media-unavailable tag] when the model cannot read it.
resize_img
def resize_img(
data:bytes, # Raw bytes (raster image or arbitrary data)
max_im_sz:int=589824, # Maximum pixel area (`width * height`)
)->bytes:Limit raster image area in data to max_im_sz pixels in the same format; non-image bytes are unchanged.
prep_img
def prep_img(
data:bytes, # Raw raster image bytes
mime:str, # Image MIME type
max_im_sz:int=None, # Maximum pixel area (defaults to `im_max`)
)->bytes:Limit raster image area before adding it to LLM context.
pdf_pages
def pdf_pages(
b:bytes
)->int:Return the page count of PDF b (largest /Count on a /Pages node, in clear text or inflated object streams).
Helpers
tool_call
def tool_call(
m
)->dict | None:Parse dict(name=..., arguments=...) when code message m’s source is a literal keyword-only call.
is_shown
def is_shown(
m
)->bool:Return whether dialog context includes message m (apart from an explicitly addressed prompt).
is_nameerr
def is_nameerr(
r
)->bool:Return whether evaluated record r represents an undefined name error.
jwrap
def jwrap(
txts:list=['']
)->list[dict]:Wrap plain text txts as minimal Jupyter stdout stream output dicts.