![]() |
From documents to prompts and back | ![]() |
Language models only understand text, while a TeXmacs selection is a tree with arbitrary markup. Two strategies are used to bridge this gap:
for corrections and translations, the markup must survive untouched: everything which is not natural language text is replaced by an opaque identifier, the model is asked to work on an HTML document which only contains text, paragraphs and these identifiers, and the identifiers are expanded again in the answer (
compress.cpp
);
for sessions, the prompt is sent as LaTeX and the model is asked to answer with a LaTeX document, which is imported with the LaTeX converter (ai_latex_output in
ai.cpp
).
atomic trees (text) are kept;
document and concat nodes are kept, and their children are compressed recursively;
every other node is replaced by a node (compressed code c1 … cn). The children ci are the compressed versions of the children of the original node which contain natural language text in the language of the surrounding text: children which are accessible, in text mode and which do not change the language, according to the current DRD the_drd (children of bib-list are never considered text). All other children stay in the original node, which is remembered under code with placeholders (decompressed) for the extracted children.
For instance, a formula or an image becomes a node without children, while strong or section becomes a node whose single child is its text. The code is xn; it is allocated in the static tables compressed (code to key) and compressed_code (key to code), where the key consists of the original node with placeholders, a space mode recording whether the node was preceded or followed by a space in its concat, and the path of the node in the compressed tree. The same markup at the same position therefore always gets the same code during a session.
each paragraph of a document becomes <p>…</p> (followed by a newline if mode contains COMPRESS_LINE_FEEDS, value 1);
a compressed node without children becomes <a id="xn">;
a compressed node with children becomes <div id="xn">c1</div>, followed by <div id="cont-xn">ci</div> for the further children;
text is converted to UTF-8 and &, < and > are escaped;
the whole is wrapped in <body> unless mode contains COMPRESS_SNIPPET (value 2).
compress_html (t, mode) combines both steps. The inverse decompress_html (s, mode) parses this subset (tolerating some inconsistent quoting produced by models), rejects identifiers which appear at a position that is not below the position where they were created (the parse stops there), and calls decompress_tree, which substitutes the stored nodes, puts the answered texts in the placeholders, and restores the spaces around the nodes from their space mode. compressed_contains_text (t) tells whether there is any text outside the codes; it is used to skip paragraphs without text.
The same encoding is used by the LanguageTool spell checker (
tools/spell/spell-lantool.scm
): lantool_correct (s, out) (
lantool.cpp
) takes the compressed HTML that was sent and the JSON reply of the server, and inserts a spell-error node for every match with replacements, skipping matches which fall inside the HTML markup or the codes.
ai_correct (t, lan, model, chat) and ai_translate (t, from, into, model, chat) (Scheme: cpp-ai-correct, cpp-ai-translate) work as follows:
the tree is compressed with compress_html;
an agent description is built:
for corrections, a request to correct the spelling and grammar of the text in the given language without explanations; for Albert, instructions to act as a native speaker who corrects HTML documents, preserves the tags, adds the instructions of the selected corrector agent, and puts explanations in HTML comments at the end;
for translations, a request to translate HTML documents without explanations, to which Albert adds the instructions of the selected translator agent;
ai_chat sends the request synchronously and splits the answer into the <body> part and what surrounds it;
the body is decompressed. For corrections the result is a tuple whose first element is the corrected tree and whose other elements are the decompressed comments (<!--…-->) found after the body.
The asynchronous translation of ai-translate* uses the lower level routines directly (see sessions, menus and agents).
Sessions use LaTeX in both directions:
The session input is serialized by ai-serialize (
tools/ai/ai-batch.scm
): a document with a single paragraph is unwrapped, plain text is sent as UTF-8, and anything else is converted to a LaTeX snippet with UTF-8 encoding.
ai_latex_command and ai_latex_request call ai_command with history enabled and with an agent description asking for an untitled LaTeX document; for Albert also without comments, with SVG pictures embedded in filecontents* environments, plus the instructions of the selected interlocutor agent.
ai_latex_output (reply, model, chat) extracts the answer with ai_output, keeps the part between \begin{document} and \end{document}, removes \maketitle, turns lstlisting into verbatim, turns literal \n sequences into newlines (un_escape_cr, which leaves macros such as \neq or \noindent alone), imports the result with the latex-snippet converter, embeds the pictures and wraps everything in (with "mode" "text" …). An answer without a document environment is returned unchanged, as a string.
Pictures in Albert answers are handled in albert_output, before the import:
replace_tikz_by_pdf copies the preamble of the answer and its first tikzpicture into a standalone document in the temporary directory, compiles it with pdflatex and replaces the picture by an \includegraphics of the resulting PDF; it repeats this for the following pictures. If pdflatex is not installed or fails, the pictures are left as they are (with a warning).
extract_svg saves the contents of each filecontents* (or filecontent*) environment to a file of the given name in the temporary directory and makes the \includesvg and \includegraphics commands refer to it.
After the import, embed_images replaces the file name of every image by the contents of the file (looking also in the temporary directory, with an .svg suffix), so that the session output does not depend on temporary files.
ai_correct and ai_translate call ai_post (r, u) with the answer string r instead of the original tree t (
ai.cpp:815
and 851). Since a string is never a document, ai_post never removes the trailing empty paragraphs it was written to remove.
The compression tables are global and never cleared, so they grow during a session, and codes are only meaningful in the session which created them: pasting with Tools\(\rightarrow\)External AI\(\rightarrow\)Paste an answer produced from a copy made in another session restores the text but loses all the markup that was replaced by codes. Identifiers which the model invents or garbles are silently dropped by decompress_tree (they decompress to the empty string), together with the markup they stood for.
The compression depends on the_drd, that is, on the current buffer; compressing a tree of another buffer may classify its children incorrectly.