forked from tetherto/qvac
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhermes.ts
More file actions
153 lines (133 loc) · 4.35 KB
/
Copy pathhermes.ts
File metadata and controls
153 lines (133 loc) · 4.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import type { Tool, ToolCall, ToolCallError } from "@/schemas";
import {
generateStableToolCallId,
isValidToolCall,
validateToolArguments,
type ParserResult,
} from "@/server/utils/tools/shared";
// Qwen3.5/3.6 can fuse its two tool templates into one frame, embedding the
// XML `<function=NAME>` token as a bare string key inside the JSON envelope:
// {"function=NAME","arguments":{...}} (invalid JSON, not parseable as-is)
// Rewrite only that exact shape to a canonical `{"name":NAME,"arguments":...}`
// frame. Kept deliberately narrow so well-formed JSON frames are never touched.
function repairFunctionEqualsJson(candidate: string): string | undefined {
const match =
/^\{\s*"function=([^"]+)"\s*,\s*"arguments"\s*:\s*([\s\S]+)\}\s*$/.exec(
candidate,
);
if (!match) return undefined;
return `{"name":${JSON.stringify(match[1])},"arguments":${match[2]}}`;
}
function parseHermesJson(candidate: string): unknown {
try {
return JSON.parse(candidate);
} catch (err) {
const repaired = repairFunctionEqualsJson(candidate);
if (repaired === undefined) throw err;
return JSON.parse(repaired);
}
}
// Hermes-style: JSON payload wrapped in `<tool_call>...</tool_call>` tags
export function parseHermesFormat(text: string, tools: Tool[]): ParserResult {
const toolCalls: ToolCall[] = [];
const errors: ToolCallError[] = [];
if (!text.includes("<tool_call>")) {
return { matched: false, toolCalls, errors };
}
// Incomplete frame: open marker without close (cutoff/abort). Recover
// the inner buffer here — fallthrough to JSON parsers can't strip the
// `<tool_call>` prefix on its own.
if (!text.includes("</tool_call>")) {
return recoverIncompleteHermesFrame(text, tools);
}
const toolCallRegex = /<tool_call>\s*({[\s\S]*?})\s*<\/tool_call>/g;
const matches = Array.from(text.matchAll(toolCallRegex));
for (const match of matches) {
const callJson = match[1];
if (!callJson) continue;
const trimmedJson = callJson.trim();
let callItem: unknown;
try {
callItem = parseHermesJson(trimmedJson);
} catch (error) {
errors.push({
code: "PARSE_ERROR",
message: `Failed to parse Hermes tool call: ${error instanceof Error ? error.message : String(error)}`,
raw: trimmedJson,
});
continue;
}
if (!isValidToolCall(callItem)) {
errors.push({
code: "PARSE_ERROR",
message: "Hermes tool call is missing name/arguments",
raw: trimmedJson,
});
continue;
}
const call = callItem;
const validation = validateToolArguments(
call.name,
call.arguments,
tools,
);
if (!validation.isValid && validation.error) {
errors.push({
...validation.error,
raw: trimmedJson,
});
continue;
}
toolCalls.push({
id: call.id || generateStableToolCallId(call.name, call.arguments),
name: call.name,
arguments: call.arguments,
raw: trimmedJson,
});
}
return { matched: true, toolCalls, errors };
}
// Strips a possible truncated close-tag tail (`</tool`, `</tool_c`)
// before parsing. Bounded to buffers that actually contain the open marker.
function recoverIncompleteHermesFrame(
text: string,
tools: Tool[],
): ParserResult {
const openIdx = text.indexOf("<tool_call>");
const inner = text.slice(openIdx + "<tool_call>".length).trim();
const partialCloseIdx = inner.search(/<\/tool/);
const candidate =
partialCloseIdx === -1 ? inner : inner.slice(0, partialCloseIdx).trim();
if (candidate.length === 0) {
return { matched: false, toolCalls: [], errors: [] };
}
let parsed: unknown;
try {
parsed = parseHermesJson(candidate);
} catch {
return { matched: false, toolCalls: [], errors: [] };
}
if (!isValidToolCall(parsed)) {
return { matched: false, toolCalls: [], errors: [] };
}
const validation = validateToolArguments(parsed.name, parsed.arguments, tools);
if (!validation.isValid && validation.error) {
return {
matched: true,
toolCalls: [],
errors: [{ ...validation.error, raw: candidate }],
};
}
return {
matched: true,
toolCalls: [
{
id: parsed.id || generateStableToolCallId(parsed.name, parsed.arguments),
name: parsed.name,
arguments: parsed.arguments,
raw: candidate,
},
],
errors: [],
};
}