GNU TeXmacsUser manualReferenceAboutEnglish
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.

1.Engines and models

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:

ChatGPT

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.

Gemini

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.

Ollama

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.

Mistral

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.

Albert

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.

2.Command trees

ai_command (s, model, agent, chat, history) does not perform the request; it returns a tree describing it, in one of two forms:

(eval_system cmd)

run the shell command cmd and use its standard output as the reply;

(http_post url (tuple h1 v1 …) data)

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:

ai_eval_command (cmd)

Synchronously, with eval_system or http_post_json; the call blocks the user interface until the reply has arrived.

ai_async_eval_command (cmd, callback)

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.

As a shell command

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.

As a Scheme string

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.

3.Transport

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:

4.Extracting the answer

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

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.

5.Conversation history

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.

6.JSON

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

json_object, json_array

Constructors, with convenience overloads for a few arguments.

json_to_tree (s, mode)

A tolerant parser: characters which cannot start a value are skipped.

tree_to_json (t, mode)

A pretty printer; short arrays and objects are printed on one line.

json_get (t, key, mode)

The value of a key in an object.

They are exported as json->tree and tree->json.

7.Pitfalls

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".