返回源码地图

packages/ai/src/utils/json-parse.ts

v1.3.0 · 71023aec1546 · 08:流式预览与最终完整参数解析,argumentsError

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import { parse as partialParse } from "partial-json";
2import type { ToolCall } from "../types.ts";
3
4const VALID_JSON_ESCAPES = new Set(['"', "\\", "/", "b", "f", "n", "r", "t"]);
5
6function isControlCharacter(char: string): boolean {
7 const codePoint = char.codePointAt(0);
8 return codePoint !== undefined && codePoint >= 0x00 && codePoint <= 0x1f;
9}
10
11function escapeControlCharacter(char: string): string {
12 switch (char) {
13 case "\b":
14 return "\\b";
15 case "\f":
16 return "\\f";
17 case "\n":
18 return "\\n";
19 case "\r":
20 return "\\r";
21 case "\t":
22 return "\\t";
23 default:
24 return `\\u${char.codePointAt(0)?.toString(16).padStart(4, "0") ?? "0000"}`;
25 }
26}
27
28/**
29 * Repairs malformed JSON string literals by:
30 * - escaping raw control characters inside strings
31 * - doubling backslashes before invalid escape characters
32 */
33export function repairJson(json: string): string {
34 let repaired = "";
35 let inString = false;
36
37 for (let index = 0; index < json.length; index++) {
38 const char = json[index];
39
40 if (!inString) {
41 repaired += char;
42 if (char === '"') {
43 inString = true;
44 }
45 continue;
46 }
47
48 if (char === '"') {
49 repaired += char;
50 inString = false;
51 continue;
52 }
53
54 if (char === "\\") {
55 const nextChar = json[index + 1];
56 if (nextChar === undefined) {
57 repaired += "\\\\";
58 continue;
59 }
60
61 if (nextChar === "u") {
62 const unicodeDigits = json.slice(index + 2, index + 6);
63 if (/^[0-9a-fA-F]{4}$/.test(unicodeDigits)) {
64 repaired += `\\u${unicodeDigits}`;
65 index += 5;
66 continue;
67 }
68 }
69
70 if (VALID_JSON_ESCAPES.has(nextChar)) {
71 repaired += `\\${nextChar}`;
72 index += 1;
73 continue;
74 }
75
76 repaired += "\\\\";
77 continue;
78 }
79
80 repaired += isControlCharacter(char) ? escapeControlCharacter(char) : char;
81 }
82
83 return repaired;
84}
85
86export function parseJsonWithRepair<T>(json: string): T {
87 try {
88 return JSON.parse(json) as T;
89 } catch (error) {
90 const repairedJson = repairJson(json);
91 if (repairedJson !== json) {
92 return JSON.parse(repairedJson) as T;
93 }
94 throw error;
95 }
96}
97
98/**
99 * Parses the model's complete arguments text of a finished tool call.
100 *
101 * Unlike {@link parseStreamingJson}, this never keeps a partially parsed prefix: once the call is
102 * finished, text that is not a valid JSON object means the model sent malformed arguments. In that
103 * case `arguments` is `{}` and `argumentsError` describes the problem, including the text the
104 * model sent, so tool validation can report it back to the model.
105 */
106export function parseToolCallArguments(json: string | undefined): Pick<ToolCall, "arguments" | "argumentsError"> {
107 if (!json?.trim()) return { arguments: {} };
108 try {
109 const parsed = parseJsonWithRepair<ToolCall["arguments"] | null>(json);
110 if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
111 throw new Error("Tool arguments must be a JSON object");
112 }
113 return { arguments: parsed };
114 } catch (error) {
115 return {
116 arguments: {},
117 argumentsError: `${error instanceof Error ? error.message : String(error)}\n\nReceived arguments:\n${json}`,
118 };
119 }
120}
121
122/**
123 * Attempts to parse potentially incomplete JSON during streaming.
124 * Always returns a valid object, even if the JSON is incomplete.
125 *
126 * @param partialJson The partial JSON string from streaming
127 * @returns Parsed object or empty object if parsing fails
128 */
129export function parseStreamingJson<T = Record<string, unknown>>(partialJson: string | undefined): T {
130 if (!partialJson || partialJson.trim() === "") {
131 return {} as T;
132 }
133
134 try {
135 return parseJsonWithRepair<T>(partialJson);
136 } catch {
137 try {
138 const result = partialParse(partialJson);
139 return (result ?? {}) as T;
140 } catch {
141 try {
142 const result = partialParse(repairJson(partialJson));
143 return (result ?? {}) as T;
144 } catch {
145 return {} as T;
146 }
147 }
148 }
149}