@zenmux/rosetta-ai 1.0.18 → 1.0.20
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/README.md
CHANGED
|
@@ -309,14 +309,18 @@ for await (const chunk of converter.convertStream(responsesStream)) {
|
|
|
309
309
|
| OpenAI Chat Completions | OpenAI Responses |
|
|
310
310
|
|---|---|
|
|
311
311
|
| `messages` | `input` (ResponseInputItem[]) |
|
|
312
|
-
| `system` / `developer` messages | `
|
|
313
|
-
| `max_completion_tokens` | `max_output_tokens` |
|
|
314
|
-
| `tools` (function) | `tools` (function) |
|
|
315
|
-
| `tool_choice` | `tool_choice` |
|
|
312
|
+
| `system` / `developer` messages | `input` messages with the same role |
|
|
313
|
+
| `max_completion_tokens` / `max_tokens` | `max_output_tokens` |
|
|
314
|
+
| `tools` (function/custom), deprecated `functions` | `tools` (function/custom) |
|
|
315
|
+
| `tool_choice`, deprecated `function_call` | `tool_choice` |
|
|
316
316
|
| `response_format` | `text.format` |
|
|
317
|
+
| `verbosity` | `text.verbosity` |
|
|
317
318
|
| `reasoning_effort` | `reasoning.effort` |
|
|
318
319
|
| `web_search_options` | `tools` (web_search) |
|
|
319
320
|
| `parallel_tool_calls` | `parallel_tool_calls` |
|
|
321
|
+
| `logprobs` / `top_logprobs` | `include` / `top_logprobs` |
|
|
322
|
+
| `metadata`, `store`, `service_tier` | Same-name fields |
|
|
323
|
+
| `safety_identifier`, `user` | Same-name fields |
|
|
320
324
|
| `prompt_cache_key` / `prompt_cache_retention` | `prompt_cache_key` / `prompt_cache_retention` |
|
|
321
325
|
|
|
322
326
|
### Chat Completions → Gemini
|
|
@@ -12,14 +12,21 @@ export declare class ChatCompletionToGeminiConverter {
|
|
|
12
12
|
private convertAssistantParts;
|
|
13
13
|
private appendToolResponse;
|
|
14
14
|
private convertFile;
|
|
15
|
+
private inferFileMimeType;
|
|
15
16
|
private convertInputAudio;
|
|
16
17
|
private convertTools;
|
|
17
18
|
private convertToolChoice;
|
|
18
19
|
private applyResponseFormat;
|
|
19
20
|
private convertReasoningEffort;
|
|
21
|
+
private convertCandidate;
|
|
22
|
+
private getPromptFeedbackRefusal;
|
|
23
|
+
private convertUsage;
|
|
24
|
+
private convertLogprobs;
|
|
25
|
+
private toUtf8Bytes;
|
|
20
26
|
private extractGroundingAnnotations;
|
|
21
27
|
private mapFinishReason;
|
|
22
28
|
private generateId;
|
|
23
29
|
private createStreamState;
|
|
30
|
+
private getChoiceStreamState;
|
|
24
31
|
private makeChunk;
|
|
25
32
|
}
|
|
@@ -10,6 +10,7 @@ class ChatCompletionToGeminiConverter {
|
|
|
10
10
|
convertRequest(params) {
|
|
11
11
|
const systemParts = [];
|
|
12
12
|
const contents = [];
|
|
13
|
+
const toolCallNames = new Map();
|
|
13
14
|
for (const msg of params.messages) {
|
|
14
15
|
if (msg.role === "system" || msg.role === "developer") {
|
|
15
16
|
const text = typeof msg.content === "string" ? msg.content : msg.content.map(p => p.text).join("\n");
|
|
@@ -22,21 +23,26 @@ class ChatCompletionToGeminiConverter {
|
|
|
22
23
|
});
|
|
23
24
|
}
|
|
24
25
|
else if (msg.role === "assistant") {
|
|
26
|
+
for (const toolCall of msg.tool_calls ?? []) {
|
|
27
|
+
if (toolCall.type === "function") {
|
|
28
|
+
toolCallNames.set(toolCall.id, toolCall.function.name);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
25
31
|
contents.push({
|
|
26
32
|
role: "model",
|
|
27
33
|
parts: this.convertAssistantParts(msg),
|
|
28
34
|
});
|
|
29
35
|
}
|
|
30
36
|
else if (msg.role === "tool") {
|
|
31
|
-
this.appendToolResponse(contents, msg);
|
|
37
|
+
this.appendToolResponse(contents, msg, toolCallNames.get(msg.tool_call_id));
|
|
32
38
|
}
|
|
33
39
|
}
|
|
34
40
|
const config = {};
|
|
35
41
|
if (systemParts.length > 0) {
|
|
36
42
|
config.systemInstruction = { parts: systemParts };
|
|
37
43
|
}
|
|
38
|
-
if (params.
|
|
39
|
-
config.maxOutputTokens = params.
|
|
44
|
+
if (params.max_completion_tokens != null || params.max_tokens != null) {
|
|
45
|
+
config.maxOutputTokens = params.max_completion_tokens ?? params.max_tokens ?? undefined;
|
|
40
46
|
}
|
|
41
47
|
if (params.temperature != null) {
|
|
42
48
|
config.temperature = params.temperature;
|
|
@@ -97,91 +103,31 @@ class ChatCompletionToGeminiConverter {
|
|
|
97
103
|
}
|
|
98
104
|
// --- Response conversion (Gemini → CC, backward) ---
|
|
99
105
|
convertResponse(response) {
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
thinkingParts.push(part.text);
|
|
110
|
-
reasoningDetails.push({
|
|
111
|
-
type: "reasoning.text",
|
|
112
|
-
text: part.text,
|
|
113
|
-
signature: part.thoughtSignature ?? undefined,
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
else if (part.functionCall) {
|
|
117
|
-
const fc = part.functionCall;
|
|
118
|
-
toolCalls.push({
|
|
119
|
-
id: fc.id ?? fc.name ?? `call_${this.generateId()}`,
|
|
120
|
-
type: "function",
|
|
121
|
-
function: {
|
|
122
|
-
name: fc.name ?? "",
|
|
123
|
-
arguments: JSON.stringify(fc.args ?? {}),
|
|
124
|
-
},
|
|
106
|
+
const choices = (response.candidates ?? []).map((candidate, index) => this.convertCandidate(candidate, candidate.index ?? index));
|
|
107
|
+
if (choices.length === 0) {
|
|
108
|
+
const refusal = this.getPromptFeedbackRefusal(response);
|
|
109
|
+
if (refusal) {
|
|
110
|
+
choices.push({
|
|
111
|
+
index: 0,
|
|
112
|
+
message: { role: "assistant", content: null, refusal },
|
|
113
|
+
finish_reason: "content_filter",
|
|
114
|
+
logprobs: null,
|
|
125
115
|
});
|
|
126
116
|
}
|
|
127
|
-
else if (part.text != null) {
|
|
128
|
-
textParts.push(part.text);
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
this.extractGroundingAnnotations(candidate, annotations);
|
|
132
|
-
const assistantMessage = {
|
|
133
|
-
role: "assistant",
|
|
134
|
-
content: textParts.length > 0 ? textParts.join("") : null,
|
|
135
|
-
refusal: null,
|
|
136
|
-
};
|
|
137
|
-
if (thinkingParts.length > 0) {
|
|
138
|
-
Object.assign(assistantMessage, {
|
|
139
|
-
reasoning: thinkingParts.join(""),
|
|
140
|
-
reasoning_details: reasoningDetails,
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
if (toolCalls.length > 0) {
|
|
144
|
-
assistantMessage.tool_calls = toolCalls;
|
|
145
|
-
}
|
|
146
|
-
if (annotations.length > 0) {
|
|
147
|
-
assistantMessage.annotations = annotations;
|
|
148
117
|
}
|
|
149
|
-
|
|
150
|
-
if (toolCalls.length > 0) {
|
|
151
|
-
finishReason = "tool_calls";
|
|
152
|
-
}
|
|
153
|
-
const usage = response.usageMetadata;
|
|
154
|
-
const promptTokens = (usage?.promptTokenCount ?? 0) + (usage?.toolUsePromptTokenCount ?? 0);
|
|
155
|
-
const thoughtsTokens = usage?.thoughtsTokenCount ?? 0;
|
|
156
|
-
const candidatesTokens = (usage?.candidatesTokenCount ?? 0) + thoughtsTokens;
|
|
118
|
+
const usage = this.convertUsage(response.usageMetadata);
|
|
157
119
|
return {
|
|
158
120
|
id: response.responseId ?? `chatcmpl-${this.generateId()}`,
|
|
159
121
|
object: "chat.completion",
|
|
160
122
|
created: Math.floor(Date.now() / 1000),
|
|
161
123
|
model: response.modelVersion ?? "",
|
|
162
|
-
choices
|
|
163
|
-
|
|
164
|
-
index: 0,
|
|
165
|
-
message: assistantMessage,
|
|
166
|
-
finish_reason: finishReason,
|
|
167
|
-
logprobs: null,
|
|
168
|
-
},
|
|
169
|
-
],
|
|
170
|
-
usage: {
|
|
171
|
-
prompt_tokens: promptTokens,
|
|
172
|
-
completion_tokens: candidatesTokens,
|
|
173
|
-
total_tokens: usage?.totalTokenCount ?? 0,
|
|
174
|
-
prompt_tokens_details: {
|
|
175
|
-
cached_tokens: usage?.cachedContentTokenCount ?? 0,
|
|
176
|
-
},
|
|
177
|
-
completion_tokens_details: {
|
|
178
|
-
reasoning_tokens: thoughtsTokens,
|
|
179
|
-
},
|
|
180
|
-
},
|
|
124
|
+
choices,
|
|
125
|
+
...(usage && { usage }),
|
|
181
126
|
};
|
|
182
127
|
}
|
|
183
128
|
// --- Stream conversion (Gemini → CC, backward) ---
|
|
184
129
|
async *convertStream(stream) {
|
|
130
|
+
this.streamState = this.createStreamState();
|
|
185
131
|
for await (const chunk of stream) {
|
|
186
132
|
const events = this.convertStreamChunk(chunk);
|
|
187
133
|
for (const event of events) {
|
|
@@ -192,8 +138,7 @@ class ChatCompletionToGeminiConverter {
|
|
|
192
138
|
convertStreamChunk(chunk) {
|
|
193
139
|
const state = this.streamState;
|
|
194
140
|
const events = [];
|
|
195
|
-
const
|
|
196
|
-
const parts = candidate?.content?.parts ?? [];
|
|
141
|
+
const candidates = chunk.candidates ?? [];
|
|
197
142
|
if (chunk.modelVersion) {
|
|
198
143
|
state.model = chunk.modelVersion;
|
|
199
144
|
}
|
|
@@ -205,80 +150,103 @@ class ChatCompletionToGeminiConverter {
|
|
|
205
150
|
if (!state.id) {
|
|
206
151
|
state.id = `chatcmpl-${this.generateId()}`;
|
|
207
152
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
153
|
+
const indexes = candidates.length > 0
|
|
154
|
+
? candidates.map((candidate, index) => candidate.index ?? index)
|
|
155
|
+
: [0];
|
|
156
|
+
events.push(this.makeChunk(indexes.map(index => ({
|
|
157
|
+
index,
|
|
158
|
+
delta: { role: "assistant" },
|
|
159
|
+
finish_reason: null,
|
|
160
|
+
}))));
|
|
161
|
+
}
|
|
162
|
+
if (candidates.length === 0) {
|
|
163
|
+
const refusal = this.getPromptFeedbackRefusal(chunk);
|
|
164
|
+
if (refusal) {
|
|
165
|
+
events.push(this.makeChunk([
|
|
166
|
+
{
|
|
167
|
+
index: 0,
|
|
168
|
+
delta: { refusal },
|
|
169
|
+
finish_reason: "content_filter",
|
|
216
170
|
},
|
|
217
|
-
|
|
171
|
+
]));
|
|
218
172
|
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
173
|
+
}
|
|
174
|
+
for (let position = 0; position < candidates.length; position++) {
|
|
175
|
+
const candidate = candidates[position];
|
|
176
|
+
const choiceIndex = candidate.index ?? position;
|
|
177
|
+
const choiceState = this.getChoiceStreamState(choiceIndex);
|
|
178
|
+
for (const part of candidate.content?.parts ?? []) {
|
|
179
|
+
if (part.thought) {
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (part.functionCall) {
|
|
183
|
+
const functionCall = part.functionCall;
|
|
184
|
+
const functionCallId = functionCall.id ?? `call_${this.generateId()}`;
|
|
185
|
+
let toolCallIndex = choiceState.toolCallIndexes.get(functionCallId);
|
|
186
|
+
if (toolCallIndex == null) {
|
|
187
|
+
toolCallIndex = choiceState.toolCallCounter++;
|
|
188
|
+
choiceState.toolCallIndexes.set(functionCallId, toolCallIndex);
|
|
189
|
+
}
|
|
190
|
+
events.push(this.makeChunk([
|
|
191
|
+
{
|
|
192
|
+
index: choiceIndex,
|
|
193
|
+
delta: {
|
|
194
|
+
tool_calls: [
|
|
195
|
+
{
|
|
196
|
+
index: toolCallIndex,
|
|
197
|
+
id: functionCallId,
|
|
198
|
+
type: "function",
|
|
199
|
+
function: {
|
|
200
|
+
name: functionCall.name ?? "",
|
|
201
|
+
arguments: JSON.stringify(functionCall.args ?? {}),
|
|
202
|
+
},
|
|
203
|
+
},
|
|
204
|
+
],
|
|
235
205
|
},
|
|
236
|
-
|
|
237
|
-
|
|
206
|
+
finish_reason: null,
|
|
207
|
+
},
|
|
208
|
+
]));
|
|
209
|
+
}
|
|
210
|
+
else if (part.text != null && part.text !== "") {
|
|
211
|
+
events.push(this.makeChunk([
|
|
212
|
+
{
|
|
213
|
+
index: choiceIndex,
|
|
214
|
+
delta: { content: part.text },
|
|
215
|
+
finish_reason: null,
|
|
216
|
+
logprobs: this.convertLogprobs(candidate),
|
|
217
|
+
},
|
|
218
|
+
]));
|
|
238
219
|
}
|
|
239
220
|
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
content: "",
|
|
249
|
-
...{ annotations },
|
|
250
|
-
}));
|
|
251
|
-
}
|
|
252
|
-
if (candidate?.finishReason) {
|
|
253
|
-
let finishReason = this.mapFinishReason(candidate.finishReason);
|
|
254
|
-
if (state.toolCallCounter > 0) {
|
|
255
|
-
finishReason = "tool_calls";
|
|
256
|
-
}
|
|
257
|
-
const usage = chunk.usageMetadata;
|
|
258
|
-
const finishChunk = {
|
|
259
|
-
id: state.id,
|
|
260
|
-
object: "chat.completion.chunk",
|
|
261
|
-
created: Math.floor(Date.now() / 1000),
|
|
262
|
-
model: state.model,
|
|
263
|
-
choices: [{ index: 0, delta: {}, finish_reason: finishReason }],
|
|
264
|
-
};
|
|
265
|
-
if (usage) {
|
|
266
|
-
const promptTokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
|
|
267
|
-
const thoughtsTokens = usage.thoughtsTokenCount ?? 0;
|
|
268
|
-
const candidatesTokens = (usage.candidatesTokenCount ?? 0) + thoughtsTokens;
|
|
269
|
-
finishChunk.usage = {
|
|
270
|
-
prompt_tokens: promptTokens,
|
|
271
|
-
completion_tokens: candidatesTokens,
|
|
272
|
-
total_tokens: usage.totalTokenCount ?? 0,
|
|
273
|
-
prompt_tokens_details: {
|
|
274
|
-
cached_tokens: usage.cachedContentTokenCount ?? 0,
|
|
221
|
+
const annotations = [];
|
|
222
|
+
this.extractGroundingAnnotations(candidate, annotations);
|
|
223
|
+
if (annotations.length > 0) {
|
|
224
|
+
events.push(this.makeChunk([
|
|
225
|
+
{
|
|
226
|
+
index: choiceIndex,
|
|
227
|
+
delta: { content: "", ...{ annotations } },
|
|
228
|
+
finish_reason: null,
|
|
275
229
|
},
|
|
276
|
-
|
|
277
|
-
|
|
230
|
+
]));
|
|
231
|
+
}
|
|
232
|
+
if (candidate.finishReason) {
|
|
233
|
+
events.push(this.makeChunk([
|
|
234
|
+
{
|
|
235
|
+
index: choiceIndex,
|
|
236
|
+
delta: {},
|
|
237
|
+
finish_reason: choiceState.toolCallCounter > 0
|
|
238
|
+
? "tool_calls"
|
|
239
|
+
: this.mapFinishReason(candidate.finishReason),
|
|
278
240
|
},
|
|
279
|
-
|
|
241
|
+
]));
|
|
280
242
|
}
|
|
281
|
-
|
|
243
|
+
}
|
|
244
|
+
const usage = this.convertUsage(chunk.usageMetadata);
|
|
245
|
+
if (usage) {
|
|
246
|
+
events.push({
|
|
247
|
+
...this.makeChunk([]),
|
|
248
|
+
usage,
|
|
249
|
+
});
|
|
282
250
|
}
|
|
283
251
|
return events;
|
|
284
252
|
}
|
|
@@ -287,20 +255,20 @@ class ChatCompletionToGeminiConverter {
|
|
|
287
255
|
if (typeof content === "string") {
|
|
288
256
|
return [{ text: content }];
|
|
289
257
|
}
|
|
290
|
-
return content.
|
|
258
|
+
return content.flatMap(part => {
|
|
291
259
|
if (part.type === "text") {
|
|
292
|
-
return { text: part.text };
|
|
260
|
+
return [{ text: part.text }];
|
|
293
261
|
}
|
|
294
262
|
if (part.type === "image_url") {
|
|
295
|
-
return this.convertImageUrl(part);
|
|
263
|
+
return [this.convertImageUrl(part)];
|
|
296
264
|
}
|
|
297
265
|
if (part.type === "file") {
|
|
298
|
-
return this.convertFile(part);
|
|
266
|
+
return [this.convertFile(part)];
|
|
299
267
|
}
|
|
300
268
|
if (part.type === "input_audio") {
|
|
301
|
-
return this.convertInputAudio(part);
|
|
269
|
+
return [this.convertInputAudio(part)];
|
|
302
270
|
}
|
|
303
|
-
return
|
|
271
|
+
return [];
|
|
304
272
|
});
|
|
305
273
|
}
|
|
306
274
|
convertImageUrl(part) {
|
|
@@ -317,7 +285,7 @@ class ChatCompletionToGeminiConverter {
|
|
|
317
285
|
return {
|
|
318
286
|
fileData: {
|
|
319
287
|
fileUri: url,
|
|
320
|
-
mimeType: "image
|
|
288
|
+
mimeType: "image/jpeg",
|
|
321
289
|
},
|
|
322
290
|
};
|
|
323
291
|
}
|
|
@@ -357,11 +325,11 @@ class ChatCompletionToGeminiConverter {
|
|
|
357
325
|
}
|
|
358
326
|
return parts;
|
|
359
327
|
}
|
|
360
|
-
appendToolResponse(contents, msg) {
|
|
328
|
+
appendToolResponse(contents, msg, functionName) {
|
|
361
329
|
const responsePart = {
|
|
362
330
|
functionResponse: {
|
|
363
331
|
id: msg.tool_call_id,
|
|
364
|
-
name: msg.tool_call_id,
|
|
332
|
+
name: functionName ?? msg.tool_call_id,
|
|
365
333
|
response: {
|
|
366
334
|
output: typeof msg.content === "string" ? msg.content : msg.content.map(p => p.text).join("\n"),
|
|
367
335
|
},
|
|
@@ -379,20 +347,40 @@ class ChatCompletionToGeminiConverter {
|
|
|
379
347
|
}
|
|
380
348
|
convertFile(part) {
|
|
381
349
|
const fileData = part.file?.file_data;
|
|
382
|
-
if (!fileData)
|
|
383
|
-
|
|
350
|
+
if (!fileData) {
|
|
351
|
+
throw new Error("Chat Completions file content requires file_data for Gemini conversion");
|
|
352
|
+
}
|
|
384
353
|
if (fileData.startsWith("data:")) {
|
|
385
354
|
const match = fileData.match(/^data:([^;]+);base64,(.+)$/);
|
|
386
355
|
if (match) {
|
|
387
356
|
return { inlineData: { mimeType: match[1], data: match[2] } };
|
|
388
357
|
}
|
|
389
358
|
}
|
|
390
|
-
return {
|
|
359
|
+
return {
|
|
360
|
+
fileData: {
|
|
361
|
+
fileUri: fileData,
|
|
362
|
+
mimeType: this.inferFileMimeType(part.file.filename ?? fileData),
|
|
363
|
+
},
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
inferFileMimeType(source) {
|
|
367
|
+
const pathname = source.split(/[?#]/, 1)[0].toLowerCase();
|
|
368
|
+
const mimeTypes = {
|
|
369
|
+
".pdf": "application/pdf",
|
|
370
|
+
".mp4": "video/mp4",
|
|
371
|
+
".avi": "video/x-msvideo",
|
|
372
|
+
".mov": "video/quicktime",
|
|
373
|
+
".mpeg": "video/mpeg",
|
|
374
|
+
".webm": "video/webm",
|
|
375
|
+
};
|
|
376
|
+
const extension = Object.keys(mimeTypes).find(candidate => pathname.endsWith(candidate));
|
|
377
|
+
return extension ? mimeTypes[extension] : "application/octet-stream";
|
|
391
378
|
}
|
|
392
379
|
convertInputAudio(part) {
|
|
393
380
|
const inputAudio = part.input_audio;
|
|
394
|
-
if (!inputAudio)
|
|
381
|
+
if (!inputAudio) {
|
|
395
382
|
return { inlineData: {} };
|
|
383
|
+
}
|
|
396
384
|
const mimeMap = {
|
|
397
385
|
mp3: "audio/mp3",
|
|
398
386
|
wav: "audio/wav",
|
|
@@ -444,7 +432,10 @@ class ChatCompletionToGeminiConverter {
|
|
|
444
432
|
return { mode: "AUTO" };
|
|
445
433
|
}
|
|
446
434
|
applyResponseFormat(config, format) {
|
|
447
|
-
if (
|
|
435
|
+
if (format.type === "text") {
|
|
436
|
+
config.responseMimeType = "text/plain";
|
|
437
|
+
}
|
|
438
|
+
else if ("json_schema" in format && format.type === "json_schema") {
|
|
448
439
|
config.responseMimeType = "application/json";
|
|
449
440
|
config.responseJsonSchema = format.json_schema.schema;
|
|
450
441
|
}
|
|
@@ -468,6 +459,105 @@ class ChatCompletionToGeminiConverter {
|
|
|
468
459
|
};
|
|
469
460
|
}
|
|
470
461
|
// --- Private: response helpers ---
|
|
462
|
+
convertCandidate(candidate, index) {
|
|
463
|
+
const textParts = [];
|
|
464
|
+
const toolCalls = [];
|
|
465
|
+
const annotations = [];
|
|
466
|
+
for (const part of candidate.content?.parts ?? []) {
|
|
467
|
+
if (part.thought) {
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
if (part.functionCall) {
|
|
471
|
+
const functionCall = part.functionCall;
|
|
472
|
+
toolCalls.push({
|
|
473
|
+
id: functionCall.id ?? functionCall.name ?? `call_${this.generateId()}`,
|
|
474
|
+
type: "function",
|
|
475
|
+
function: {
|
|
476
|
+
name: functionCall.name ?? "",
|
|
477
|
+
arguments: JSON.stringify(functionCall.args ?? {}),
|
|
478
|
+
},
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
else if (part.text != null) {
|
|
482
|
+
textParts.push(part.text);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
this.extractGroundingAnnotations(candidate, annotations);
|
|
486
|
+
return {
|
|
487
|
+
index,
|
|
488
|
+
message: {
|
|
489
|
+
role: "assistant",
|
|
490
|
+
content: textParts.join(""),
|
|
491
|
+
refusal: null,
|
|
492
|
+
...(toolCalls.length > 0 && { tool_calls: toolCalls }),
|
|
493
|
+
...(annotations.length > 0 && { annotations }),
|
|
494
|
+
},
|
|
495
|
+
finish_reason: toolCalls.length > 0 ? "tool_calls" : this.mapFinishReason(candidate.finishReason),
|
|
496
|
+
logprobs: this.convertLogprobs(candidate),
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
getPromptFeedbackRefusal(response) {
|
|
500
|
+
const feedback = response.promptFeedback;
|
|
501
|
+
if (!feedback?.blockReason) {
|
|
502
|
+
return null;
|
|
503
|
+
}
|
|
504
|
+
return feedback.blockReasonMessage ?? feedback.blockReason;
|
|
505
|
+
}
|
|
506
|
+
convertUsage(usage) {
|
|
507
|
+
if (!usage ||
|
|
508
|
+
[
|
|
509
|
+
usage.promptTokenCount,
|
|
510
|
+
usage.candidatesTokenCount,
|
|
511
|
+
usage.totalTokenCount,
|
|
512
|
+
usage.cachedContentTokenCount,
|
|
513
|
+
usage.thoughtsTokenCount,
|
|
514
|
+
usage.toolUsePromptTokenCount,
|
|
515
|
+
usage.promptTokensDetails,
|
|
516
|
+
usage.candidatesTokensDetails,
|
|
517
|
+
usage.cacheTokensDetails,
|
|
518
|
+
usage.toolUsePromptTokensDetails,
|
|
519
|
+
].every(value => value == null)) {
|
|
520
|
+
return undefined;
|
|
521
|
+
}
|
|
522
|
+
const thoughtsTokens = usage.thoughtsTokenCount ?? 0;
|
|
523
|
+
const promptTokens = (usage.promptTokenCount ?? 0) + (usage.toolUsePromptTokenCount ?? 0);
|
|
524
|
+
const completionTokens = (usage.candidatesTokenCount ?? 0) + thoughtsTokens;
|
|
525
|
+
const promptAudioTokens = usage.promptTokensDetails?.find(detail => detail.modality === "AUDIO")?.tokenCount;
|
|
526
|
+
return {
|
|
527
|
+
prompt_tokens: promptTokens,
|
|
528
|
+
completion_tokens: completionTokens,
|
|
529
|
+
total_tokens: usage.totalTokenCount ?? 0,
|
|
530
|
+
prompt_tokens_details: {
|
|
531
|
+
cached_tokens: usage.cachedContentTokenCount ?? 0,
|
|
532
|
+
audio_tokens: promptAudioTokens ?? 0,
|
|
533
|
+
},
|
|
534
|
+
completion_tokens_details: {
|
|
535
|
+
reasoning_tokens: thoughtsTokens,
|
|
536
|
+
},
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
convertLogprobs(candidate) {
|
|
540
|
+
const chosenCandidates = candidate.logprobsResult?.chosenCandidates;
|
|
541
|
+
if (!chosenCandidates || chosenCandidates.length === 0) {
|
|
542
|
+
return null;
|
|
543
|
+
}
|
|
544
|
+
return {
|
|
545
|
+
content: chosenCandidates.map((chosen, index) => ({
|
|
546
|
+
token: chosen.token ?? "",
|
|
547
|
+
bytes: this.toUtf8Bytes(chosen.token),
|
|
548
|
+
logprob: chosen.logProbability ?? -9999,
|
|
549
|
+
top_logprobs: (candidate.logprobsResult?.topCandidates?.[index]?.candidates ?? []).map(topCandidate => ({
|
|
550
|
+
token: topCandidate.token ?? "",
|
|
551
|
+
bytes: this.toUtf8Bytes(topCandidate.token),
|
|
552
|
+
logprob: topCandidate.logProbability ?? -9999,
|
|
553
|
+
})),
|
|
554
|
+
})),
|
|
555
|
+
refusal: null,
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
toUtf8Bytes(value) {
|
|
559
|
+
return value == null ? null : Array.from(new TextEncoder().encode(value));
|
|
560
|
+
}
|
|
471
561
|
extractGroundingAnnotations(candidate, annotations) {
|
|
472
562
|
if (!candidate?.groundingMetadata?.groundingChunks)
|
|
473
563
|
return;
|
|
@@ -493,7 +583,6 @@ class ChatCompletionToGeminiConverter {
|
|
|
493
583
|
case "MAX_TOKENS":
|
|
494
584
|
return "length";
|
|
495
585
|
case "SAFETY":
|
|
496
|
-
case "RECITATION":
|
|
497
586
|
case "BLOCKLIST":
|
|
498
587
|
case "PROHIBITED_CONTENT":
|
|
499
588
|
return "content_filter";
|
|
@@ -510,19 +599,30 @@ class ChatCompletionToGeminiConverter {
|
|
|
510
599
|
id: "",
|
|
511
600
|
model: "",
|
|
512
601
|
started: false,
|
|
513
|
-
|
|
514
|
-
prevText: "",
|
|
515
|
-
prevThought: "",
|
|
516
|
-
seenFunctionCallIds: new Set(),
|
|
602
|
+
choices: new Map(),
|
|
517
603
|
};
|
|
518
604
|
}
|
|
519
|
-
|
|
605
|
+
getChoiceStreamState(index) {
|
|
606
|
+
let choiceState = this.streamState.choices.get(index);
|
|
607
|
+
if (!choiceState) {
|
|
608
|
+
choiceState = {
|
|
609
|
+
toolCallCounter: 0,
|
|
610
|
+
toolCallIndexes: new Map(),
|
|
611
|
+
};
|
|
612
|
+
this.streamState.choices.set(index, choiceState);
|
|
613
|
+
}
|
|
614
|
+
return choiceState;
|
|
615
|
+
}
|
|
616
|
+
makeChunk(choices) {
|
|
520
617
|
return {
|
|
521
618
|
id: this.streamState.id,
|
|
522
619
|
object: "chat.completion.chunk",
|
|
523
620
|
created: Math.floor(Date.now() / 1000),
|
|
524
621
|
model: this.streamState.model,
|
|
525
|
-
choices:
|
|
622
|
+
choices: choices.map(choice => ({
|
|
623
|
+
...choice,
|
|
624
|
+
logprobs: choice.logprobs ?? null,
|
|
625
|
+
})),
|
|
526
626
|
};
|
|
527
627
|
}
|
|
528
628
|
}
|
|
@@ -4,20 +4,27 @@ type RespStreamEvent = OpenAI.Responses.ResponseStreamEvent;
|
|
|
4
4
|
type CCParams = OpenAI.Chat.Completions.ChatCompletionCreateParams;
|
|
5
5
|
export declare class ChatCompletionToResponsesConverter {
|
|
6
6
|
private streamState;
|
|
7
|
+
private legacyFunctionMode;
|
|
7
8
|
constructor();
|
|
8
9
|
convertRequest(params: CCParams): OpenAI.Responses.ResponseCreateParams;
|
|
9
10
|
convertResponse(response: RespResponse): OpenAI.ChatCompletion;
|
|
10
|
-
private
|
|
11
|
+
private convertOutputMessages;
|
|
11
12
|
private convertReasoning;
|
|
12
|
-
private messageStatusToFinishReason;
|
|
13
13
|
convertStream(stream: AsyncIterable<RespStreamEvent>): AsyncIterable<OpenAI.ChatCompletionChunk>;
|
|
14
14
|
convertStreamEvent(event: RespStreamEvent): OpenAI.ChatCompletionChunk | OpenAI.ChatCompletionChunk[] | null;
|
|
15
15
|
private convertMessages;
|
|
16
|
+
private convertAssistantMessage;
|
|
17
|
+
private convertUserContent;
|
|
16
18
|
private convertTools;
|
|
17
19
|
private convertToolChoice;
|
|
20
|
+
private convertLegacyFunctionChoice;
|
|
21
|
+
private convertAllowedTool;
|
|
22
|
+
private convertCustomToolFormat;
|
|
18
23
|
private convertResponseFormat;
|
|
19
24
|
private mapStatus;
|
|
25
|
+
private applyToolCalls;
|
|
20
26
|
private convertUsage;
|
|
27
|
+
private convertTokenLogprob;
|
|
21
28
|
private createStreamState;
|
|
22
29
|
private makeChunk;
|
|
23
30
|
private handleResponseCreated;
|
|
@@ -25,10 +32,12 @@ export declare class ChatCompletionToResponsesConverter {
|
|
|
25
32
|
private handleOutputItemDone;
|
|
26
33
|
private handleTextDelta;
|
|
27
34
|
private handleFunctionCallDelta;
|
|
35
|
+
private handleCustomToolCallDelta;
|
|
28
36
|
private handleRefusalDelta;
|
|
29
37
|
private handleReasoningSummaryDelta;
|
|
30
38
|
private handleCompleted;
|
|
31
39
|
private handleIncomplete;
|
|
32
40
|
private handleFailed;
|
|
41
|
+
private recordStreamAnnotation;
|
|
33
42
|
}
|
|
34
43
|
export {};
|