fix(ai): connect and read bookings through any OpenAI-compatible own server

Connecting an own server asked Ollama's /api/tags and gave up on any answer
that was not a 404, and every failure, a refused key included, read as "not
responding". The model list is now looked for at /api/tags, at the address as
entered and at /v1/models, an answer only counts when it is a list, and a
refused key or a server that answered without a list say so (#2808).

AI parsing through an own server always called Ollama's /api/chat, which an
OpenAI-compatible server such as Groq answers with 404. A server without it
now gets the same extraction over /chat/completions at the address as
entered (#2806).
This commit is contained in:
Maurice
2026-10-26 09:46:30 +01:00
parent 8ba7add541
commit b8990782cc
39 changed files with 538 additions and 39 deletions
@@ -91,7 +91,17 @@ const PROVIDER_MESSAGES: Partial<Record<AssistantErrorCode, string>> = {
provider_unavailable: 'The provider is not responding',
};
/** A provider's failure as the refusal a REST route answers with. */
/**
* A provider's failure as the refusal a REST route answers with. An own server
* that answered without a model list says so in `reason`, so the form can name
* the address instead of calling a server that is up unresponsive (#2808).
*/
export function providerRefusal(err: AiProviderError): DomainError {
if (err.providerCode === 'no_model_list') {
return new DomainError(REFUSAL_STATUS[err.code], 'The server answered, but sent no model list', {
code: err.code,
details: { code: err.code, reason: 'no_model_list' },
});
}
return aiRefusal(err.code, PROVIDER_MESSAGES[err.code] ?? 'The provider refused the request');
}
@@ -238,7 +238,15 @@ export class ModelCatalogService {
const { models } = await this.llmLocal.listModels(baseUrl ?? undefined, apiKey ?? undefined);
return models.map((m) => ({ id: m.name, label: m.name, supportsTools: true }));
} catch (err) {
if (err instanceof DomainError) throw new AiProviderError('provider_unavailable', err.getStatus(), true);
// The server's own answer decides what the admin reads: a refused key, a
// server that answered without a model list, or one that is not there.
// All three read as "not responding" before, which sent people looking
// at a server that was up (#2808).
if (err instanceof DomainError) {
if (err.code === 'llm_key_refused') throw new AiProviderError('invalid_key', err.getStatus(), false);
const reason = err.code === 'llm_no_model_list' ? 'no_model_list' : undefined;
throw new AiProviderError('provider_unavailable', err.getStatus(), true, undefined, reason);
}
throw err;
}
}
+73 -29
View File
@@ -26,6 +26,12 @@ const tagsResponseSchema = z.object({
/** The OpenAI-compatible list (`GET /v1/models`) that LM Studio, vLLM and llama.cpp serve. */
const openAiModelsSchema = z.object({ data: z.array(z.object({ id: z.string().optional() })) });
/** One place a server may list its models, and how its answer reads. */
interface ModelListSource {
url: string;
read: (body: unknown) => { name?: string; size?: number }[] | undefined;
}
/** The Bearer header the extraction sends, when a key is configured. */
function authHeader(apiKey: string | undefined): Record<string, string> {
return apiKey ? { authorization: `Bearer ${apiKey}` } : {};
@@ -43,11 +49,23 @@ function upstreamRefusal(status: number, apiKey: string | undefined, fallback: s
apiKey
? `Local LLM server rejected the API key (${status})`
: `Local LLM server requires an API key (${status}). Save the key for this address first.`,
{ code: 'llm_key_refused' },
);
}
return new DomainError(502, fallback);
}
/**
* A URL without its trailing slashes. Scanned off instead of `/\/+$/`-replaced:
* that pattern re-walks the slash run from every start position of the
* admin-supplied URL.
*/
function trimTrailingSlashes(url: string): string {
let end = url.length;
while (end > 0 && url.charCodeAt(end - 1) === 47 /* '/' */) end--;
return url.slice(0, end);
}
/**
* Admin helpers for managing a local OpenAI-compatible LLM server (Ollama).
* Talks to Ollama's *management* API (`/api/tags`, `/api/pull`), which lives at
@@ -72,11 +90,7 @@ export class LlmLocalService {
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new HttpException({ error: 'Base URL must be http(s)' }, 400);
}
// Trailing slashes are scanned off instead of `/\/+$/`-replaced: that pattern
// re-walks the slash run from every start position of the admin-supplied URL.
let end = raw.length;
while (end > 0 && raw.charCodeAt(end - 1) === 47 /* '/' */) end--;
return raw.slice(0, end).replace(/\/v1$/, '');
return trimTrailingSlashes(raw).replace(/\/v1$/, '');
}
/**
@@ -94,39 +108,69 @@ export class LlmLocalService {
}
/**
* List models already pulled on the local server. A server without Ollama's
* `/api/tags` (LM Studio, vLLM, llama.cpp) answers 404 there, so its
* OpenAI-compatible `/v1/models` is asked instead.
* List the models the server offers. Ollama's `/api/tags` is asked first, then
* the OpenAI-compatible list: at the address as entered (the one the chat
* calls `/chat/completions` on, `https://api.groq.com/openai/v1` say), then at
* `/v1/models` under the root for an address given without `/v1`.
*
* An answer only counts when it reads as a model list. LM Studio answers an
* unknown path with 200 and an error object, and a proxy may answer it with a
* login page, so stopping at the first answer that is not a 404 refused
* servers whose list was one request further (#2808).
*/
async listModels(
baseUrl: string | undefined,
apiKey?: string,
): Promise<{ models: { name: string; size: number }[] }> {
const root = this.ollamaRoot(baseUrl);
let res = await this.getModelList(`${root}/api/tags`, root, apiKey);
let openAi = false;
if (res.status === 404) {
const fallback = await this.getModelList(`${root}/v1/models`, root, apiKey);
if (fallback.ok) {
discardBody(res);
res = fallback;
openAi = true;
const asEntered = trimTrailingSlashes((baseUrl ?? '').trim()) || root;
const lists: ModelListSource[] = [
{ url: `${root}/api/tags`, read: (body) => tagsResponseSchema.safeParse(body).data?.models },
...[...new Set([`${asEntered}/models`, `${root}/v1/models`])].map((url) => ({
url,
read: (body: unknown) => openAiModelsSchema.safeParse(body).data?.data.map((m) => ({ name: m.id, size: 0 })),
})),
];
const seen = { firstStatus: 0, refusedStatus: 0 };
const listed = await this.firstModelList(lists, 0, root, apiKey, seen);
if (listed) return { models: listed.map((m) => ({ name: m.name ?? '', size: m.size ?? 0 })).filter((m) => m.name) };
if (seen.refusedStatus) throw upstreamRefusal(seen.refusedStatus, apiKey, '');
throw new DomainError(502, `Local LLM server sent no model list (${seen.firstStatus})`, {
code: 'llm_no_model_list',
});
}
/**
* The first of `lists`, from `index` on, that answers with a readable list,
* asked one after the other. Only the first request tells whether the server
* is there at all; a later one failing is that path, not the server.
*/
private async firstModelList(
lists: ModelListSource[],
index: number,
root: string,
apiKey: string | undefined,
seen: { firstStatus: number; refusedStatus: number },
): Promise<{ name?: string; size?: number }[] | null> {
const list = lists[index];
if (!list) return null;
let res: Response | null = null;
try {
res = await this.getModelList(list.url, root, apiKey);
} catch (err) {
if (index === 0) throw err;
}
if (res) {
seen.firstStatus ||= res.status;
if (res.status === 401 || res.status === 403) seen.refusedStatus ||= res.status;
if (res.ok) {
const listed = list.read(await readCappedJson<unknown>(res, MAX_LIST_BYTES).catch(() => undefined));
if (listed) return listed;
} else {
// Neither list exists: report the first answer, as before.
discardBody(fallback);
discardBody(res);
}
}
if (!res.ok) {
discardBody(res);
throw upstreamRefusal(res.status, apiKey, `Local LLM server error (${res.status})`);
}
const body = await readCappedJson<unknown>(res, MAX_LIST_BYTES);
const listed = openAi
? openAiModelsSchema.safeParse(body).data?.data.map((m) => ({ name: m.id, size: 0 }))
: tagsResponseSchema.safeParse(body).data?.models;
if (!listed) throw new DomainError(502, 'Local LLM server sent an unreadable model list');
const models = listed.map((m) => ({ name: m.name ?? '', size: m.size ?? 0 })).filter((m) => m.name);
return { models };
return this.firstModelList(lists, index + 1, root, apiKey, seen);
}
private async getModelList(url: string, root: string, apiKey: string | undefined): Promise<Response> {
@@ -1,5 +1,7 @@
/**
* Minimal Ollama native-API client used by the extraction router.
* Minimal Ollama native-API client used by the extraction router. A server that
* has no `/api/chat` gets the same extraction over OpenAI-compatible
* `/chat/completions` instead (see extractOpenAiCompatible below).
*
* Why not the OpenAI-compatible `/v1/chat/completions` path the rest of llm-parse uses?
* Ollama's `/v1` endpoint does NOT faithfully honour OpenAI's `response_format:{json_schema,strict}`
@@ -12,7 +14,9 @@
*/
import { readEnv } from '../../../app-config';
import { safeFetchLlm } from '../../../utils/ssrfGuard';
import { OpenAiCompatibleClient } from '../clients/openai-compatible.client';
import { parseLenientJson } from '../lenient-json';
import type { LlmExtractionFile } from '../llm-provider.interface';
export interface EnforcedExtractInput {
/** Ollama base URL — accepts the addon's `…/v1` form; the `/v1` suffix is stripped. */
@@ -40,6 +44,13 @@ export function toNativeBase(baseUrl: string): string {
return baseUrl.slice(0, end).replace(/\/v1$/, '');
}
/**
* The answers that say the server has no `/api/chat` at all, unless the body is
* Ollama's own 404 for a model it has not pulled (OLLAMA_MISSING_MODEL).
*/
const NOT_OLLAMA_STATUSES = new Set([404, 405, 501]);
const OLLAMA_MISSING_MODEL = /model.*not found/i;
/**
* Run one schema-constrained chat completion against Ollama's native `/api/chat`.
* Returns the parsed JSON object (constrained to `schema`), or null if the request
@@ -85,10 +96,61 @@ export async function extractEnforced(input: EnforcedExtractInput): Promise<Reco
if (!res.ok) {
const detail = await res.text().catch(() => '');
if (NOT_OLLAMA_STATUSES.has(res.status) && !OLLAMA_MISSING_MODEL.test(detail))
return extractOpenAiCompatible(input);
throw new Error(`Ollama /api/chat failed (${res.status}): ${detail.slice(0, 200)}`);
}
const data = (await res.json()) as { message?: { content?: string } };
const data = (await res.json().catch(() => null)) as { message?: { content?: string } } | null;
// LM Studio answers a path it does not serve with 200 and an error object,
// so an answer without Ollama's `message` is a server of another kind too.
if (!data || typeof data.message !== 'object') return extractOpenAiCompatible(input);
const parsed = parseLenientJson(data.message?.content);
return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : null;
}
/**
* The same extraction against an OpenAI-compatible server (Groq, vLLM,
* LM Studio, a LiteLLM proxy), which the "Own server" connection also names.
* It goes to `/chat/completions` at the address as entered, the endpoint the
* assistant chats on, through the client that already handles what such
* servers refuse (`json_schema`, `max_tokens`, `temperature`). The schema is
* asked for as a one-element list, the shape that client reads (#2806).
*/
async function extractOpenAiCompatible(input: EnforcedExtractInput): Promise<Record<string, unknown> | null> {
const [file, ...pageImages] = (input.images ?? []).map(imageFile);
const list = await new OpenAiCompatibleClient().extract({
// The shape goes into the prompt as well: the client's later rungs send no
// schema (json_object, then nothing), and json_object wants the word JSON.
prompt:
`${input.system} Answer with JSON only, as {"result": [object]} where the object follows this ` +
`JSON Schema: ${JSON.stringify(input.schema)}`,
jsonSchema: {
type: 'object',
properties: { result: { type: 'array', items: input.schema } },
required: ['result'],
},
rootKey: 'result',
userText: input.user,
model: input.model,
baseUrl: input.baseUrl,
apiKey: input.apiKey,
file,
pageImages,
});
const first = list[0];
return first && typeof first === 'object' ? first : null;
}
/** The first characters of a base64 image, per type. Anything else is sent as JPEG. */
const IMAGE_PREFIXES: [string, string][] = [
['iVBOR', 'image/png'],
['UklGR', 'image/webp'],
['R0lGOD', 'image/gif'],
];
/** A base64 image as a file, its type read from its first bytes. */
function imageFile(base64: string): LlmExtractionFile {
const mimeType = IMAGE_PREFIXES.find(([prefix]) => base64.startsWith(prefix))?.[1] ?? 'image/jpeg';
return { mimeType, data: Buffer.from(base64, 'base64') };
}