<!--
Copyright (c) 2026 Kataglyphis
SPDX-License-Identifier: MIT
-->

# Language AI: text, LLMs and speech across the family

OxidANT, OrchestrANT, AccelerANTgine and OmniAccelerANT run computer vision today. This page is
the plan for adding language processing to them and the contract they share: the one engine,
the text API, the model packages and the order of work. Owner goal of 2026-10-30.

## Decisions

| Question | Decision (owner, 2026-10-30) |
|---|---|
| Local engine | ONNX Runtime GenAI from the chain, nothing else, outside the browser. GenAI has no web build, so the browser runs the GenAI model directory's decoder on the hub's ORT Web with a generation loop of its own (owner, 2026-11-24): [`ort-web-generate.mjs`](docs-sites.md#generating-text-with-ort-web). llama.cpp stays reachable through Ollama over HTTP; LiteRT-LM is not an engine here. |
| Weights | One model package per ModelANT release (`.deb`, `.msi`). App installers carry no language-model weights. |
| Licences | Gemma and Llama are allowed, with their obligations ([§ Licences](#licences)). |
| Chat widgets | ANThology, so every Flutter app of the family can use them. |
| Android and web | Android: endpoint only until the chain builds GenAI for Android. Web: the endpoint, and local on ORT Web in the app's worker (owner, 2026-11-24): WebGPU when a real adapter answers, the CPU build otherwise. Greedy or seeded sampling; a JSON schema is refused visibly (`json_schema_unsupported`). |
| Speech output | Decided in milestone 5: the usable German voices need espeak-ng, which is GPL-3.0. |

## What the images carry

| Piece | Where | Gap |
|---|---|---|
| GenAI at `ONNXRUNTIME_GENAI_VERSION` | Linux `/usr/local/lib/onnxruntime-genai` on amd64, arm64 and riscv64 (CPU; CUDA in the nvidia variant); Windows `ONNX_GENAI_ROOT` (DirectML; CUDA in the nvidia variant); the `:winarm64` bundle | no Android build, no web build |
| llguidance: JSON schema and grammars | Linux, `--use_guidance` in `60-build-genai.sh`; Windows, `-DUSE_GUIDANCE=ON` in `Build-OnnxGenaiFromSource.ps1` | `:winamd64` ships it: its smoke gate (`Test-Container.ps1`) runs `genai-guidance-smoke.py`, a schema-constrained `generate()` over the [test model](#the-test-model); arm64 has only the build's byte check |
| `ort_genai.h`, `ort_genai_c.h` | GenAI's `include/` | required by the Linux artifact check since LAI-H1 ([contract](consumer-image-contract.md#genais-library-and-headers)) |
| Ollama, Open WebUI, the APISIX gateway | [`linux/llm-stack/`](../linux/llm-stack/README.md) | none |
| GenieX on Snapdragon | [`geniex-local-ai-setup.md`](geniex-local-ai-setup.md) | HTTP only |
| HailoRT for Hailo-10H | [`hailo-support.md`](hailo-support.md) | its GenAI part is not built |

## The text contract

Each binding offers the same calls against the backends it has:

- **local:** GenAI in the process, from the chain build only, loaded the way that binding
  loads ONNX Runtime.
- **endpoint:** an OpenAI-compatible server, by URL or by name through
  [`backends.json`](../linux/llm-stack/README.md#named-backends).

| Binding | Repository | local | endpoint |
|---|---|---|---|
| Rust | OxidANT | `crates/text/src/genai.rs` | `crates/text/src/endpoint.rs` |
| Python | OrchestrANT | `orchestrant/genai/engine.py` | `orchestrant/benchmark/client.py` |
| C++, C | AccelerANTgine | `Src/text_generation.cpp` | none |
| Dart | OmniAccelerANT | through OxidANT's bridge (`lib/src/rust/api/text.dart`) | the playground's `endpoint_chat.dart` |
| JS, the browser | ANTfrastructure | [`ort-web-generate.mjs`](docs-sites.md#generating-text-with-ort-web) | [`endpoint-generate.mjs`](docs-sites.md#generating-text-over-an-endpoint) |

**The stream lines.** [`shared/contracts/openai-stream-lines.json`](../shared/contracts/openai-stream-lines.json)
holds OpenAI chat stream lines with what a reader makes of them: text and thinking deltas, the finish reason,
usage and whether `[DONE]` arrived, or the error. `data:` without a space, a usage-only chunk, keep-alives, a stream
cut before `[DONE]`, reasoning under either name, an error object, a plain-text error, an `error:` line and a chunk
that is no JSON are its cases. Owner decision 2026-11-19: a chunk that is no JSON fails the stream, and an `error:`
line is the server's error. Owner decision 2026-11-21 (D8, CON288): any non-null `error` fails the stream, `false`,
`""` and `{}` among them, with the message when the error is or holds a non-empty string and with the error's JSON
text otherwise; a chunk that is not an object fails it with its text; reading stops at `[DONE]`; the finish reason
keeps its raw value (`content_filter`); usage counts prompt and completion alone, a whole-number float counts, and a
negative count is missing, which leaves the usage null. Errors match as substrings.
[`openai-chat-answers.json`](../shared/contracts/openai-chat-answers.json) holds whole, non-streamed answers under the
same rules. OxidANT's `endpoint.rs`, OrchestrANT's `answers.py` and OmniAccelerANT's `endpoint_reply.dart` replay
every stream case; the D8 cases (2026-11-22) fail a binding until its reader follows them at its next pin, and a
binding with a non-streamed path replays the answers file there too.

[`openai-tool-calls.json`](../shared/contracts/openai-tool-calls.json) holds what a binding sends with
tools and what it reads back. A tool's `acts` flag is the family's consent bit and is not sent. A reader keeps each
call's id, name and raw arguments, joins stream deltas by index and fails a call without a name. Its template cases
map a local model's text to its calls. `test-openai-stream-lines.sh` replays the file through a reference reader, and
readers that drop, merge or reorder a call fail it. The tiny model's `tool_cases` force a call it never predicts.

**The think split.** [`shared/contracts/think-split.json`](../shared/contracts/think-split.json) maps a reply's
text pieces to five outputs (owner decision D5, 2026-11-21): `shown`, what a reader gives out while the pieces
stream; `answer`, the visible answer by OxidANT's per-block rule (text outside `<think>` blocks, the white space
right after a closing tag dropped, all answer before a late `</think>` turned into thinking); `final`, the text
after the last `</think>` that the lab grades, which stops at a `<think>` opening after it that never closes
(owner, 2026-11-23); the thinking count; and the late closes. Text before a late close in its own piece is never
shown, as the web shows it, while what an earlier piece showed stays shown. Its cases hold several blocks, text
before `<think>`, an unclosed block after an answer, a block that never closed and late closes in one piece and in
a later one; `test-think-split.sh` replays them through a reference splitter, OmniAccelerANT's in Python, so the
file cannot ask a binding for an outcome D5 does not give.

| Call | Contract |
|---|---|
| generate | Messages (`system`, `user`, `assistant`, `tool`) and options in; text deltas out through a callback or a stream. The chat template is the model's own. |
| options | `max_new_tokens`, `temperature`, `top_p`, `top_k`, `seed`, and an optional `json_schema`. |
| cancel | Allowed at any time from another thread; the result's finish reason is `cancelled`. |
| result | `finish_reason` (`stop`, `length`, `cancelled`), prompt and completion token counts, time to first token with the prefill included, decode tokens per second. |
| embed | Texts in, one L2-normalised float vector per text out. |

`seed`, `json_schema` and stop strings work in AccelerANTgine (C++, the C ABI, Python, its CLI), OxidANT
(local and endpoint backends, its CLI, the Flutter bridge) and OrchestrANT (`GenerationOptions`,
`orchestrant-chat`, `orchestrant-serve`), and the OmniAccelerANT playground sends them through OxidANT's
bridge. On Windows, `json_schema` answers the unsupported error until an image built with guidance ships.

GenAI has no embedding call. An `embed` in process reads the `hidden_states` output of a decoder exported
with `include_hidden_states=true`, takes the mean over the text's tokens and scales it to unit length.
OxidANT does this; a model directory without that output answers its own error, which names the option.

Each failure has its own error and is never an empty answer: model not found, invalid model
directory, execution provider unavailable, `json_schema` unsupported on this lane, endpoint
unreachable, endpoint HTTP status, and a prompt whose tokens plus the budget exceed the context
(`context_length_exceeded`, owner D7 of 2026-11-21), which `orchestrant-serve` answers with HTTP
400. Greedy decoding (`temperature` 0) of one model on one execution provider yields the same tokens
on every run; the tests rely on that.

## Models and model packages

ModelANT builds and releases every model ([`data-repositories.md`](data-repositories.md)). A
language-model release `<name>-v<N>` adds three things:

- **The GenAI model directory** as `<name>-<ep>.tar.xz`, one per execution provider (`cpu`,
  `cuda`, `dml`), because the GenAI builder exports per provider. The hub fetcher unpacks it
  with `--extract`.
- **A `text-generation-v1` contract archive:** a fixed prompt and the token ids greedy decoding
  must produce. The release workflow checks it before it publishes.
- **`kataglyphis-model-<name>`** as an architecture-independent `.deb` and as an `.msi`.

A package installs to `/usr/share/kataglyphis/models/<name>-<ep>/` on Linux and to
`%ProgramData%\Kataglyphis\models\<name>-<ep>\` on Windows. An app looks for a model in this
order: an explicit path, its own resources directory, the package directory. An app's package
recommends the model package and never contains it. CI and development fetch the same archives
through a separate `llm.lock`, so the app's `models.lock` keeps listing only what its installer
bundles.

GitHub ends a release asset at 2 GiB, so a larger model splits its ONNX external data across
files.

## Licences

ModelANT's rule was "permissive only". Since 2026-10-30 a model may also carry the Llama or the
Gemma licence. `model.json` records the licence class and its obligations; the package and every
app that ships the model carry them out.

| Licence | Obligations when redistributing, checked per model version |
|---|---|
| Llama | Ship the licence agreement and the acceptable use policy, display "Built with Llama", and start a derived model's name with "Llama". The multimodal Llama models exclude users resident in the EU (Llama 3.2 Vision), so none is used here. |
| Gemma | Ship the terms of use and the prohibited use policy, with the notice that the model is provided under them. |

## Models chosen so far

| Use | Model | Licence |
|---|---|---|
| tests | SmolLM2-135M-Instruct | Apache-2.0 |
| chat | Qwen3-0.6B, the default on every target (LAI-M4); Qwen3-1.7B for larger devices | Apache-2.0 |
| comparison in the lab | Llama 3.2 1B and 3B Instruct, Gemma 3 1B and 4B | Llama, Gemma |
| quality on a GPU | Phi-4-mini-instruct | MIT |
| embeddings | multilingual-e5-small, then bge-m3 | MIT |
| speech recognition | Whisper base or small | MIT |
| image and text | Phi-4-multimodal-instruct or Qwen3-VL-4B | MIT, Apache-2.0 |

German and English are required, which is why the chat and embedding models are multilingual.
Each licence and each model's support in the pinned GenAI release is checked before its export.
The two embedding models are BERT and XLM-Roberta, which the model builder of GenAI 0.17 does not
export, so today they reach an app through an endpoint only.

## The test model

`linux/scripts/lib/tiny-genai-model.py --out DIR` writes a complete GenAI model directory of about
270 KB with the standard library alone: `model.onnx`, `genai_config.json`, a byte-level BPE
`tokenizer.json` with its `tokenizer_config.json` and chat template, and `fixture.json`.

- **The rule:** every byte token predicts its successor, and byte 255 predicts the end token. Greedy
  decoding of `abc` with `max_length` 7 therefore yields `defg`, token ids 100 to 103.
- **The oracle:** `fixture.json` holds the prompt, its ids, the continuation and `max_length`, and
  `schema_case`: a JSON schema whose one legal answer the successor rule never predicts, with that
  answer, so only a live guidance mask produces it. The image smoke reads it from there. `cases` lists
  requests (messages and options) with their answer (`text`, maybe `ids`, `finish`) or their error kind,
  `invalid_options` or `generation_failed` in the contract's words, each measured on the image's GenAI:
  greedy to the budget, the schema case, two schemas that are no object, one object the grammar compiler
  refuses, no messages and no budget. Five more are refused before GenAI runs (CON288 (c), owner D7): a role
  outside the four, a NaN temperature, the prompt and the budget over the context
  (`context_length_exceeded`), and a NUL byte in a message and in a stop string. JSON holds no NaN, so the
  file writes `"temperature": "NaN"` and each binding's replay turns it into a float NaN (owner,
  2026-11-23). AccelerANTgine (C++ and Python), OxidANT and OrchestrANT replay every case; a binding maps
  the kind to its own error type, and passes `temperature` and `stop` where a case sets them.
  A binding test reads it instead of retyping the numbers.
- **The cache:** one layer whose `present` outputs concatenate the past with one embedding per
  token, so GenAI exercises its KV-cache loop exactly as with a real decoder.

`--check` decodes the model through the installed `onnxruntime_genai`: exit 0 when tokens, decoded
text and chat template match, 1 on a mismatch, 2 when the wheel is absent.

`--hidden-states` adds a `hidden_states` output, `[batch, sequence, 4]`, as an export with
`include_hidden_states=true` has it. Each byte token's row is its base-4 digits plus one, and
`fixture.json` gains `embedding`, the unit-length mean of the prompt's rows. `--check` then pools
that output too.

**Proven 2026-10-30** on the published index `7d4d4129` (amd64): the Python wheel and a C17 program
against `ort_genai_c.h` (GCC 16.2, `-Wall -Werror`) both decode `defg`. `test-tiny-genai-model.sh`
reads the bytes back on any host: graph, weights, names, tokenizer, and the check mode's verdict.
The image smoke's GenAI tier 4 decodes it on every arch it runs on (LAI-H5): proven on the amd64
image on 2026-10-30, arm64 and riscv64 from the next chain. **Not covered:** the decode on a host
without the wheel.

## Roadmap

Every item is open until its row says otherwise. Each repository's backlog names the IDs.

### Milestone 0: groundwork in the hub and ModelANT

| ID | Work | Repo |
|---|---|---|
| LAI-H1 | Require the GenAI library and both headers in the Linux artifact check; the header copy fails instead of `\|\| true`. Done 2026-10-30. | hub |
| LAI-H2 | Build GenAI with llguidance on Windows. Done: `:winamd64` ships it, and its smoke gate runs a schema-constrained `generate()` over the [test model](#the-test-model) with the schema case from its `fixture.json`. | hub |
| LAI-H3 | This page: the decisions, the contract, the model search order. Done 2026-10-30. | hub |
| LAI-H4 | A fixture that writes a tiny GenAI model, its config and tokenizer, so no test loads a model file ([§ The test model](#the-test-model)). Done 2026-10-30. | hub |
| LAI-H5 | The image smoke's GenAI tier 4 decodes the test model on every arch instead of reporting `generate()` as unproven. Done 2026-10-30; arm64 and riscv64 prove it at the next chain. | hub |
| LAI-M1 | ModelANT's licence rule, README and model guide follow [§ Licences](#licences). Done 2026-10-30 (`scripts/license_policy.py`); its release notes still state Apache-2.0 for every model. | ModelANT |
| LAI-M2 | The `text-generation-v1` contract and its release check. Done 2026-10-30. | ModelANT |
| LAI-M3 | GenAI export and package scripts. Done 2026-10-30 (`scripts/export_genai.py`): a reproducible `.tar.xz` and a `.deb`; no `.msi` yet. | ModelANT |
| LAI-M4 | The first release, SmolLM2-135M-Instruct for CPU; then the default chat model. `smollm2_135m_instruct-v1` published 2026-10-30. The default chat model is Qwen3-0.6B (owner, 2026-11-30): exported for `cpu`, `cuda`, `dml` and the web, with a `text-generation-v1` case that emits a tool call, and rows in the consumers' `llm.lock`; open. | ModelANT |

### Milestone 1: text in every repository

| ID | Work | Repo |
|---|---|---|
| LAI-A1 | `kataglyphis.text_generation` over `ort_genai.h`, beside the detector; the execution provider comes from the config. Done 2026-10-30: GenAI is loaded at run time, and the provider is an argument of `initialize`. | AccelerANTgine |
| LAI-A2 | C API with opaque handles and a token callback. Done 2026-10-30 (`kataglyphis_c_api.h`). OmniAccelerANT's plugin no longer links AccelerANTgine (its owner decision D1, 2026-11-21), so no app calls it. | AccelerANTgine |
| LAI-A3 | nanobind class with a lock, CLI `chat`, a `[text_generation]` config section. Done 2026-10-30 without the config section, which nothing would read yet. | AccelerANTgine |
| LAI-O1 | A text crate over `ort_genai_c.h`, loaded dynamically and verified like ORT; the endpoint through `ureq`. Done 2026-10-30 (`crates/text`): a GenAI that does not embed the chain's build tree is refused. | OxidANT |
| LAI-O2 | CLI `chat` and `embed`. Done 2026-10-30: `chat` on both backends, `embed` on an endpoint. | OxidANT |
| LAI-O3 | FRB `api/text.rs` with a `StreamSink` for tokens. Done 2026-10-30. | OxidANT |
| LAI-P1 | `orchestrant/genai/`, `orchestrant-chat`, and `orchestrant-serve` as an OpenAI-compatible server over GenAI. Done 2026-10-30. | OrchestrANT |
| LAI-P2 | `orchestrant-bench` measures the chain's own engine next to Ollama and GenieX. Done 2026-10-30: `backends.json` names it `chain-genai`. The first figures are SmolLM2 alone on the amd64 build host's CPU; a run beside Ollama and GenieX needs their hosts. | OrchestrANT |
| LAI-F1 | The AI Playground page (`aiPlayground`) with streaming and the speed figures. Done 2026-10-30. | OmniAccelerANT |
| LAI-F2 | Endpoint settings on every platform; local through LAI-O3 on Windows and Linux. Done 2026-10-30; the web build fetches whole answers, and the settings are not saved yet. | OmniAccelerANT |
| LAI-F3 | Chat widgets: message list, Markdown answer, input. Done 2026-10-30 (`lib/Widgets/Chat/`). | ANThology |

### Milestones 2 to 5

| Milestone | IDs | Work |
|---|---|---|
| 2 NLP and search | LAI-O5 | Embeddings in OxidANT. Done 2026-11-04: `GenaiGenerator::embed`, the CLI's `embed --model-dir` and the bridge's `text_embed`, proven on the test model's `hidden_states`; no released model has that output yet. |
| 2 NLP and search | LAI-P3 | The NAS document AI. Its first slice runs in OrchestrANT: `orchestrant-docs` indexes a tree's text and answers with citations; OCR, images and semantic search are open. |
| 2 NLP and search | LAI-P4 | Classification, entities, summaries and translation between German and English with a JSON schema. Done 2026-11-04 (`orchestrant-text`): the tiny model proves the plumbing, and no quality has been measured. |
| 3 Speech | LAI-A4, LAI-F4 | A GStreamer audio appsink and Whisper captions as `textoverlay` and WebRTC data; microphone input in the app. |
| 4 Language meets vision | LAI-O4 | ObservANT's `/ask` and a daily summary over `/visits`. Done 2026-11-04: the model reads the log's figures, not the picture; a summary is on request, and nothing sends one on a schedule. Proven on the CPU with the test model and SmolLM2, whose answers are not good; the default chat model is LAI-M4's. |
| 4 Language meets vision | LAI-F5 | Questions on the Stream page. Done 2026-11-04: a camera whose `/healthz` says `ask` offers them on its own web page; proven in Chrome against the real service with the test model and SmolLM2. Native builds have no ObservANT to ask. |
| 4 Language meets vision | LAI-P5 | `yolo-monitor --describe`. Done 2026-11-04: a sentence from the detection counts, off the frame loop. |
| 5 Extensions | LAI-H6 and spikes | GenAI for Android; HailoRT GenAI on Hailo-10H; QNN in process; a tool-calling agent over OrchestrANT's metrics; speech output. |

## Fetching a released model

A consumer's `llm.lock` pins the archive like any other data file, and the hub fetcher unpacks it:

```text
# sha256                                                          file                               url
b3853a1cd5c0af0d604fdae0b3d495a2f3d4ec7ab0653704b4e6b896d5a27f8f  smollm2_135m_instruct-cpu.tar.xz  https://github.com/Kataglyphis/ModelANT/releases/download/smollm2_135m_instruct-v1/smollm2_135m_instruct-cpu.tar.xz
```

`fetch-data-lock.py --lock llm.lock --dest DIR --extract` leaves the GenAI model directory at
`DIR/smollm2_135m_instruct-cpu/`. The release's `contract.tar.gz` holds the cases a binding replays
against it, such as "What is the capital of France?" decoding to "The capital of France is Paris."

## Rules every item keeps

- ORT and GenAI come from the chain only: [`onnxruntime-single-source.md`](onnxruntime-single-source.md).
- Weights live in ModelANT and arrive by lock.
- A test asserts tokens. "The model loads" is not a pass.
- GenAI has no free-threading marker. Python imports it lazily, and a free-threaded run asserts
  that it is absent.
- Every new gate is mutation-tested.
