# Model input and dialog conversion


[`aihist.hist`](hist.html) turns [`aidialog.dialog.Dialog`](https://AnswerDotAI.github.io/aidialog/dialog.html#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`.

``` python
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`](#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

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

``` python
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'` references
```

*Return sorted unique `$` vars, commands, and `&` tool references from the prompt’s prefit context.*

### count_tokens

``` python
def count_tokens(
    text:str
)->int:
```

*Return an approximate token count for `text` calibrated against OpenAI’s o200k tokenizer.*

### dlg2hist

``` python
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, ...]` turns
```

*Convert `dlg` into alternating user parts and saved reply strings.*

## Dialogs, chats, and Markdown

Use [`dlg2chat`](#dlg2chat) and [`chat2dlg`](#chat2dlg) to round-trip between an [`aidialog.dialog.Dialog`](https://AnswerDotAI.github.io/aidialog/dialog.html#dialog) and canonical chat messages whose tool calls are structured parts. Use [`reply2dlg`](#reply2dlg) and [`dlg2reply`](#dlg2reply) to explode a single AI reply into editable note and code cells and collapse it back.

### dlg2chat

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

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

``` python
def reply2chat(
    outp:str
)->list[aidialog.msg_parts.Msg]:
```

*Parse stored reply `outp` into canonical chat `Msg` objects in strict call/result alternation.*

### reply2dlg

``` python
def reply2dlg(
    pmsg
)->aidialog.dialog.Dialog:
```

*Explode `pmsg`’s AI reply into a `Dialog` of editable note and code messages.*

### dlg2reply

``` python
def dlg2reply(
    sub:aidialog.dialog.Dialog
)->str:
```

*Implode a sub-dialog of note and code messages back into saved reply Markdown.*

### dlg2md

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

``` python
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 code
```

*Render one message as Markdown with stored attachments inlined, language fences, and output/prompt divs.*

### msg2text

``` python
def msg2text(
    m, part:str='input'
)->str:
```

*Extract `'input'` source or plain-text `'output'` for copying one message part.*

### msgs2py

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

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

``` python
def cell_media(
    m, aim_info:dict=None
)->list[dict]:
```

*Return canonical Responses media parts for one message.*

### cell_reply

``` python
def cell_reply(
    m
)->str | None:
```

*Return a prompt message’s normalized saved reply, or `None` for other message types.*

### hist_xml

``` python
def hist_xml(
    m
)->str:
```

*Render message `m` as the XML string a model reads.*

### to_parts

``` python
def to_parts(
    m, aim_info:dict=None
)->list:
```

*Convert message `m` to history parts: its media followed by its XML.*

### to_media

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

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

``` python
def output_parts(
    m, aim_info:dict=None
)->list:
```

*Return message `m`’s output images as `Part`s (each `<media>` tag and image, or an unavailable note).*

### merge_media

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

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

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

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

``` python
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).*

## Prompt variables and tags

Hosts evaluate `$` expressions and `&` references discovered by [`references`](#references), then pass the records to [`vars_tag`](#vars_tag) or [`vars_hist`](#vars_hist) to inject variable values and media into the prompt context.

### vars_tag

``` python
def vars_tag(
    aim_info:dict, # Model capabilities dict
    recs:dict=None, # Evaluated variable records mapping names to values/media
)->dict:
```

*Build `dict(vars_tag=..., vars_bytes=...)` for evaluated `recs`, or `{}` when all names are undefined.*

### vars_hist

``` python
def vars_hist(
    aim_info:dict, # Model capabilities dict
    recs:dict=None, # Evaluated variable records mapping names to values/media
)->list:
```

*Build `[vars_turn, ack]` holding evaluated `recs`, or `[]` when all names are undefined.*

### get_refs

``` python
def get_refs(
    cts:str
)->list[str] | None:
```

*Return sorted unique names referenced as `` &`name` `` or `` &`[a, b]` `` in `cts`, or `None` when none match.*

### get_exprs

``` python
def get_exprs(
    msgs:list
)->list[str]:
```

*Return sorted unique `$` expressions across the prompt messages of `msgs`.*

### task_tags

``` python
def task_tags(
    task:str, # Prompt text
    sid:str=None, # Optional message ID placed on `<prompt sid="...">`
)->str:
```

*Wrap `task` in the `<instructions>` and `<prompt>` envelope that a model reads.*

### warning_tag

``` python
def warning_tag(
    warning:str
)->str | None:
```

*Wrap non-empty `warning` in a `<system-reminder>` tag, or return `None` when empty.*

## Helpers

### tool_call

``` python
def tool_call(
    m
)->dict | None:
```

*Parse `dict(name=..., arguments=...)` when code message `m`’s source is a literal keyword-only call.*

### is_shown

``` python
def is_shown(
    m
)->bool:
```

*Return whether dialog context includes message `m` (apart from an explicitly addressed prompt).*

### is_nameerr

``` python
def is_nameerr(
    r
)->bool:
```

*Return whether evaluated record `r` represents an undefined name error.*

### jwrap

``` python
def jwrap(
    txts:list=['']
)->list[dict]:
```

*Wrap plain text `txts` as minimal Jupyter stdout stream output dicts.*
