char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Aleksander Grygierui: Improve Chat Messages rendering performance (#28460)0afb805b1

char/aliceai-t5-moe
1.3 KiB38 linesraw
1// Generic helper for parsing tool-result blobs (the "out" side of a
2// tool call). Used by the per-tool meta parsers under
3// `src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/`.
4// Each tool needs to surface fields like `error`, `result`, `bytes`,
5// `edits_applied` without repeating the try/JSON.parse/object guard inline.
6
7import { JSON_OBJECT_OPEN } from '$lib/constants';
8
9/**
10 * Parse a tool-result blob into a JSON object, or `null` if it isn't
11 * one. Returns null for:
12 *   - missing / empty input,
13 *   - a JSON object that turns out to be an array or primitive,
14 *   - any parse failure (always returns null rather than throwing).
15 */
16export function tryParseToolResultObject(
17	toolResultString: string | undefined
18): Record<string, unknown> | null {
19	if (!toolResultString) return null;
20
21	// Tool results are usually large plain text (file contents, stdout); only
22	// a JSON object root can carry fields, so skip the parse otherwise
23	const trimmed = toolResultString.trimStart();
24
25	if (trimmed[0] !== JSON_OBJECT_OPEN) return null;
26
27	try {
28		const parsed: unknown = JSON.parse(trimmed);
29
30		if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
31			return parsed as Record<string, unknown>;
32		}
33
34		return null;
35	} catch {
36		return null;
37	}
38}