Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Coach: a compatible endpoint whose API has no /v1 (Open WebUI's /openai mount) is reached on a 404 fallback (#508)

Duarte Santos17fa38a1c890
diff --git a/api/coach/core/adapters/compatible.js b/api/coach/core/adapters/compatible.js
index c2aa4af8f..641764159 100644
--- a/api/coach/core/adapters/compatible.js
+++ b/api/coach/core/adapters/compatible.js
@@ -6,6 +6,7 @@ import { httpAdapter } from './http.js';
import { chatCompletionsSpec } from './openai.js';
// temperature 0: a plan diff wants determinism, and greedy decoding is also what grammar-
-// constrained sampling on a local server handles fastest.
-export const compatibleSpec = chatCompletionsSpec('compatible', { maxTokensField: 'max_tokens', temperature: 0 });
+// constrained sampling on a local server handles fastest. A gateway that mounts the API under a
+// path without a version (Open WebUI's /openai) is reached by the 404 fallback in http.js (#508).
+export const compatibleSpec = chatCompletionsSpec('compatible', { maxTokensField: 'max_tokens', temperature: 0, versionlessFallback: true });
export default httpAdapter(compatibleSpec);
diff --git a/api/coach/core/adapters/http.js b/api/coach/core/adapters/http.js
index f105e3a46..982580586 100644
--- a/api/coach/core/adapters/http.js
+++ b/api/coach/core/adapters/http.js
@@ -48,7 +48,35 @@ const VERSION_SEGMENT = /\/v\d+(?:(?:alpha|beta)\d*)?(?=\/|$)/i;
export function endpointUrl(base, path) {
const basePath = base.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i, '');
if (!VERSION_SEGMENT.test(basePath)) return base + path;
- return base + path.replace(new RegExp('^' + VERSION_SEGMENT.source, 'i'), '');
+ return base + path.replace(LEADING_VERSION, '');
+}
+const LEADING_VERSION = new RegExp('^' + VERSION_SEGMENT.source, 'i');
+
+// The third shape (#508): a prefix but no version at all, like Open WebUI's /openai mount, which
+// answers {base}/chat/completions and 404s anything with /v1 in it. A spec that opts in
+// (`versionlessFallback`) tries the other form once on a 404, and the base that answered
+// without the version is remembered so the next request goes there first. A bare host and every
+// base that works today still gets exactly the request it got before.
+const versionlessBases = new Set();
+function candidateUrls(spec, base, path) {
+ const url = endpointUrl(base, path);
+ if (!spec.versionlessFallback) return [url];
+ const bare = base + path.replace(LEADING_VERSION, '');
+ if (bare === url) return [url];
+ return versionlessBases.has(base) ? [bare, url] : [url, bare];
+}
+
+/** `send(url)` with the fallback above. When the other form fails as well, the first answer is
+ * the one returned, so Ollama's "model not found" 404 still reaches the person unchanged. */
+async function reach(spec, base, path, send) {
+ const urls = candidateUrls(spec, base, path);
+ const first = await send(urls[0]);
+ if (first.status !== 404 || urls.length < 2) return first;
+ const second = await send(urls[1]);
+ if (!second.ok) { try { await second.text(); } catch { /* drained or gone */ } return first; }
+ if (urls[1] === endpointUrl(base, path)) versionlessBases.delete(base);
+ else versionlessBases.add(base);
+ return second;
}
/** A fetch, bounded by AbortController. Never throws for HTTP status; throws for transport. */
@@ -111,7 +139,7 @@ export function httpAdapter(spec) {
if (!key && !meta.keyOptional) return { ok: false, error: 'no API key configured', models: [] };
let res;
try {
- res = await call(fetchImpl, endpointUrl(base, spec.modelsPath), { method: 'GET', headers: { ...extraHeadersFor(id, cfg), ...spec.headers(key) } }, timeoutMs, signal);
+ res = await reach(spec, base, spec.modelsPath, url => call(fetchImpl, url, { method: 'GET', headers: { ...extraHeadersFor(id, cfg), ...spec.headers(key) } }, timeoutMs, signal));
} catch (e) {
return { ok: false, error: e.name === 'AbortError' ? 'timed out' : `could not reach ${hostOf(base)}: ${trim(e.message, 120)}`, models: [] };
}
@@ -143,11 +171,11 @@ export function httpAdapter(spec) {
for (;;) {
let res;
try {
- res = await call(fetchImpl, endpointUrl(base, spec.path(chosen)), {
+ res = await reach(spec, base, spec.path(chosen), url => call(fetchImpl, url, {
method: 'POST',
headers: { ...extraHeadersFor(id, cfg), 'content-type': 'application/json', ...spec.headers(key) },
body: JSON.stringify(body)
- }, timeoutMs, signal);
+ }, timeoutMs, signal));
} catch (e) {
if (e.name === 'AbortError') return { code: -1, text: '', stderr: 'timed out', timedOut: true };
return { code: 1, text: '', stderr: `could not reach ${hostOf(base)}: ${trim(e.message, 200)}` };
diff --git a/api/coach/core/adapters/openai.js b/api/coach/core/adapters/openai.js
index 02d8ee5f8..f206fb010 100644
--- a/api/coach/core/adapters/openai.js
+++ b/api/coach/core/adapters/openai.js
@@ -7,9 +7,10 @@
import { httpAdapter } from './http.js';
import { SYSTEM_PROMPT } from '../system-prompt.js';
-export function chatCompletionsSpec(id, { maxTokensField = 'max_completion_tokens', temperature = null } = {}) {
+export function chatCompletionsSpec(id, { maxTokensField = 'max_completion_tokens', temperature = null, versionlessFallback = false } = {}) {
return {
id,
+ versionlessFallback,
path: () => '/v1/chat/completions',
modelsPath: '/v1/models',
headers: key => (key ? { authorization: 'Bearer ' + key } : {}),
diff --git a/api/test/adapters-http.test.js b/api/test/adapters-http.test.js
index d2629e947..6849c2f37 100644
--- a/api/test/adapters-http.test.js
+++ b/api/test/adapters-http.test.js
@@ -132,6 +132,64 @@ test('compatible: a base that already names its API version is used as the full
}
});
+test('compatible: a mount whose API has no version segment is reached on the 404 fallback and remembered (#508)', async () => {
+ // The issue's repro: an OpenAI-shaped mount (Open WebUI's /openai) that 404s anything with /v1.
+ const { createServer } = await import('node:http');
+ const hits = [];
+ const server = createServer((req, res) => {
+ const url = req.url.split('?')[0];
+ hits.push(req.method + ' ' + url);
+ const send = (status, o) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(o)); };
+ if (url === '/openai/models') return send(200, { object: 'list', data: [{ id: 'a-local-model', object: 'model' }] });
+ if (url === '/openai/chat/completions' && req.method === 'POST') {
+ req.resume();
+ return req.on('end', () => send(200, { object: 'chat.completion', choices: [{ index: 0, message: { role: 'assistant', content: ANSWER }, finish_reason: 'stop' }] }));
+ }
+ req.resume();
+ return send(404, { detail: 'Not Found' });
+ });
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ try {
+ const base = `http://127.0.0.1:${server.address().port}/openai`;
+ const cfg = { provider: 'compatible', providerOptions: { compatible: { baseUrl: validateBaseUrl(base).value } } };
+ const m = await compatible.models(cfg, env);
+ assert.deepEqual(m, { ok: true, models: ['a-local-model'] });
+ const r = await compatible.invoke({ cfg, env, model: 'a-local-model', prompt: 'ping', maxTokens: 64 });
+ assert.equal(r.code, 0, r.stderr);
+ assert.equal(r.text, ANSWER);
+ // The first call of all tried /v1, every later one went straight to the form that answered.
+ assert.deepEqual(hits, ['GET /openai/v1/models', 'GET /openai/models', 'POST /openai/chat/completions']);
+ } finally {
+ await new Promise(resolve => server.close(resolve));
+ }
+});
+
+test('compatible: the 404 fallback keeps the first error when neither form answers, and never touches other providers (#508)', async () => {
+ // Ollama answers an unknown model with a 404 of its own; that message must survive the retry.
+ const f = fakeFetch(n => (n === 1
+ ? { status: 404, body: { error: { message: 'model "nope" not found, try pulling it first' } } }
+ : { status: 404, body: '404 page not found' }));
+ const r = await compatible.invoke({ cfg: cfgCompat, prompt: 'P', env: {}, model: 'nope', fetch: f });
+ assert.deepEqual(f.calls.map(c => c.url), ['http://ollama.lan:11434/v1/chat/completions', 'http://ollama.lan:11434/chat/completions']);
+ assert.equal(r.code, 1);
+ assert.match(r.stderr, /^404 model "nope" not found/);
+ // …and a failed fallback teaches nothing: the next request still starts at /v1.
+ const g = fakeFetch([ok({ data: [] })]);
+ await compatible.models(cfgCompat, {}, { fetch: g });
+ assert.equal(g.calls[0].url, 'http://ollama.lan:11434/v1/models');
+
+ // A base that carries its version has only one form, so a 404 there is final.
+ const v = fakeFetch([{ status: 404, body: { error: 'nope' } }]);
+ await compatible.invoke({ cfg: { provider: 'compatible', providerOptions: { compatible: { baseUrl: 'https://openrouter.ai/api/v1' } } }, prompt: 'P', env: {}, model: 'm', fetch: v });
+ assert.equal(v.calls.length, 1);
+
+ // OpenAI itself always lives at /v1; a 404 there is a real answer, not a missing prefix.
+ const o = fakeFetch([{ status: 404, body: { error: { message: 'The model `x` does not exist' } } }]);
+ const ro = await openai.invoke({ cfg: {}, prompt: 'P', env, model: 'x', fetch: o });
+ assert.equal(o.calls.length, 1);
+ assert.match(ro.stderr, /^404 The model/);
+});
+
test('compatible: no endpoint configured, or no model chosen, is a clean failure rather than a request', async () => {
const f = fakeFetch([]);
const none = await compatible.invoke({ cfg: {}, prompt: 'P', env: {}, model: 'x', fetch: f });
diff --git a/docs/AI_COACH.md b/docs/AI_COACH.md
index 71eb243df..6666179b0 100644
--- a/docs/AI_COACH.md
+++ b/docs/AI_COACH.md
@@ -77,7 +77,8 @@ answers on instead, and a key only if it wants one.
jobs went. Paste the base the way the provider documents it: a bare host
(`http://ollama.lan:11434`) gets `/v1` added, and a base that already carries its version
(`https://openrouter.ai/api/v1`, Zhipu's `…/paas/v4`, Gemini's `…/v1beta/openai`) is used
- as it is.
+ as it is. A base whose API has no version at all (Open WebUI's `…/openai` mount) works too:
+ when `{base}/v1/…` answers 404, the app tries `{base}/…` and remembers which one answered.
- A gateway that demands extra headers gets them under **Extra headers**: one `Name: value`
per line (e.g. opencode Go's `x-opencode-session`), sent with the list, test and job
calls. `Authorization` and `Content-Type` are refused there — auth framing always wins.