From 7c0c749bcc8e2ec9fd73662047beccb9d5154cec Mon Sep 17 00:00:00 2001 From: Maurice Date: Sat, 28 Nov 2026 22:12:59 +0100 Subject: [PATCH] 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 --- .../llm-parse/clients/anthropic.client.ts | 8 +- server/src/nest/llm-parse/lenient-json.ts | 39 ++++++- .../nest/llm-parse/key-whitespace.test.ts | 110 ++++++++++++++++++ .../unit/nest/llm-parse/lenient-json.test.ts | 55 ++++++++- 4 files changed, 206 insertions(+), 6 deletions(-) create mode 100644 server/tests/unit/nest/llm-parse/key-whitespace.test.ts diff --git a/server/src/nest/llm-parse/clients/anthropic.client.ts b/server/src/nest/llm-parse/clients/anthropic.client.ts index 9c98560d1..5ab907ccf 100644 --- a/server/src/nest/llm-parse/clients/anthropic.client.ts +++ b/server/src/nest/llm-parse/clients/anthropic.client.ts @@ -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 | undefined; + return toReservationList(toolInput?.[rootKey], rootKey); } } diff --git a/server/src/nest/llm-parse/lenient-json.ts b/server/src/nest/llm-parse/lenient-json.ts index 1700a9383..83f05d3f5 100644 --- a/server/src/nest/llm-parse/lenient-json.ts +++ b/server/src/nest/llm-parse/lenient-json.ts @@ -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); + const out: Record = {}; + 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 []; diff --git a/server/tests/unit/nest/llm-parse/key-whitespace.test.ts b/server/tests/unit/nest/llm-parse/key-whitespace.test.ts new file mode 100644 index 000000000..e69c70682 --- /dev/null +++ b/server/tests/unit/nest/llm-parse/key-whitespace.test.ts @@ -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[]) { + const nodes = list.map((node) => normalizeNode(kiReservationSchema.parse(node)) as unknown as KiReservation); + return mapReservations(nodes, 'voucher.pdf', 'ai').items; +} + +function expectTimes(list: Record[]) { + 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' }); + }); +}); diff --git a/server/tests/unit/nest/llm-parse/lenient-json.test.ts b/server/tests/unit/nest/llm-parse/lenient-json.test.ts index 729796921..a4954ef1e 100644 --- a/server/tests/unit/nest/llm-parse/lenient-json.test.ts +++ b/server/tests/unit/nest/llm-parse/lenient-json.test.ts @@ -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; + 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' }]); + }); +});