@zenmux/rosetta-ai 1.0.28 → 1.0.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat-completions/messages.js +3 -2
- package/dist/gemini/messages.js +3 -2
- package/dist/responses/gemini.d.ts +7 -1
- package/dist/responses/gemini.js +660 -277
- package/dist/responses/messages.js +2 -1
- package/dist/sanitize-anthropic-schema.d.ts +16 -0
- package/dist/sanitize-anthropic-schema.js +87 -0
- package/package.json +1 -1
package/dist/responses/gemini.js
CHANGED
|
@@ -52,7 +52,7 @@ class ResponsesToGeminiConverter {
|
|
|
52
52
|
for (const inc of params.include) {
|
|
53
53
|
if (inc === "message.output_text.logprobs") {
|
|
54
54
|
config.responseLogprobs = true;
|
|
55
|
-
config.logprobs = 20;
|
|
55
|
+
config.logprobs = params.top_logprobs ?? 20;
|
|
56
56
|
break;
|
|
57
57
|
}
|
|
58
58
|
}
|
|
@@ -66,26 +66,47 @@ class ResponsesToGeminiConverter {
|
|
|
66
66
|
// --- Response conversion (Gemini → Responses, backward) ---
|
|
67
67
|
convertResponse(response) {
|
|
68
68
|
const candidate = response.candidates?.[0];
|
|
69
|
-
const parts = candidate?.content?.parts ?? [];
|
|
69
|
+
const parts = (candidate?.content?.parts ?? []).map(part => ({ ...part }));
|
|
70
70
|
const output = [];
|
|
71
|
+
const signed = [];
|
|
72
|
+
// A signature-only Part belongs to the preceding text or function call.
|
|
73
|
+
let previous;
|
|
74
|
+
for (const part of parts) {
|
|
75
|
+
if (part.functionCall || part.text)
|
|
76
|
+
previous = part;
|
|
77
|
+
else if (part.thoughtSignature && previous)
|
|
78
|
+
previous.thoughtSignature = part.thoughtSignature;
|
|
79
|
+
}
|
|
71
80
|
for (const part of parts) {
|
|
72
81
|
if (part.thought && part.text) {
|
|
82
|
+
const id = `rs_${this.generateId()}`;
|
|
73
83
|
output.push({
|
|
74
84
|
type: "reasoning",
|
|
75
|
-
id
|
|
85
|
+
id,
|
|
76
86
|
summary: [{ type: "summary_text", text: part.text }],
|
|
77
87
|
});
|
|
88
|
+
if (part.thoughtSignature)
|
|
89
|
+
signed.push({ id, parts: [part] });
|
|
78
90
|
}
|
|
79
91
|
}
|
|
80
92
|
for (const part of parts) {
|
|
81
93
|
if (part.functionCall) {
|
|
82
94
|
const fc = part.functionCall;
|
|
95
|
+
const id = `fc_${this.generateId()}`;
|
|
96
|
+
const callId = fc.id ?? `call_${this.generateId()}`;
|
|
97
|
+
const args = fc.args ?? {};
|
|
98
|
+
if (part.thoughtSignature) {
|
|
99
|
+
signed.push({
|
|
100
|
+
id,
|
|
101
|
+
parts: [{ ...part, functionCall: { id: callId, name: fc.name ?? "", args } }],
|
|
102
|
+
});
|
|
103
|
+
}
|
|
83
104
|
output.push({
|
|
84
105
|
type: "function_call",
|
|
85
|
-
id
|
|
86
|
-
call_id:
|
|
106
|
+
id,
|
|
107
|
+
call_id: callId,
|
|
87
108
|
name: fc.name ?? "",
|
|
88
|
-
arguments: JSON.stringify(
|
|
109
|
+
arguments: JSON.stringify(args),
|
|
89
110
|
status: "completed",
|
|
90
111
|
});
|
|
91
112
|
}
|
|
@@ -94,41 +115,56 @@ class ResponsesToGeminiConverter {
|
|
|
94
115
|
const annotations = [];
|
|
95
116
|
for (const part of parts) {
|
|
96
117
|
if (part.text != null && !part.thought) {
|
|
97
|
-
textParts.push(part
|
|
118
|
+
textParts.push(part);
|
|
98
119
|
}
|
|
99
120
|
}
|
|
100
121
|
this.extractGroundingAnnotations(candidate, annotations);
|
|
101
122
|
if (textParts.length > 0 || annotations.length > 0) {
|
|
102
|
-
const
|
|
103
|
-
content.push({
|
|
104
|
-
type: "output_text",
|
|
105
|
-
text: textParts.join(""),
|
|
106
|
-
annotations,
|
|
107
|
-
logprobs: null,
|
|
108
|
-
});
|
|
123
|
+
const id = `msg_${this.generateId()}`;
|
|
109
124
|
output.push({
|
|
110
125
|
type: "message",
|
|
111
|
-
id
|
|
126
|
+
id,
|
|
112
127
|
role: "assistant",
|
|
113
128
|
status: "completed",
|
|
114
|
-
content
|
|
129
|
+
content: [
|
|
130
|
+
{
|
|
131
|
+
type: "output_text",
|
|
132
|
+
text: textParts.map(part => part.text).join(""),
|
|
133
|
+
annotations,
|
|
134
|
+
logprobs: [],
|
|
135
|
+
},
|
|
136
|
+
],
|
|
115
137
|
});
|
|
138
|
+
if (textParts.some(part => part.thoughtSignature))
|
|
139
|
+
signed.push({ id, parts: textParts });
|
|
140
|
+
}
|
|
141
|
+
const blockReason = response.promptFeedback?.blockReason;
|
|
142
|
+
const status = blockReason ? "failed" : this.finishReasonToStatus(candidate?.finishReason);
|
|
143
|
+
const failureMessage = blockReason
|
|
144
|
+
? `Gemini blocked the prompt: ${blockReason}`
|
|
145
|
+
: `Gemini finished with ${candidate?.finishReason}`;
|
|
146
|
+
for (const item of output) {
|
|
147
|
+
if (item.type === "message" || item.type === "reasoning")
|
|
148
|
+
item.status = status === "completed" ? "completed" : "incomplete";
|
|
116
149
|
}
|
|
117
|
-
if (output.length === 0) {
|
|
150
|
+
if (status === "completed" && output.length === 0) {
|
|
118
151
|
output.push({
|
|
119
152
|
type: "message",
|
|
120
153
|
id: `msg_${this.generateId()}`,
|
|
121
154
|
role: "assistant",
|
|
122
155
|
status: "completed",
|
|
123
|
-
content: [{ type: "output_text", text: "", annotations: [], logprobs:
|
|
156
|
+
content: [{ type: "output_text", text: "", annotations: [], logprobs: [] }],
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
if (signed.length) {
|
|
160
|
+
output.push({
|
|
161
|
+
type: "reasoning",
|
|
162
|
+
id: `rs_${this.generateId()}`,
|
|
163
|
+
summary: [],
|
|
164
|
+
status: "completed",
|
|
165
|
+
encrypted_content: packGeminiSignatures(signed),
|
|
124
166
|
});
|
|
125
167
|
}
|
|
126
|
-
const hasToolCall = output.some(o => o.type === "function_call");
|
|
127
|
-
const status = this.finishReasonToStatus(candidate?.finishReason, hasToolCall);
|
|
128
|
-
const usage = response.usageMetadata;
|
|
129
|
-
const promptTokens = (usage?.promptTokenCount ?? 0) + (usage?.toolUsePromptTokenCount ?? 0);
|
|
130
|
-
const thoughtsTokens = usage?.thoughtsTokenCount ?? 0;
|
|
131
|
-
const candidatesTokens = (usage?.candidatesTokenCount ?? 0) + thoughtsTokens;
|
|
132
168
|
const respResult = {
|
|
133
169
|
id: response.responseId ?? `resp_${this.generateId()}`,
|
|
134
170
|
object: "response",
|
|
@@ -136,7 +172,9 @@ class ResponsesToGeminiConverter {
|
|
|
136
172
|
model: response.modelVersion ?? "",
|
|
137
173
|
output,
|
|
138
174
|
status,
|
|
139
|
-
error:
|
|
175
|
+
error: status === "failed"
|
|
176
|
+
? { code: blockReason ? "invalid_prompt" : "server_error", message: failureMessage }
|
|
177
|
+
: null,
|
|
140
178
|
incomplete_details: status === "incomplete" ? { reason: "max_output_tokens" } : null,
|
|
141
179
|
instructions: null,
|
|
142
180
|
metadata: {},
|
|
@@ -151,17 +189,7 @@ class ResponsesToGeminiConverter {
|
|
|
151
189
|
reasoning: null,
|
|
152
190
|
truncation: null,
|
|
153
191
|
user: undefined,
|
|
154
|
-
usage:
|
|
155
|
-
input_tokens: promptTokens,
|
|
156
|
-
output_tokens: candidatesTokens,
|
|
157
|
-
total_tokens: usage?.totalTokenCount ?? 0,
|
|
158
|
-
input_tokens_details: {
|
|
159
|
-
cached_tokens: usage?.cachedContentTokenCount ?? 0,
|
|
160
|
-
},
|
|
161
|
-
output_tokens_details: {
|
|
162
|
-
reasoning_tokens: thoughtsTokens,
|
|
163
|
-
},
|
|
164
|
-
},
|
|
192
|
+
usage: this.convertUsage(response.usageMetadata),
|
|
165
193
|
};
|
|
166
194
|
// Split namespaced function_call names into { namespace, name }.
|
|
167
195
|
(0, utils_1.denamespaceResponse)(respResult);
|
|
@@ -169,222 +197,260 @@ class ResponsesToGeminiConverter {
|
|
|
169
197
|
}
|
|
170
198
|
// --- Stream conversion (Gemini → Responses, backward) ---
|
|
171
199
|
async *convertStream(stream) {
|
|
200
|
+
let terminal;
|
|
172
201
|
for await (const chunk of stream) {
|
|
173
|
-
const
|
|
174
|
-
|
|
175
|
-
|
|
202
|
+
for (const event of this.convertStreamChunk(chunk)) {
|
|
203
|
+
if (event.type === "response.completed" ||
|
|
204
|
+
event.type === "response.incomplete" ||
|
|
205
|
+
event.type === "response.failed") {
|
|
206
|
+
terminal = event;
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
yield event;
|
|
210
|
+
}
|
|
176
211
|
}
|
|
177
212
|
}
|
|
213
|
+
if (terminal) {
|
|
214
|
+
if (this.streamState.usage) {
|
|
215
|
+
terminal.response.usage = this.convertUsage(this.streamState.usage);
|
|
216
|
+
}
|
|
217
|
+
yield terminal;
|
|
218
|
+
}
|
|
178
219
|
}
|
|
179
220
|
convertStreamChunk(chunk) {
|
|
180
|
-
const state = this.streamState;
|
|
181
221
|
const events = [];
|
|
222
|
+
const state = this.streamState;
|
|
182
223
|
const candidate = chunk.candidates?.[0];
|
|
183
224
|
const parts = candidate?.content?.parts ?? [];
|
|
184
|
-
if (chunk.
|
|
225
|
+
if (chunk.usageMetadata)
|
|
226
|
+
state.usage = { ...state.usage, ...chunk.usageMetadata };
|
|
227
|
+
if (state.finished)
|
|
228
|
+
return events;
|
|
229
|
+
if (chunk.modelVersion)
|
|
185
230
|
state.model = chunk.modelVersion;
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
state.id = chunk.responseId;
|
|
189
|
-
}
|
|
231
|
+
if (candidate?.groundingMetadata)
|
|
232
|
+
state.grounding = { ...state.grounding, ...candidate.groundingMetadata };
|
|
190
233
|
if (!state.started) {
|
|
191
234
|
state.started = true;
|
|
192
|
-
|
|
193
|
-
state.id = `resp_${this.generateId()}`;
|
|
194
|
-
}
|
|
195
|
-
const skeleton = this.makeSkeletonResponse();
|
|
235
|
+
state.id = chunk.responseId ?? `resp_${this.generateId()}`;
|
|
196
236
|
events.push({
|
|
197
237
|
type: "response.created",
|
|
198
|
-
response:
|
|
238
|
+
response: this.makeSkeletonResponse(),
|
|
199
239
|
sequence_number: state.seq++,
|
|
200
|
-
}
|
|
201
|
-
events.push({
|
|
240
|
+
}, {
|
|
202
241
|
type: "response.in_progress",
|
|
203
|
-
response:
|
|
242
|
+
response: this.makeSkeletonResponse(),
|
|
204
243
|
sequence_number: state.seq++,
|
|
205
244
|
});
|
|
206
245
|
}
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
if (
|
|
210
|
-
state.
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
type: "reasoning",
|
|
215
|
-
id: `rs_${this.generateId()}`,
|
|
216
|
-
summary: [],
|
|
217
|
-
},
|
|
218
|
-
output_index: state.outputIndex,
|
|
219
|
-
sequence_number: state.seq++,
|
|
220
|
-
});
|
|
221
|
-
events.push({
|
|
222
|
-
type: "response.reasoning_summary_part.added",
|
|
223
|
-
item_id: `rs_${this.generateId()}`,
|
|
224
|
-
output_index: state.outputIndex,
|
|
225
|
-
summary_index: 0,
|
|
226
|
-
part: { type: "summary_text", text: "" },
|
|
227
|
-
sequence_number: state.seq++,
|
|
228
|
-
});
|
|
246
|
+
try {
|
|
247
|
+
for (const [partIndex, part] of parts.entries()) {
|
|
248
|
+
if (part.functionCall) {
|
|
249
|
+
if (state.current?.type === "reasoning")
|
|
250
|
+
this.finishReasoning(state.current, "completed", events);
|
|
251
|
+
state.current = null;
|
|
252
|
+
this.convertFunctionPart(part, events);
|
|
229
253
|
}
|
|
230
|
-
|
|
231
|
-
type: "
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
254
|
+
else if (part.text != null && part.text !== "") {
|
|
255
|
+
const type = part.thought ? "reasoning" : "message";
|
|
256
|
+
if (state.current?.type !== type) {
|
|
257
|
+
if (state.current?.type === "reasoning")
|
|
258
|
+
this.finishReasoning(state.current, "completed", events);
|
|
259
|
+
const ctx = {
|
|
260
|
+
type,
|
|
261
|
+
id: `${type === "reasoning" ? "rs" : "msg"}_${this.generateId()}`,
|
|
262
|
+
index: state.items.length,
|
|
263
|
+
text: "",
|
|
264
|
+
parts: [],
|
|
265
|
+
annotations: [],
|
|
266
|
+
};
|
|
267
|
+
state.items.push(ctx);
|
|
268
|
+
state.current = ctx;
|
|
269
|
+
events.push({
|
|
270
|
+
type: "response.output_item.added",
|
|
271
|
+
output_index: ctx.index,
|
|
272
|
+
sequence_number: state.seq++,
|
|
273
|
+
item: type === "reasoning"
|
|
274
|
+
? { type: "reasoning", id: ctx.id, summary: [], status: "in_progress" }
|
|
275
|
+
: {
|
|
276
|
+
type: "message",
|
|
277
|
+
id: ctx.id,
|
|
278
|
+
role: "assistant",
|
|
279
|
+
status: "in_progress",
|
|
280
|
+
content: [],
|
|
281
|
+
},
|
|
282
|
+
});
|
|
283
|
+
events.push(type === "reasoning"
|
|
284
|
+
? {
|
|
285
|
+
type: "response.reasoning_summary_part.added",
|
|
286
|
+
item_id: ctx.id,
|
|
287
|
+
output_index: ctx.index,
|
|
288
|
+
summary_index: 0,
|
|
289
|
+
part: { type: "summary_text", text: "" },
|
|
290
|
+
sequence_number: state.seq++,
|
|
291
|
+
}
|
|
292
|
+
: {
|
|
293
|
+
type: "response.content_part.added",
|
|
294
|
+
item_id: ctx.id,
|
|
295
|
+
output_index: ctx.index,
|
|
296
|
+
content_index: 0,
|
|
297
|
+
part: { type: "output_text", text: "", annotations: [], logprobs: [] },
|
|
298
|
+
sequence_number: state.seq++,
|
|
299
|
+
});
|
|
246
300
|
}
|
|
247
|
-
state.
|
|
248
|
-
const
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
301
|
+
const ctx = state.current;
|
|
302
|
+
const last = state.sourceParts.at(-1);
|
|
303
|
+
// The first text part of the next chunk can continue the preceding Gemini Part.
|
|
304
|
+
if (partIndex === 0 &&
|
|
305
|
+
last?.ctx === ctx &&
|
|
306
|
+
last.part.text != null &&
|
|
307
|
+
!last.part.thoughtSignature) {
|
|
308
|
+
last.part.text += part.text;
|
|
309
|
+
if (part.thoughtSignature)
|
|
310
|
+
last.part.thoughtSignature = part.thoughtSignature;
|
|
311
|
+
}
|
|
312
|
+
else {
|
|
313
|
+
const saved = structuredClone(part);
|
|
314
|
+
ctx.parts.push(saved);
|
|
315
|
+
state.sourceParts.push({ ctx, part: saved });
|
|
316
|
+
}
|
|
317
|
+
ctx.text += part.text;
|
|
318
|
+
if (type === "reasoning")
|
|
319
|
+
events.push({
|
|
320
|
+
type: "response.reasoning_summary_text.delta",
|
|
321
|
+
item_id: ctx.id,
|
|
322
|
+
output_index: ctx.index,
|
|
323
|
+
summary_index: 0,
|
|
324
|
+
delta: part.text,
|
|
325
|
+
sequence_number: state.seq++,
|
|
326
|
+
});
|
|
327
|
+
else {
|
|
264
328
|
events.push({
|
|
265
|
-
type: "response.
|
|
266
|
-
item_id:
|
|
267
|
-
output_index:
|
|
268
|
-
|
|
329
|
+
type: "response.output_text.delta",
|
|
330
|
+
item_id: ctx.id,
|
|
331
|
+
output_index: ctx.index,
|
|
332
|
+
content_index: 0,
|
|
333
|
+
delta: part.text,
|
|
334
|
+
logprobs: [],
|
|
269
335
|
sequence_number: state.seq++,
|
|
270
336
|
});
|
|
271
337
|
}
|
|
272
338
|
}
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
const msgOutputIndex = state.outputIndex + (state.reasoningStarted ? 1 : 0) + state.toolCallCount;
|
|
278
|
-
events.push({
|
|
279
|
-
type: "response.output_item.added",
|
|
280
|
-
item: {
|
|
281
|
-
type: "message",
|
|
282
|
-
id: `msg_${this.generateId()}`,
|
|
283
|
-
role: "assistant",
|
|
284
|
-
status: "in_progress",
|
|
285
|
-
content: [],
|
|
286
|
-
},
|
|
287
|
-
output_index: msgOutputIndex,
|
|
288
|
-
sequence_number: state.seq++,
|
|
289
|
-
});
|
|
290
|
-
events.push({
|
|
291
|
-
type: "response.content_part.added",
|
|
292
|
-
item_id: `msg_${this.generateId()}`,
|
|
293
|
-
output_index: msgOutputIndex,
|
|
294
|
-
content_index: 0,
|
|
295
|
-
part: { type: "output_text", text: "", annotations: [] },
|
|
296
|
-
sequence_number: state.seq++,
|
|
297
|
-
});
|
|
339
|
+
else if (part.thoughtSignature) {
|
|
340
|
+
const last = state.sourceParts.at(-1);
|
|
341
|
+
if (last)
|
|
342
|
+
last.part.thoughtSignature = part.thoughtSignature;
|
|
298
343
|
}
|
|
299
|
-
events.push({
|
|
300
|
-
type: "response.output_text.delta",
|
|
301
|
-
item_id: `msg_${this.generateId()}`,
|
|
302
|
-
output_index: state.outputIndex + (state.reasoningStarted ? 1 : 0) + state.toolCallCount,
|
|
303
|
-
content_index: 0,
|
|
304
|
-
delta: part.text,
|
|
305
|
-
sequence_number: state.seq++,
|
|
306
|
-
});
|
|
307
344
|
}
|
|
308
345
|
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
const resp = this.makeSkeletonResponse();
|
|
313
|
-
resp.status = status;
|
|
314
|
-
const usage = chunk.usageMetadata;
|
|
315
|
-
if (usage) {
|
|
316
|
-
const promptTokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
|
|
317
|
-
const thoughtsTokens = usage.thoughtsTokenCount ?? 0;
|
|
318
|
-
const candidatesTokens = (usage.candidatesTokenCount ?? 0) + thoughtsTokens;
|
|
319
|
-
resp.usage = {
|
|
320
|
-
input_tokens: promptTokens,
|
|
321
|
-
output_tokens: candidatesTokens,
|
|
322
|
-
total_tokens: usage.totalTokenCount ?? 0,
|
|
323
|
-
input_tokens_details: {
|
|
324
|
-
cached_tokens: usage.cachedContentTokenCount ?? 0,
|
|
325
|
-
},
|
|
326
|
-
output_tokens_details: {
|
|
327
|
-
reasoning_tokens: thoughtsTokens,
|
|
328
|
-
},
|
|
329
|
-
};
|
|
330
|
-
}
|
|
331
|
-
if (status === "incomplete") {
|
|
332
|
-
events.push({
|
|
333
|
-
type: "response.incomplete",
|
|
334
|
-
response: resp,
|
|
335
|
-
sequence_number: state.seq++,
|
|
336
|
-
});
|
|
337
|
-
}
|
|
338
|
-
else {
|
|
339
|
-
events.push({
|
|
340
|
-
type: "response.completed",
|
|
341
|
-
response: resp,
|
|
342
|
-
sequence_number: state.seq++,
|
|
343
|
-
});
|
|
344
|
-
}
|
|
346
|
+
catch (error) {
|
|
347
|
+
this.finishResponse("failed", error instanceof Error ? error.message : String(error), events);
|
|
348
|
+
return (0, utils_1.denamespaceStreamEvents)(events);
|
|
345
349
|
}
|
|
350
|
+
if (chunk.promptFeedback?.blockReason)
|
|
351
|
+
this.finishResponse("failed", `Gemini blocked the prompt: ${chunk.promptFeedback.blockReason}`, events);
|
|
352
|
+
else if (candidate?.finishReason && candidate.finishReason !== "FINISH_REASON_UNSPECIFIED")
|
|
353
|
+
this.finishResponse(this.finishReasonToStatus(candidate.finishReason), `Gemini finished with ${candidate.finishReason}`, events);
|
|
346
354
|
return (0, utils_1.denamespaceStreamEvents)(events);
|
|
347
355
|
}
|
|
356
|
+
convertFunctionPart(part, events) {
|
|
357
|
+
const state = this.streamState;
|
|
358
|
+
const fc = part.functionCall;
|
|
359
|
+
const existing = fc.id ? state.functions.get(fc.id) : undefined;
|
|
360
|
+
// Keep the original first-call-wins behavior for repeated call IDs.
|
|
361
|
+
if (existing) {
|
|
362
|
+
if (part.thoughtSignature)
|
|
363
|
+
existing.parts[0].thoughtSignature = part.thoughtSignature;
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
const args = structuredClone(fc.args ?? {});
|
|
367
|
+
const ctx = {
|
|
368
|
+
type: "function_call",
|
|
369
|
+
id: `fc_${this.generateId()}`,
|
|
370
|
+
index: state.items.length,
|
|
371
|
+
callId: fc.id ?? `call_${this.generateId()}`,
|
|
372
|
+
name: fc.name ?? "",
|
|
373
|
+
arguments: JSON.stringify(args),
|
|
374
|
+
parts: [],
|
|
375
|
+
};
|
|
376
|
+
const saved = { functionCall: { id: ctx.callId, name: ctx.name, args } };
|
|
377
|
+
if (part.thoughtSignature)
|
|
378
|
+
saved.thoughtSignature = part.thoughtSignature;
|
|
379
|
+
ctx.parts.push(saved);
|
|
380
|
+
state.sourceParts.push({ ctx, part: saved });
|
|
381
|
+
state.items.push(ctx);
|
|
382
|
+
if (fc.id)
|
|
383
|
+
state.functions.set(fc.id, ctx);
|
|
384
|
+
events.push({
|
|
385
|
+
type: "response.output_item.added",
|
|
386
|
+
output_index: ctx.index,
|
|
387
|
+
sequence_number: state.seq++,
|
|
388
|
+
item: {
|
|
389
|
+
type: "function_call",
|
|
390
|
+
id: ctx.id,
|
|
391
|
+
call_id: ctx.callId,
|
|
392
|
+
name: ctx.name,
|
|
393
|
+
arguments: "",
|
|
394
|
+
status: "in_progress",
|
|
395
|
+
},
|
|
396
|
+
}, {
|
|
397
|
+
type: "response.function_call_arguments.delta",
|
|
398
|
+
item_id: ctx.id,
|
|
399
|
+
output_index: ctx.index,
|
|
400
|
+
delta: ctx.arguments,
|
|
401
|
+
sequence_number: state.seq++,
|
|
402
|
+
});
|
|
403
|
+
this.finishFunction(ctx, events);
|
|
404
|
+
}
|
|
348
405
|
// --- Private: request helpers ---
|
|
349
406
|
convertInput(systemParts, contents, input) {
|
|
350
407
|
if (typeof input === "string") {
|
|
351
408
|
contents.push({ role: "user", parts: [{ text: input }] });
|
|
352
409
|
return;
|
|
353
410
|
}
|
|
354
|
-
const
|
|
355
|
-
const
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
411
|
+
const signed = unpackGeminiSignatures(input);
|
|
412
|
+
const calls = new Map();
|
|
413
|
+
const append = (role, parts) => {
|
|
414
|
+
if (!parts.length)
|
|
415
|
+
return;
|
|
416
|
+
const last = contents.at(-1);
|
|
417
|
+
const previous = last?.parts?.at(-1);
|
|
418
|
+
const signedTurn = role === "model" &&
|
|
419
|
+
(parts.some(part => part.thoughtSignature) ||
|
|
420
|
+
last?.parts?.some(part => part.thoughtSignature));
|
|
421
|
+
// Preserve message boundaries; only group tool exchanges and signed native turns.
|
|
422
|
+
if (last?.role === role &&
|
|
423
|
+
(signedTurn ||
|
|
424
|
+
(previous?.functionCall && parts[0].functionCall) ||
|
|
425
|
+
(previous?.functionResponse && parts[0].functionResponse)))
|
|
426
|
+
last.parts.push(...parts);
|
|
427
|
+
else
|
|
428
|
+
contents.push({ role, parts });
|
|
360
429
|
};
|
|
361
|
-
for (const item of input) {
|
|
430
|
+
for (const item of input ?? []) {
|
|
362
431
|
const typed = item;
|
|
363
|
-
|
|
364
|
-
|
|
432
|
+
const signedParts = signed.get(typed.id);
|
|
433
|
+
if (typed.type === "reasoning") {
|
|
434
|
+
if (signedParts)
|
|
435
|
+
append("model", signedParts);
|
|
436
|
+
}
|
|
437
|
+
else if (typed.type === "message" || (typed.type == null && typed.role)) {
|
|
365
438
|
if (typed.role === "system" || typed.role === "developer") {
|
|
366
439
|
const text = this.extractText(typed.content);
|
|
367
440
|
if (text)
|
|
368
441
|
systemParts.push({ text });
|
|
369
442
|
}
|
|
370
|
-
else if (typed.role === "user") {
|
|
371
|
-
const parts = this.
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
for (const p of typed.content) {
|
|
378
|
-
if (p.type === "output_text")
|
|
379
|
-
parts.push({ text: p.text });
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
if (parts.length > 0) {
|
|
383
|
-
contents.push({ role: "model", parts });
|
|
384
|
-
}
|
|
443
|
+
else if (typed.role === "user" || typed.role === "assistant") {
|
|
444
|
+
const parts = this.convertMessageContent(typed.content, typed.role === "user");
|
|
445
|
+
const original = typed.role === "assistant" &&
|
|
446
|
+
signedParts &&
|
|
447
|
+
signedParts.map(part => part.text ?? "").join("") ===
|
|
448
|
+
parts.map(part => part.text ?? "").join("");
|
|
449
|
+
append(typed.role === "assistant" ? "model" : "user", original ? signedParts : parts);
|
|
385
450
|
}
|
|
386
451
|
}
|
|
387
452
|
else if (typed.type === "function_call") {
|
|
453
|
+
const name = qualifiedFunctionName(typed);
|
|
388
454
|
let args;
|
|
389
455
|
try {
|
|
390
456
|
args = JSON.parse(typed.arguments);
|
|
@@ -392,54 +458,30 @@ class ResponsesToGeminiConverter {
|
|
|
392
458
|
catch {
|
|
393
459
|
args = {};
|
|
394
460
|
}
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
461
|
+
calls.set(typed.call_id, name);
|
|
462
|
+
const part = { functionCall: { id: typed.call_id, name, args } };
|
|
463
|
+
const original = signedParts?.[0]?.functionCall;
|
|
464
|
+
if (signedParts?.length === 1 &&
|
|
465
|
+
original?.id === typed.call_id &&
|
|
466
|
+
original?.name === name &&
|
|
467
|
+
sameJson(original?.args ?? {}, args)) {
|
|
468
|
+
part.functionCall = structuredClone(original);
|
|
469
|
+
part.thoughtSignature = signedParts[0].thoughtSignature;
|
|
470
|
+
}
|
|
471
|
+
append("model", [part]);
|
|
402
472
|
}
|
|
403
473
|
else if (typed.type === "function_call_output") {
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
474
|
+
append("user", [
|
|
475
|
+
{
|
|
476
|
+
functionResponse: {
|
|
477
|
+
id: typed.call_id,
|
|
478
|
+
name: calls.get(typed.call_id) ?? typed.call_id,
|
|
479
|
+
response: { output: typed.output ?? "" },
|
|
480
|
+
},
|
|
410
481
|
},
|
|
411
|
-
|
|
412
|
-
const last = contents[contents.length - 1];
|
|
413
|
-
if (last && last.role === "user" && last.parts?.length) {
|
|
414
|
-
const lastPart = last.parts[last.parts.length - 1];
|
|
415
|
-
if (lastPart.functionResponse) {
|
|
416
|
-
last.parts.push(responsePart);
|
|
417
|
-
continue;
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
contents.push({ role: "user", parts: [responsePart] });
|
|
421
|
-
}
|
|
422
|
-
else if ("role" in typed && "content" in typed && typeof typed.content === "string") {
|
|
423
|
-
flushFunctionCalls();
|
|
424
|
-
const role = typed.role;
|
|
425
|
-
if (role === "system" || role === "developer") {
|
|
426
|
-
systemParts.push({ text: typed.content });
|
|
427
|
-
}
|
|
428
|
-
else if (role === "user") {
|
|
429
|
-
contents.push({
|
|
430
|
-
role: "user",
|
|
431
|
-
parts: [{ text: typed.content }],
|
|
432
|
-
});
|
|
433
|
-
}
|
|
434
|
-
else if (role === "assistant") {
|
|
435
|
-
contents.push({
|
|
436
|
-
role: "model",
|
|
437
|
-
parts: [{ text: typed.content }],
|
|
438
|
-
});
|
|
439
|
-
}
|
|
482
|
+
]);
|
|
440
483
|
}
|
|
441
484
|
}
|
|
442
|
-
flushFunctionCalls();
|
|
443
485
|
}
|
|
444
486
|
extractText(content) {
|
|
445
487
|
if (typeof content === "string")
|
|
@@ -452,17 +494,20 @@ class ResponsesToGeminiConverter {
|
|
|
452
494
|
}
|
|
453
495
|
return "";
|
|
454
496
|
}
|
|
455
|
-
|
|
497
|
+
convertMessageContent(content, emptyFallback = true) {
|
|
456
498
|
if (typeof content === "string") {
|
|
457
499
|
return [{ text: content }];
|
|
458
500
|
}
|
|
459
501
|
if (!Array.isArray(content))
|
|
460
|
-
return [{ text: "" }];
|
|
502
|
+
return emptyFallback ? [{ text: "" }] : [];
|
|
461
503
|
const parts = [];
|
|
462
504
|
for (const p of content) {
|
|
463
|
-
if (p.type === "input_text") {
|
|
505
|
+
if (p.type === "input_text" || p.type === "output_text") {
|
|
464
506
|
parts.push({ text: p.text });
|
|
465
507
|
}
|
|
508
|
+
else if (p.type === "refusal") {
|
|
509
|
+
parts.push({ text: p.refusal });
|
|
510
|
+
}
|
|
466
511
|
else if (p.type === "input_image") {
|
|
467
512
|
const url = p.image_url || "";
|
|
468
513
|
const match = url.match(/^data:([^;]+);base64,(.+)$/);
|
|
@@ -493,7 +538,7 @@ class ResponsesToGeminiConverter {
|
|
|
493
538
|
}
|
|
494
539
|
}
|
|
495
540
|
}
|
|
496
|
-
return parts.length > 0 ? parts : [{ text: "" }];
|
|
541
|
+
return parts.length > 0 || !emptyFallback ? parts : [{ text: "" }];
|
|
497
542
|
}
|
|
498
543
|
convertTools(tools) {
|
|
499
544
|
tools = (0, utils_1.expandNamespaceTools)(tools);
|
|
@@ -540,25 +585,26 @@ class ResponsesToGeminiConverter {
|
|
|
540
585
|
if (choice.type === "function" && choice.name) {
|
|
541
586
|
return {
|
|
542
587
|
mode: "ANY",
|
|
543
|
-
allowedFunctionNames: [choice
|
|
588
|
+
allowedFunctionNames: [qualifiedFunctionName(choice)],
|
|
544
589
|
};
|
|
545
590
|
}
|
|
546
591
|
}
|
|
547
592
|
return { mode: "AUTO" };
|
|
548
593
|
}
|
|
549
594
|
convertReasoning(reasoning) {
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
595
|
+
const effort = reasoning.effort;
|
|
596
|
+
if (!effort?.trim())
|
|
597
|
+
return {};
|
|
598
|
+
if (effort === "none")
|
|
599
|
+
return { includeThoughts: false, thinkingBudget: 0 };
|
|
600
|
+
const budgets = {
|
|
601
|
+
minimal: 128,
|
|
554
602
|
low: 2048,
|
|
555
603
|
medium: 5120,
|
|
556
604
|
high: 10240,
|
|
605
|
+
xhigh: 20480,
|
|
557
606
|
};
|
|
558
|
-
return {
|
|
559
|
-
includeThoughts: true,
|
|
560
|
-
thinkingBudget: budgetMap[reasoning.effort] ?? 10240,
|
|
561
|
-
};
|
|
607
|
+
return { includeThoughts: true, thinkingBudget: budgets[effort] ?? 10240 };
|
|
562
608
|
}
|
|
563
609
|
applyTextFormat(config, format) {
|
|
564
610
|
if (format.type === "json_schema") {
|
|
@@ -570,9 +616,7 @@ class ResponsesToGeminiConverter {
|
|
|
570
616
|
}
|
|
571
617
|
}
|
|
572
618
|
// --- Private: response helpers ---
|
|
573
|
-
finishReasonToStatus(reason
|
|
574
|
-
if (hasToolCall)
|
|
575
|
-
return "completed";
|
|
619
|
+
finishReasonToStatus(reason) {
|
|
576
620
|
switch (reason) {
|
|
577
621
|
case "STOP":
|
|
578
622
|
return "completed";
|
|
@@ -582,51 +626,329 @@ class ResponsesToGeminiConverter {
|
|
|
582
626
|
case "RECITATION":
|
|
583
627
|
case "BLOCKLIST":
|
|
584
628
|
case "PROHIBITED_CONTENT":
|
|
629
|
+
case "SPII":
|
|
630
|
+
case "MALFORMED_FUNCTION_CALL":
|
|
631
|
+
case "UNEXPECTED_TOOL_CALL":
|
|
632
|
+
case "LANGUAGE":
|
|
633
|
+
case "OTHER":
|
|
634
|
+
case "IMAGE_SAFETY":
|
|
635
|
+
case "IMAGE_PROHIBITED_CONTENT":
|
|
636
|
+
case "IMAGE_RECITATION":
|
|
637
|
+
case "IMAGE_OTHER":
|
|
638
|
+
case "NO_IMAGE":
|
|
585
639
|
return "failed";
|
|
586
640
|
default:
|
|
587
641
|
return "completed";
|
|
588
642
|
}
|
|
589
643
|
}
|
|
590
644
|
extractGroundingAnnotations(candidate, annotations) {
|
|
591
|
-
|
|
645
|
+
const metadata = candidate?.groundingMetadata;
|
|
646
|
+
if (!metadata)
|
|
592
647
|
return;
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
648
|
+
const parts = candidate?.content?.parts ?? [];
|
|
649
|
+
const supports = metadata.groundingSupports ?? [];
|
|
650
|
+
for (const support of supports) {
|
|
651
|
+
const segment = support.segment;
|
|
652
|
+
const partIndex = segment?.partIndex ?? 0;
|
|
653
|
+
const part = parts[partIndex];
|
|
654
|
+
let start = 0;
|
|
655
|
+
let end = 0;
|
|
656
|
+
if (part?.text != null &&
|
|
657
|
+
!part.thought &&
|
|
658
|
+
segment?.startIndex != null &&
|
|
659
|
+
segment.endIndex != null &&
|
|
660
|
+
Number.isInteger(segment.startIndex) &&
|
|
661
|
+
Number.isInteger(segment.endIndex) &&
|
|
662
|
+
segment.startIndex >= 0 &&
|
|
663
|
+
segment.endIndex >= segment.startIndex &&
|
|
664
|
+
segment.endIndex <= new TextEncoder().encode(part.text).length) {
|
|
665
|
+
const base = parts
|
|
666
|
+
.slice(0, partIndex)
|
|
667
|
+
.reduce((offset, part) => offset + (part.thought ? 0 : Array.from(part.text ?? "").length), 0);
|
|
668
|
+
start = base + byteToCharacterOffset(part.text, segment.startIndex);
|
|
669
|
+
end = base + byteToCharacterOffset(part.text, segment.endIndex);
|
|
670
|
+
}
|
|
671
|
+
for (const index of support.groundingChunkIndices ?? []) {
|
|
672
|
+
const web = metadata.groundingChunks?.[index]?.web;
|
|
673
|
+
if (!web)
|
|
674
|
+
continue;
|
|
596
675
|
annotations.push({
|
|
597
676
|
type: "url_citation",
|
|
598
677
|
url: web.uri || "",
|
|
599
678
|
title: web.title || "",
|
|
679
|
+
start_index: start,
|
|
680
|
+
end_index: end,
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
for (const [index, chunk] of (metadata.groundingChunks ?? []).entries()) {
|
|
685
|
+
if (chunk.web && !supports.some(support => support.groundingChunkIndices?.includes(index)))
|
|
686
|
+
annotations.push({
|
|
687
|
+
type: "url_citation",
|
|
688
|
+
url: chunk.web.uri || "",
|
|
689
|
+
title: chunk.web.title || "",
|
|
600
690
|
start_index: 0,
|
|
601
691
|
end_index: 0,
|
|
602
692
|
});
|
|
603
|
-
}
|
|
604
693
|
}
|
|
605
694
|
}
|
|
606
695
|
generateId() {
|
|
607
696
|
return Math.random().toString(36).substring(2, 15);
|
|
608
697
|
}
|
|
609
698
|
// --- Private: stream helpers ---
|
|
699
|
+
convertUsage(usage) {
|
|
700
|
+
const inputTokens = (usage?.promptTokenCount ?? 0) + (usage?.toolUsePromptTokenCount ?? 0);
|
|
701
|
+
const reasoningTokens = usage?.thoughtsTokenCount ?? 0;
|
|
702
|
+
const outputTokens = (usage?.candidatesTokenCount ?? 0) + reasoningTokens;
|
|
703
|
+
return {
|
|
704
|
+
input_tokens: inputTokens,
|
|
705
|
+
output_tokens: outputTokens,
|
|
706
|
+
total_tokens: usage?.totalTokenCount ?? 0,
|
|
707
|
+
input_tokens_details: { cached_tokens: usage?.cachedContentTokenCount ?? 0 },
|
|
708
|
+
output_tokens_details: { reasoning_tokens: reasoningTokens },
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
applyGrounding() {
|
|
712
|
+
const state = this.streamState;
|
|
713
|
+
const metadata = state.grounding;
|
|
714
|
+
if (!metadata)
|
|
715
|
+
return;
|
|
716
|
+
const fallback = state.items.find((item) => item.type === "message");
|
|
717
|
+
if (!fallback)
|
|
718
|
+
return;
|
|
719
|
+
const supports = metadata.groundingSupports ?? [];
|
|
720
|
+
const add = (ctx, uri, title, start, end) => {
|
|
721
|
+
ctx.annotations.push({
|
|
722
|
+
type: "url_citation",
|
|
723
|
+
url: uri,
|
|
724
|
+
title,
|
|
725
|
+
start_index: start,
|
|
726
|
+
end_index: end,
|
|
727
|
+
});
|
|
728
|
+
};
|
|
729
|
+
for (const support of supports) {
|
|
730
|
+
const segment = support.segment;
|
|
731
|
+
const source = state.sourceParts[segment?.partIndex ?? 0];
|
|
732
|
+
const ctx = source?.ctx.type === "message" ? source.ctx : fallback;
|
|
733
|
+
let start = 0;
|
|
734
|
+
let end = 0;
|
|
735
|
+
if (source?.ctx.type === "message" &&
|
|
736
|
+
source.part.text != null &&
|
|
737
|
+
segment?.startIndex != null &&
|
|
738
|
+
segment.endIndex != null &&
|
|
739
|
+
Number.isInteger(segment.startIndex) &&
|
|
740
|
+
Number.isInteger(segment.endIndex) &&
|
|
741
|
+
segment.startIndex >= 0 &&
|
|
742
|
+
segment.endIndex >= segment.startIndex &&
|
|
743
|
+
segment.endIndex <= new TextEncoder().encode(source.part.text).length) {
|
|
744
|
+
let base = 0;
|
|
745
|
+
for (const part of ctx.parts) {
|
|
746
|
+
if (part === source.part)
|
|
747
|
+
break;
|
|
748
|
+
base += Array.from(part.text ?? "").length;
|
|
749
|
+
}
|
|
750
|
+
start = base + byteToCharacterOffset(source.part.text, segment.startIndex);
|
|
751
|
+
end = base + byteToCharacterOffset(source.part.text, segment.endIndex);
|
|
752
|
+
}
|
|
753
|
+
for (const index of support.groundingChunkIndices ?? []) {
|
|
754
|
+
const web = metadata.groundingChunks?.[index]?.web;
|
|
755
|
+
if (web)
|
|
756
|
+
add(ctx, web.uri ?? "", web.title ?? "", start, end);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
for (const [index, chunk] of (metadata.groundingChunks ?? []).entries()) {
|
|
760
|
+
if (chunk.web && !supports.some(support => support.groundingChunkIndices?.includes(index)))
|
|
761
|
+
add(fallback, chunk.web.uri ?? "", chunk.web.title ?? "", 0, 0);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
finishFunction(ctx, events) {
|
|
765
|
+
const item = {
|
|
766
|
+
type: "function_call",
|
|
767
|
+
id: ctx.id,
|
|
768
|
+
call_id: ctx.callId,
|
|
769
|
+
name: ctx.name,
|
|
770
|
+
arguments: ctx.arguments,
|
|
771
|
+
status: "completed",
|
|
772
|
+
};
|
|
773
|
+
events?.push({
|
|
774
|
+
type: "response.function_call_arguments.done",
|
|
775
|
+
item_id: ctx.id,
|
|
776
|
+
output_index: ctx.index,
|
|
777
|
+
name: ctx.name,
|
|
778
|
+
arguments: ctx.arguments,
|
|
779
|
+
sequence_number: this.streamState.seq++,
|
|
780
|
+
}, {
|
|
781
|
+
type: "response.output_item.done",
|
|
782
|
+
item: { ...item },
|
|
783
|
+
output_index: ctx.index,
|
|
784
|
+
sequence_number: this.streamState.seq++,
|
|
785
|
+
});
|
|
786
|
+
return item;
|
|
787
|
+
}
|
|
788
|
+
finishReasoning(ctx, status, events) {
|
|
789
|
+
const part = { type: "summary_text", text: ctx.text };
|
|
790
|
+
const item = {
|
|
791
|
+
type: "reasoning",
|
|
792
|
+
id: ctx.id,
|
|
793
|
+
summary: [part],
|
|
794
|
+
status: ctx.completed ? "completed" : status,
|
|
795
|
+
};
|
|
796
|
+
// Keep an already completed reasoning item stable and do not emit done events twice.
|
|
797
|
+
if (!ctx.completed) {
|
|
798
|
+
events.push({
|
|
799
|
+
type: "response.reasoning_summary_text.done",
|
|
800
|
+
item_id: ctx.id,
|
|
801
|
+
output_index: ctx.index,
|
|
802
|
+
summary_index: 0,
|
|
803
|
+
text: ctx.text,
|
|
804
|
+
sequence_number: this.streamState.seq++,
|
|
805
|
+
}, {
|
|
806
|
+
type: "response.reasoning_summary_part.done",
|
|
807
|
+
item_id: ctx.id,
|
|
808
|
+
output_index: ctx.index,
|
|
809
|
+
summary_index: 0,
|
|
810
|
+
part: { ...part },
|
|
811
|
+
sequence_number: this.streamState.seq++,
|
|
812
|
+
}, {
|
|
813
|
+
type: "response.output_item.done",
|
|
814
|
+
item: structuredClone(item),
|
|
815
|
+
output_index: ctx.index,
|
|
816
|
+
sequence_number: this.streamState.seq++,
|
|
817
|
+
});
|
|
818
|
+
ctx.completed = item.status === "completed";
|
|
819
|
+
}
|
|
820
|
+
return item;
|
|
821
|
+
}
|
|
822
|
+
finishResponse(status, failureMessage, events) {
|
|
823
|
+
const state = this.streamState;
|
|
824
|
+
state.finished = true;
|
|
825
|
+
this.applyGrounding();
|
|
826
|
+
const output = [];
|
|
827
|
+
for (const ctx of state.items) {
|
|
828
|
+
let item;
|
|
829
|
+
if (ctx.type === "function_call") {
|
|
830
|
+
output.push(this.finishFunction(ctx));
|
|
831
|
+
continue;
|
|
832
|
+
}
|
|
833
|
+
else if (ctx.type === "reasoning") {
|
|
834
|
+
output.push(this.finishReasoning(ctx, status === "completed" ? "completed" : "incomplete", events));
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
else {
|
|
838
|
+
const part = {
|
|
839
|
+
type: "output_text",
|
|
840
|
+
text: ctx.text,
|
|
841
|
+
annotations: ctx.annotations,
|
|
842
|
+
logprobs: [],
|
|
843
|
+
};
|
|
844
|
+
item = {
|
|
845
|
+
type: "message",
|
|
846
|
+
id: ctx.id,
|
|
847
|
+
role: "assistant",
|
|
848
|
+
status: status === "completed" ? "completed" : "incomplete",
|
|
849
|
+
content: [part],
|
|
850
|
+
};
|
|
851
|
+
ctx.annotations.forEach((annotation, annotationIndex) => events.push({
|
|
852
|
+
type: "response.output_text.annotation.added",
|
|
853
|
+
item_id: ctx.id,
|
|
854
|
+
output_index: ctx.index,
|
|
855
|
+
content_index: 0,
|
|
856
|
+
annotation_index: annotationIndex,
|
|
857
|
+
annotation: structuredClone(annotation),
|
|
858
|
+
sequence_number: state.seq++,
|
|
859
|
+
}));
|
|
860
|
+
events.push({
|
|
861
|
+
type: "response.output_text.done",
|
|
862
|
+
item_id: ctx.id,
|
|
863
|
+
output_index: ctx.index,
|
|
864
|
+
content_index: 0,
|
|
865
|
+
text: ctx.text,
|
|
866
|
+
logprobs: [],
|
|
867
|
+
sequence_number: state.seq++,
|
|
868
|
+
}, {
|
|
869
|
+
type: "response.content_part.done",
|
|
870
|
+
item_id: ctx.id,
|
|
871
|
+
output_index: ctx.index,
|
|
872
|
+
content_index: 0,
|
|
873
|
+
part: structuredClone(part),
|
|
874
|
+
sequence_number: state.seq++,
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
output.push(item);
|
|
878
|
+
events.push({
|
|
879
|
+
type: "response.output_item.done",
|
|
880
|
+
item: structuredClone(item),
|
|
881
|
+
output_index: ctx.index,
|
|
882
|
+
sequence_number: state.seq++,
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
const signed = state.items
|
|
886
|
+
.filter(ctx => ctx.parts.some(part => part.thoughtSignature))
|
|
887
|
+
.map(ctx => ({ id: ctx.id, parts: ctx.parts }));
|
|
888
|
+
if (signed.length) {
|
|
889
|
+
const id = `rs_${this.generateId()}`;
|
|
890
|
+
const index = output.length;
|
|
891
|
+
const item = {
|
|
892
|
+
type: "reasoning",
|
|
893
|
+
id,
|
|
894
|
+
summary: [],
|
|
895
|
+
status: "completed",
|
|
896
|
+
encrypted_content: packGeminiSignatures(signed),
|
|
897
|
+
};
|
|
898
|
+
events.push({
|
|
899
|
+
type: "response.output_item.added",
|
|
900
|
+
item: { type: "reasoning", id, summary: [], status: "in_progress" },
|
|
901
|
+
output_index: index,
|
|
902
|
+
sequence_number: state.seq++,
|
|
903
|
+
}, {
|
|
904
|
+
type: "response.output_item.done",
|
|
905
|
+
item: structuredClone(item),
|
|
906
|
+
output_index: index,
|
|
907
|
+
sequence_number: state.seq++,
|
|
908
|
+
});
|
|
909
|
+
output.push(item);
|
|
910
|
+
}
|
|
911
|
+
const response = this.makeSkeletonResponse();
|
|
912
|
+
response.status = status;
|
|
913
|
+
response.output = structuredClone(output);
|
|
914
|
+
if (state.usage)
|
|
915
|
+
response.usage = this.convertUsage(state.usage);
|
|
916
|
+
if (status === "incomplete")
|
|
917
|
+
response.incomplete_details = { reason: "max_output_tokens" };
|
|
918
|
+
if (status === "failed")
|
|
919
|
+
response.error = {
|
|
920
|
+
code: failureMessage.includes("blocked the prompt") ? "invalid_prompt" : "server_error",
|
|
921
|
+
message: failureMessage,
|
|
922
|
+
};
|
|
923
|
+
events.push({
|
|
924
|
+
type: status === "failed"
|
|
925
|
+
? "response.failed"
|
|
926
|
+
: status === "incomplete"
|
|
927
|
+
? "response.incomplete"
|
|
928
|
+
: "response.completed",
|
|
929
|
+
response,
|
|
930
|
+
sequence_number: state.seq++,
|
|
931
|
+
});
|
|
932
|
+
}
|
|
610
933
|
createStreamState() {
|
|
611
934
|
return {
|
|
612
935
|
id: "",
|
|
613
936
|
model: "",
|
|
937
|
+
createdAt: Math.floor(Date.now() / 1000),
|
|
614
938
|
seq: 0,
|
|
615
939
|
started: false,
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
prevThought: "",
|
|
622
|
-
seenFunctionCallIds: new Set(),
|
|
940
|
+
finished: false,
|
|
941
|
+
current: null,
|
|
942
|
+
items: [],
|
|
943
|
+
functions: new Map(),
|
|
944
|
+
sourceParts: [],
|
|
623
945
|
};
|
|
624
946
|
}
|
|
625
947
|
makeSkeletonResponse() {
|
|
626
948
|
return {
|
|
627
949
|
id: this.streamState.id,
|
|
628
950
|
object: "response",
|
|
629
|
-
created_at:
|
|
951
|
+
created_at: this.streamState.createdAt,
|
|
630
952
|
model: this.streamState.model,
|
|
631
953
|
output: [],
|
|
632
954
|
status: "in_progress",
|
|
@@ -649,3 +971,64 @@ class ResponsesToGeminiConverter {
|
|
|
649
971
|
}
|
|
650
972
|
}
|
|
651
973
|
exports.ResponsesToGeminiConverter = ResponsesToGeminiConverter;
|
|
974
|
+
function isObject(value) {
|
|
975
|
+
return value != null && typeof value === "object" && !Array.isArray(value);
|
|
976
|
+
}
|
|
977
|
+
function qualifiedFunctionName(tool) {
|
|
978
|
+
return tool.namespace ? `${tool.namespace}___${tool.name}` : tool.name;
|
|
979
|
+
}
|
|
980
|
+
function sameJson(a, b) {
|
|
981
|
+
if (a === b)
|
|
982
|
+
return true;
|
|
983
|
+
if (Array.isArray(a) && Array.isArray(b))
|
|
984
|
+
return a.length === b.length && a.every((value, index) => sameJson(value, b[index]));
|
|
985
|
+
if (!isObject(a) || !isObject(b))
|
|
986
|
+
return false;
|
|
987
|
+
const keys = Object.keys(a);
|
|
988
|
+
return (keys.length === Object.keys(b).length &&
|
|
989
|
+
keys.every(key => Object.hasOwn(b, key) && sameJson(a[key], b[key])));
|
|
990
|
+
}
|
|
991
|
+
const SIGNATURE_PREFIX = "rosetta:gemini:signatures:v1:";
|
|
992
|
+
/** This is an opaque transport envelope, not locally encrypted data. Signatures remain provider-owned. */
|
|
993
|
+
function packGeminiSignatures(items) {
|
|
994
|
+
return SIGNATURE_PREFIX + Buffer.from(JSON.stringify(items), "utf8").toString("base64url");
|
|
995
|
+
}
|
|
996
|
+
function unpackGeminiSignatures(input) {
|
|
997
|
+
const result = new Map();
|
|
998
|
+
if (!Array.isArray(input))
|
|
999
|
+
return result;
|
|
1000
|
+
for (const item of input) {
|
|
1001
|
+
if (item?.type !== "reasoning" ||
|
|
1002
|
+
typeof item.encrypted_content !== "string" ||
|
|
1003
|
+
!item.encrypted_content.startsWith(SIGNATURE_PREFIX))
|
|
1004
|
+
continue;
|
|
1005
|
+
try {
|
|
1006
|
+
const entries = JSON.parse(Buffer.from(item.encrypted_content.slice(SIGNATURE_PREFIX.length), "base64url").toString("utf8"));
|
|
1007
|
+
if (!Array.isArray(entries))
|
|
1008
|
+
continue;
|
|
1009
|
+
for (const entry of entries) {
|
|
1010
|
+
if (!isObject(entry) ||
|
|
1011
|
+
typeof entry.id !== "string" ||
|
|
1012
|
+
!Array.isArray(entry.parts) ||
|
|
1013
|
+
!entry.parts.length)
|
|
1014
|
+
continue;
|
|
1015
|
+
if (!entry.parts.every((p) => isObject(p) &&
|
|
1016
|
+
(typeof p.text === "string" || isObject(p.functionCall)) &&
|
|
1017
|
+
(p.thoughtSignature == null || typeof p.thoughtSignature === "string")))
|
|
1018
|
+
continue;
|
|
1019
|
+
if (!entry.parts.some((p) => p.thoughtSignature))
|
|
1020
|
+
continue;
|
|
1021
|
+
result.set(entry.id, structuredClone(entry.parts));
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
catch {
|
|
1025
|
+
// An unreadable envelope cannot restore signatures; retain the ordinary input history.
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
return result;
|
|
1029
|
+
}
|
|
1030
|
+
/** Gemini offsets are UTF-8 bytes; Responses annotations use character offsets. */
|
|
1031
|
+
function byteToCharacterOffset(text, byteOffset) {
|
|
1032
|
+
const bytes = new TextEncoder().encode(text);
|
|
1033
|
+
return Array.from(new TextDecoder().decode(bytes.slice(0, Math.max(0, byteOffset)))).length;
|
|
1034
|
+
}
|