![]() |
Engines, requests and transport | ![]() |
This page describes
Data/Convert/AI/ai.cpp
and
json.cpp
: how a request for a given engine is built, how it is sent, and how the answer is extracted from the reply.
An AI request is always made for a model name, which is also the name of the corresponding plug-in session ("chatgpt", "gemini", "ollama", "open-mistral-7b", "albert") and the value of the preference "ai" set by Tools\(\rightarrow\)AI engine. ai_engine (model) maps it to an engine by prefix: chatgpt, gemini, ollama, open-mistral (engine "mistral") and albert; any other name gives "unknown", for which no request is built.
The engines differ in how they are reached, where their key comes from and how their reply is read:
The prompt is written to $TEXMACS_HOME_PATH/system/tmp/chatgpt.txt and passed to the command line tool openai -k 5000 complete file (from the Python package openai-cli), which reads the key from OPENAI_API_KEY. The output of the tool is the answer.
A curl command posting to the generateContent endpoint of the model gemini-2.0-flash (the model name is fixed in the code), with the key from GEMINI_API_KEY in an X-goog-api-key header. The answer is the value of the first "text" field, located by string search.
A curl command posting to http://server:port/api/generate with "stream": false. Server, port and model come from the preferences ollama server (default localhost), ollama port (11434) and ollama model; the model default is resolved by the Scheme function ollama-default-model, which runs ollama list and prefers a model whose name starts with llama. The answer is the "response" field, located by string search.
A curl command posting to https://api.mistral.ai/v1/chat/completions, with the model name as given (open-mistral-7b) and the key from MISTRAL_API_KEY in a bearer authorization header. The answer is the first "content" field.
The French government service albert.api.etalab.gouv.fr. This is the only engine whose request is a structured HTTP POST rather than a shell command. The key comes from ALBERT_API_KEY or the preference albert api key, the model from the preference albert model (default openweight-large). The request is an OpenAI style chat completion with a system message (the agent description, see below), the conversation history and the prompt. The reply is parsed as JSON and the answer is choices[0].message.content.
Apart from Albert, the agent description (the instructions which say what kind of answer is expected) is simply prepended to the prompt.
ai_command (s, model, agent, chat, history) does not perform the request; it returns a tree describing it, in one of two forms:
run the shell command cmd and use its standard output as the reply;
post the JSON document data (a tree, see below) to url with the given header names and values.
Separating the description from the execution lets the same request be executed in four ways:
Synchronously, with eval_system or http_post_json; the call blocks the user interface until the reply has arrived.
Asynchronously, with async_eval_system or async_http_post_json; the Scheme callback is called with the reply from async_eval_pending, that is, from the interpose handler of the server. Following the convention of async_eval_system, it returns true on failure.
The static to_shell_command renders either form as a shell command (an http_post becomes a curl --silent -X POST with --data-binary); ai_latex_command uses it for the :cmdline sessions.
ai_latex_request returns the tree printed with tree_to_scheme; the :request link reads it back with scheme_to_tree and executes it (see sessions, menus and agents).
The prompt is inserted into the shell commands with ai_quote, which escapes double quotes, backslashes and newlines for the JSON string and turns single quotes into '\'' for the surrounding single quoted shell argument. ai_unquote undoes the JSON escapes when the answer is extracted.
eval_system and async_eval_system (
System/Misc/sys_utils.cpp
) run a command through the shell (popen in a detached thread for the asynchronous variant, with 2> /dev/null appended). The HTTP routines of
System/Files/web_files.hpp
have two implementations:
in Qt 6 builds,
Plugins/Qt/qt_http.cpp
uses a shared QNetworkAccessManager; the synchronous qt_http_post runs a nested event loop until the reply has arrived, the asynchronous variant connects a QTMHTTPHandler to the finished signal. The transfer timeout is the preference http request timeout (in seconds, default 10), set in the AI tab of the Convert page of the preferences (ai-preferences-widget in
preferences-widgets.scm
). http_from_json uses QJsonDocument;
otherwise (Qt 5, and the ports without Qt: Vue, SDL, X11, Cocoa),
web_files.cpp
makes the request with libcurl when it was found (USE_LIBCURL; the asynchronous requests are driven by http_async_pending from the main loop), and else builds a curl command line with the headers and the data and runs it with system or async_eval_system, without any timeout; http_from_json is the json_to_tree of
json.cpp
.
ai_output (reply, model, chat) dispatches to chatgpt_output, gemini_output, ollama_output, mistral_output or albert_output, which return the answer as a string (empty if the reply could not be understood). Except for Albert, the reply is not parsed: the answer is located by searching for a fixed key, cut at a fixed terminator and unquoted; a few JSON escapes such as \u003c are then replaced by hand. albert_output in addition
records the prompt and the answer in the conversation history;
renders TikZ pictures and extracts embedded SVG files (see from documents to prompts and back);
replaces the narrow no-break space U+202F by an ordinary space.
ai_chat (s, model, agent, chat) combines ai_command, ai_eval_command and ai_output; the variant with pre and post arguments also splits the answer with ai_get_body, which returns the part between <body> and </body> (both included) and what precedes and follows it.
Requests carry a chat name which identifies a conversation. Only Albert uses it: when ai_command is called with history set (which ai_latex_request and ai_latex_command do), the request includes the last prompts and answers of the conversation model-chat, at most the value of the preference albert chat history size (default 3) of each. They are stored in static tables of
ai.cpp
, so the history lives as long as the program and is not saved. A second mechanism, ai_get_continuation and ai_set_continuation, remembers the "id" of the last answer and asks the model to follow up on it; it is only enabled for model names starting with none, which no engine accepts, so it is currently dead code.
json.cpp
represents JSON values as trees: objects are attr trees with alternating keys and values, arrays are tuple trees and strings are atomic trees. Depending on the mode bits JSON_NULL, JSON_BOOLEAN and JSON_NUMBER, null, booleans and numbers are either plain strings or the compound trees json-null, json-boolean and json-number. The functions are
Constructors, with convenience overloads for a few arguments.
A tolerant parser: characters which cannot start a value are skipped.
A pretty printer; short arrays and objects are printed on one line.
The value of a key in an object.
They are exported as json->tree and tree->json.
Keys on command lines. The Gemini and Mistral keys are part of the curl command line, and so is the Albert key in builds without Qt 6. They are visible to other users of the machine in the process list. The curl based http_post also prints the whole command, key included, as an error when it fails, and when -debug-io is active.
Asynchronous requests to Albert always fail. ai_async_eval_command only accepts an http_post whose data is atomic, but the data built by albert_command is a JSON tree; the function reports “wrong command” and returns true without ever calling the callback.
Shell quoting. The Ollama server, port and model preferences are inserted into the shell command without quoting. ai_quote does not escape tabs and other control characters, which are not allowed in JSON strings. In gemini_command, the line -X POST \ is not followed by a newline, so an escaped space is passed to curl as an extra argument.
The JSON parser is incomplete. \uxxxx escapes are not decoded (the backslash is dropped and the letter u and the digits are kept), \f is turned into a backspace, and numbers with a sign or an exponent are not recognized (the minus sign is skipped). This matters for Albert answers in builds without Qt 6, which use this parser.
The extraction of answers for Gemini, Ollama and Mistral by string search breaks as soon as the services change the layout of their replies.