Repository navigation
Expand file tree
/
Copy pathopenai.ts
More file actions
333 lines (315 loc) · 10 KB
/
Copy pathopenai.ts
File metadata and controls
333 lines (315 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import type {
LlmContentBlock,
LlmMessage,
LlmStreamHandle,
LlmStreamOptions,
} from "../assistant/llm-protocol";
declare const com: any;
/**
* Minimal streaming client for the OpenAI Responses API. NativeScript cannot
* use the Node SDK, so this shares the okhttp/SSE bridge used by Anthropic.
*/
const OPENAI_RESPONSES_URL = "https://api.openai.com/v1/responses";
type StreamingOutput =
| { type: "text"; text: string }
| { type: "tool_use"; id: string; name: string; inputJson: string; itemId: string; item: any }
| { type: "provider_item"; item: any };
export function streamOpenAiResponse(options: LlmStreamOptions): LlmStreamHandle {
const apiKey = options.apiKey.trim();
let request: any = null;
let settled = false;
let text = "";
let stopReason: string | null = null;
let refusal = false;
const outputs = new Map<number, StreamingOutput>();
const fail = (message: string) => {
if (settled) return;
settled = true;
options.onError(message);
};
const done = () => {
if (settled) return;
settled = true;
const content = finalizeOutputs(outputs);
const hasToolUse = content.some((block) => block.type === "tool_use");
options.onDone({
text,
content,
stopReason: refusal ? "refusal" : hasToolUse ? "tool_use" : stopReason ?? "end_turn",
});
};
if (!global.isAndroid) {
setTimeout(() => fail("OpenAI API is only wired up on Android"), 0);
return { cancel: () => {} };
}
if (!apiKey) {
setTimeout(() => fail("No OpenAI API key set"), 0);
return { cancel: () => {} };
}
const body: any = {
model: options.model,
input: buildOpenAiInput(options.messages),
stream: true,
store: false,
include: ["reasoning.encrypted_content"],
max_output_tokens: options.maxTokens ?? 8192,
};
if (options.system) body.instructions = options.system;
if (options.tools?.length) {
body.tools = options.tools.map((tool) => ({
type: "function",
name: tool.name,
description: tool.description,
parameters: tool.input_schema,
}));
}
if (options.effort) body.reasoning = { effort: options.effort };
const listener = new com.faceclaw.app.FaceclawSseListener({
onLine: (line: string) => {
if (settled) return;
const event = parseSseDataLine(String(line));
if (!event) return;
const outputIndex = Number(event.output_index);
switch (event.type) {
case "response.output_item.added": {
const item = event.item;
if (item?.type === "function_call") {
outputs.set(outputIndex, {
type: "tool_use",
id: String(item.call_id ?? item.id ?? ""),
name: String(item.name ?? ""),
inputJson: String(item.arguments ?? ""),
itemId: String(item.id ?? ""),
item,
});
} else if (item?.type === "message") {
outputs.set(outputIndex, { type: "text", text: "" });
} else if (item?.type === "reasoning") {
outputs.set(outputIndex, { type: "provider_item", item });
}
return;
}
case "response.output_text.delta": {
const delta = String(event.delta ?? "");
text += delta;
const output = outputs.get(outputIndex);
if (output?.type === "text") {
output.text += delta;
} else {
outputs.set(outputIndex, { type: "text", text: delta });
}
options.onTextDelta?.(delta, text);
return;
}
case "response.function_call_arguments.delta": {
const output = findToolOutput(outputs, outputIndex, String(event.item_id ?? ""));
if (output) output.inputJson += String(event.delta ?? "");
return;
}
case "response.output_item.done": {
const item = event.item;
if (item?.type === "function_call") {
outputs.set(outputIndex, {
type: "tool_use",
id: String(item.call_id ?? item.id ?? ""),
name: String(item.name ?? ""),
inputJson: String(item.arguments ?? ""),
itemId: String(item.id ?? ""),
item,
});
} else if (item?.type === "message") {
const output = outputs.get(outputIndex);
const completedText = extractMessageText(item);
outputs.set(outputIndex, {
type: "text",
text: completedText || (output?.type === "text" ? output.text : ""),
});
if (completedText && !text) text = completedText;
} else if (item?.type === "reasoning") {
outputs.set(outputIndex, { type: "provider_item", item });
}
return;
}
case "response.refusal.delta":
case "response.refusal.done":
refusal = true;
return;
case "response.completed":
done();
return;
case "response.incomplete":
stopReason = String(event.response?.incomplete_details?.reason ?? "incomplete");
done();
return;
case "response.failed":
fail(`OpenAI: ${String(event.response?.error?.message ?? "response failed")}`);
return;
case "error":
fail(`OpenAI: ${String(event.message ?? event.error?.message ?? "stream error")}`);
return;
default:
return;
}
},
onHttpError: (code: number, errorBody: string) => {
fail(describeHttpError(Number(code), String(errorBody)));
},
onComplete: () => {
done();
},
onFailure: (message: string) => {
fail(`OpenAI connection failed: ${String(message)}`);
},
});
const headers = Array.create("java.lang.String", 2) as string[];
headers[0] = "Authorization";
headers[1] = `Bearer ${apiKey}`;
try {
request = new com.faceclaw.app.FaceclawSseRequest(
OPENAI_RESPONSES_URL,
JSON.stringify(body),
headers,
listener,
);
} catch (error) {
setTimeout(() => fail(`OpenAI request failed: ${String((error as Error)?.message ?? error)}`), 0);
return { cancel: () => {} };
}
return {
cancel: () => {
settled = true;
try {
request?.cancel();
} catch {
// ignore
}
},
};
}
/** Convert neutral conversation history to Responses API input items. */
function buildOpenAiInput(messages: LlmMessage[]): any[] {
const input: any[] = [];
for (const message of messages) {
if (typeof message.content === "string") {
input.push({ role: message.role, content: message.content });
continue;
}
let pendingText = "";
const flushText = () => {
if (!pendingText) return;
input.push({ role: message.role, content: pendingText });
pendingText = "";
};
for (const block of message.content) {
if (block.type === "text") {
pendingText += block.text;
} else if (block.type === "tool_use") {
flushText();
if (block.provider_item?.provider === "openai") {
input.push(block.provider_item.item);
} else {
input.push({
type: "function_call",
call_id: block.id,
name: block.name,
arguments: JSON.stringify(block.input ?? {}),
});
}
} else if (block.type === "tool_result") {
flushText();
input.push({
type: "function_call_output",
call_id: block.tool_use_id,
output: block.is_error ? `Error: ${block.content}` : block.content,
});
} else if (block.provider === "openai") {
flushText();
input.push(block.item);
}
}
flushText();
}
return input;
}
function finalizeOutputs(outputs: Map<number, StreamingOutput>): LlmContentBlock[] {
const content: LlmContentBlock[] = [];
for (const index of Array.from(outputs.keys()).sort((a, b) => a - b)) {
const output = outputs.get(index)!;
if (output.type === "text") {
if (output.text) content.push({ type: "text", text: output.text });
continue;
}
if (output.type === "provider_item") {
content.push({ type: "provider_item", provider: "openai", item: output.item });
continue;
}
let input: any = {};
if (output.inputJson.trim()) {
try {
input = JSON.parse(output.inputJson);
} catch {
// Let the tool handler report any required arguments that are missing.
}
}
content.push({
type: "tool_use",
id: output.id,
name: output.name,
input,
provider_item: { provider: "openai", item: output.item },
});
}
return content;
}
function findToolOutput(
outputs: Map<number, StreamingOutput>,
outputIndex: number,
itemId: string,
): Extract<StreamingOutput, { type: "tool_use" }> | null {
const indexed = outputs.get(outputIndex);
if (indexed?.type === "tool_use") return indexed;
for (const output of outputs.values()) {
if (output.type === "tool_use" && output.itemId === itemId) return output;
}
return null;
}
function extractMessageText(item: any): string {
if (!Array.isArray(item?.content)) return "";
return item.content
.filter((part: any) => part?.type === "output_text")
.map((part: any) => String(part.text ?? ""))
.join("");
}
function parseSseDataLine(line: string): any | null {
if (!line.startsWith("data:")) return null;
const payload = line.slice(5).trim();
if (!payload || payload === "[DONE]") return null;
try {
return JSON.parse(payload);
} catch {
return null;
}
}
function describeHttpError(code: number, body: string): string {
let detail = "";
try {
detail = String(JSON.parse(body)?.error?.message ?? "");
} catch {
// non-JSON error body
}
switch (code) {
case 401:
return "OpenAI: invalid API key";
case 403:
return "OpenAI: API key lacks permission";
case 429:
return "OpenAI: rate limited, try again shortly";
case 500:
case 502:
case 503:
case 504:
return "OpenAI: service unavailable, try again shortly";
default:
return `OpenAI: HTTP ${code}${detail ? ` (${detail})` : ""}`;
}
}