Skip to main content

Saved and streaming replies

Stream model replies, parse and edit tool blocks, and render folded Markdown displays.

aihist.reply reads and writes Solveit’s saved reply format: Markdown with fenced json {.tool} blocks for tool calls and results and a fenced json {.usage} block for token usage.

from aidialog.msg_parts import Text

r = Reply()
assert r.add(Text('Hello')) == 'Hello'
saved = r.finish()
assert fmt2hist(saved)[0].content[0].text == 'Hello'

Streaming and writing replies

Reply accumulates streamed items as a turn runs and returns the text to display after each chunk. Call finish when a turn stops early. Use write_reply to serialize completed assistant and tool messages, and fmt2hist to parse a saved reply back into chat messages.

Reply

def Reply():

Accumulate streamed turn items (Thinking, Text, ToolUse, ToolResult) into Solveit’s saved reply format.

Reply.add

def add(
    o, # Streamed item (`Thinking`, `Text`, `ToolUse`, or `ToolResult`)
)->str: # Display text, thinking glyph, pending row, or completed tool block

Add a stream item and return the incremental text to display.

Reply.finish

def finish(
    note:str=None
)->str:

Finalize and return the saved reply text, optionally appending note.

write_reply

def write_reply(
    msgs:list[aidialog.msg_parts.Msg]
)->str:

Serialize a completed turn’s assistant and tool messages as a saved reply.

fmt2hist

def fmt2hist(
    outp:str
)->list[aidialog.msg_parts.Msg]:

Parse saved reply outp into assistant and tool Msg objects.

Parsing and editing tool blocks

Use parse_tools to walk text and parsed {.tool} dictionaries in order, set_result to update one call’s stored result in place without altering the rest of the reply, and strip_tools to remove tool and usage blocks.

parse_tools

def parse_tools(
    s:str
)->list[tuple[str, dict | None]]:

Split s into (text, data) segments where data is each parsed {.tool} block dict (None for the trailing segment).

set_result

def set_result(
    text, id, result
):

text with the stored result of call id replaced by result, kept whole. Every other byte stays as it was.

strip_tools

def strip_tools(
    s:str, # Saved reply Markdown
    tools:bool=True, # Remove `{.tool}` blocks?
    usage:bool=True, # Remove `{.usage}` blocks?
)->str:

Remove {.tool} and/or {.usage} fenced blocks from s.

conv_tools

def conv_tools(
    s:str
)->str:

Convert legacy <details> tool and usage envelopes in s to the fenced JSON wire format (idempotent).

Display Markdown

fmt_tools

def fmt_tools(
    s:str
)->str:

Rewrite fenced JSON tool and usage blocks in s into folded ::: details display Markdown.

tool_md

def tool_md(
    d:dict
)->str:

Render one parsed {.tool} block as a folded ::: details div labeled func(params)→result.

usage_md

def usage_md(
    d:dict
)->str:

Render one parsed {.usage} block as a folded ::: details div labeled with cost or tokens.