@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.
@@ -3,11 +3,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ChatCompletionToResponsesConverter = void 0;
4
4
  class ChatCompletionToResponsesConverter {
5
5
  streamState;
6
+ legacyFunctionMode = false;
6
7
  constructor() {
7
8
  this.streamState = this.createStreamState();
8
9
  }
9
10
  // --- Request conversion (CC → Responses, forward) ---
10
11
  convertRequest(params) {
12
+ this.streamState = this.createStreamState();
13
+ this.streamState.includeUsage = params.stream_options?.include_usage ?? false;
14
+ this.streamState.includeLogprobs = params.top_logprobs != null;
15
+ this.legacyFunctionMode =
16
+ params.function_call != null || (params.tools == null && params.functions != null);
11
17
  const result = {
12
18
  model: params.model,
13
19
  input: this.convertMessages(params.messages),
@@ -45,17 +51,41 @@ class ChatCompletionToResponsesConverter {
45
51
  if (params.service_tier != null) {
46
52
  result.service_tier = params.service_tier;
47
53
  }
48
- if (params.tools || params.web_search_options != null) {
49
- result.tools = this.convertTools(params);
54
+ if (params.store != null) {
55
+ result.store = params.store;
56
+ }
57
+ if (params.safety_identifier != null) {
58
+ result.safety_identifier = params.safety_identifier;
59
+ }
60
+ if (params.user != null) {
61
+ result.user = params.user;
62
+ }
63
+ const tools = this.convertTools(params);
64
+ if (tools.length > 0) {
65
+ result.tools = tools;
50
66
  }
51
67
  if (params.tool_choice != null) {
52
68
  result.tool_choice = this.convertToolChoice(params.tool_choice);
53
69
  }
70
+ else if (params.function_call != null) {
71
+ result.tool_choice = this.convertLegacyFunctionChoice(params.function_call);
72
+ }
54
73
  if (params.response_format) {
55
74
  result.text = this.convertResponseFormat(params.response_format);
56
75
  }
57
- if (params.stream) {
58
- result.stream = true;
76
+ if (params.verbosity != null) {
77
+ result.text = {
78
+ ...(result.text ?? {}),
79
+ verbosity: params.verbosity,
80
+ };
81
+ }
82
+ if (params.stream != null) {
83
+ result.stream = params.stream;
84
+ }
85
+ if (params.stream_options?.include_obfuscation != null) {
86
+ result.stream_options = {
87
+ include_obfuscation: params.stream_options.include_obfuscation,
88
+ };
59
89
  }
60
90
  return result;
61
91
  }
@@ -63,11 +93,12 @@ class ChatCompletionToResponsesConverter {
63
93
  convertResponse(response) {
64
94
  const choices = [];
65
95
  const toolCalls = [];
66
- let reasoningItem = null;
96
+ const messages = [];
97
+ const reasoningItems = response.output.filter((item) => item.type === "reasoning");
67
98
  let webSearchCount = 0;
68
99
  for (const item of response.output) {
69
100
  if (item.type === "message") {
70
- choices.push(this.convertOutputMessage(item, reasoningItem, response.incomplete_details));
101
+ messages.push(item);
71
102
  }
72
103
  else if (item.type === "function_call") {
73
104
  const fc = item;
@@ -77,21 +108,13 @@ class ChatCompletionToResponsesConverter {
77
108
  function: { name: fc.name, arguments: fc.arguments },
78
109
  });
79
110
  }
80
- else if (item.type === "reasoning") {
81
- reasoningItem = item;
82
- if (response.output.length === 1) {
83
- choices.push({
84
- index: 0,
85
- finish_reason: null,
86
- message: {
87
- role: "assistant",
88
- content: null,
89
- refusal: null,
90
- ...this.convertReasoning(reasoningItem),
91
- },
92
- logprobs: null,
93
- });
94
- }
111
+ else if (item.type === "custom_tool_call") {
112
+ const custom = item;
113
+ toolCalls.push({
114
+ id: custom.call_id,
115
+ type: "custom",
116
+ custom: { name: custom.name, input: custom.input },
117
+ });
95
118
  }
96
119
  else if (item.type === "web_search_call" &&
97
120
  item.status === "completed" &&
@@ -99,19 +122,46 @@ class ChatCompletionToResponsesConverter {
99
122
  webSearchCount++;
100
123
  }
101
124
  }
102
- if (toolCalls.length > 0) {
125
+ if (messages.length > 0) {
126
+ const choice = this.convertOutputMessages(messages, reasoningItems, response.status, response.incomplete_details);
127
+ this.applyToolCalls(choice, toolCalls, response.status);
128
+ choices.push(choice);
129
+ }
130
+ else if (toolCalls.length > 0) {
131
+ const choice = {
132
+ index: 0,
133
+ finish_reason: this.mapStatus(response.status, response.incomplete_details),
134
+ message: {
135
+ role: "assistant",
136
+ content: null,
137
+ refusal: null,
138
+ },
139
+ logprobs: null,
140
+ };
141
+ this.applyToolCalls(choice, toolCalls, response.status);
142
+ choices.push(choice);
143
+ }
144
+ else if (reasoningItems.length > 0) {
103
145
  choices.push({
104
146
  index: 0,
105
- finish_reason: "tool_calls",
147
+ finish_reason: this.mapStatus(response.status, response.incomplete_details),
106
148
  message: {
107
149
  role: "assistant",
108
150
  content: null,
109
151
  refusal: null,
110
- tool_calls: toolCalls,
152
+ ...this.convertReasoning(reasoningItems),
111
153
  },
112
154
  logprobs: null,
113
155
  });
114
156
  }
157
+ else {
158
+ choices.push({
159
+ index: 0,
160
+ finish_reason: this.mapStatus(response.status, response.incomplete_details),
161
+ message: { role: "assistant", content: null, refusal: null },
162
+ logprobs: null,
163
+ });
164
+ }
115
165
  return {
116
166
  id: response.id,
117
167
  object: "chat.completion",
@@ -119,92 +169,91 @@ class ChatCompletionToResponsesConverter {
119
169
  model: response.model,
120
170
  service_tier: response.service_tier ?? undefined,
121
171
  choices,
122
- usage: this.convertUsage(response.usage, webSearchCount),
172
+ ...(response.usage ? { usage: this.convertUsage(response.usage, webSearchCount) } : {}),
123
173
  };
124
174
  }
125
- convertOutputMessage(message, reasoning, incompleteDetails) {
126
- const content = message.content[0];
127
- let finishReason = this.messageStatusToFinishReason(message.status);
128
- if (finishReason === "length" && incompleteDetails?.reason === "content_filter") {
129
- finishReason = "content_filter";
130
- }
131
- if (content?.type === "refusal") {
132
- return {
133
- index: 0,
134
- finish_reason: finishReason,
135
- logprobs: null,
136
- message: {
137
- role: "assistant",
138
- content: null,
139
- refusal: content.refusal,
140
- ...this.convertReasoning(reasoning),
141
- },
142
- };
175
+ convertOutputMessages(messages, reasoningItems, status, incompleteDetails) {
176
+ const textParts = [];
177
+ const refusalParts = [];
178
+ const annotations = [];
179
+ const logprobs = [];
180
+ let hasLogprobs = false;
181
+ let textOffset = 0;
182
+ for (const message of messages) {
183
+ for (const part of message.content) {
184
+ if (part.type === "refusal") {
185
+ refusalParts.push(part.refusal);
186
+ continue;
187
+ }
188
+ for (const annotation of part.annotations ?? []) {
189
+ if (annotation.type !== "url_citation")
190
+ continue;
191
+ annotations.push({
192
+ type: "url_citation",
193
+ url_citation: {
194
+ title: annotation.title,
195
+ url: annotation.url,
196
+ start_index: textOffset + annotation.start_index,
197
+ end_index: textOffset + annotation.end_index,
198
+ },
199
+ });
200
+ }
201
+ if (part.logprobs != null) {
202
+ hasLogprobs = true;
203
+ logprobs.push(...part.logprobs.map(logprob => this.convertTokenLogprob(logprob)));
204
+ }
205
+ textParts.push(part.text);
206
+ textOffset += part.text.length;
207
+ }
143
208
  }
144
- const textContent = content?.type === "output_text" ? content : null;
145
- const annotations = (textContent?.annotations ?? [])
146
- .filter((a) => a.type === "url_citation")
147
- .map((a) => ({
148
- type: "url_citation",
149
- url_citation: {
150
- title: a.title,
151
- url: a.url,
152
- start_index: a.start_index,
153
- end_index: a.end_index,
154
- },
155
- }));
156
209
  return {
157
210
  index: 0,
158
- finish_reason: finishReason,
211
+ finish_reason: this.mapStatus(status, incompleteDetails),
159
212
  message: {
160
213
  role: "assistant",
161
- content: textContent?.text ?? null,
162
- refusal: null,
163
- ...(annotations.length > 0 ? { annotations } : {}),
164
- ...this.convertReasoning(reasoning),
214
+ content: textParts.length > 0 ? textParts.join("") : null,
215
+ refusal: refusalParts.length > 0 ? refusalParts.join("") : null,
216
+ annotations,
217
+ ...this.convertReasoning(reasoningItems),
165
218
  },
166
- logprobs: textContent?.logprobs
219
+ logprobs: hasLogprobs
167
220
  ? {
168
- content: textContent.logprobs.map((l) => ({
169
- token: l.token,
170
- logprob: l.logprob,
171
- bytes: l.bytes,
172
- top_logprobs: l.top_logprobs,
173
- })),
221
+ content: logprobs,
174
222
  refusal: null,
175
223
  }
176
224
  : null,
177
225
  };
178
226
  }
179
- convertReasoning(reasoning) {
180
- if (!reasoning || !reasoning.summary || reasoning.summary.length === 0)
227
+ convertReasoning(reasoningItems) {
228
+ const summaries = [];
229
+ const details = [];
230
+ for (const reasoning of reasoningItems) {
231
+ if (!reasoning.summary || reasoning.summary.length === 0) {
232
+ continue;
233
+ }
234
+ for (const part of reasoning.summary) {
235
+ summaries.push(part.text);
236
+ details.push({
237
+ index: "0",
238
+ format: "openai-responses-v1",
239
+ type: "reasoning.summary",
240
+ summary: part.text,
241
+ });
242
+ }
243
+ if (reasoning.encrypted_content) {
244
+ details.push({
245
+ id: reasoning.id,
246
+ index: "0",
247
+ format: "openai-responses-v1",
248
+ type: "reasoning.encrypted",
249
+ data: reasoning.encrypted_content,
250
+ });
251
+ }
252
+ }
253
+ if (summaries.length === 0) {
181
254
  return {};
182
- const summary = reasoning.summary[0].text;
183
- const details = [
184
- {
185
- index: "0",
186
- format: "openai-responses-v1",
187
- type: "reasoning.summary",
188
- summary,
189
- },
190
- ];
191
- if (reasoning.encrypted_content) {
192
- details.push({
193
- id: reasoning.id,
194
- index: "0",
195
- format: "openai-responses-v1",
196
- type: "reasoning.encrypted",
197
- data: reasoning.encrypted_content,
198
- });
199
255
  }
200
- return { reasoning: summary, reasoning_details: details };
201
- }
202
- messageStatusToFinishReason(status) {
203
- if (status === "completed")
204
- return "stop";
205
- if (status === "incomplete")
206
- return "length";
207
- return "stop";
256
+ return { reasoning: summaries.join(""), reasoning_details: details };
208
257
  }
209
258
  // --- Stream conversion (Responses → CC, backward) ---
210
259
  async *convertStream(stream) {
@@ -231,6 +280,8 @@ class ChatCompletionToResponsesConverter {
231
280
  return this.handleTextDelta(event);
232
281
  case "response.function_call_arguments.delta":
233
282
  return this.handleFunctionCallDelta(event);
283
+ case "response.custom_tool_call_input.delta":
284
+ return this.handleCustomToolCallDelta(event);
234
285
  case "response.refusal.delta":
235
286
  return this.handleRefusalDelta(event);
236
287
  case "response.reasoning_summary_text.delta":
@@ -247,10 +298,7 @@ class ChatCompletionToResponsesConverter {
247
298
  this.handleOutputItemDone(event);
248
299
  return null;
249
300
  case "response.output_text.annotation.added":
250
- this.streamState.annotations.push({
251
- type: "url_citation",
252
- url_citation: event.annotation,
253
- });
301
+ this.recordStreamAnnotation(event.annotation);
254
302
  return null;
255
303
  default:
256
304
  return null;
@@ -259,7 +307,9 @@ class ChatCompletionToResponsesConverter {
259
307
  // --- Private: request helpers ---
260
308
  convertMessages(messages) {
261
309
  const input = [];
262
- for (const msg of messages) {
310
+ const toolCallTypes = new Map();
311
+ const legacyCallIds = new Map();
312
+ for (const [messageIndex, msg] of messages.entries()) {
263
313
  if (msg.role === "system" || msg.role === "developer") {
264
314
  if (typeof msg.content === "string") {
265
315
  input.push({ role: msg.role, type: "message", content: msg.content });
@@ -280,31 +330,23 @@ class ChatCompletionToResponsesConverter {
280
330
  input.push({
281
331
  role: "user",
282
332
  type: "message",
283
- content: msg.content.map(p => {
284
- if (p.type === "text")
285
- return { type: "input_text", text: p.text };
286
- if (p.type === "image_url")
287
- return {
288
- type: "input_image",
289
- image_url: p.image_url.url,
290
- detail: p.image_url.detail ?? "auto",
291
- };
292
- if (p.type === "file")
293
- return {
294
- type: "input_file",
295
- file_data: p.file.file_data,
296
- file_id: p.file.file_id,
297
- filename: p.file.filename,
298
- };
299
- return { type: "input_text", text: "" };
300
- }),
333
+ content: this.convertUserContent(msg.content),
301
334
  });
302
335
  }
303
336
  }
304
337
  else if (msg.role === "assistant") {
305
- if (msg.tool_calls && msg.tool_calls.length > 0) {
306
- for (const tc of msg.tool_calls) {
338
+ const toolCalls = msg.tool_calls ?? [];
339
+ const hasToolCalls = toolCalls.length > 0;
340
+ const hasLegacyFunctionCall = msg.function_call != null;
341
+ if ((!hasToolCalls && !hasLegacyFunctionCall) ||
342
+ msg.content != null ||
343
+ msg.refusal != null) {
344
+ input.push(this.convertAssistantMessage(msg));
345
+ }
346
+ if (hasToolCalls) {
347
+ for (const tc of toolCalls) {
307
348
  if (tc.type === "function") {
349
+ toolCallTypes.set(tc.id, "function");
308
350
  input.push({
309
351
  type: "function_call",
310
352
  name: tc.function.name,
@@ -312,54 +354,116 @@ class ChatCompletionToResponsesConverter {
312
354
  arguments: tc.function.arguments,
313
355
  });
314
356
  }
357
+ else if (tc.type === "custom") {
358
+ toolCallTypes.set(tc.id, "custom");
359
+ input.push({
360
+ type: "custom_tool_call",
361
+ name: tc.custom.name,
362
+ call_id: tc.id,
363
+ input: tc.custom.input,
364
+ });
365
+ }
315
366
  }
316
367
  }
317
- else {
318
- const content = msg.content;
319
- if (typeof content === "string") {
320
- input.push({
321
- role: "assistant",
322
- type: "message",
323
- content: [{ type: "output_text", text: content }],
324
- });
325
- }
326
- else if (content == null) {
327
- input.push({
328
- role: "assistant",
329
- type: "message",
330
- content: content ?? "",
331
- });
332
- }
333
- else {
334
- input.push({
335
- role: "assistant",
336
- type: "message",
337
- content: content
338
- .filter((p) => p.type === "text")
339
- .map((p) => ({ type: "output_text", text: p.text })),
340
- });
341
- }
342
- }
343
- }
344
- else if (msg.role === "tool") {
345
- if (typeof msg.content === "string") {
368
+ if (msg.function_call != null) {
369
+ const callId = `call_legacy_${messageIndex}`;
370
+ const pendingIds = legacyCallIds.get(msg.function_call.name) ?? [];
371
+ pendingIds.push(callId);
372
+ legacyCallIds.set(msg.function_call.name, pendingIds);
346
373
  input.push({
347
- type: "function_call_output",
348
- call_id: msg.tool_call_id,
349
- output: msg.content,
350
- });
351
- }
352
- else {
353
- input.push({
354
- type: "function_call_output",
355
- call_id: msg.tool_call_id,
356
- output: msg.content.map((p) => ({ type: "input_text", text: p.text })),
374
+ type: "function_call",
375
+ name: msg.function_call.name,
376
+ call_id: callId,
377
+ arguments: msg.function_call.arguments,
357
378
  });
358
379
  }
359
380
  }
381
+ else if (msg.role === "tool") {
382
+ const output = typeof msg.content === "string"
383
+ ? msg.content
384
+ : msg.content.map(p => ({ type: "input_text", text: p.text }));
385
+ input.push({
386
+ type: toolCallTypes.get(msg.tool_call_id) === "custom"
387
+ ? "custom_tool_call_output"
388
+ : "function_call_output",
389
+ call_id: msg.tool_call_id,
390
+ output,
391
+ });
392
+ }
393
+ else if (msg.role === "function") {
394
+ const pendingIds = legacyCallIds.get(msg.name) ?? [];
395
+ const callId = pendingIds.shift() ?? `call_legacy_${messageIndex}`;
396
+ input.push({
397
+ type: "function_call_output",
398
+ call_id: callId,
399
+ output: msg.content ?? "",
400
+ });
401
+ }
360
402
  }
361
403
  return input;
362
404
  }
405
+ convertAssistantMessage(message) {
406
+ const content = message.content;
407
+ if (typeof content === "string") {
408
+ return {
409
+ role: "assistant",
410
+ type: "message",
411
+ content,
412
+ };
413
+ }
414
+ if (Array.isArray(content)) {
415
+ const parts = content.map(part => part.type === "refusal"
416
+ ? { type: "refusal", refusal: part.refusal }
417
+ : { type: "output_text", text: part.text });
418
+ if (message.refusal != null && !content.some(part => part.type === "refusal")) {
419
+ parts.push({ type: "refusal", refusal: message.refusal });
420
+ }
421
+ return {
422
+ role: "assistant",
423
+ type: "message",
424
+ // The Responses API requires assistant history blocks to use output_text/refusal,
425
+ // while the current SDK types only expose ResponseInputContent for EasyInputMessage.
426
+ content: parts,
427
+ };
428
+ }
429
+ if (message.refusal != null) {
430
+ return {
431
+ role: "assistant",
432
+ type: "message",
433
+ // The Responses API models refusal as its own assistant content part.
434
+ content: [{ type: "refusal", refusal: message.refusal }],
435
+ };
436
+ }
437
+ return {
438
+ role: "assistant",
439
+ type: "message",
440
+ content: "",
441
+ };
442
+ }
443
+ convertUserContent(parts) {
444
+ const content = [];
445
+ for (const part of parts) {
446
+ if (part.type === "text") {
447
+ content.push({ type: "input_text", text: part.text });
448
+ }
449
+ else if (part.type === "image_url") {
450
+ content.push({
451
+ type: "input_image",
452
+ image_url: part.image_url.url,
453
+ detail: part.image_url.detail ?? "auto",
454
+ });
455
+ }
456
+ else if (part.type === "file") {
457
+ content.push({
458
+ type: "input_file",
459
+ file_data: part.file.file_data,
460
+ file_id: part.file.file_id,
461
+ filename: part.file.filename,
462
+ });
463
+ }
464
+ }
465
+ return content;
466
+ }
363
467
  convertTools(params) {
364
468
  const tools = [];
365
469
  if (params.tools) {
@@ -373,10 +477,43 @@ class ChatCompletionToResponsesConverter {
373
477
  parameters: t.function.parameters ?? null,
374
478
  });
375
479
  }
480
+ else if (t.type === "custom") {
481
+ tools.push({
482
+ type: "custom",
483
+ name: t.custom.name,
484
+ description: t.custom.description,
485
+ ...(t.custom.format ? { format: this.convertCustomToolFormat(t.custom.format) } : {}),
486
+ });
487
+ }
488
+ }
489
+ }
490
+ else if (params.functions) {
491
+ for (const fn of params.functions) {
492
+ tools.push({
493
+ type: "function",
494
+ name: fn.name,
495
+ description: fn.description,
496
+ strict: null,
497
+ parameters: fn.parameters ?? null,
498
+ });
376
499
  }
377
500
  }
378
501
  if (params.web_search_options != null) {
379
- tools.push({ type: "web_search" });
502
+ const options = params.web_search_options;
503
+ tools.push({
504
+ type: "web_search",
505
+ ...(options.search_context_size != null
506
+ ? { search_context_size: options.search_context_size }
507
+ : {}),
508
+ ...(options.user_location != null
509
+ ? {
510
+ user_location: {
511
+ type: "approximate",
512
+ ...options.user_location.approximate,
513
+ },
514
+ }
515
+ : {}),
516
+ });
380
517
  }
381
518
  return tools;
382
519
  }
@@ -391,9 +528,50 @@ class ChatCompletionToResponsesConverter {
391
528
  if (c.type === "function" && c.function?.name) {
392
529
  return { type: "function", name: c.function.name };
393
530
  }
531
+ if (c.type === "custom" && c.custom?.name) {
532
+ return { type: "custom", name: c.custom.name };
533
+ }
534
+ if (c.type === "allowed_tools") {
535
+ return {
536
+ type: "allowed_tools",
537
+ mode: c.allowed_tools.mode,
538
+ tools: c.allowed_tools.tools.map(tool => this.convertAllowedTool(tool)),
539
+ };
540
+ }
394
541
  }
395
542
  return "auto";
396
543
  }
544
+ convertLegacyFunctionChoice(choice) {
545
+ if (choice === "auto" || choice === "none") {
546
+ return choice;
547
+ }
548
+ return { type: "function", name: choice.name };
549
+ }
550
+ convertAllowedTool(tool) {
551
+ if (tool.type === "function" && tool.function && typeof tool.function === "object") {
552
+ const fn = tool.function;
553
+ if (typeof fn.name === "string") {
554
+ return { type: "function", name: fn.name };
555
+ }
556
+ }
557
+ if (tool.type === "custom" && tool.custom && typeof tool.custom === "object") {
558
+ const custom = tool.custom;
559
+ if (typeof custom.name === "string") {
560
+ return { type: "custom", name: custom.name };
561
+ }
562
+ }
563
+ return tool;
564
+ }
565
+ convertCustomToolFormat(format) {
566
+ if (format?.type === "grammar") {
567
+ return {
568
+ type: "grammar",
569
+ definition: format.grammar.definition,
570
+ syntax: format.grammar.syntax,
571
+ };
572
+ }
573
+ return { type: "text" };
574
+ }
397
575
  convertResponseFormat(format) {
398
576
  if (!format)
399
577
  return undefined;
@@ -406,6 +584,10 @@ class ChatCompletionToResponsesConverter {
406
584
  type: "json_schema",
407
585
  name: format.json_schema.name,
408
586
  schema: format.json_schema.schema ?? {},
587
+ ...(format.json_schema.description != null
588
+ ? { description: format.json_schema.description }
589
+ : {}),
590
+ ...(format.json_schema.strict != null ? { strict: format.json_schema.strict } : {}),
409
591
  },
410
592
  };
411
593
  }
@@ -426,6 +608,22 @@ class ChatCompletionToResponsesConverter {
426
608
  return "stop";
427
609
  }
428
610
  }
611
+ applyToolCalls(choice, toolCalls, responseStatus) {
612
+ if (toolCalls.length === 0)
613
+ return;
614
+ const firstCall = toolCalls[0];
615
+ if (this.legacyFunctionMode && firstCall.type === "function") {
616
+ choice.message.function_call = { ...firstCall.function };
617
+ if (responseStatus === "completed") {
618
+ choice.finish_reason = "function_call";
619
+ }
620
+ return;
621
+ }
622
+ choice.message.tool_calls = toolCalls;
623
+ if (responseStatus === "completed") {
624
+ choice.finish_reason = "tool_calls";
625
+ }
626
+ }
429
627
  convertUsage(usage, webSearchCount = 0) {
430
628
  return {
431
629
  prompt_tokens: usage.input_tokens,
@@ -440,6 +638,20 @@ class ChatCompletionToResponsesConverter {
440
638
  },
441
639
  };
442
640
  }
641
+ convertTokenLogprob(logprob) {
642
+ return {
643
+ token: logprob.token,
644
+ logprob: logprob.logprob,
645
+ bytes: logprob.bytes ?? null,
646
+ top_logprobs: (logprob.top_logprobs ?? [])
647
+ .filter((top) => typeof top.token === "string" && typeof top.logprob === "number")
648
+ .map(top => ({
649
+ token: top.token,
650
+ logprob: top.logprob,
651
+ bytes: top.bytes ?? null,
652
+ })),
653
+ };
654
+ }
443
655
  // --- Private: stream helpers ---
444
656
  createStreamState() {
445
657
  return {
@@ -449,21 +661,36 @@ class ChatCompletionToResponsesConverter {
449
661
  serviceTier: null,
450
662
  toolCallCounter: -1,
451
663
  hasToolCall: false,
664
+ toolCallIndexes: new Map(),
452
665
  webSearchCount: 0,
453
666
  annotations: [],
454
667
  includeUsage: false,
668
+ includeLogprobs: false,
455
669
  };
456
670
  }
457
- makeChunk(delta, finish_reason = null, usage) {
458
- return {
671
+ makeChunk(delta, finish_reason = null, usage, logprobs) {
672
+ const chunk = {
459
673
  id: this.streamState.id,
460
674
  object: "chat.completion.chunk",
461
675
  created: this.streamState.created,
462
676
  model: this.streamState.model,
463
677
  service_tier: this.streamState.serviceTier,
464
- choices: [{ index: 0, delta, finish_reason }],
465
- ...(usage ? { usage } : {}),
678
+ choices: [
679
+ {
680
+ index: 0,
681
+ delta,
682
+ finish_reason,
683
+ logprobs: logprobs ?? null,
684
+ },
685
+ ],
466
686
  };
687
+ if (this.streamState.includeUsage) {
688
+ chunk.usage = usage ?? null;
689
+ }
690
+ else if (usage != null) {
691
+ chunk.usage = usage;
692
+ }
693
+ return chunk;
467
694
  }
468
695
  handleResponseCreated(event) {
469
696
  const resp = event.response;
@@ -477,19 +704,46 @@ class ChatCompletionToResponsesConverter {
477
704
  }
478
705
  handleOutputItemAdded(event) {
479
706
  const item = event.item;
480
- if (item.type === "function_call") {
707
+ if (item.type === "function_call" || item.type === "custom_tool_call") {
481
708
  this.streamState.hasToolCall = true;
482
709
  this.streamState.toolCallCounter++;
483
- const fc = item;
710
+ const index = this.streamState.toolCallCounter;
711
+ this.streamState.toolCallIndexes.set(item.call_id, index);
712
+ if (item.id) {
713
+ this.streamState.toolCallIndexes.set(item.id, index);
714
+ }
715
+ if (item.type === "function_call") {
716
+ const fc = item;
717
+ if (this.legacyFunctionMode) {
718
+ return this.makeChunk({
719
+ role: "assistant",
720
+ content: null,
721
+ function_call: { name: fc.name, arguments: "" },
722
+ });
723
+ }
724
+ return this.makeChunk({
725
+ role: "assistant",
726
+ content: null,
727
+ tool_calls: [
728
+ {
729
+ index,
730
+ id: fc.call_id,
731
+ type: "function",
732
+ function: { name: fc.name, arguments: "" },
733
+ },
734
+ ],
735
+ });
736
+ }
737
+ const custom = item;
484
738
  return this.makeChunk({
485
739
  role: "assistant",
486
740
  content: null,
487
741
  tool_calls: [
488
742
  {
489
- index: this.streamState.toolCallCounter,
490
- id: fc.call_id,
491
- type: "function",
492
- function: { name: fc.name, arguments: "" },
743
+ index,
744
+ id: custom.call_id,
745
+ type: "custom",
746
+ custom: { name: custom.name, input: "" },
493
747
  },
494
748
  ],
495
749
  });
@@ -505,21 +759,49 @@ class ChatCompletionToResponsesConverter {
505
759
  }
506
760
  }
507
761
  handleTextDelta(event) {
508
- return this.makeChunk({ role: "assistant", content: event.delta });
762
+ const logprobs = this.streamState.includeLogprobs
763
+ ? {
764
+ content: event.logprobs.map(logprob => this.convertTokenLogprob(logprob)),
765
+ refusal: null,
766
+ }
767
+ : undefined;
768
+ return this.makeChunk({ role: "assistant", content: event.delta }, null, undefined, logprobs);
509
769
  }
510
770
  handleFunctionCallDelta(event) {
771
+ const index = this.streamState.toolCallIndexes.get(event.item_id) ?? this.streamState.toolCallCounter;
772
+ if (this.legacyFunctionMode) {
773
+ return this.makeChunk({
774
+ role: "assistant",
775
+ content: "",
776
+ function_call: { arguments: event.delta },
777
+ });
778
+ }
511
779
  return this.makeChunk({
512
780
  role: "assistant",
513
781
  content: "",
514
782
  tool_calls: [
515
783
  {
516
- index: this.streamState.toolCallCounter,
784
+ index,
517
785
  type: "function",
518
786
  function: { arguments: event.delta },
519
787
  },
520
788
  ],
521
789
  });
522
790
  }
791
+ handleCustomToolCallDelta(event) {
792
+ const index = this.streamState.toolCallIndexes.get(event.item_id) ?? this.streamState.toolCallCounter;
793
+ return this.makeChunk({
794
+ role: "assistant",
795
+ content: "",
796
+ tool_calls: [
797
+ {
798
+ index,
799
+ type: "custom",
800
+ custom: { input: event.delta },
801
+ },
802
+ ],
803
+ });
804
+ }
523
805
  handleRefusalDelta(event) {
524
806
  return this.makeChunk({ refusal: event.delta });
525
807
  }
@@ -544,7 +826,9 @@ class ChatCompletionToResponsesConverter {
544
826
  const state = this.streamState;
545
827
  const resp = event.response;
546
828
  const finishReason = state.hasToolCall
547
- ? "tool_calls"
829
+ ? this.legacyFunctionMode
830
+ ? "function_call"
831
+ : "tool_calls"
548
832
  : this.mapStatus(resp.status, resp.incomplete_details);
549
833
  const delta = { content: null };
550
834
  if (state.annotations.length > 0) {
@@ -569,7 +853,7 @@ class ChatCompletionToResponsesConverter {
569
853
  handleIncomplete(event) {
570
854
  const state = this.streamState;
571
855
  const resp = event.response;
572
- const finishChunk = this.makeChunk({}, "length");
856
+ const finishChunk = this.makeChunk({}, this.mapStatus(resp.status, resp.incomplete_details));
573
857
  const chunks = [finishChunk];
574
858
  if (state.includeUsage && resp.usage) {
575
859
  const usageChunk = {
@@ -588,5 +872,30 @@ class ChatCompletionToResponsesConverter {
588
872
  handleFailed() {
589
873
  return this.makeChunk({ content: "" }, "stop");
590
874
  }
875
+ recordStreamAnnotation(annotation) {
876
+ if (annotation == null ||
877
+ typeof annotation !== "object" ||
878
+ !("type" in annotation) ||
879
+ annotation.type !== "url_citation" ||
880
+ !("title" in annotation) ||
881
+ typeof annotation.title !== "string" ||
882
+ !("url" in annotation) ||
883
+ typeof annotation.url !== "string" ||
884
+ !("start_index" in annotation) ||
885
+ typeof annotation.start_index !== "number" ||
886
+ !("end_index" in annotation) ||
887
+ typeof annotation.end_index !== "number") {
888
+ return;
889
+ }
890
+ this.streamState.annotations.push({
891
+ type: "url_citation",
892
+ url_citation: {
893
+ title: annotation.title,
894
+ url: annotation.url,
895
+ start_index: annotation.start_index,
896
+ end_index: annotation.end_index,
897
+ },
898
+ });
899
+ }
591
900
  }
592
901
  exports.ChatCompletionToResponsesConverter = ChatCompletionToResponsesConverter;