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 [];