-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathapi-request-log-errors.ts
More file actions
260 lines (240 loc) · 7.94 KB
/
api-request-log-errors.ts
File metadata and controls
260 lines (240 loc) · 7.94 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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import * as z from 'zod';
import type OpenAI from 'openai';
import type Anthropic from '@anthropic-ai/sdk';
import { createParser } from 'eventsource-parser';
import type { GatewayRequest } from '@/lib/ai-gateway/providers/openrouter/types';
export const toolCallArgumentErrorSchema = z.discriminatedUnion('kind', [
z.object({
tool_call_id: z.string(),
tool_name: z.string(),
kind: z.literal('unparseable_json'),
details: z.string(),
}),
z.object({
tool_call_id: z.string(),
tool_name: z.string(),
kind: z.literal('schema_mismatch'),
details: z.unknown(),
}),
z.object({
tool_call_id: z.string(),
tool_name: z.string(),
kind: z.literal('unknown_tool'),
}),
]);
export const apiRequestLogErrorSchema = z.object({
invalid_tool_call_arguments: z.array(toolCallArgumentErrorSchema),
});
export type ApiRequestLogError = z.infer<typeof apiRequestLogErrorSchema>;
type ToolCallError = z.infer<typeof toolCallArgumentErrorSchema>;
function checkKnownTool(
knownToolNames: Set<string>,
toolCallId: string,
toolName: string,
errors: ToolCallError[]
): boolean {
if (knownToolNames.has(toolName)) return true;
errors.push({
tool_call_id: toolCallId,
tool_name: toolName,
kind: 'unknown_tool',
});
return false;
}
function validateAgainstSchema(
parsedArgs: unknown,
parameters: unknown,
toolCallId: string,
toolName: string,
errors: ToolCallError[]
): void {
if (parameters == null) return;
let zodSchema: ReturnType<typeof z.fromJSONSchema>;
try {
zodSchema = z.fromJSONSchema(parameters as Parameters<typeof z.fromJSONSchema>[0]);
} catch {
// Unsupported schema features — skip validation for this tool
return;
}
const result = zodSchema.safeParse(parsedArgs);
if (!result.success) {
errors.push({
tool_call_id: toolCallId,
tool_name: toolName,
kind: 'schema_mismatch',
details: z.treeifyError(result.error),
});
}
}
function parseArgsString(
argsStr: string,
toolCallId: string,
toolName: string,
errors: ToolCallError[]
): { parsed: unknown; ok: true } | { ok: false } {
try {
return { parsed: JSON.parse(argsStr), ok: true };
} catch (e) {
errors.push({
tool_call_id: toolCallId,
tool_name: toolName,
kind: 'unparseable_json',
details: e instanceof Error ? e.message : String(e),
});
return { ok: false };
}
}
/**
* Returns the JSON payload strings from SSE `data:` events, excluding `[DONE]`.
* Returns an empty array if the text does not look like an SSE stream.
*/
function parseSseDataLines(text: string): string[] {
const payloads: string[] = [];
const parser = createParser({
onEvent(event) {
if (event.data !== '[DONE]') payloads.push(event.data);
},
});
parser.feed(text);
return payloads;
}
type ToolAccumulator = { id: string; name: string; arguments: string };
function detectChatCompletionSseErrors(
lines: string[],
tools: OpenAI.Chat.ChatCompletionTool[] | null | undefined
): ToolCallError[] {
const toolSchemaByName = new Map<string, unknown>();
const knownToolNames = new Set<string>();
for (const tool of tools ?? []) {
if (tool.type === 'function') {
knownToolNames.add(tool.function.name);
toolSchemaByName.set(tool.function.name, tool.function.parameters);
}
}
// Accumulate tool call arguments by index across chunks (choice 0 only)
const byIndex = new Map<number, ToolAccumulator>();
for (const line of lines) {
const chunk: OpenAI.Chat.Completions.ChatCompletionChunk = JSON.parse(line);
const choice = chunk.choices.find(c => c.index === 0);
for (const toolCall of choice?.delta.tool_calls ?? []) {
const acc = byIndex.get(toolCall.index) ?? { id: '', name: '', arguments: '' };
if (toolCall.id) acc.id = toolCall.id;
if (toolCall.function?.name) acc.name = toolCall.function.name;
acc.arguments += toolCall.function?.arguments ?? '';
byIndex.set(toolCall.index, acc);
}
}
const errors: ToolCallError[] = [];
for (const [, acc] of byIndex) {
if (!acc.name) continue;
if (!checkKnownTool(knownToolNames, acc.id, acc.name, errors)) continue;
const result = parseArgsString(acc.arguments, acc.id, acc.name, errors);
if (result.ok) {
validateAgainstSchema(
result.parsed,
toolSchemaByName.get(acc.name),
acc.id,
acc.name,
errors
);
}
}
return errors;
}
function detectResponsesSseErrors(
lines: string[],
tools: OpenAI.Responses.ResponseCreateParams['tools']
): ToolCallError[] {
const toolSchemaByName = new Map<string, unknown>();
const knownToolNames = new Set<string>();
for (const tool of tools ?? []) {
if (tool.type === 'function') {
knownToolNames.add(tool.name);
toolSchemaByName.set(tool.name, tool.parameters);
}
}
// response.output_item.done carries the fully assembled function_call item
const errors: ToolCallError[] = [];
for (const line of lines) {
const event = JSON.parse(line);
if (event.type !== 'response.output_item.done' || event.item?.type !== 'function_call')
continue;
const callId: string = event.item.call_id;
const name: string = event.item.name;
const argsStr: string = event.item.arguments;
if (!checkKnownTool(knownToolNames, callId, name, errors)) continue;
const result = parseArgsString(argsStr, callId, name, errors);
if (result.ok) {
validateAgainstSchema(result.parsed, toolSchemaByName.get(name), callId, name, errors);
}
}
return errors;
}
function detectMessagesSseErrors(
lines: string[],
tools: Anthropic.MessageCreateParams['tools']
): ToolCallError[] {
const toolSchemaByName = new Map<string, unknown>();
const knownToolNames = new Set<string>();
for (const tool of tools ?? []) {
knownToolNames.add(tool.name);
// Anthropic.Tool has input_schema; server tools (BashTool, TextEditorTool, etc.) do not
if ('input_schema' in tool) {
toolSchemaByName.set(tool.name, tool.input_schema);
}
}
// Accumulate partial_json fragments by content block index
const byIndex = new Map<number, ToolAccumulator>();
for (const line of lines) {
const event = JSON.parse(line);
if (event.type === 'content_block_start' && event.content_block?.type === 'tool_use') {
const id: string = event.content_block.id;
const name: string = event.content_block.name;
byIndex.set(event.index, { id, name, arguments: '' });
} else if (event.type === 'content_block_delta' && event.delta?.type === 'input_json_delta') {
const acc = byIndex.get(event.index);
if (acc) acc.arguments += event.delta.partial_json;
}
}
const errors: ToolCallError[] = [];
for (const [, acc] of byIndex) {
if (!checkKnownTool(knownToolNames, acc.id, acc.name, errors)) continue;
const result = parseArgsString(acc.arguments, acc.id, acc.name, errors);
if (result.ok) {
// acc.arguments is accumulated JSON — validate against tool schema
validateAgainstSchema(
result.parsed,
toolSchemaByName.get(acc.name),
acc.id,
acc.name,
errors
);
}
}
return errors;
}
/**
* Checks SSE-streamed response tool call arguments for JSON parse errors or schema mismatches.
* Returns null if the response is not an SSE stream or if no errors are found.
*/
export function detectToolCallArgumentErrors(
responseText: string,
request: GatewayRequest
): ApiRequestLogError | null {
const lines = parseSseDataLines(responseText);
if (lines.length === 0) return null;
let errors: ToolCallError[];
try {
if (request.kind === 'chat_completions') {
errors = detectChatCompletionSseErrors(lines, request.body.tools);
} else if (request.kind === 'responses') {
errors = detectResponsesSseErrors(lines, request.body.tools);
} else {
errors = detectMessagesSseErrors(lines, request.body.tools);
}
} catch {
return null;
}
if (errors.length === 0) return null;
return { invalid_tool_call_arguments: errors };
}