mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 16:10:07 +00:00
fix(extract): retry with json_object and surface AI import failures (#1546)
OpenAI-compatible providers that only support json_object (DeepSeek, Mistral, some vLLM/llama.cpp) reject the json_schema response_format with a 400, and the resulting error was swallowed silently: not logged server-side and never rendered by the background-task widget, leaving only a generic "no reservations" message. - Retry the chat/completions request once with response_format json_object when the json_schema attempt returns 400 (non-NuExtract only); the system prompt already dictates the output shape - Log swallowed llm-parse errors with an [llm-parse] tag so failures show up in server logs - Render task warnings under the empty-preview note in the background tasks widget so the actual provider error reaches the user
This commit is contained in:
@@ -18,6 +18,10 @@ const MAX_TOKENS = 4096;
|
||||
* template inlined in a single user message, no system prompt and no
|
||||
* `response_format` (see ./nuextract.ts) — that's how the fine-tune expects to
|
||||
* be driven; the generic instruct path applies to every other model.
|
||||
*
|
||||
* Structured output is requested as `json_schema` first; servers that only
|
||||
* support `json_object` (DeepSeek, Mistral, some vLLM/llama.cpp) reject that
|
||||
* with a 400, so the request is retried once in `json_object` mode.
|
||||
*/
|
||||
export class OpenAiCompatibleClient implements LlmExtractionClient {
|
||||
async extract(input: LlmExtractionInput): Promise<Record<string, unknown>[]> {
|
||||
@@ -39,7 +43,7 @@ export class OpenAiCompatibleClient implements LlmExtractionClient {
|
||||
});
|
||||
}
|
||||
|
||||
const body = {
|
||||
const baseBody = {
|
||||
model: input.model,
|
||||
max_tokens: MAX_TOKENS,
|
||||
// Extraction is a deterministic task — Ollama defaults to 0.7, which makes
|
||||
@@ -53,33 +57,24 @@ export class OpenAiCompatibleClient implements LlmExtractionClient {
|
||||
{ role: 'system', content: input.prompt },
|
||||
{ role: 'user', content: userContent },
|
||||
],
|
||||
...(nuextract
|
||||
? {}
|
||||
: {
|
||||
response_format: {
|
||||
type: 'json_schema' as const,
|
||||
json_schema: { name: 'reservations', schema: input.jsonSchema, strict: false },
|
||||
},
|
||||
}),
|
||||
};
|
||||
const body = nuextract
|
||||
? baseBody
|
||||
: {
|
||||
...baseBody,
|
||||
response_format: {
|
||||
type: 'json_schema' as const,
|
||||
json_schema: { name: 'reservations', schema: input.jsonSchema, strict: false },
|
||||
},
|
||||
};
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
||||
let res: Response;
|
||||
try {
|
||||
// baseUrl is user-configurable — guard it against pointing at the cloud
|
||||
// metadata endpoint, while still allowing a local/LAN Ollama.
|
||||
res = await safeFetchLlm(url, {
|
||||
method: 'POST',
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
...(input.apiKey ? { authorization: `Bearer ${input.apiKey}` } : {}),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
let res = await this.send(url, body, input.apiKey);
|
||||
// Servers that only support `json_object` (DeepSeek, Mistral, some
|
||||
// vLLM/llama.cpp) reject `json_schema` with a 400 — retry once in
|
||||
// `json_object` mode. The system prompt already dictates the exact output
|
||||
// shape (and mentions JSON, which json_object mode requires).
|
||||
if (!res.ok && res.status === 400 && !nuextract) {
|
||||
res = await this.send(url, { ...baseBody, response_format: { type: 'json_object' as const } }, input.apiKey);
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
@@ -93,6 +88,26 @@ export class OpenAiCompatibleClient implements LlmExtractionClient {
|
||||
const content = data.choices?.[0]?.message?.content;
|
||||
return nuextract ? parseNuExtract(content) : parseReservations(content);
|
||||
}
|
||||
|
||||
private async send(url: string, body: unknown, apiKey?: string): Promise<Response> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
||||
try {
|
||||
// baseUrl is user-configurable — guard it against pointing at the cloud
|
||||
// metadata endpoint, while still allowing a local/LAN Ollama.
|
||||
return await safeFetchLlm(url, {
|
||||
method: 'POST',
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Strip code fences and JSON.parse; `null` on failure. */
|
||||
|
||||
@@ -71,6 +71,7 @@ export class LlmParseService {
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[llm-parse] Could not read "${file.originalName}":`, err instanceof Error ? err.message : err);
|
||||
return {
|
||||
kiItems: [],
|
||||
warnings: [`${file.originalName}: could not read file — ${err instanceof Error ? err.message : String(err)}`],
|
||||
@@ -90,6 +91,7 @@ export class LlmParseService {
|
||||
});
|
||||
return { kiItems: routed.kiItems, warnings: [...warnings, ...routed.warnings] };
|
||||
} catch (err) {
|
||||
console.error(`[llm-parse] AI parsing failed for "${file.originalName}" (provider=${config.provider}):`, err instanceof Error ? err.message : err);
|
||||
return {
|
||||
kiItems: [],
|
||||
warnings: [`${file.originalName}: AI parsing failed — ${err instanceof Error ? err.message : String(err)}`],
|
||||
@@ -102,6 +104,7 @@ export class LlmParseService {
|
||||
raw = await createLlmClient(config).extract(input);
|
||||
console.debug('[DEBUG] Raw LLM Response: ', raw);
|
||||
} catch (err) {
|
||||
console.error(`[llm-parse] AI parsing failed for "${file.originalName}" (provider=${config.provider}):`, err instanceof Error ? err.message : err);
|
||||
return {
|
||||
kiItems: [],
|
||||
warnings: [`${file.originalName}: AI parsing failed — ${err instanceof Error ? err.message : String(err)}`],
|
||||
|
||||
Reference in New Issue
Block a user