fix(llm-parse): read a model answer whose keys carry stray whitespace

Small local models now and then write a key with a space around it, such as 'departureTime ', and the mappers look every field up by its exact name, so an imported booking lost its times. Every model answer now has its keys trimmed at the one place all of them pass through (parseLenientJson for a written answer, toReservationList for a filled tool call, and the Anthropic client's own root key lookup). Values stay as they are; an exact key wins over one that only trims to the same name.

Closes #3260
This commit is contained in:
Maurice
2026-11-28 22:12:59 +01:00
parent 94163f76e0
commit 7c0c749bcc
4 changed files with 206 additions and 6 deletions
@@ -1,6 +1,6 @@
import { readEnv } from '../../../app-config';
import { safeFetchLlm } from '../../../utils/ssrfGuard';
import { toReservationList } from '../lenient-json';
import { toReservationList, trimKeys } from '../lenient-json';
import type { LlmExtractionClient, LlmExtractionInput } from '../llm-provider.interface';
import { isContextOverflow, LlmContextOverflowError } from './context-overflow';
import { llmRequestError } from './llm-request-error';
@@ -109,7 +109,11 @@ export class AnthropicClient implements LlmExtractionClient {
const toolUse = data.content?.find((b) => b.type === 'tool_use' && b.name === toolName);
if (!toolUse) throw new UnreadableLlmResponse(`the model answered without calling ${toolName}`);
return toReservationList(toolUse.input?.[rootKey], rootKey);
// The root key is looked up here, before toReservationList trims anything,
// so the input is trimmed first: a 'reservations ' key would otherwise drop
// the whole answer (#3260). A string under the key still unwraps (#1968).
const toolInput = trimKeys(toolUse.input) as Record<string, unknown> | undefined;
return toReservationList(toolInput?.[rootKey], rootKey);
}
}
+36 -3
View File
@@ -24,16 +24,49 @@ export function parseLenientJson(content: string | undefined | null): unknown {
.replace(/```$/, '')
.trim();
try {
return JSON.parse(stripped);
return trimKeys(JSON.parse(stripped));
} catch {
try {
return JSON5.parse(stripped);
return trimKeys(JSON5.parse(stripped));
} catch {
return null;
}
}
}
/**
* The value with whitespace trimmed off every object key, at any depth.
*
* Small local models now and then write a key with a stray space, such as
* `'departureTime ': '2026-10-21T13:30:00'` (#3260). The value is right, but
* the mappers look the field up by its exact name, so the time never arrived.
* Every model answer passes through here (a written answer through
* parseLenientJson, a filled tool call through toReservationList), so the
* mappers only ever see clean names.
*
* A key that was already exact wins over one that only trims to the same
* name, and between two keys that both had to be trimmed the first one
* written wins. Values stay as they are, apart from the keys of the objects
* nested in them.
*/
export function trimKeys(value: unknown): unknown {
if (Array.isArray(value)) return value.map(trimKeys);
if (!value || typeof value !== 'object') return value;
const entries = Object.entries(value as Record<string, unknown>);
const out: Record<string, unknown> = {};
const put = (key: string, v: unknown) =>
// defineProperty, so a key that trims to `__proto__` stays a plain field
// and never swaps the prototype of the object handed on.
Object.defineProperty(out, key, { value: trimKeys(v), enumerable: true, writable: true, configurable: true });
const exact = new Set(entries.map(([key]) => key).filter((key) => key === key.trim()));
for (const [key, v] of entries) {
const trimmed = key.trim();
if (key === trimmed) put(key, v);
else if (!exact.has(trimmed) && !Object.prototype.hasOwnProperty.call(out, trimmed)) put(trimmed, v);
}
return out;
}
/**
* Whatever a provider handed back, as a list of reservation nodes.
*
@@ -79,7 +112,7 @@ export function toReservationList(value: unknown, rootKey = 'reservations'): Rec
return null;
};
const direct = list(value);
const direct = list(trimKeys(value));
if (direct) return direct;
if (typeof value === 'string') return list(parseLenientJson(value)) ?? [];
return [];
@@ -0,0 +1,110 @@
/**
* A model answer whose keys carry stray whitespace (#3260): a small local
* model wrote `'departureTime ': '2026-10-21T13:30:00'`, the mapper looked for
* `departureTime` and the reservation opened without its times. Each provider
* client hands the answer on through the same place, so each is fed the same
* answer here and the times have to arrive at the mapper.
*/
import { mapReservations } from '../../../../src/nest/booking-import/kitinerary-mapper';
import type { KiReservation } from '../../../../src/nest/booking-import/kitinerary.types';
import { AnthropicClient } from '../../../../src/nest/llm-parse/clients/anthropic.client';
import { ConnectionReadClient } from '../../../../src/nest/llm-parse/clients/connection-read.client';
import { OpenAiCompatibleClient } from '../../../../src/nest/llm-parse/clients/openai-compatible.client';
import type { LlmExtractionInput } from '../../../../src/nest/llm-parse/llm-provider.interface';
import { normalizeNode } from '../../../../src/nest/llm-parse/reservation-normalize';
import { extractEnforced } from '../../../../src/nest/llm-parse/router/ollama-format.client';
import { kiReservationSchema } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const { safeFetchLlmMock } = vi.hoisted(() => ({ safeFetchLlmMock: vi.fn() }));
vi.mock('../../../../src/utils/ssrfGuard', () => ({ safeFetchLlm: safeFetchLlmMock }));
function answerWith(body: unknown) {
safeFetchLlmMock.mockImplementation(
async () =>
({
ok: true,
status: 200,
headers: new Headers(),
json: async () => body,
text: async () => JSON.stringify(body),
}) as unknown as Response,
);
}
/** The bus voucher of the report, keys as the model wrote them. */
const BUS = {
'@type': 'BusReservation',
reservationFor: {
busName: 'my bus',
departureBusStop: { name: 'Airport ' },
arrivalBusStop: { 'name ': 'Old Town' },
'departureTime ': '2026-10-21T13:30:00',
'arrivalTime ': '2026-10-21T16:30:00',
},
};
const input: LlmExtractionInput = { prompt: 'system', jsonSchema: { type: 'object' }, model: 'm', text: 'Bus' };
/** What the import does with a client's list: validate, fold, map. */
function mapped(list: Record<string, unknown>[]) {
const nodes = list.map((node) => normalizeNode(kiReservationSchema.parse(node)) as unknown as KiReservation);
return mapReservations(nodes, 'voucher.pdf', 'ai').items;
}
function expectTimes(list: Record<string, unknown>[]) {
const [item] = mapped(list);
expect(item.reservation_time).toBe('2026-10-21T13:30:00');
expect(item.reservation_end_time).toBe('2026-10-21T16:30:00');
expect(item.endpoints?.map((e) => e.name)).toEqual(['Airport ', 'Old Town']);
}
beforeEach(() => safeFetchLlmMock.mockReset());
describe('a model answer with whitespace around its keys (#3260)', () => {
it('KEYWS-001: reaches the mapper with its times on an OpenAI-compatible connection', async () => {
answerWith({ choices: [{ message: { content: JSON.stringify({ 'reservations ': [BUS] }) } }] });
expectTimes(await new OpenAiCompatibleClient().extract(input));
});
it('KEYWS-002: reaches the mapper with its times from an Anthropic tool call', async () => {
answerWith({
stop_reason: 'tool_use',
content: [{ type: 'tool_use', name: 'emit_reservations', input: { reservations: [BUS] } }],
});
expectTimes(await new AnthropicClient().extract({ ...input, apiKey: 'k' }));
});
it('KEYWS-005: keeps an Anthropic tool call whose root key carries whitespace', async () => {
answerWith({
stop_reason: 'tool_use',
content: [{ type: 'tool_use', name: 'emit_reservations', input: { 'reservations ': [BUS] } }],
});
expectTimes(await new AnthropicClient().extract({ ...input, apiKey: 'k' }));
});
it('KEYWS-006: keeps a filled shape whose root key carries whitespace', async () => {
const filled = new ConnectionReadClient(async () => ({ filled: { ' reservations': [BUS] } }));
expectTimes(await filled.extract(input));
});
it('KEYWS-003: reaches the mapper with its times from a filled shape and from written text', async () => {
const filled = new ConnectionReadClient(async () => ({ filled: { reservations: [BUS] } }));
expectTimes(await filled.extract(input));
const written = new ConnectionReadClient(async () => ({ text: JSON.stringify([BUS]) }));
expectTimes(await written.extract(input));
});
it('KEYWS-004: comes out of the local enforced read with clean names', async () => {
answerWith({ message: { content: JSON.stringify({ 'departureTime ': '2026-10-21T13:30:00' }) } });
const out = await extractEnforced({
baseUrl: 'http://ollama:11434/v1',
model: 'qwen3:8b',
system: 'sys',
user: 'doc',
schema: { type: 'object' },
});
expect(out).toEqual({ departureTime: '2026-10-21T13:30:00' });
});
});
@@ -1,4 +1,4 @@
import { parseLenientJson, toReservationList } from '../../../../src/nest/llm-parse/lenient-json';
import { parseLenientJson, toReservationList, trimKeys } from '../../../../src/nest/llm-parse/lenient-json';
import { describe, it, expect } from 'vitest';
@@ -118,3 +118,56 @@ describe('toReservationList', () => {
expect(toReservationList('{"reservations":[]}')).toEqual([]);
});
});
/*
* A small local model wrote `'departureTime '` for `departureTime` (#3260);
* the mapper reads fields by their exact name, so the value was lost.
*/
describe('trimKeys', () => {
it('trims every key, in nested objects and in arrays, and leaves the values as they are', () => {
expect(
trimKeys([
{
' @type': 'BusReservation',
'reservationFor ': { 'departureTime ': ' 13:30 ', stops: [{ '\tname\n': 'A ' }] },
},
]),
).toEqual([{ '@type': 'BusReservation', reservationFor: { departureTime: ' 13:30 ', stops: [{ name: 'A ' }] } }]);
});
it('lets a key that was already exact win over one that only trims to it, wherever it stands', () => {
expect(trimKeys({ 'price ': 1, price: 2 })).toEqual({ price: 2 });
expect(trimKeys({ price: 2, ' price': 1 })).toEqual({ price: 2 });
});
it('keeps the first of two keys that both had to be trimmed', () => {
expect(trimKeys({ 'seat ': '12A', ' seat': '14C' })).toEqual({ seat: '12A' });
});
it('keeps the key order of an answer that needed no trimming', () => {
expect(Object.keys(trimKeys({ b: 1, a: 2, ' c': 3 }) as object)).toEqual(['b', 'a', 'c']);
});
it('keeps a key that trims to __proto__ a plain field', () => {
const out = trimKeys(JSON.parse('{"__proto__ ": {"polluted": true}}')) as Record<string, unknown>;
expect(Object.getPrototypeOf(out)).toBe(Object.prototype);
expect(Object.prototype.hasOwnProperty.call(out, '__proto__')).toBe(true);
expect((out as { polluted?: unknown }).polluted).toBeUndefined();
});
it('passes scalars and null through', () => {
expect(trimKeys(' x ')).toBe(' x ');
expect(trimKeys(3)).toBe(3);
expect(trimKeys(null)).toBeNull();
});
it('runs on what parseLenientJson and toReservationList hand on', () => {
expect(parseLenientJson("{ 'departureTime ': '2026-10-21T13:30:00' }")).toEqual({
departureTime: '2026-10-21T13:30:00',
});
expect(toReservationList({ 'reservations ': [{ '@type ': 'BusReservation' }] })).toEqual([
{ '@type': 'BusReservation' },
]);
expect(toReservationList({ '@type ': 'BusReservation' })).toEqual([{ '@type': 'BusReservation' }]);
});
});