Files
Sprachmittler-Kit/docs/OLLAMA_TRANSLATION_API.md
T

194 lines
9.6 KiB
Markdown

# Ollama translation API contract
Status: Draft v1.0 · Verified against **Ollama 0.40.18, 2026-11-26, Apple M5 Pro 48 GB, macOS 27.2.1**, model `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M`.
Items marked **VERIFY** must be confirmed against your Ollama with `make fixtures` (T1.1) before code depends on them. Record the Ollama version and model digest in `Fixtures/capture-meta.json`.
All networking lives in `SprachmittlerOllama`. Base URL comes from settings (default `http://127.0.0.1:11434`) and passes `EndpointPolicy.validate` (see `docs/SECURITY_PRIVACY.md`).
## 1. Translation request: `POST /api/chat`
One user message. No system message, no images, no `think` for Hy-MT3.
```json
{
"model": "hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M",
"messages": [
{
"role": "user",
"content": "Translate the following text into German. Note that you should **only output the translated result without any additional explanation**:\n\nThe figure above plots …"
}
],
"stream": true,
"keep_alive": "30m",
"options": {
"temperature": 0.7,
"top_p": 0.6,
"top_k": 20,
"repeat_penalty": 1.05,
"num_predict": 4096,
"num_ctx": 8192
}
}
```
Rules:
- `content` is the adapter's documented prompt for the selected variant (see `docs/HYMT3_MODEL.md`). The default template is byte-exact.
- `messages` contains exactly one user message. Do not add a system message: the model has no default system prompt, and the template uses `<|extra_4|>` only for a system message.
- Do not send `images`; Hy-MT3 is text-only.
- Do not send `think`; `/api/show` reports only `completion`, not `thinking`.
- `keep_alive` comes from settings. `"0"` unloads the model after the response; `"30m"` keeps it warm.
- `num_predict` is always set (output cap). `num_ctx` is always set to 8192 (the model card's translation context; see §7).
- Send only the option keys above. Do not rely on Ollama ignoring unknown keys.
- No `format` (JSON mode) in v1. The prompt itself preserves JSON when the source is JSON.
### 1.1 Streaming response
NDJSON, one object per line. A delta:
```json
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T09:00:00Z","message":{"role":"assistant","content":"Die obige Grafik"},"done":false}
```
The final line:
```json
{"model":"…","created_at":"…","message":{"role":"assistant","content":""},"done":true,"done_reason":"stop",
"total_duration":6519029875,"load_duration":799545833,"prompt_eval_count":178,"prompt_eval_duration":199759000,
"eval_count":246,"eval_duration":5513836000}
```
- Durations are nanoseconds. Map them into `ChatMetrics` (load, prompt eval, eval, total; token counts).
- `done_reason`: `"stop"` = normal end; `"length"` = hit `num_predict` → warning `truncated`, Replace disabled by default. Treat any other value as `"stop"` but log it at `.info`. **VERIFY** the full set of values.
- A line `{"error":"…"}` may appear mid-stream. Map it with §5 and stop.
### 1.2 Decoding rules
- Read with `URLSession.bytes(for:)`, split on `\n`, decode each complete line; carry a partial line over to the next chunk.
- Append `message.content` deltas to a buffer and forward them to the session and the `TranslationGuard` as they arrive.
- Never assume one token per line.
- Cancellation: `AsyncThrowingStream.onTermination` cancels the URL task.
- The stream buffer is bounded by the chunk size; do not accumulate unbounded output.
### 1.3 Timeouts
| Phase | Default | Meaning |
|---|---|---|
| connect | 3 s | TCP connect plus TLS |
| firstToken | 120 s | request sent → first `message.content` byte; includes cold model load |
| idle | 20 s | gap between lines once streaming has started |
| totalPerChunk | 180 s | hard cap per chunk |
All injectable via a `Clock` for tests.
## 2. Model discovery
### 2.1 `GET /api/version`
`{"version":"0.40.18"}`. The minimum supported version is recorded in T1.1 and checked in onboarding.
### 2.2 `GET /api/tags`
```json
{"models":[{"name":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M",
"modified_at":"…","size":5150000000,"digest":"sha256…","details":{"format":"gguf","family":"hunyuan-dense",
"parameter_size":"7.5B","quantization_level":"Q4_K_M"}}]}
```
Store `name`, `digest`, `size` and `details`. Normalise `name:latest` ↔ `name` when comparing with presets. Detect the Hy-MT3 family by a case-insensitive `hy-mt3` match, not by a hard-coded installed list.
### 2.3 `POST /api/show`
Request `{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M"}`. Verified fields:
| Field | Observed value | Use |
|---|---|---|
| `capabilities` | `["completion"]` | Text-only; no vision, no thinking |
| `details` | family `hunyuan-dense`, parameter size `7.5B`, quantization `Q4_K_M` | UI metadata |
| `parameters` | only stop tokens (`<|startoftext|>`, `<|extra_4|>`, `<|extra_0|>`, `<|eos|>`) | No sampling defaults; the adapter must set them |
| `template` | `{{ if .System }}…{{ if .Prompt }}<|startoftext|>{{ .Prompt }}<|extra_0|>{{ end }}{{ .Response }}<|eos|>` | Confirms no default system prompt |
| `model_info` | `hunyuan-dense.context_length = 262144` | Informational; the card's translation context is 8192 |
| `license` | `null` in Ollama | Show the Hugging Face licence (Apache-2.0) in Settings |
**VERIFY** for the 1.8B tag and for future versions.
### 2.4 `GET /api/ps`
```json
{"models":[{"name":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","size":6488609259,"size_vram":6488609259,"expires_at":"…"}]}
```
Used by diagnostics and the evaluation harness for resident memory. Not polled by the app.
## 3. Warm-up
Optional (`warmUpOnLaunch`, local endpoint only): send `POST /api/chat` with the selected model, a fixed synthetic sentence (for example `Hello.`), `num_predict: 8`, and discard the output. **Never** use the user's text for warm-up. The request shape is the same as §1.
## 4. Option mapping
| Publisher setting | Ollama option | Default |
|---|---|---|
| `temperature` | `temperature` | 0.7 |
| `top_p` | `top_p` | 0.6 |
| `top_k` | `top_k` | 20 |
| `repetition_penalty` | `repeat_penalty` | 1.05 |
| `max_tokens` | `num_predict` | 4096 |
| `max_context` | `num_ctx` | 8192 |
The names matter: Ollama does not read `repetition_penalty` or `max_tokens`. Do not send `do_sample`, `seed` or `stop` unless an ADR adds them.
## 5. Error classification
| Condition | HTTP / transport | Map to |
|---|---|---|
| Connection refused / host unreachable | `URLError.cannotConnectToHost`, `.cannotFindHost`, connect timeout | `ollamaUnreachable` |
| Redirect | 3xx (delegate refuses) | `endpointRejected(.redirect)` |
| Model not installed | typically 404 with body containing `not found` | `modelNotInstalled(model)` |
| Model has no Hy-MT3 adapter | discovery succeeds but name does not match | `noAdapter(model)` |
| Model is not text-capable | 400, or capabilities lack `completion` | `badRequest` / `noAdapter` |
| Out of memory / model failed to load | 500 with message containing `memory` or `load` | `server(status, message)` with recovery "Use the smaller 1.8B model or close other apps" |
| Context too small / prompt truncated | 400 or `done_reason: "length"` | `badRequest` / warning `truncated` |
| Error line mid-stream | `{"error":"…"}` | classify by message, else `server(0, message)` |
| First-token, idle or total timeout | timer | `timeout(phase)`; one retry before any delta |
| Task cancelled | `CancellationError` / `URLError.cancelled` | `cancelled`; not an error for the UI |
| Other 4xx/5xx | status | `server(status, message)` |
Error bodies are JSON `{"error":"…"}`. Fall back to the raw text (truncated to 500 characters, never containing translated text). The UI shows `userMessage`, never the raw body.
## 6. Fixtures
`scripts/capture-fixtures.sh` records into `Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/`:
- `version.json`, `tags.json`, `ps.json`
- `show-<model-slug>.json` for each installed Hy-MT3 tag
- `chat-<model-slug>-en-de.ndjson` for a fixed synthetic English sentence → German
- `chat-<model-slug>-de-en.ndjson` for a fixed synthetic German sentence → English
- `chat-<model-slug>-markdown.ndjson` for a Markdown/URL/placeholder sample
- `chat-<model-slug>-truncated.ndjson` with `num_predict: 16` → `done_reason: "length"`
- `error-missing-model.json`
- `capture-meta.json`: Ollama version, date, hardware, digests, options
Rules: synthetic inputs only; keep each fixture under 200 KB; never record private text. The recorded streams also become validator fixtures.
## 7. Prompt cache and context
- Ollama reuses the prompt prefix cache. The owner's run reported **177 of 178 prompt tokens cached**; our cold-ish run reported 178 prompt tokens with a 199 ms prompt eval. Keep the prefix byte-stable and append only the source text.
- The GGUF metadata reports `context_length = 262144`, but the model card documents **8192** for translation. Set `num_ctx: 8192`; do not rely on Ollama's default, which may be smaller and silently truncate.
- With `num_ctx: 8192`, `ollama ps` reported **6.49 GB** resident for the 7B Q4_K_M. Budget accordingly on 16 GB Macs.
## 8. Open VERIFY items
Resolved on 2026-11-26 (Ollama 0.40.18, digest `262ac792aeb5`, M5 Pro 48 GB):
- `done_reason` observed: `stop` and `length` (the truncated fixture with `num_predict: 16` ends with `length`). No `load` value seen.
- Cold/first load observed: 0.80 s and 2.05 s in two runs; warm load ~1 ms.
- A `system` message was not sent; v1 does not send one.
- Ollama strips the template's `<|eos|>` from the returned content (observed: yes).
Still open:
- Whether `keep_alive: "0"` fully unloads the model and how quickly `/api/ps` reflects it.
- The 1.8B tag behaviour: capabilities, context, memory, speed, quality.
- The full set of `done_reason` values on other inputs (e.g. an aborted stream).