mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
fix(llm): let a model refuse temperature, and say which extractor is installed
Two reports, both about an import that fails without saying why. #2262 — temperature: 0 sat in the shared request body, so it went out on every attempt including both retries. Reasoning models (the gpt-5 family) reject any explicit temperature, and the json_object retry fires on any 400, so the import spent two doomed requests and could not succeed at all. The parameter is now dropped once a server has explicitly said it will not take it. Not as a third link in the chain, though. A gpt-5 rejects max_tokens AND temperature, the API names one parameter per response, and it may name either first — a chain of one-shot ifs converges on only one of the two orders. The retries are a loop over what the server actually said instead: each remedy applies at most once and they compose. Detection is a phrase, not the bare word, because dropping temperature costs the deterministic sampling that small local models depend on, and an unfamiliar wording still falls through to the json_object retry exactly as before. NuExtract and Ollama are untouched: the first attempt always carries temperature, and it is the only one they ever see. #2261 — the bundled extractor is Debian trixie's 24.12.3, roughly eighteen months behind upstream, and the reporter is right that this is invisible: a stale extractor, a mistyped KITINERARY_EXTRACTOR_PATH and a genuinely unsupported provider all look the same from the UI, which is nothing imported and no reason given. The version now appears in the startup log and in a new admin-only GET /api/admin/system-info, and LOG_LEVEL=debug passes the extractor's raw stderr through — the JS ERROR and Invalid-result-type lines the filter drops are the only evidence that a vendor script is missing or failing. Capped at 200 lines, and opt-in because those lines can carry document fragments. Not bumping the package: the filter the reporter needs first ships in KDE Gear 26.08 and no Debian suite carries it, and sid's 26.04.3 wants KF6 6.22 and Qt6 6.10.2 against trixie's 6.6 and 6.8.2 — a partial upgrade of Qt6, KF6 and libc6 from unstable into the production image, on two architectures, that still would not fix the reported carrier. It comes for free with the base-image move after Debian 14.
This commit is contained in:
@@ -8,7 +8,8 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
* at all, and every branch that resolves it is a filesystem lookup that behaves
|
||||
* differently on the three platforms TREK ships to.
|
||||
*/
|
||||
const { existsSync, readdirSync, readEnv, execFileSync, execFile } = vi.hoisted(() => ({
|
||||
const { existsSync, readdirSync, readEnv, execFileSync, execFile, logDebug } = vi.hoisted(() => ({
|
||||
logDebug: vi.fn(),
|
||||
existsSync: vi.fn(),
|
||||
readdirSync: vi.fn(),
|
||||
readEnv: vi.fn(),
|
||||
@@ -29,6 +30,11 @@ vi.mock('node:fs', () => ({
|
||||
// installed.
|
||||
vi.mock('node:child_process', () => ({ execFileSync, execFile }));
|
||||
vi.mock('../../../../src/app-config', () => ({ readEnv }));
|
||||
// The logger reads readEnv().app.logLevel while its module is evaluated, so it
|
||||
// has to be mocked rather than imported for real.
|
||||
vi.mock('../../../../src/nest/audit/audit-log.logger', () => ({
|
||||
logDebug, logInfo: vi.fn(), logWarn: vi.fn(), logError: vi.fn(),
|
||||
}));
|
||||
|
||||
import { join } from 'node:path';
|
||||
import { KitineraryExtractorService } from '../../../../src/nest/booking-import/kitinerary-extractor.service';
|
||||
@@ -124,3 +130,91 @@ describe('KitineraryExtractorService binary probe', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// #2261 — the extractor's age decides which providers parse at all, and a stale
|
||||
// one is indistinguishable from an unsupported provider without this.
|
||||
describe('KitineraryExtractorService diagnostics', () => {
|
||||
it('KIT-EXT-010: reports the version the binary prints', () => {
|
||||
existsSync.mockImplementation((p: string) => p === '/opt/ki');
|
||||
execFileSync.mockReturnValue(Buffer.from('kitinerary-extractor 6.3.3
|
||||
'));
|
||||
|
||||
expect(boot({ kitineraryExtractorPath: '/opt/ki' }).describe()).toEqual({
|
||||
available: true, path: '/opt/ki', version: '6.3.3', configuredPath: '/opt/ki',
|
||||
});
|
||||
});
|
||||
|
||||
it('KIT-EXT-011: a binary that will not answer --version stays usable', () => {
|
||||
existsSync.mockImplementation((p: string) => p === '/opt/ki');
|
||||
execFileSync.mockImplementation(() => { throw new Error('nope'); });
|
||||
|
||||
const described = boot({ kitineraryExtractorPath: '/opt/ki' }).describe();
|
||||
expect(described.available).toBe(true);
|
||||
expect(described.version).toBeNull();
|
||||
});
|
||||
|
||||
it('KIT-EXT-012: a configured path that does not exist is reported as such', () => {
|
||||
existsSync.mockReturnValue(false);
|
||||
|
||||
expect(boot({ kitineraryExtractorPath: '/nope/ki' }).describe()).toEqual({
|
||||
available: false, path: null, version: null, configuredPath: '/nope/ki',
|
||||
});
|
||||
});
|
||||
|
||||
it('KIT-EXT-013: nothing found at all reads as nothing configured', () => {
|
||||
expect(boot().describe()).toEqual({
|
||||
available: false, path: null, version: null, configuredPath: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('KIT-EXT-014: the version is probed for the /usr/lib branch too, not only for PATH', () => {
|
||||
const found = join('/usr/lib', 'x86_64-linux-gnu', 'libexec', 'kf6', 'kitinerary-extractor');
|
||||
readdirSync.mockReturnValue(['x86_64-linux-gnu']);
|
||||
existsSync.mockImplementation((p: string) => p === found);
|
||||
execFileSync.mockReturnValue(Buffer.from('kitinerary-extractor 6.3.3'));
|
||||
|
||||
expect(boot().describe().version).toBe('6.3.3');
|
||||
});
|
||||
});
|
||||
|
||||
describe('KitineraryExtractorService stderr handling', () => {
|
||||
/** Drive one extraction with a canned stderr. */
|
||||
async function extractWith(stderr: string) {
|
||||
existsSync.mockImplementation((p: string) => p === '/opt/ki');
|
||||
execFileSync.mockReturnValue(Buffer.from('kitinerary-extractor 6.3.3'));
|
||||
execFile.mockImplementation((_bin: string, _args: string[], _opts: unknown, cb: (e: unknown, r: unknown) => void) => {
|
||||
cb(null, { stdout: '[]', stderr });
|
||||
});
|
||||
await boot({ kitineraryExtractorPath: '/opt/ki' }).extract(Buffer.from(''), 'booking.eml');
|
||||
}
|
||||
|
||||
it('KIT-EXT-015: passes every raw line to the debug log, script errors included', async () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
await extractWith('JS ERROR: lufthansa.js failed
|
||||
Invalid result type from script
|
||||
');
|
||||
|
||||
const logged = logDebug.mock.calls.map(c => String(c[0]));
|
||||
expect(logged.some(l => l.includes('JS ERROR: lufthansa.js failed'))).toBe(true);
|
||||
expect(logged.some(l => l.includes('Invalid result type from script'))).toBe(true);
|
||||
// And the default level still says nothing about them.
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it('KIT-EXT-016: an unexpected line still reaches console.warn', async () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
await extractWith('JS ERROR: noise
|
||||
something genuinely odd
|
||||
');
|
||||
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining('booking.eml'), 'something genuinely odd');
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it('KIT-EXT-017: the debug dump is capped so one document cannot flood the log', async () => {
|
||||
await extractWith(Array.from({ length: 500 }, (_, i) => `line ${i}`).join('
|
||||
'));
|
||||
expect(logDebug.mock.calls.length).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -121,6 +121,72 @@ describe('OpenAiCompatibleClient', () => {
|
||||
expect(second.messages).toEqual(first.messages);
|
||||
});
|
||||
|
||||
// #2262 — reasoning models (the gpt-5 family) reject any explicit temperature.
|
||||
// temperature: 0 sat in the shared body, so it went out on every attempt
|
||||
// including both retries, and the import could not succeed at all.
|
||||
const TEMP_400 = { error: { message: "Unsupported value: 'temperature' does not support 0 with this model. Only the default (1) value is supported.", code: 'unsupported_value' } };
|
||||
|
||||
it('drops temperature when the model rejects it (400, #2262)', async () => {
|
||||
safeFetchLlmMock
|
||||
.mockResolvedValueOnce(jsonResponse(TEMP_400, false, 400))
|
||||
.mockResolvedValueOnce(jsonResponse({ choices: [{ message: { content: '{"reservations":[{"@type":"FlightReservation"}]}' } }] }));
|
||||
const out = await new OpenAiCompatibleClient().extract(baseInput);
|
||||
expect(out).toEqual([{ '@type': 'FlightReservation' }]);
|
||||
expect(safeFetchLlmMock).toHaveBeenCalledTimes(2);
|
||||
|
||||
const first = JSON.parse((safeFetchLlmMock.mock.calls[0][1] as RequestInit).body as string);
|
||||
const second = JSON.parse((safeFetchLlmMock.mock.calls[1][1] as RequestInit).body as string);
|
||||
expect(first.temperature).toBe(0);
|
||||
expect('temperature' in second).toBe(false);
|
||||
// Only temperature goes; the schema and the token param are untouched.
|
||||
expect(second.response_format.type).toBe('json_schema');
|
||||
expect(second.max_tokens).toBe(4096);
|
||||
});
|
||||
|
||||
// A gpt-5 rejects both parameters, and the API names one per response. Either
|
||||
// order has to converge, which a chain of one-shot ifs cannot do.
|
||||
it('combines the token-param and temperature remedies, token param named first', async () => {
|
||||
safeFetchLlmMock
|
||||
.mockResolvedValueOnce(jsonResponse({ error: { message: "Unsupported parameter: 'max_tokens' is not supported with this model. Use 'max_completion_tokens' instead." } }, false, 400))
|
||||
.mockResolvedValueOnce(jsonResponse(TEMP_400, false, 400))
|
||||
.mockResolvedValueOnce(jsonResponse({ choices: [{ message: { content: '{"reservations":[{"@type":"FlightReservation"}]}' } }] }));
|
||||
const out = await new OpenAiCompatibleClient().extract(baseInput);
|
||||
expect(out).toEqual([{ '@type': 'FlightReservation' }]);
|
||||
expect(safeFetchLlmMock).toHaveBeenCalledTimes(3);
|
||||
|
||||
const third = JSON.parse((safeFetchLlmMock.mock.calls[2][1] as RequestInit).body as string);
|
||||
expect(third.max_completion_tokens).toBe(4096);
|
||||
expect('temperature' in third).toBe(false);
|
||||
expect(third.response_format.type).toBe('json_schema');
|
||||
});
|
||||
|
||||
it('combines them the other way round too, temperature named first', async () => {
|
||||
safeFetchLlmMock
|
||||
.mockResolvedValueOnce(jsonResponse(TEMP_400, false, 400))
|
||||
.mockResolvedValueOnce(jsonResponse({ error: { message: "Unsupported parameter: 'max_tokens' is not supported with this model. Use 'max_completion_tokens' instead." } }, false, 400))
|
||||
.mockResolvedValueOnce(jsonResponse({ choices: [{ message: { content: '{"reservations":[{"@type":"FlightReservation"}]}' } }] }));
|
||||
const out = await new OpenAiCompatibleClient().extract(baseInput);
|
||||
expect(out).toEqual([{ '@type': 'FlightReservation' }]);
|
||||
expect(safeFetchLlmMock).toHaveBeenCalledTimes(3);
|
||||
|
||||
const third = JSON.parse((safeFetchLlmMock.mock.calls[2][1] as RequestInit).body as string);
|
||||
expect(third.max_completion_tokens).toBe(4096);
|
||||
expect('temperature' in third).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps temperature when a 400 only mentions the word in passing', async () => {
|
||||
safeFetchLlmMock
|
||||
.mockResolvedValueOnce(jsonResponse({ error: { message: 'Your prompt mentions temperature but the schema is invalid' } }, false, 400))
|
||||
.mockResolvedValueOnce(jsonResponse({ choices: [{ message: { content: '{"reservations":[]}' } }] }));
|
||||
await new OpenAiCompatibleClient().extract(baseInput);
|
||||
|
||||
const second = JSON.parse((safeFetchLlmMock.mock.calls[1][1] as RequestInit).body as string);
|
||||
// Not a parameter rejection, so it falls through to the json_object retry
|
||||
// with deterministic sampling intact — which is what local models need.
|
||||
expect(second.temperature).toBe(0);
|
||||
expect(second.response_format.type).toBe('json_object');
|
||||
});
|
||||
|
||||
it('throws when the json_object retry also fails (400 twice)', async () => {
|
||||
safeFetchLlmMock
|
||||
.mockResolvedValueOnce(jsonResponse({ error: 'no json_schema' }, false, 400))
|
||||
|
||||
Reference in New Issue
Block a user