@stacksjs/ai 0.70.257 → 0.70.259

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.
@@ -1,368 +1,3 @@
1
- import { fetchWithRetry } from "../../utils/retry";
2
- import { recordUsage } from "../../utils/usage";
3
- import { normalizeMessagesForProvider } from "../../utils/vision";
4
- const DEFAULT_MODEL = "gpt-4o", DEFAULT_MAX_TOKENS = 4096, DEFAULT_EMBEDDING_MODEL = "text-embedding-3-small", DEFAULT_BASE_URL = "https://api.openai.com/v1";
5
- let globalConfig = null;
6
- export function configure(config) {
7
- globalConfig = config;
8
- }
9
- function getConfig(config) {
10
- const merged = { ...globalConfig, ...config };
11
- if (!merged.apiKey)
12
- merged.apiKey = process.env.OPENAI_API_KEY || "";
13
- return merged;
14
- }
15
- export function createOpenAIDriver(config) {
16
- const {
17
- apiKey,
18
- model = DEFAULT_MODEL,
19
- maxTokens = DEFAULT_MAX_TOKENS,
20
- baseUrl = DEFAULT_BASE_URL,
21
- embeddingModel = DEFAULT_EMBEDDING_MODEL
22
- } = config;
23
- return {
24
- name: "OpenAI",
25
- async process(command, systemPrompt, history) {
26
- if (!apiKey)
27
- throw Error("OpenAI API key not set. Configure your API key in settings.");
28
- const response = await fetchWithRetry(`${baseUrl}/chat/completions`, {
29
- method: "POST",
30
- headers: {
31
- "Content-Type": "application/json",
32
- Authorization: `Bearer ${apiKey}`
33
- },
34
- body: JSON.stringify({
35
- model,
36
- max_tokens: maxTokens,
37
- messages: [
38
- { role: "system", content: systemPrompt },
39
- ...history,
40
- { role: "user", content: command }
41
- ]
42
- })
43
- });
44
- if (!response.ok) {
45
- const error = await response.text();
46
- throw Error(`OpenAI API error: ${error}`);
47
- }
48
- const data = await response.json();
49
- if (!data.choices || data.choices.length === 0)
50
- throw Error("OpenAI API returned empty choices");
51
- return data.choices[0].message.content;
52
- },
53
- async* stream(command, systemPrompt, history) {
54
- if (!apiKey)
55
- throw Error("OpenAI API key not set. Configure your API key in settings.");
56
- const response = await fetch(`${baseUrl}/chat/completions`, {
57
- method: "POST",
58
- headers: {
59
- "Content-Type": "application/json",
60
- Authorization: `Bearer ${apiKey}`
61
- },
62
- body: JSON.stringify({
63
- model,
64
- max_tokens: maxTokens,
65
- stream: !0,
66
- messages: [
67
- { role: "system", content: systemPrompt },
68
- ...history,
69
- { role: "user", content: command }
70
- ]
71
- })
72
- });
73
- if (!response.ok) {
74
- const error = await response.text();
75
- throw Error(`OpenAI API error: ${error}`);
76
- }
77
- const reader = response.body?.getReader();
78
- if (!reader)
79
- throw Error("No response body");
80
- const decoder = new TextDecoder;
81
- let buffer = "";
82
- const handlePayload = function* (data) {
83
- if (data === "[DONE]")
84
- return;
85
- let parsed;
86
- try {
87
- parsed = JSON.parse(data);
88
- } catch {
89
- return;
90
- }
91
- if (parsed?.error) {
92
- const msg = parsed.error.message || JSON.stringify(parsed.error);
93
- throw Error(`[openai/stream] mid-stream error: ${msg}`);
94
- }
95
- const content = parsed.choices?.[0]?.delta?.content;
96
- if (content)
97
- yield content;
98
- };
99
- while (!0) {
100
- const { done, value } = await reader.read();
101
- if (done)
102
- break;
103
- buffer += decoder.decode(value, { stream: !0 });
104
- const lines = buffer.split(`
105
- `);
106
- buffer = lines.pop() || "";
107
- for (const line of lines)
108
- if (line.startsWith("data: "))
109
- yield* handlePayload(line.slice(6));
110
- }
111
- if (buffer.startsWith("data: "))
112
- yield* handlePayload(buffer.slice(6));
113
- },
114
- async embed(input) {
115
- if (!apiKey)
116
- throw Error("OpenAI API key not set. Configure your API key in settings.");
117
- const response = await fetch(`${baseUrl}/embeddings`, {
118
- method: "POST",
119
- headers: {
120
- "Content-Type": "application/json",
121
- Authorization: `Bearer ${apiKey}`
122
- },
123
- body: JSON.stringify({
124
- model: embeddingModel,
125
- input
126
- })
127
- });
128
- if (!response.ok) {
129
- const error = await response.text();
130
- throw Error(`OpenAI Embeddings API error: ${error}`);
131
- }
132
- const data = await response.json();
133
- if (Array.isArray(input))
134
- return data.data.map((d) => d.embedding);
135
- return data.data[0].embedding;
136
- }
137
- };
138
- }
139
- export async function chat(messages, options = {}) {
140
- const config = getConfig(), {
141
- model = DEFAULT_MODEL,
142
- maxTokens = DEFAULT_MAX_TOKENS,
143
- temperature,
144
- topP,
145
- stop,
146
- tools,
147
- toolChoice,
148
- responseFormat
149
- } = options, normalizedMessages = normalizeMessagesForProvider(messages, "openai"), startedAt = Date.now(), body = {
150
- model,
151
- max_tokens: maxTokens,
152
- temperature,
153
- top_p: topP,
154
- stop,
155
- messages: normalizedMessages
156
- };
157
- if (tools?.length)
158
- body.tools = tools.map((tool) => ({
159
- type: "function",
160
- function: {
161
- name: tool.name,
162
- description: tool.description,
163
- parameters: tool.parameters ?? { type: "object", properties: {} }
164
- }
165
- }));
166
- if (toolChoice !== void 0)
167
- body.tool_choice = typeof toolChoice === "object" ? { type: "function", function: { name: toolChoice.name } } : toolChoice;
168
- if (responseFormat && responseFormat.type !== "text")
169
- body.response_format = responseFormat;
170
- const response = await fetchWithRetry(`${config.baseUrl || DEFAULT_BASE_URL}/chat/completions`, {
171
- method: "POST",
172
- headers: {
173
- "Content-Type": "application/json",
174
- Authorization: `Bearer ${config.apiKey}`
175
- },
176
- body: JSON.stringify(body)
177
- });
178
- if (!response.ok) {
179
- const error = await response.text();
180
- throw Error(`OpenAI API error: ${error}`);
181
- }
182
- const data = await response.json();
183
- if (!data.choices || data.choices.length === 0)
184
- throw Error("OpenAI API returned empty choices");
185
- const result = {
186
- content: data.choices[0].message.content,
187
- model: data.model,
188
- usage: {
189
- promptTokens: data.usage?.prompt_tokens || 0,
190
- completionTokens: data.usage?.completion_tokens || 0,
191
- totalTokens: data.usage?.total_tokens || 0
192
- },
193
- finishReason: data.choices[0].finish_reason
194
- };
195
- recordUsage({
196
- provider: "openai",
197
- model: data.model,
198
- promptTokens: result.usage.promptTokens,
199
- completionTokens: result.usage.completionTokens,
200
- totalTokens: result.usage.totalTokens,
201
- durationMs: Date.now() - startedAt,
202
- timestamp: Date.now()
203
- });
204
- return result;
205
- }
206
- export async function* streamChat(messages, options = {}) {
207
- const config = getConfig(), {
208
- model = DEFAULT_MODEL,
209
- maxTokens = DEFAULT_MAX_TOKENS,
210
- temperature,
211
- topP,
212
- stop
213
- } = options, response = await fetch(`${config.baseUrl || DEFAULT_BASE_URL}/chat/completions`, {
214
- method: "POST",
215
- headers: {
216
- "Content-Type": "application/json",
217
- Authorization: `Bearer ${config.apiKey}`
218
- },
219
- body: JSON.stringify({
220
- model,
221
- max_tokens: maxTokens,
222
- temperature,
223
- top_p: topP,
224
- stop,
225
- stream: !0,
226
- messages: normalizeMessagesForProvider(messages, "openai")
227
- })
228
- });
229
- if (!response.ok) {
230
- const error = await response.text();
231
- throw Error(`OpenAI API error: ${error}`);
232
- }
233
- const reader = response.body?.getReader();
234
- if (!reader)
235
- throw Error("No response body");
236
- const decoder = new TextDecoder;
237
- let buffer = "";
238
- while (!0) {
239
- const { done, value } = await reader.read();
240
- if (done)
241
- break;
242
- buffer += decoder.decode(value, { stream: !0 });
243
- const lines = buffer.split(`
244
- `);
245
- buffer = lines.pop() || "";
246
- for (const line of lines)
247
- if (line.startsWith("data: ")) {
248
- const data = line.slice(6);
249
- if (data === "[DONE]")
250
- continue;
251
- try {
252
- const content = JSON.parse(data).choices[0]?.delta?.content;
253
- if (content)
254
- yield content;
255
- } catch {}
256
- }
257
- }
258
- }
259
- export async function embed(input, model = DEFAULT_EMBEDDING_MODEL) {
260
- const config = getConfig(), response = await fetch(`${config.baseUrl || DEFAULT_BASE_URL}/embeddings`, {
261
- method: "POST",
262
- headers: {
263
- "Content-Type": "application/json",
264
- Authorization: `Bearer ${config.apiKey}`
265
- },
266
- body: JSON.stringify({ model, input })
267
- });
268
- if (!response.ok) {
269
- const error = await response.text();
270
- throw Error(`OpenAI Embeddings API error: ${error}`);
271
- }
272
- const data = await response.json();
273
- if (Array.isArray(input))
274
- return data.data.map((d) => d.embedding);
275
- return data.data[0].embedding;
276
- }
277
- export async function generateImage(prompt, options = {}) {
278
- const config = getConfig(), {
279
- model = "dall-e-3",
280
- size = "1024x1024",
281
- quality = "standard",
282
- n = 1,
283
- responseFormat = "url"
284
- } = options, response = await fetch(`${config.baseUrl || DEFAULT_BASE_URL}/images/generations`, {
285
- method: "POST",
286
- headers: {
287
- "Content-Type": "application/json",
288
- Authorization: `Bearer ${config.apiKey}`
289
- },
290
- body: JSON.stringify({
291
- model,
292
- prompt,
293
- size,
294
- quality,
295
- n,
296
- response_format: responseFormat
297
- })
298
- });
299
- if (!response.ok) {
300
- const error = await response.text();
301
- throw Error(`OpenAI Image API error: ${error}`);
302
- }
303
- return (await response.json()).data;
304
- }
305
- export async function transcribe(audioFile, options = {}) {
306
- const config = getConfig(), formData = new FormData;
307
- formData.append("file", audioFile);
308
- formData.append("model", options.model || "whisper-1");
309
- if (options.language)
310
- formData.append("language", options.language);
311
- if (options.prompt)
312
- formData.append("prompt", options.prompt);
313
- if (options.responseFormat)
314
- formData.append("response_format", options.responseFormat);
315
- if (options.temperature !== void 0)
316
- formData.append("temperature", String(options.temperature));
317
- const response = await fetch(`${config.baseUrl || DEFAULT_BASE_URL}/audio/transcriptions`, {
318
- method: "POST",
319
- headers: {
320
- Authorization: `Bearer ${config.apiKey}`
321
- },
322
- body: formData
323
- });
324
- if (!response.ok) {
325
- const error = await response.text();
326
- throw Error(`OpenAI Whisper API error: ${error}`);
327
- }
328
- return response.json();
329
- }
330
- export async function textToSpeech(input, options = {}) {
331
- const config = getConfig(), {
332
- model = "tts-1",
333
- voice = "alloy",
334
- responseFormat = "mp3",
335
- speed = 1
336
- } = options, response = await fetch(`${config.baseUrl || DEFAULT_BASE_URL}/audio/speech`, {
337
- method: "POST",
338
- headers: {
339
- "Content-Type": "application/json",
340
- Authorization: `Bearer ${config.apiKey}`
341
- },
342
- body: JSON.stringify({
343
- model,
344
- input,
345
- voice,
346
- response_format: responseFormat,
347
- speed
348
- })
349
- });
350
- if (!response.ok) {
351
- const error = await response.text();
352
- throw Error(`OpenAI TTS API error: ${error}`);
353
- }
354
- return response.arrayBuffer();
355
- }
356
- export const openaiDriver = {
357
- create: createOpenAIDriver
358
- }, openai = {
359
- configure,
360
- chat,
361
- streamChat,
362
- embed,
363
- generateImage,
364
- transcribe,
365
- textToSpeech,
366
- createDriver: createOpenAIDriver
367
- };
368
- export default openai;
1
+ import{fetchWithRetry}from"../../utils/retry";import{recordUsage}from"../../utils/usage";import{normalizeMessagesForProvider}from"../../utils/vision";const DEFAULT_MODEL="gpt-4o",DEFAULT_MAX_TOKENS=4096,DEFAULT_EMBEDDING_MODEL="text-embedding-3-small",DEFAULT_BASE_URL="https://api.openai.com/v1";let globalConfig=null;export function configure(config){globalConfig=config}function getConfig(config){const merged={...globalConfig,...config};if(!merged.apiKey)merged.apiKey=process.env.OPENAI_API_KEY||"";return merged}export function createOpenAIDriver(config){const{apiKey,model=DEFAULT_MODEL,maxTokens=DEFAULT_MAX_TOKENS,baseUrl=DEFAULT_BASE_URL,embeddingModel=DEFAULT_EMBEDDING_MODEL}=config;return{name:"OpenAI",async process(command,systemPrompt,history){if(!apiKey)throw Error("OpenAI API key not set. Configure your API key in settings.");const response=await fetchWithRetry(`${baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${apiKey}`},body:JSON.stringify({model,max_tokens:maxTokens,messages:[{role:"system",content:systemPrompt},...history,{role:"user",content:command}]})});if(!response.ok){const error=await response.text();throw Error(`OpenAI API error: ${error}`)}const data=await response.json();if(!data.choices||data.choices.length===0)throw Error("OpenAI API returned empty choices");return data.choices[0].message.content},async*stream(command,systemPrompt,history){if(!apiKey)throw Error("OpenAI API key not set. Configure your API key in settings.");const response=await fetch(`${baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${apiKey}`},body:JSON.stringify({model,max_tokens:maxTokens,stream:!0,messages:[{role:"system",content:systemPrompt},...history,{role:"user",content:command}]})});if(!response.ok){const error=await response.text();throw Error(`OpenAI API error: ${error}`)}const reader=response.body?.getReader();if(!reader)throw Error("No response body");const decoder=new TextDecoder;let buffer="";const handlePayload=function*(data){if(data==="[DONE]")return;let parsed;try{parsed=JSON.parse(data)}catch{return}if(parsed?.error){const msg=parsed.error.message||JSON.stringify(parsed.error);throw Error(`[openai/stream] mid-stream error: ${msg}`)}const content=parsed.choices?.[0]?.delta?.content;if(content)yield content};while(!0){const{done,value}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});const lines=buffer.split(`
2
+ `);buffer=lines.pop()||"";for(const line of lines)if(line.startsWith("data: "))yield*handlePayload(line.slice(6))}if(buffer.startsWith("data: "))yield*handlePayload(buffer.slice(6))},async embed(input){if(!apiKey)throw Error("OpenAI API key not set. Configure your API key in settings.");const response=await fetch(`${baseUrl}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${apiKey}`},body:JSON.stringify({model:embeddingModel,input})});if(!response.ok){const error=await response.text();throw Error(`OpenAI Embeddings API error: ${error}`)}const data=await response.json();if(Array.isArray(input))return data.data.map((d)=>d.embedding);return data.data[0].embedding}}}export async function chat(messages,options={}){const config=getConfig(),{model=DEFAULT_MODEL,maxTokens=DEFAULT_MAX_TOKENS,temperature,topP,stop,tools,toolChoice,responseFormat}=options,normalizedMessages=normalizeMessagesForProvider(messages,"openai"),startedAt=Date.now(),body={model,max_tokens:maxTokens,temperature,top_p:topP,stop,messages:normalizedMessages};if(tools?.length)body.tools=tools.map((tool)=>({type:"function",function:{name:tool.name,description:tool.description,parameters:tool.parameters??{type:"object",properties:{}}}}));if(toolChoice!==void 0)body.tool_choice=typeof toolChoice==="object"?{type:"function",function:{name:toolChoice.name}}:toolChoice;if(responseFormat&&responseFormat.type!=="text")body.response_format=responseFormat;const response=await fetchWithRetry(`${config.baseUrl||DEFAULT_BASE_URL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${config.apiKey}`},body:JSON.stringify(body)});if(!response.ok){const error=await response.text();throw Error(`OpenAI API error: ${error}`)}const data=await response.json();if(!data.choices||data.choices.length===0)throw Error("OpenAI API returned empty choices");const result={content:data.choices[0].message.content,model:data.model,usage:{promptTokens:data.usage?.prompt_tokens||0,completionTokens:data.usage?.completion_tokens||0,totalTokens:data.usage?.total_tokens||0},finishReason:data.choices[0].finish_reason};recordUsage({provider:"openai",model:data.model,promptTokens:result.usage.promptTokens,completionTokens:result.usage.completionTokens,totalTokens:result.usage.totalTokens,durationMs:Date.now()-startedAt,timestamp:Date.now()});return result}export async function*streamChat(messages,options={}){const config=getConfig(),{model=DEFAULT_MODEL,maxTokens=DEFAULT_MAX_TOKENS,temperature,topP,stop}=options,response=await fetch(`${config.baseUrl||DEFAULT_BASE_URL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${config.apiKey}`},body:JSON.stringify({model,max_tokens:maxTokens,temperature,top_p:topP,stop,stream:!0,messages:normalizeMessagesForProvider(messages,"openai")})});if(!response.ok){const error=await response.text();throw Error(`OpenAI API error: ${error}`)}const reader=response.body?.getReader();if(!reader)throw Error("No response body");const decoder=new TextDecoder;let buffer="";while(!0){const{done,value}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});const lines=buffer.split(`
3
+ `);buffer=lines.pop()||"";for(const line of lines)if(line.startsWith("data: ")){const data=line.slice(6);if(data==="[DONE]")continue;try{const content=JSON.parse(data).choices[0]?.delta?.content;if(content)yield content}catch{}}}}export async function embed(input,model=DEFAULT_EMBEDDING_MODEL){const config=getConfig(),response=await fetch(`${config.baseUrl||DEFAULT_BASE_URL}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${config.apiKey}`},body:JSON.stringify({model,input})});if(!response.ok){const error=await response.text();throw Error(`OpenAI Embeddings API error: ${error}`)}const data=await response.json();if(Array.isArray(input))return data.data.map((d)=>d.embedding);return data.data[0].embedding}export async function generateImage(prompt,options={}){const config=getConfig(),{model="dall-e-3",size="1024x1024",quality="standard",n=1,responseFormat="url"}=options,response=await fetch(`${config.baseUrl||DEFAULT_BASE_URL}/images/generations`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${config.apiKey}`},body:JSON.stringify({model,prompt,size,quality,n,response_format:responseFormat})});if(!response.ok){const error=await response.text();throw Error(`OpenAI Image API error: ${error}`)}return(await response.json()).data}export async function transcribe(audioFile,options={}){const config=getConfig(),formData=new FormData;formData.append("file",audioFile);formData.append("model",options.model||"whisper-1");if(options.language)formData.append("language",options.language);if(options.prompt)formData.append("prompt",options.prompt);if(options.responseFormat)formData.append("response_format",options.responseFormat);if(options.temperature!==void 0)formData.append("temperature",String(options.temperature));const response=await fetch(`${config.baseUrl||DEFAULT_BASE_URL}/audio/transcriptions`,{method:"POST",headers:{Authorization:`Bearer ${config.apiKey}`},body:formData});if(!response.ok){const error=await response.text();throw Error(`OpenAI Whisper API error: ${error}`)}return response.json()}export async function textToSpeech(input,options={}){const config=getConfig(),{model="tts-1",voice="alloy",responseFormat="mp3",speed=1}=options,response=await fetch(`${config.baseUrl||DEFAULT_BASE_URL}/audio/speech`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${config.apiKey}`},body:JSON.stringify({model,input,voice,response_format:responseFormat,speed})});if(!response.ok){const error=await response.text();throw Error(`OpenAI TTS API error: ${error}`)}return response.arrayBuffer()}export const openaiDriver={create:createOpenAIDriver},openai={configure,chat,streamChat,embed,generateImage,transcribe,textToSpeech,createDriver:createOpenAIDriver};export default openai;