# AI model connections Every AI surface in the app talks to an OpenAI-compatible chat-completions endpoint. By default that is the Unsloth Studio box on the LAN, configured by environment variables. A stored connection lets a different provider or model be chosen from the admin panel without editing `.env` or redeploying. ## The three surfaces Each surface has its own selector, because they want different things from a model: | Surface | What it asks for | Bean counter note | |---|---|---| | AI Compose | prose, wrapped into the field's JSON shape | runs on every allowlisted field, so the cheapest capable model wins | | Dialogue draft | a whole conversation as one strict JSON object | needs the strongest schema adherence | | Dialogue rewrite | one rewritten line | prose only, a small model is fine | **Settings → AI Settings** (`ai-settings`, a global) holds the three selectors. Blank means the environment defaults, so an empty global changes nothing. ## Creating a connection **Server → AI Connections** (`ai-connections`). | Field | Notes | |---|---| | Label | shown in the selectors and recorded in draft provenance; say which provider and model | | Base URL | includes the API prefix, e.g. `http://192.168.1.7:8888/v1` or `https://api.deepseek.com/v1`. `/chat/completions` is appended | | Model id | exactly what the provider expects, e.g. `deepseek-v4.1-flash` | | API key | write-only (see below). Blank leaves the stored key alone | | Structured mode | `json_schema`, `json_object`, or `prompt` | | Send reasoning off | sends `reasoning_effort: "none"`, off for strict providers | ### The key is write-only The `apiKey` field's read access denies everyone, so it never appears in the admin form, REST, GraphQL, or a populated relationship. The server reads it with `overrideAccess: true` when it makes a request. That design makes a blank submission ambiguous, so the rule is: **blank means unchanged**. Replacing the key means typing a new one. Deleting it means ticking **Clear API key** and saving. `hasApiKey` shows whether one is stored without revealing it. The `clearApiKey` checkbox resets itself after each save so a later edit cannot silently delete a key that was just set. The key is stored as plain text in the database (there is no at-rest encryption here), so database backups contain it. If that is unacceptable for a provider, keep using the `UNSLOTH_API_KEY` env var and leave the connection's key blank: a blank connection key falls back to the env var. ## Structured output modes `json_schema` is the default and the best option: the provider enforces the schema, so a malformed draft is rejected before it reaches the app. Some OpenAI-compatible providers reject a `json_schema` request. For those: - `json_object` asks for JSON mode and puts the schema in the system prompt. - `prompt` asks for nothing and relies on the prompt, then parses the reply. Both weaker modes serialise the schema into the prompt and parse the reply, so a model that does not follow instructions still fails, but through the app's existing validate-and-retry loop rather than a provider 400. ## Test the connection before trusting it The **Test connection** button on the edit view runs two probes against the saved values: 1. a plain completion, which validates URL, key and model id; 2. a tiny structured object, which validates the configured mode. Both must pass. Every request carries a ten minute ceiling, so a host that accepts the connection and never answers fails visibly instead of hanging the button. The second one is the important one: a provider that rejects `json_schema` looks perfectly healthy on a plain completion and fails every draft. The result is stored on the record (`lastTestOk`, `lastTestedAt`, `lastTestMessage`) and cleared whenever the base URL, model id, structured mode, reasoning flag or key changes, because a passing test only describes the configuration that was tested. The clearing happens in `beforeChange`, not `afterChange`: an after-change return value is only the response of the operation, so the stored row would keep showing a stale pass while the API looked correct. Only fields actually submitted count as changed, otherwise the Test button's own result write would invalidate itself. ## What changes when a connection is active - Requests go to `baseUrl` with `modelId` and the stored key instead of the `UNSLOTH_*` values. - `reasoning_effort: "none"` is sent only when the connection allows it. - A draft's provenance records the connection label and model id, so a stored conversation still says which provider produced it. - Compose's model dropdown has a single fixed entry ("Active AI connection"). The plugin's config is built once at boot and cannot list database rows, so the label names the routing rule; the handler resolves the actual connection per request. ## Failure messages worth recognising - `… API error: 401 … Invalid API key`: the key is wrong or expired. Note that the Unsloth box rejects an unknown key with this, so a 401 against the LAN host usually means `UNSLOTH_API_KEY` is stale, not that a connection is misconfigured. - `The provider stopped sending data (60s with no response).`: the provider answered and then went quiet mid-response. The idle watchdog abandons the call rather than waiting for the total ceiling. Try again: the request is likely to route to a different upstream, and the connection's Test button tells you whether the endpoint itself is healthy. - `… API error: 400 … response_format`: the provider rejects the structured mode. Switch to `json_object` or `prompt`, or turn off the reasoning toggle if the error names `reasoning_effort`. - Drafts fail twice with `before blaming the model`: the prompt voice is suspect, not the provider. The message names which voice was in use. ## Sending the request Two things about the request are easy to get wrong, and both produced silent hangs rather than errors: - **The chat-completions endpoint, always.** `chatModelFor` reaches the model through `provider.chat(modelId)`. Calling the provider as a function (`provider(modelId)`) resolves to OpenAI's *Responses* API, which only OpenAI implements: OpenRouter, DeepSeek, Unsloth Studio and Ollama serve `/chat/completions` and nothing else. There the request still returned 200 and the draft never arrived. - **The stream must be drained.** `streamObject` is lazy: `result.object` does not resolve unless something reads the stream, so awaiting that promise alone waits for a parse that never starts. `generateStructured` drains `textStream` first. Measured against OpenRouter with one identical request: object-only never returned in 60s, draining returned a draft in 6.9s. - Transport retries are off (`maxRetries: 0`) so one stall is one wait. The draft runner already retries for a better reason: validator complaints. ## Tests - `tests/int/ai-connections.int.spec.ts`: key write-only contract, blank-means-keep, clear, per-surface resolution, half-filled fallback, test-result invalidation. - `tests/int/ai-structured-stream.int.spec.ts`: the lazy-stream guard. Fails if the drain is ever removed, which is the bug that made every draft hang. - `tests/int/ai-idle-watchdog.int.spec.ts`: healthy body passes through, a silent body fails in the silence window, a body-less response is left alone. - `tests/int/ai-generate-modes.int.spec.ts`: request shape against a local stub server (URL, model, key header, reasoning toggle), all three structured modes, and provider-error surfacing.