-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfix-gemini.mjs
More file actions
186 lines (174 loc) · 5.89 KB
/
Copy pathfix-gemini.mjs
File metadata and controls
186 lines (174 loc) · 5.89 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
const UNSUPPORTED_SCHEMA_KEYS = new Set([
"$defs", "definitions", "$ref", "ref", "$schema",
"exclusiveMinimum", "exclusiveMaximum",
"patternProperties", "if", "then", "else", "not",
"contentMediaType", "contentEncoding",
"$id", "$anchor", "$comment",
]);
function resolveRefs(schema, defs, seen) {
if (!schema || typeof schema !== "object") return schema;
if (Array.isArray(schema)) return schema.map((s) => resolveRefs(s, defs, seen));
if (schema.$ref || schema.ref) {
const refName = (schema.$ref || schema.ref)
.replace(/^#\/\$defs\//, "")
.replace(/^#\/definitions\//, "");
const resolving = seen || new Set();
if (resolving.has(refName)) return {};
resolving.add(refName);
const resolved = defs?.[refName];
if (resolved) {
const merged = { ...resolveRefs(resolved, defs, resolving) };
if (schema.description) merged.description = schema.description;
if (schema.default !== undefined) merged.default = schema.default;
return merged;
}
}
const result = {};
for (const [k, v] of Object.entries(schema)) {
if (UNSUPPORTED_SCHEMA_KEYS.has(k)) continue;
result[k] = resolveRefs(v, defs, seen);
}
if (schema.exclusiveMinimum !== undefined && result.minimum === undefined) {
result.minimum = schema.exclusiveMinimum;
}
if (schema.exclusiveMaximum !== undefined && result.maximum === undefined) {
result.maximum = schema.exclusiveMaximum;
}
return result;
}
function fixToolSchemas(body) {
if (!body.tools?.length) return body;
return {
...body,
tools: body.tools.map((tool) => {
if (tool.type !== "function" || !tool.function?.parameters) return tool;
const params = tool.function.parameters;
const defs = params.$defs || params.definitions || {};
return {
...tool,
function: {
...tool.function,
parameters: resolveRefs(params, defs),
},
};
}),
};
}
export function isGeminiModel(model) {
return typeof model === "string" && model.toLowerCase().includes("gemini");
}
function isGemini3(model) {
if (typeof model !== "string") return false;
const m = model.toLowerCase();
return m.includes("gemini") && (m.includes("3 ") || m.includes("3."));
}
function rewriteToolCallHistory(body) {
if (!body.messages?.length) return body;
const messages = [];
let pendingToolCalls = {};
let toolResults = [];
function flushToolResults() {
if (!toolResults.length) return;
messages.push({ role: "user", content: toolResults.join("\n\n") });
toolResults = [];
}
for (const msg of body.messages) {
if (msg.role === "assistant" && msg.tool_calls?.length) {
flushToolResults();
for (const tc of msg.tool_calls) {
pendingToolCalls[tc.id] = tc.function;
}
if (msg.content) {
messages.push({ role: "assistant", content: msg.content });
}
} else if (msg.role === "tool") {
if (!toolResults.length && messages.length && messages[messages.length - 1].role !== "assistant") {
messages.push({ role: "assistant", content: "Processing..." });
}
const fn = pendingToolCalls[msg.tool_call_id];
const toolContent = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
if (fn) {
let args = fn.arguments;
try { args = JSON.stringify(JSON.parse(args)); } catch {}
toolResults.push(`<tool_result name="${fn.name}" arguments='${args}'>\n${toolContent}\n</tool_result>`);
} else {
toolResults.push(toolContent);
}
} else {
flushToolResults();
messages.push(msg);
}
}
flushToolResults();
const merged = [];
for (const msg of messages) {
const prev = merged.length ? merged[merged.length - 1] : null;
if (prev && prev.role === msg.role && msg.role === "user") {
prev.content = (prev.content || "") + "\n\n" + (msg.content || "");
} else {
merged.push({ ...msg });
}
}
return { ...body, messages: merged };
}
export function fixGeminiRequest(body) {
if (body.tools) {
body = fixToolSchemas(body);
}
if (isGemini3(body.model)) {
body = rewriteToolCallHistory(body);
}
return body;
}
export function fixGeminiThinkingRequest(body) {
if (!body.thinking) return { body, hadThinking: false };
if (body.thinking.type === "disabled") {
const { thinking, ...rest } = body;
return { body: rest, hadThinking: true };
}
const thinking = { ...body.thinking };
if (thinking.budgetTokens !== undefined && thinking.budget_tokens === undefined) {
thinking.budget_tokens = thinking.budgetTokens;
delete thinking.budgetTokens;
}
const result = { ...body, thinking };
if (thinking.budget_tokens && result.max_tokens && result.max_tokens <= thinking.budget_tokens) {
result.max_tokens = thinking.budget_tokens + 4096;
}
return { body: result, hadThinking: true };
}
export function fixGeminiStream(text) {
return text.replace(/data: ({.*})\n/g, (match, jsonStr) => {
try {
const parsed = JSON.parse(jsonStr);
let changed = false;
if (parsed.choices) {
for (const choice of parsed.choices) {
if (choice.finish_reason === "STOP") {
choice.finish_reason = "stop";
changed = true;
}
if (choice.finish_reason === "stop" && choice.delta?.tool_calls?.length) {
choice.finish_reason = "tool_calls";
changed = true;
}
const blocks = choice.delta?.content_blocks;
if (blocks?.length) {
for (const block of blocks) {
if (block.delta?.thinking) {
choice.delta.reasoning_content = block.delta.thinking;
changed = true;
}
}
delete choice.delta.content_blocks;
changed = true;
}
}
}
if (changed) {
return "data: " + JSON.stringify(parsed) + "\n";
}
} catch {}
return match;
});
}