@lenylvt/pi-ai 0.64.0
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 +203 -0
- package/dist/api-registry.d.ts +20 -0
- package/dist/api-registry.d.ts.map +1 -0
- package/dist/api-registry.js +44 -0
- package/dist/api-registry.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +119 -0
- package/dist/cli.js.map +1 -0
- package/dist/env-api-keys.d.ts +7 -0
- package/dist/env-api-keys.d.ts.map +1 -0
- package/dist/env-api-keys.js +13 -0
- package/dist/env-api-keys.js.map +1 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/models.d.ts +24 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.generated.d.ts +2332 -0
- package/dist/models.generated.d.ts.map +1 -0
- package/dist/models.generated.js +2186 -0
- package/dist/models.generated.js.map +1 -0
- package/dist/models.js +60 -0
- package/dist/models.js.map +1 -0
- package/dist/oauth.d.ts +2 -0
- package/dist/oauth.d.ts.map +1 -0
- package/dist/oauth.js +2 -0
- package/dist/oauth.js.map +1 -0
- package/dist/providers/anthropic.d.ts +40 -0
- package/dist/providers/anthropic.d.ts.map +1 -0
- package/dist/providers/anthropic.js +749 -0
- package/dist/providers/anthropic.js.map +1 -0
- package/dist/providers/faux.d.ts +56 -0
- package/dist/providers/faux.d.ts.map +1 -0
- package/dist/providers/faux.js +367 -0
- package/dist/providers/faux.js.map +1 -0
- package/dist/providers/github-copilot-headers.d.ts +8 -0
- package/dist/providers/github-copilot-headers.d.ts.map +1 -0
- package/dist/providers/github-copilot-headers.js +29 -0
- package/dist/providers/github-copilot-headers.js.map +1 -0
- package/dist/providers/openai-codex-responses.d.ts +9 -0
- package/dist/providers/openai-codex-responses.d.ts.map +1 -0
- package/dist/providers/openai-codex-responses.js +741 -0
- package/dist/providers/openai-codex-responses.js.map +1 -0
- package/dist/providers/openai-completions.d.ts +15 -0
- package/dist/providers/openai-completions.d.ts.map +1 -0
- package/dist/providers/openai-completions.js +687 -0
- package/dist/providers/openai-completions.js.map +1 -0
- package/dist/providers/openai-responses-shared.d.ts +17 -0
- package/dist/providers/openai-responses-shared.d.ts.map +1 -0
- package/dist/providers/openai-responses-shared.js +458 -0
- package/dist/providers/openai-responses-shared.js.map +1 -0
- package/dist/providers/openai-responses.d.ts +13 -0
- package/dist/providers/openai-responses.d.ts.map +1 -0
- package/dist/providers/openai-responses.js +190 -0
- package/dist/providers/openai-responses.js.map +1 -0
- package/dist/providers/register-builtins.d.ts +16 -0
- package/dist/providers/register-builtins.d.ts.map +1 -0
- package/dist/providers/register-builtins.js +140 -0
- package/dist/providers/register-builtins.js.map +1 -0
- package/dist/providers/simple-options.d.ts +8 -0
- package/dist/providers/simple-options.d.ts.map +1 -0
- package/dist/providers/simple-options.js +35 -0
- package/dist/providers/simple-options.js.map +1 -0
- package/dist/providers/transform-messages.d.ts +8 -0
- package/dist/providers/transform-messages.d.ts.map +1 -0
- package/dist/providers/transform-messages.js +155 -0
- package/dist/providers/transform-messages.js.map +1 -0
- package/dist/stream.d.ts +8 -0
- package/dist/stream.d.ts.map +1 -0
- package/dist/stream.js +27 -0
- package/dist/stream.js.map +1 -0
- package/dist/types.d.ts +283 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/event-stream.d.ts +21 -0
- package/dist/utils/event-stream.d.ts.map +1 -0
- package/dist/utils/event-stream.js +81 -0
- package/dist/utils/event-stream.js.map +1 -0
- package/dist/utils/hash.d.ts +3 -0
- package/dist/utils/hash.d.ts.map +1 -0
- package/dist/utils/hash.js +14 -0
- package/dist/utils/hash.js.map +1 -0
- package/dist/utils/json-parse.d.ts +9 -0
- package/dist/utils/json-parse.d.ts.map +1 -0
- package/dist/utils/json-parse.js +29 -0
- package/dist/utils/json-parse.js.map +1 -0
- package/dist/utils/oauth/anthropic.d.ts +25 -0
- package/dist/utils/oauth/anthropic.d.ts.map +1 -0
- package/dist/utils/oauth/anthropic.js +335 -0
- package/dist/utils/oauth/anthropic.js.map +1 -0
- package/dist/utils/oauth/github-copilot.d.ts +30 -0
- package/dist/utils/oauth/github-copilot.d.ts.map +1 -0
- package/dist/utils/oauth/github-copilot.js +292 -0
- package/dist/utils/oauth/github-copilot.js.map +1 -0
- package/dist/utils/oauth/index.d.ts +36 -0
- package/dist/utils/oauth/index.d.ts.map +1 -0
- package/dist/utils/oauth/index.js +92 -0
- package/dist/utils/oauth/index.js.map +1 -0
- package/dist/utils/oauth/oauth-page.d.ts +3 -0
- package/dist/utils/oauth/oauth-page.d.ts.map +1 -0
- package/dist/utils/oauth/oauth-page.js +105 -0
- package/dist/utils/oauth/oauth-page.js.map +1 -0
- package/dist/utils/oauth/openai-codex.d.ts +34 -0
- package/dist/utils/oauth/openai-codex.d.ts.map +1 -0
- package/dist/utils/oauth/openai-codex.js +373 -0
- package/dist/utils/oauth/openai-codex.js.map +1 -0
- package/dist/utils/oauth/pkce.d.ts +13 -0
- package/dist/utils/oauth/pkce.d.ts.map +1 -0
- package/dist/utils/oauth/pkce.js +31 -0
- package/dist/utils/oauth/pkce.js.map +1 -0
- package/dist/utils/oauth/types.d.ts +47 -0
- package/dist/utils/oauth/types.d.ts.map +1 -0
- package/dist/utils/oauth/types.js +2 -0
- package/dist/utils/oauth/types.js.map +1 -0
- package/dist/utils/overflow.d.ts +53 -0
- package/dist/utils/overflow.d.ts.map +1 -0
- package/dist/utils/overflow.js +119 -0
- package/dist/utils/overflow.js.map +1 -0
- package/dist/utils/sanitize-unicode.d.ts +22 -0
- package/dist/utils/sanitize-unicode.d.ts.map +1 -0
- package/dist/utils/sanitize-unicode.js +26 -0
- package/dist/utils/sanitize-unicode.js.map +1 -0
- package/dist/utils/typebox-helpers.d.ts +17 -0
- package/dist/utils/typebox-helpers.d.ts.map +1 -0
- package/dist/utils/typebox-helpers.js +21 -0
- package/dist/utils/typebox-helpers.js.map +1 -0
- package/dist/utils/validation.d.ts +18 -0
- package/dist/utils/validation.d.ts.map +1 -0
- package/dist/utils/validation.js +80 -0
- package/dist/utils/validation.js.map +1 -0
- package/package.json +89 -0
- package/src/api-registry.ts +98 -0
- package/src/cli.ts +136 -0
- package/src/env-api-keys.ts +22 -0
- package/src/index.ts +29 -0
- package/src/models.generated.ts +2188 -0
- package/src/models.ts +82 -0
- package/src/oauth.ts +1 -0
- package/src/providers/anthropic.ts +905 -0
- package/src/providers/faux.ts +498 -0
- package/src/providers/github-copilot-headers.ts +37 -0
- package/src/providers/openai-codex-responses.ts +929 -0
- package/src/providers/openai-completions.ts +811 -0
- package/src/providers/openai-responses-shared.ts +513 -0
- package/src/providers/openai-responses.ts +251 -0
- package/src/providers/register-builtins.ts +232 -0
- package/src/providers/simple-options.ts +46 -0
- package/src/providers/transform-messages.ts +172 -0
- package/src/stream.ts +59 -0
- package/src/types.ts +294 -0
- package/src/utils/event-stream.ts +87 -0
- package/src/utils/hash.ts +13 -0
- package/src/utils/json-parse.ts +28 -0
- package/src/utils/oauth/anthropic.ts +402 -0
- package/src/utils/oauth/github-copilot.ts +396 -0
- package/src/utils/oauth/index.ts +123 -0
- package/src/utils/oauth/oauth-page.ts +109 -0
- package/src/utils/oauth/openai-codex.ts +450 -0
- package/src/utils/oauth/pkce.ts +34 -0
- package/src/utils/oauth/types.ts +59 -0
- package/src/utils/overflow.ts +125 -0
- package/src/utils/sanitize-unicode.ts +25 -0
- package/src/utils/typebox-helpers.ts +24 -0
- package/src/utils/validation.ts +93 -0
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
import { calculateCost } from "../models.js";
|
|
2
|
+
import { shortHash } from "../utils/hash.js";
|
|
3
|
+
import { parseStreamingJson } from "../utils/json-parse.js";
|
|
4
|
+
import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
|
|
5
|
+
import { transformMessages } from "./transform-messages.js";
|
|
6
|
+
// =============================================================================
|
|
7
|
+
// Utilities
|
|
8
|
+
// =============================================================================
|
|
9
|
+
function encodeTextSignatureV1(id, phase) {
|
|
10
|
+
const payload = { v: 1, id };
|
|
11
|
+
if (phase)
|
|
12
|
+
payload.phase = phase;
|
|
13
|
+
return JSON.stringify(payload);
|
|
14
|
+
}
|
|
15
|
+
function parseTextSignature(signature) {
|
|
16
|
+
if (!signature)
|
|
17
|
+
return undefined;
|
|
18
|
+
if (signature.startsWith("{")) {
|
|
19
|
+
try {
|
|
20
|
+
const parsed = JSON.parse(signature);
|
|
21
|
+
if (parsed.v === 1 && typeof parsed.id === "string") {
|
|
22
|
+
if (parsed.phase === "commentary" || parsed.phase === "final_answer") {
|
|
23
|
+
return { id: parsed.id, phase: parsed.phase };
|
|
24
|
+
}
|
|
25
|
+
return { id: parsed.id };
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
// Fall through to legacy plain-string handling.
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return { id: signature };
|
|
33
|
+
}
|
|
34
|
+
// =============================================================================
|
|
35
|
+
// Message conversion
|
|
36
|
+
// =============================================================================
|
|
37
|
+
export function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
|
|
38
|
+
const messages = [];
|
|
39
|
+
const normalizeIdPart = (part) => {
|
|
40
|
+
const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
41
|
+
const normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;
|
|
42
|
+
return normalized.replace(/_+$/, "");
|
|
43
|
+
};
|
|
44
|
+
const buildForeignResponsesItemId = (itemId) => {
|
|
45
|
+
const normalized = `fc_${shortHash(itemId)}`;
|
|
46
|
+
return normalized.length > 64 ? normalized.slice(0, 64) : normalized;
|
|
47
|
+
};
|
|
48
|
+
const normalizeToolCallId = (id, _targetModel, source) => {
|
|
49
|
+
if (!allowedToolCallProviders.has(model.provider))
|
|
50
|
+
return normalizeIdPart(id);
|
|
51
|
+
if (!id.includes("|"))
|
|
52
|
+
return normalizeIdPart(id);
|
|
53
|
+
const [callId, itemId] = id.split("|");
|
|
54
|
+
const normalizedCallId = normalizeIdPart(callId);
|
|
55
|
+
const isForeignToolCall = source.provider !== model.provider || source.api !== model.api;
|
|
56
|
+
let normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);
|
|
57
|
+
// OpenAI Responses API requires item id to start with "fc"
|
|
58
|
+
if (!normalizedItemId.startsWith("fc_")) {
|
|
59
|
+
normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);
|
|
60
|
+
}
|
|
61
|
+
return `${normalizedCallId}|${normalizedItemId}`;
|
|
62
|
+
};
|
|
63
|
+
const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);
|
|
64
|
+
const includeSystemPrompt = options?.includeSystemPrompt ?? true;
|
|
65
|
+
if (includeSystemPrompt && context.systemPrompt) {
|
|
66
|
+
const role = model.reasoning ? "developer" : "system";
|
|
67
|
+
messages.push({
|
|
68
|
+
role,
|
|
69
|
+
content: sanitizeSurrogates(context.systemPrompt),
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
let msgIndex = 0;
|
|
73
|
+
for (const msg of transformedMessages) {
|
|
74
|
+
if (msg.role === "user") {
|
|
75
|
+
if (typeof msg.content === "string") {
|
|
76
|
+
messages.push({
|
|
77
|
+
role: "user",
|
|
78
|
+
content: [{ type: "input_text", text: sanitizeSurrogates(msg.content) }],
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
const content = msg.content.map((item) => {
|
|
83
|
+
if (item.type === "text") {
|
|
84
|
+
return {
|
|
85
|
+
type: "input_text",
|
|
86
|
+
text: sanitizeSurrogates(item.text),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
type: "input_image",
|
|
91
|
+
detail: "auto",
|
|
92
|
+
image_url: `data:${item.mimeType};base64,${item.data}`,
|
|
93
|
+
};
|
|
94
|
+
});
|
|
95
|
+
const filteredContent = !model.input.includes("image")
|
|
96
|
+
? content.filter((c) => c.type !== "input_image")
|
|
97
|
+
: content;
|
|
98
|
+
if (filteredContent.length === 0)
|
|
99
|
+
continue;
|
|
100
|
+
messages.push({
|
|
101
|
+
role: "user",
|
|
102
|
+
content: filteredContent,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
else if (msg.role === "assistant") {
|
|
107
|
+
const output = [];
|
|
108
|
+
const assistantMsg = msg;
|
|
109
|
+
const isDifferentModel = assistantMsg.model !== model.id &&
|
|
110
|
+
assistantMsg.provider === model.provider &&
|
|
111
|
+
assistantMsg.api === model.api;
|
|
112
|
+
for (const block of msg.content) {
|
|
113
|
+
if (block.type === "thinking") {
|
|
114
|
+
if (block.thinkingSignature) {
|
|
115
|
+
const reasoningItem = JSON.parse(block.thinkingSignature);
|
|
116
|
+
output.push(reasoningItem);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
else if (block.type === "text") {
|
|
120
|
+
const textBlock = block;
|
|
121
|
+
const parsedSignature = parseTextSignature(textBlock.textSignature);
|
|
122
|
+
// OpenAI requires id to be max 64 characters
|
|
123
|
+
let msgId = parsedSignature?.id;
|
|
124
|
+
if (!msgId) {
|
|
125
|
+
msgId = `msg_${msgIndex}`;
|
|
126
|
+
}
|
|
127
|
+
else if (msgId.length > 64) {
|
|
128
|
+
msgId = `msg_${shortHash(msgId)}`;
|
|
129
|
+
}
|
|
130
|
+
output.push({
|
|
131
|
+
type: "message",
|
|
132
|
+
role: "assistant",
|
|
133
|
+
content: [{ type: "output_text", text: sanitizeSurrogates(textBlock.text), annotations: [] }],
|
|
134
|
+
status: "completed",
|
|
135
|
+
id: msgId,
|
|
136
|
+
phase: parsedSignature?.phase,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
else if (block.type === "toolCall") {
|
|
140
|
+
const toolCall = block;
|
|
141
|
+
const [callId, itemIdRaw] = toolCall.id.split("|");
|
|
142
|
+
let itemId = itemIdRaw;
|
|
143
|
+
// For different-model messages, set id to undefined to avoid pairing validation.
|
|
144
|
+
// OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.
|
|
145
|
+
// By omitting the id, we avoid triggering that validation (like cross-provider does).
|
|
146
|
+
if (isDifferentModel && itemId?.startsWith("fc_")) {
|
|
147
|
+
itemId = undefined;
|
|
148
|
+
}
|
|
149
|
+
output.push({
|
|
150
|
+
type: "function_call",
|
|
151
|
+
id: itemId,
|
|
152
|
+
call_id: callId,
|
|
153
|
+
name: toolCall.name,
|
|
154
|
+
arguments: JSON.stringify(toolCall.arguments),
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (output.length === 0)
|
|
159
|
+
continue;
|
|
160
|
+
messages.push(...output);
|
|
161
|
+
}
|
|
162
|
+
else if (msg.role === "toolResult") {
|
|
163
|
+
const textResult = msg.content
|
|
164
|
+
.filter((c) => c.type === "text")
|
|
165
|
+
.map((c) => c.text)
|
|
166
|
+
.join("\n");
|
|
167
|
+
const hasImages = msg.content.some((c) => c.type === "image");
|
|
168
|
+
const hasText = textResult.length > 0;
|
|
169
|
+
const [callId] = msg.toolCallId.split("|");
|
|
170
|
+
let output;
|
|
171
|
+
if (hasImages && model.input.includes("image")) {
|
|
172
|
+
const contentParts = [];
|
|
173
|
+
if (hasText) {
|
|
174
|
+
contentParts.push({
|
|
175
|
+
type: "input_text",
|
|
176
|
+
text: sanitizeSurrogates(textResult),
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
for (const block of msg.content) {
|
|
180
|
+
if (block.type === "image") {
|
|
181
|
+
contentParts.push({
|
|
182
|
+
type: "input_image",
|
|
183
|
+
detail: "auto",
|
|
184
|
+
image_url: `data:${block.mimeType};base64,${block.data}`,
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
output = contentParts;
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
output = sanitizeSurrogates(hasText ? textResult : "(see attached image)");
|
|
192
|
+
}
|
|
193
|
+
messages.push({
|
|
194
|
+
type: "function_call_output",
|
|
195
|
+
call_id: callId,
|
|
196
|
+
output,
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
msgIndex++;
|
|
200
|
+
}
|
|
201
|
+
return messages;
|
|
202
|
+
}
|
|
203
|
+
// =============================================================================
|
|
204
|
+
// Tool conversion
|
|
205
|
+
// =============================================================================
|
|
206
|
+
export function convertResponsesTools(tools, options) {
|
|
207
|
+
const strict = options?.strict === undefined ? false : options.strict;
|
|
208
|
+
return tools.map((tool) => ({
|
|
209
|
+
type: "function",
|
|
210
|
+
name: tool.name,
|
|
211
|
+
description: tool.description,
|
|
212
|
+
parameters: tool.parameters, // TypeBox already generates JSON Schema
|
|
213
|
+
strict,
|
|
214
|
+
}));
|
|
215
|
+
}
|
|
216
|
+
// =============================================================================
|
|
217
|
+
// Stream processing
|
|
218
|
+
// =============================================================================
|
|
219
|
+
export async function processResponsesStream(openaiStream, output, stream, model, options) {
|
|
220
|
+
let currentItem = null;
|
|
221
|
+
let currentBlock = null;
|
|
222
|
+
const blocks = output.content;
|
|
223
|
+
const blockIndex = () => blocks.length - 1;
|
|
224
|
+
for await (const event of openaiStream) {
|
|
225
|
+
if (event.type === "response.created") {
|
|
226
|
+
output.responseId = event.response.id;
|
|
227
|
+
}
|
|
228
|
+
else if (event.type === "response.output_item.added") {
|
|
229
|
+
const item = event.item;
|
|
230
|
+
if (item.type === "reasoning") {
|
|
231
|
+
currentItem = item;
|
|
232
|
+
currentBlock = { type: "thinking", thinking: "" };
|
|
233
|
+
output.content.push(currentBlock);
|
|
234
|
+
stream.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output });
|
|
235
|
+
}
|
|
236
|
+
else if (item.type === "message") {
|
|
237
|
+
currentItem = item;
|
|
238
|
+
currentBlock = { type: "text", text: "" };
|
|
239
|
+
output.content.push(currentBlock);
|
|
240
|
+
stream.push({ type: "text_start", contentIndex: blockIndex(), partial: output });
|
|
241
|
+
}
|
|
242
|
+
else if (item.type === "function_call") {
|
|
243
|
+
currentItem = item;
|
|
244
|
+
currentBlock = {
|
|
245
|
+
type: "toolCall",
|
|
246
|
+
id: `${item.call_id}|${item.id}`,
|
|
247
|
+
name: item.name,
|
|
248
|
+
arguments: {},
|
|
249
|
+
partialJson: item.arguments || "",
|
|
250
|
+
};
|
|
251
|
+
output.content.push(currentBlock);
|
|
252
|
+
stream.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
else if (event.type === "response.reasoning_summary_part.added") {
|
|
256
|
+
if (currentItem && currentItem.type === "reasoning") {
|
|
257
|
+
currentItem.summary = currentItem.summary || [];
|
|
258
|
+
currentItem.summary.push(event.part);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
else if (event.type === "response.reasoning_summary_text.delta") {
|
|
262
|
+
if (currentItem?.type === "reasoning" && currentBlock?.type === "thinking") {
|
|
263
|
+
currentItem.summary = currentItem.summary || [];
|
|
264
|
+
const lastPart = currentItem.summary[currentItem.summary.length - 1];
|
|
265
|
+
if (lastPart) {
|
|
266
|
+
currentBlock.thinking += event.delta;
|
|
267
|
+
lastPart.text += event.delta;
|
|
268
|
+
stream.push({
|
|
269
|
+
type: "thinking_delta",
|
|
270
|
+
contentIndex: blockIndex(),
|
|
271
|
+
delta: event.delta,
|
|
272
|
+
partial: output,
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
else if (event.type === "response.reasoning_summary_part.done") {
|
|
278
|
+
if (currentItem?.type === "reasoning" && currentBlock?.type === "thinking") {
|
|
279
|
+
currentItem.summary = currentItem.summary || [];
|
|
280
|
+
const lastPart = currentItem.summary[currentItem.summary.length - 1];
|
|
281
|
+
if (lastPart) {
|
|
282
|
+
currentBlock.thinking += "\n\n";
|
|
283
|
+
lastPart.text += "\n\n";
|
|
284
|
+
stream.push({
|
|
285
|
+
type: "thinking_delta",
|
|
286
|
+
contentIndex: blockIndex(),
|
|
287
|
+
delta: "\n\n",
|
|
288
|
+
partial: output,
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
else if (event.type === "response.content_part.added") {
|
|
294
|
+
if (currentItem?.type === "message") {
|
|
295
|
+
currentItem.content = currentItem.content || [];
|
|
296
|
+
// Filter out ReasoningText, only accept output_text and refusal
|
|
297
|
+
if (event.part.type === "output_text" || event.part.type === "refusal") {
|
|
298
|
+
currentItem.content.push(event.part);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
else if (event.type === "response.output_text.delta") {
|
|
303
|
+
if (currentItem?.type === "message" && currentBlock?.type === "text") {
|
|
304
|
+
if (!currentItem.content || currentItem.content.length === 0) {
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
const lastPart = currentItem.content[currentItem.content.length - 1];
|
|
308
|
+
if (lastPart?.type === "output_text") {
|
|
309
|
+
currentBlock.text += event.delta;
|
|
310
|
+
lastPart.text += event.delta;
|
|
311
|
+
stream.push({
|
|
312
|
+
type: "text_delta",
|
|
313
|
+
contentIndex: blockIndex(),
|
|
314
|
+
delta: event.delta,
|
|
315
|
+
partial: output,
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
else if (event.type === "response.refusal.delta") {
|
|
321
|
+
if (currentItem?.type === "message" && currentBlock?.type === "text") {
|
|
322
|
+
if (!currentItem.content || currentItem.content.length === 0) {
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
const lastPart = currentItem.content[currentItem.content.length - 1];
|
|
326
|
+
if (lastPart?.type === "refusal") {
|
|
327
|
+
currentBlock.text += event.delta;
|
|
328
|
+
lastPart.refusal += event.delta;
|
|
329
|
+
stream.push({
|
|
330
|
+
type: "text_delta",
|
|
331
|
+
contentIndex: blockIndex(),
|
|
332
|
+
delta: event.delta,
|
|
333
|
+
partial: output,
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
else if (event.type === "response.function_call_arguments.delta") {
|
|
339
|
+
if (currentItem?.type === "function_call" && currentBlock?.type === "toolCall") {
|
|
340
|
+
currentBlock.partialJson += event.delta;
|
|
341
|
+
currentBlock.arguments = parseStreamingJson(currentBlock.partialJson);
|
|
342
|
+
stream.push({
|
|
343
|
+
type: "toolcall_delta",
|
|
344
|
+
contentIndex: blockIndex(),
|
|
345
|
+
delta: event.delta,
|
|
346
|
+
partial: output,
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
else if (event.type === "response.function_call_arguments.done") {
|
|
351
|
+
if (currentItem?.type === "function_call" && currentBlock?.type === "toolCall") {
|
|
352
|
+
currentBlock.partialJson = event.arguments;
|
|
353
|
+
currentBlock.arguments = parseStreamingJson(currentBlock.partialJson);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
else if (event.type === "response.output_item.done") {
|
|
357
|
+
const item = event.item;
|
|
358
|
+
if (item.type === "reasoning" && currentBlock?.type === "thinking") {
|
|
359
|
+
currentBlock.thinking = item.summary?.map((s) => s.text).join("\n\n") || "";
|
|
360
|
+
currentBlock.thinkingSignature = JSON.stringify(item);
|
|
361
|
+
stream.push({
|
|
362
|
+
type: "thinking_end",
|
|
363
|
+
contentIndex: blockIndex(),
|
|
364
|
+
content: currentBlock.thinking,
|
|
365
|
+
partial: output,
|
|
366
|
+
});
|
|
367
|
+
currentBlock = null;
|
|
368
|
+
}
|
|
369
|
+
else if (item.type === "message" && currentBlock?.type === "text") {
|
|
370
|
+
currentBlock.text = item.content.map((c) => (c.type === "output_text" ? c.text : c.refusal)).join("");
|
|
371
|
+
currentBlock.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);
|
|
372
|
+
stream.push({
|
|
373
|
+
type: "text_end",
|
|
374
|
+
contentIndex: blockIndex(),
|
|
375
|
+
content: currentBlock.text,
|
|
376
|
+
partial: output,
|
|
377
|
+
});
|
|
378
|
+
currentBlock = null;
|
|
379
|
+
}
|
|
380
|
+
else if (item.type === "function_call") {
|
|
381
|
+
const args = currentBlock?.type === "toolCall" && currentBlock.partialJson
|
|
382
|
+
? parseStreamingJson(currentBlock.partialJson)
|
|
383
|
+
: parseStreamingJson(item.arguments || "{}");
|
|
384
|
+
const toolCall = {
|
|
385
|
+
type: "toolCall",
|
|
386
|
+
id: `${item.call_id}|${item.id}`,
|
|
387
|
+
name: item.name,
|
|
388
|
+
arguments: args,
|
|
389
|
+
};
|
|
390
|
+
currentBlock = null;
|
|
391
|
+
stream.push({ type: "toolcall_end", contentIndex: blockIndex(), toolCall, partial: output });
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
else if (event.type === "response.completed") {
|
|
395
|
+
const response = event.response;
|
|
396
|
+
if (response?.id) {
|
|
397
|
+
output.responseId = response.id;
|
|
398
|
+
}
|
|
399
|
+
if (response?.usage) {
|
|
400
|
+
const cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0;
|
|
401
|
+
output.usage = {
|
|
402
|
+
// OpenAI includes cached tokens in input_tokens, so subtract to get non-cached input
|
|
403
|
+
input: (response.usage.input_tokens || 0) - cachedTokens,
|
|
404
|
+
output: response.usage.output_tokens || 0,
|
|
405
|
+
cacheRead: cachedTokens,
|
|
406
|
+
cacheWrite: 0,
|
|
407
|
+
totalTokens: response.usage.total_tokens || 0,
|
|
408
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
calculateCost(model, output.usage);
|
|
412
|
+
if (options?.applyServiceTierPricing) {
|
|
413
|
+
const serviceTier = response?.service_tier ?? options.serviceTier;
|
|
414
|
+
options.applyServiceTierPricing(output.usage, serviceTier);
|
|
415
|
+
}
|
|
416
|
+
// Map status to stop reason
|
|
417
|
+
output.stopReason = mapStopReason(response?.status);
|
|
418
|
+
if (output.content.some((b) => b.type === "toolCall") && output.stopReason === "stop") {
|
|
419
|
+
output.stopReason = "toolUse";
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
else if (event.type === "error") {
|
|
423
|
+
throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error");
|
|
424
|
+
}
|
|
425
|
+
else if (event.type === "response.failed") {
|
|
426
|
+
const error = event.response?.error;
|
|
427
|
+
const details = event.response?.incomplete_details;
|
|
428
|
+
const msg = error
|
|
429
|
+
? `${error.code || "unknown"}: ${error.message || "no message"}`
|
|
430
|
+
: details?.reason
|
|
431
|
+
? `incomplete: ${details.reason}`
|
|
432
|
+
: "Unknown error (no error details in response)";
|
|
433
|
+
throw new Error(msg);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
function mapStopReason(status) {
|
|
438
|
+
if (!status)
|
|
439
|
+
return "stop";
|
|
440
|
+
switch (status) {
|
|
441
|
+
case "completed":
|
|
442
|
+
return "stop";
|
|
443
|
+
case "incomplete":
|
|
444
|
+
return "length";
|
|
445
|
+
case "failed":
|
|
446
|
+
case "cancelled":
|
|
447
|
+
return "error";
|
|
448
|
+
// These two are wonky ...
|
|
449
|
+
case "in_progress":
|
|
450
|
+
case "queued":
|
|
451
|
+
return "stop";
|
|
452
|
+
default: {
|
|
453
|
+
const _exhaustive = status;
|
|
454
|
+
throw new Error(`Unhandled stop reason: ${_exhaustive}`);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
//# sourceMappingURL=openai-responses-shared.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openai-responses-shared.js","sourceRoot":"","sources":["../../src/providers/openai-responses-shared.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAgB7C,OAAO,EAAE,SAAS,EAAE,MAAM,k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AC,CAAC;QAC1D,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import type OpenAI from \"openai\";\nimport type {\n\tTool as OpenAITool,\n\tResponseCreateParamsStreaming,\n\tResponseFunctionCallOutputItemList,\n\tResponseFunctionToolCall,\n\tResponseInput,\n\tResponseInputContent,\n\tResponseInputImage,\n\tResponseInputText,\n\tResponseOutputMessage,\n\tResponseReasoningItem,\n\tResponseStreamEvent,\n} from \"openai/resources/responses/responses.js\";\nimport { calculateCost } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tImageContent,\n\tModel,\n\tStopReason,\n\tTextContent,\n\tTextSignatureV1,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tUsage,\n} from \"../types.js\";\nimport type { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { shortHash } from \"../utils/hash.js\";\nimport { parseStreamingJson } from \"../utils/json-parse.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { transformMessages } from \"./transform-messages.js\";\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\nfunction encodeTextSignatureV1(id: string, phase?: TextSignatureV1[\"phase\"]): string {\n\tconst payload: TextSignatureV1 = { v: 1, id };\n\tif (phase) payload.phase = phase;\n\treturn JSON.stringify(payload);\n}\n\nfunction parseTextSignature(\n\tsignature: string | undefined,\n): { id: string; phase?: TextSignatureV1[\"phase\"] } | undefined {\n\tif (!signature) return undefined;\n\tif (signature.startsWith(\"{\")) {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(signature) as Partial<TextSignatureV1>;\n\t\t\tif (parsed.v === 1 && typeof parsed.id === \"string\") {\n\t\t\t\tif (parsed.phase === \"commentary\" || parsed.phase === \"final_answer\") {\n\t\t\t\t\treturn { id: parsed.id, phase: parsed.phase };\n\t\t\t\t}\n\t\t\t\treturn { id: parsed.id };\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to legacy plain-string handling.\n\t\t}\n\t}\n\treturn { id: signature };\n}\n\nexport interface OpenAIResponsesStreamOptions {\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"];\n\tapplyServiceTierPricing?: (\n\t\tusage: Usage,\n\t\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t) => void;\n}\n\nexport interface ConvertResponsesMessagesOptions {\n\tincludeSystemPrompt?: boolean;\n}\n\nexport interface ConvertResponsesToolsOptions {\n\tstrict?: boolean | null;\n}\n\n// =============================================================================\n// Message conversion\n// =============================================================================\n\nexport function convertResponsesMessages<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\tallowedToolCallProviders: ReadonlySet<string>,\n\toptions?: ConvertResponsesMessagesOptions,\n): ResponseInput {\n\tconst messages: ResponseInput = [];\n\n\tconst normalizeIdPart = (part: string): string => {\n\t\tconst sanitized = part.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\t\tconst normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n\t\treturn normalized.replace(/_+$/, \"\");\n\t};\n\n\tconst buildForeignResponsesItemId = (itemId: string): string => {\n\t\tconst normalized = `fc_${shortHash(itemId)}`;\n\t\treturn normalized.length > 64 ? normalized.slice(0, 64) : normalized;\n\t};\n\n\tconst normalizeToolCallId = (id: string, _targetModel: Model<TApi>, source: AssistantMessage): string => {\n\t\tif (!allowedToolCallProviders.has(model.provider)) return normalizeIdPart(id);\n\t\tif (!id.includes(\"|\")) return normalizeIdPart(id);\n\t\tconst [callId, itemId] = id.split(\"|\");\n\t\tconst normalizedCallId = normalizeIdPart(callId);\n\t\tconst isForeignToolCall = source.provider !== model.provider || source.api !== model.api;\n\t\tlet normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);\n\t\t// OpenAI Responses API requires item id to start with \"fc\"\n\t\tif (!normalizedItemId.startsWith(\"fc_\")) {\n\t\t\tnormalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);\n\t\t}\n\t\treturn `${normalizedCallId}|${normalizedItemId}`;\n\t};\n\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n\n\tconst includeSystemPrompt = options?.includeSystemPrompt ?? true;\n\tif (includeSystemPrompt && context.systemPrompt) {\n\t\tconst role = model.reasoning ? \"developer\" : \"system\";\n\t\tmessages.push({\n\t\t\trole,\n\t\t\tcontent: sanitizeSurrogates(context.systemPrompt),\n\t\t});\n\t}\n\n\tlet msgIndex = 0;\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [{ type: \"input_text\", text: sanitizeSurrogates(msg.content) }],\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst content: ResponseInputContent[] = msg.content.map((item): ResponseInputContent => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t\t} satisfies ResponseInputText;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\timage_url: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t} satisfies ResponseInputImage;\n\t\t\t\t});\n\t\t\t\tconst filteredContent = !model.input.includes(\"image\")\n\t\t\t\t\t? content.filter((c) => c.type !== \"input_image\")\n\t\t\t\t\t: content;\n\t\t\t\tif (filteredContent.length === 0) continue;\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: filteredContent,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst output: ResponseInput = [];\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isDifferentModel =\n\t\t\t\tassistantMsg.model !== model.id &&\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api;\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (block.thinkingSignature) {\n\t\t\t\t\t\tconst reasoningItem = JSON.parse(block.thinkingSignature) as ResponseReasoningItem;\n\t\t\t\t\t\toutput.push(reasoningItem);\n\t\t\t\t\t}\n\t\t\t\t} else if (block.type === \"text\") {\n\t\t\t\t\tconst textBlock = block as TextContent;\n\t\t\t\t\tconst parsedSignature = parseTextSignature(textBlock.textSignature);\n\t\t\t\t\t// OpenAI requires id to be max 64 characters\n\t\t\t\t\tlet msgId = parsedSignature?.id;\n\t\t\t\t\tif (!msgId) {\n\t\t\t\t\t\tmsgId = `msg_${msgIndex}`;\n\t\t\t\t\t} else if (msgId.length > 64) {\n\t\t\t\t\t\tmsgId = `msg_${shortHash(msgId)}`;\n\t\t\t\t\t}\n\t\t\t\t\toutput.push({\n\t\t\t\t\t\ttype: \"message\",\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent: [{ type: \"output_text\", text: sanitizeSurrogates(textBlock.text), annotations: [] }],\n\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\tid: msgId,\n\t\t\t\t\t\tphase: parsedSignature?.phase,\n\t\t\t\t\t} satisfies ResponseOutputMessage);\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tconst [callId, itemIdRaw] = toolCall.id.split(\"|\");\n\t\t\t\t\tlet itemId: string | undefined = itemIdRaw;\n\n\t\t\t\t\t// For different-model messages, set id to undefined to avoid pairing validation.\n\t\t\t\t\t// OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.\n\t\t\t\t\t// By omitting the id, we avoid triggering that validation (like cross-provider does).\n\t\t\t\t\tif (isDifferentModel && itemId?.startsWith(\"fc_\")) {\n\t\t\t\t\t\titemId = undefined;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push({\n\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\tid: itemId,\n\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\targuments: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (output.length === 0) continue;\n\t\t\tmessages.push(...output);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst textResult = msg.content\n\t\t\t\t.filter((c): c is TextContent => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst hasImages = msg.content.some((c): c is ImageContent => c.type === \"image\");\n\t\t\tconst hasText = textResult.length > 0;\n\t\t\tconst [callId] = msg.toolCallId.split(\"|\");\n\n\t\t\tlet output: string | ResponseFunctionCallOutputItemList;\n\t\t\tif (hasImages && model.input.includes(\"image\")) {\n\t\t\t\tconst contentParts: ResponseFunctionCallOutputItemList = [];\n\n\t\t\t\tif (hasText) {\n\t\t\t\t\tcontentParts.push({\n\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\ttext: sanitizeSurrogates(textResult),\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tfor (const block of msg.content) {\n\t\t\t\t\tif (block.type === \"image\") {\n\t\t\t\t\t\tcontentParts.push({\n\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\t\timage_url: `data:${block.mimeType};base64,${block.data}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\toutput = contentParts;\n\t\t\t} else {\n\t\t\t\toutput = sanitizeSurrogates(hasText ? textResult : \"(see attached image)\");\n\t\t\t}\n\n\t\t\tmessages.push({\n\t\t\t\ttype: \"function_call_output\",\n\t\t\t\tcall_id: callId,\n\t\t\t\toutput,\n\t\t\t});\n\t\t}\n\t\tmsgIndex++;\n\t}\n\n\treturn messages;\n}\n\n// =============================================================================\n// Tool conversion\n// =============================================================================\n\nexport function convertResponsesTools(tools: Tool[], options?: ConvertResponsesToolsOptions): OpenAITool[] {\n\tconst strict = options?.strict === undefined ? false : options.strict;\n\treturn tools.map((tool) => ({\n\t\ttype: \"function\",\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters as any, // TypeBox already generates JSON Schema\n\t\tstrict,\n\t}));\n}\n\n// =============================================================================\n// Stream processing\n// =============================================================================\n\nexport async function processResponsesStream<TApi extends Api>(\n\topenaiStream: AsyncIterable<ResponseStreamEvent>,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<TApi>,\n\toptions?: OpenAIResponsesStreamOptions,\n): Promise<void> {\n\tlet currentItem: ResponseReasoningItem | ResponseOutputMessage | ResponseFunctionToolCall | null = null;\n\tlet currentBlock: ThinkingContent | TextContent | (ToolCall & { partialJson: string }) | null = null;\n\tconst blocks = output.content;\n\tconst blockIndex = () => blocks.length - 1;\n\n\tfor await (const event of openaiStream) {\n\t\tif (event.type === \"response.created\") {\n\t\t\toutput.responseId = event.response.id;\n\t\t} else if (event.type === \"response.output_item.added\") {\n\t\t\tconst item = event.item;\n\t\t\tif (item.type === \"reasoning\") {\n\t\t\t\tcurrentItem = item;\n\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\" };\n\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t} else if (item.type === \"message\") {\n\t\t\t\tcurrentItem = item;\n\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t} else if (item.type === \"function_call\") {\n\t\t\t\tcurrentItem = item;\n\t\t\t\tcurrentBlock = {\n\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\tid: `${item.call_id}|${item.id}`,\n\t\t\t\t\tname: item.name,\n\t\t\t\t\targuments: {},\n\t\t\t\t\tpartialJson: item.arguments || \"\",\n\t\t\t\t};\n\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t}\n\t\t} else if (event.type === \"response.reasoning_summary_part.added\") {\n\t\t\tif (currentItem && currentItem.type === \"reasoning\") {\n\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\tcurrentItem.summary.push(event.part);\n\t\t\t}\n\t\t} else if (event.type === \"response.reasoning_summary_text.delta\") {\n\t\t\tif (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\tconst lastPart = currentItem.summary[currentItem.summary.length - 1];\n\t\t\t\tif (lastPart) {\n\t\t\t\t\tcurrentBlock.thinking += event.delta;\n\t\t\t\t\tlastPart.text += event.delta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.reasoning_summary_part.done\") {\n\t\t\tif (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\tconst lastPart = currentItem.summary[currentItem.summary.length - 1];\n\t\t\t\tif (lastPart) {\n\t\t\t\t\tcurrentBlock.thinking += \"\\n\\n\";\n\t\t\t\t\tlastPart.text += \"\\n\\n\";\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: \"\\n\\n\",\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.content_part.added\") {\n\t\t\tif (currentItem?.type === \"message\") {\n\t\t\t\tcurrentItem.content = currentItem.content || [];\n\t\t\t\t// Filter out ReasoningText, only accept output_text and refusal\n\t\t\t\tif (event.part.type === \"output_text\" || event.part.type === \"refusal\") {\n\t\t\t\t\tcurrentItem.content.push(event.part);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.output_text.delta\") {\n\t\t\tif (currentItem?.type === \"message\" && currentBlock?.type === \"text\") {\n\t\t\t\tif (!currentItem.content || currentItem.content.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst lastPart = currentItem.content[currentItem.content.length - 1];\n\t\t\t\tif (lastPart?.type === \"output_text\") {\n\t\t\t\t\tcurrentBlock.text += event.delta;\n\t\t\t\t\tlastPart.text += event.delta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.refusal.delta\") {\n\t\t\tif (currentItem?.type === \"message\" && currentBlock?.type === \"text\") {\n\t\t\t\tif (!currentItem.content || currentItem.content.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst lastPart = currentItem.content[currentItem.content.length - 1];\n\t\t\t\tif (lastPart?.type === \"refusal\") {\n\t\t\t\t\tcurrentBlock.text += event.delta;\n\t\t\t\t\tlastPart.refusal += event.delta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.function_call_arguments.delta\") {\n\t\t\tif (currentItem?.type === \"function_call\" && currentBlock?.type === \"toolCall\") {\n\t\t\t\tcurrentBlock.partialJson += event.delta;\n\t\t\t\tcurrentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (event.type === \"response.function_call_arguments.done\") {\n\t\t\tif (currentItem?.type === \"function_call\" && currentBlock?.type === \"toolCall\") {\n\t\t\t\tcurrentBlock.partialJson = event.arguments;\n\t\t\t\tcurrentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n\t\t\t}\n\t\t} else if (event.type === \"response.output_item.done\") {\n\t\t\tconst item = event.item;\n\n\t\t\tif (item.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n\t\t\t\tcurrentBlock.thinking = item.summary?.map((s) => s.text).join(\"\\n\\n\") || \"\";\n\t\t\t\tcurrentBlock.thinkingSignature = JSON.stringify(item);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\tcurrentBlock = null;\n\t\t\t} else if (item.type === \"message\" && currentBlock?.type === \"text\") {\n\t\t\t\tcurrentBlock.text = item.content.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\");\n\t\t\t\tcurrentBlock.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\tcurrentBlock = null;\n\t\t\t} else if (item.type === \"function_call\") {\n\t\t\t\tconst args =\n\t\t\t\t\tcurrentBlock?.type === \"toolCall\" && currentBlock.partialJson\n\t\t\t\t\t\t? parseStreamingJson(currentBlock.partialJson)\n\t\t\t\t\t\t: parseStreamingJson(item.arguments || \"{}\");\n\t\t\t\tconst toolCall: ToolCall = {\n\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\tid: `${item.call_id}|${item.id}`,\n\t\t\t\t\tname: item.name,\n\t\t\t\t\targuments: args,\n\t\t\t\t};\n\n\t\t\t\tcurrentBlock = null;\n\t\t\t\tstream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n\t\t\t}\n\t\t} else if (event.type === \"response.completed\") {\n\t\t\tconst response = event.response;\n\t\t\tif (response?.id) {\n\t\t\t\toutput.responseId = response.id;\n\t\t\t}\n\t\t\tif (response?.usage) {\n\t\t\t\tconst cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0;\n\t\t\t\toutput.usage = {\n\t\t\t\t\t// OpenAI includes cached tokens in input_tokens, so subtract to get non-cached input\n\t\t\t\t\tinput: (response.usage.input_tokens || 0) - cachedTokens,\n\t\t\t\t\toutput: response.usage.output_tokens || 0,\n\t\t\t\t\tcacheRead: cachedTokens,\n\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\ttotalTokens: response.usage.total_tokens || 0,\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t};\n\t\t\t}\n\t\t\tcalculateCost(model, output.usage);\n\t\t\tif (options?.applyServiceTierPricing) {\n\t\t\t\tconst serviceTier = response?.service_tier ?? options.serviceTier;\n\t\t\t\toptions.applyServiceTierPricing(output.usage, serviceTier);\n\t\t\t}\n\t\t\t// Map status to stop reason\n\t\t\toutput.stopReason = mapStopReason(response?.status);\n\t\t\tif (output.content.some((b) => b.type === \"toolCall\") && output.stopReason === \"stop\") {\n\t\t\t\toutput.stopReason = \"toolUse\";\n\t\t\t}\n\t\t} else if (event.type === \"error\") {\n\t\t\tthrow new Error(`Error Code ${event.code}: ${event.message}` || \"Unknown error\");\n\t\t} else if (event.type === \"response.failed\") {\n\t\t\tconst error = event.response?.error;\n\t\t\tconst details = event.response?.incomplete_details;\n\t\t\tconst msg = error\n\t\t\t\t? `${error.code || \"unknown\"}: ${error.message || \"no message\"}`\n\t\t\t\t: details?.reason\n\t\t\t\t\t? `incomplete: ${details.reason}`\n\t\t\t\t\t: \"Unknown error (no error details in response)\";\n\t\t\tthrow new Error(msg);\n\t\t}\n\t}\n}\n\nfunction mapStopReason(status: OpenAI.Responses.ResponseStatus | undefined): StopReason {\n\tif (!status) return \"stop\";\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn \"stop\";\n\t\tcase \"incomplete\":\n\t\t\treturn \"length\";\n\t\tcase \"failed\":\n\t\tcase \"cancelled\":\n\t\t\treturn \"error\";\n\t\t// These two are wonky ...\n\t\tcase \"in_progress\":\n\t\tcase \"queued\":\n\t\t\treturn \"stop\";\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = status;\n\t\t\tthrow new Error(`Unhandled stop reason: ${_exhaustive}`);\n\t\t}\n\t}\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ResponseCreateParamsStreaming } from "openai/resources/responses/responses.js";
|
|
2
|
+
import type { SimpleStreamOptions, StreamFunction, StreamOptions } from "../types.js";
|
|
3
|
+
export interface OpenAIResponsesOptions extends StreamOptions {
|
|
4
|
+
reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
5
|
+
reasoningSummary?: "auto" | "detailed" | "concise" | null;
|
|
6
|
+
serviceTier?: ResponseCreateParamsStreaming["service_tier"];
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Generate function for OpenAI Responses API
|
|
10
|
+
*/
|
|
11
|
+
export declare const streamOpenAIResponses: StreamFunction<"openai-responses", OpenAIResponsesOptions>;
|
|
12
|
+
export declare const streamSimpleOpenAIResponses: StreamFunction<"openai-responses", SimpleStreamOptions>;
|
|
13
|
+
//# sourceMappingURL=openai-responses.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openai-responses.d.ts","sourceRoot":"","sources":["../../src/providers/openai-responses.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AAG7F,OAAO,KAAK,EAMX,mBAAmB,EACnB,cAAc,EACd,aAAa,EAEb,MAAM,aAAa,CAAC;AAqCrB,MAAM,WAAW,sBAAuB,SAAQ,aAAa;IAC5D,eAAe,CAAC,EAAE,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;IAClE,gBAAgB,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,GAAG,IAAI,CAAC;IAC1D,WAAW,CAAC,EAAE,6BAA6B,CAAC,cAAc,CAAC,CAAC;CAC5D;AAED;;GAEG;AACH,eAAO,MAAM,qBAAqB,EAAE,cAAc,CAAC,kBAAkB,EAAE,sBAAsB,CAmE5F,CAAC;AAEF,eAAO,MAAM,2BAA2B,EAAE,cAAc,CAAC,kBAAkB,EAAE,mBAAmB,CAiB/F,CAAC","sourcesContent":["import OpenAI from \"openai\";\nimport type { ResponseCreateParamsStreaming } from \"openai/resources/responses/responses.js\";\nimport { getEnvApiKey } from \"../env-api-keys.js\";\nimport { supportsXhigh } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tUsage,\n} from \"../types.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.js\";\nimport { convertResponsesMessages, convertResponsesTools, processResponsesStream } from \"./openai-responses-shared.js\";\nimport { buildBaseOptions, clampReasoning } from \"./simple-options.js\";\n\nconst OPENAI_TOOL_CALL_PROVIDERS = new Set([\"github-copilot\", \"openai-codex\"]);\n\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses PI_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention?: CacheRetention): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\n/**\n * Get prompt cache retention based on cacheRetention and base URL.\n * Only applies to direct OpenAI API calls (api.openai.com).\n */\nfunction getPromptCacheRetention(baseUrl: string, cacheRetention: CacheRetention): \"24h\" | undefined {\n\tif (cacheRetention !== \"long\") {\n\t\treturn undefined;\n\t}\n\tif (baseUrl.includes(\"api.openai.com\")) {\n\t\treturn \"24h\";\n\t}\n\treturn undefined;\n}\n\n// OpenAI Responses-specific options\nexport interface OpenAIResponsesOptions extends StreamOptions {\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\treasoningSummary?: \"auto\" | \"detailed\" | \"concise\" | null;\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"];\n}\n\n/**\n * Generate function for OpenAI Responses API\n */\nexport const streamOpenAIResponses: StreamFunction<\"openai-responses\", OpenAIResponsesOptions> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: OpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t// Start async processing\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\t// Create OpenAI client\n\t\t\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider) || \"\";\n\t\t\tconst client = createClient(model, context, apiKey, options?.headers);\n\t\t\tlet params = buildParams(model, context, options);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as ResponseCreateParamsStreaming;\n\t\t\t}\n\t\t\tconst openaiStream = await client.responses.create(\n\t\t\t\tparams,\n\t\t\t\toptions?.signal ? { signal: options.signal } : undefined,\n\t\t\t);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tawait processResponsesStream(openaiStream, output, stream, model, {\n\t\t\t\tserviceTier: options?.serviceTier,\n\t\t\t\tapplyServiceTierPricing,\n\t\t\t});\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(\"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) delete (block as { index?: number }).index;\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\nexport const streamSimpleOpenAIResponses: StreamFunction<\"openai-responses\", SimpleStreamOptions> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider);\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = buildBaseOptions(model, options, apiKey);\n\tconst reasoningEffort = supportsXhigh(model) ? options?.reasoning : clampReasoning(options?.reasoning);\n\n\treturn streamOpenAIResponses(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t} satisfies OpenAIResponsesOptions);\n};\n\nfunction createClient(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\tapiKey?: string,\n\toptionsHeaders?: Record<string, string>,\n) {\n\tif (!apiKey) {\n\t\tif (!process.env.OPENAI_API_KEY) {\n\t\t\tthrow new Error(\n\t\t\t\t\"OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.\",\n\t\t\t);\n\t\t}\n\t\tapiKey = process.env.OPENAI_API_KEY;\n\t}\n\n\tconst headers = { ...model.headers };\n\tif (model.provider === \"github-copilot\") {\n\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\tconst copilotHeaders = buildCopilotDynamicHeaders({\n\t\t\tmessages: context.messages,\n\t\t\thasImages,\n\t\t});\n\t\tObject.assign(headers, copilotHeaders);\n\t}\n\n\t// Merge options headers last so they can override defaults\n\tif (optionsHeaders) {\n\t\tObject.assign(headers, optionsHeaders);\n\t}\n\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders: headers,\n\t});\n}\n\nfunction buildParams(model: Model<\"openai-responses\">, context: Context, options?: OpenAIResponsesOptions) {\n\tconst messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS);\n\n\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention);\n\tconst params: ResponseCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tinput: messages,\n\t\tstream: true,\n\t\tprompt_cache_key: cacheRetention === \"none\" ? undefined : options?.sessionId,\n\t\tprompt_cache_retention: getPromptCacheRetention(model.baseUrl, cacheRetention),\n\t\tstore: false,\n\t};\n\n\tif (options?.maxTokens) {\n\t\tparams.max_output_tokens = options?.maxTokens;\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options?.temperature;\n\t}\n\n\tif (options?.serviceTier !== undefined) {\n\t\tparams.service_tier = options.serviceTier;\n\t}\n\n\tif (context.tools) {\n\t\tparams.tools = convertResponsesTools(context.tools);\n\t}\n\n\tif (model.reasoning) {\n\t\tif (options?.reasoningEffort || options?.reasoningSummary) {\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: options?.reasoningEffort || \"medium\",\n\t\t\t\tsummary: options?.reasoningSummary || \"auto\",\n\t\t\t};\n\t\t\tparams.include = [\"reasoning.encrypted_content\"];\n\t\t} else if (model.provider !== \"github-copilot\") {\n\t\t\tparams.reasoning = { effort: \"none\" };\n\t\t}\n\t}\n\n\treturn params;\n}\n\nfunction getServiceTierCostMultiplier(serviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined): number {\n\tswitch (serviceTier) {\n\t\tcase \"flex\":\n\t\t\treturn 0.5;\n\t\tcase \"priority\":\n\t\t\treturn 2;\n\t\tdefault:\n\t\t\treturn 1;\n\t}\n}\n\nfunction applyServiceTierPricing(usage: Usage, serviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined) {\n\tconst multiplier = getServiceTierCostMultiplier(serviceTier);\n\tif (multiplier === 1) return;\n\n\tusage.cost.input *= multiplier;\n\tusage.cost.output *= multiplier;\n\tusage.cost.cacheRead *= multiplier;\n\tusage.cost.cacheWrite *= multiplier;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n}\n"]}
|