call-ai 0.10.2 → 0.11.0-dev-preview3

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.
Files changed (71) hide show
  1. package/README.md +60 -58
  2. package/api-core.d.ts +13 -0
  3. package/{dist/api-core.js → api-core.js} +51 -126
  4. package/api-core.js.map +1 -0
  5. package/api.d.ts +4 -0
  6. package/api.js +364 -0
  7. package/api.js.map +1 -0
  8. package/api.ts.off +595 -0
  9. package/{dist/error-handling.d.ts → error-handling.d.ts} +4 -2
  10. package/{dist/error-handling.js → error-handling.js} +34 -70
  11. package/error-handling.js.map +1 -0
  12. package/image.d.ts +2 -0
  13. package/{dist/image.js → image.js} +10 -33
  14. package/image.js.map +1 -0
  15. package/index.d.ts +6 -0
  16. package/index.js +7 -0
  17. package/index.js.map +1 -0
  18. package/index.ts.bak +16 -0
  19. package/key-management.d.ts +29 -0
  20. package/key-management.js +189 -0
  21. package/key-management.js.map +1 -0
  22. package/{dist/non-streaming.d.ts → non-streaming.d.ts} +5 -8
  23. package/{dist/non-streaming.js → non-streaming.js} +28 -87
  24. package/non-streaming.js.map +1 -0
  25. package/package.json +15 -31
  26. package/response-metadata.d.ts +6 -0
  27. package/response-metadata.js +22 -0
  28. package/response-metadata.js.map +1 -0
  29. package/strategies/index.d.ts +2 -0
  30. package/strategies/index.js +3 -0
  31. package/strategies/index.js.map +1 -0
  32. package/strategies/model-strategies.d.ts +6 -0
  33. package/{dist/strategies → strategies}/model-strategies.js +26 -72
  34. package/strategies/model-strategies.js.map +1 -0
  35. package/strategies/strategy-selector.d.ts +2 -0
  36. package/strategies/strategy-selector.js +66 -0
  37. package/strategies/strategy-selector.js.map +1 -0
  38. package/streaming.d.ts +4 -0
  39. package/{dist/streaming.js → streaming.js} +66 -184
  40. package/streaming.js.map +1 -0
  41. package/streaming.ts.off +571 -0
  42. package/tsconfig.json +18 -0
  43. package/types.d.ts +226 -0
  44. package/types.js +33 -0
  45. package/types.js.map +1 -0
  46. package/utils.d.ts +32 -0
  47. package/utils.js +129 -0
  48. package/utils.js.map +1 -0
  49. package/version.d.ts +1 -0
  50. package/version.js +2 -0
  51. package/version.js.map +1 -0
  52. package/dist/api-core.d.ts +0 -40
  53. package/dist/api.d.ts +0 -15
  54. package/dist/api.js +0 -498
  55. package/dist/image.d.ts +0 -12
  56. package/dist/index.d.ts +0 -7
  57. package/dist/index.js +0 -32
  58. package/dist/key-management.d.ts +0 -43
  59. package/dist/key-management.js +0 -312
  60. package/dist/response-metadata.d.ts +0 -18
  61. package/dist/response-metadata.js +0 -44
  62. package/dist/strategies/index.d.ts +0 -5
  63. package/dist/strategies/index.js +0 -21
  64. package/dist/strategies/model-strategies.d.ts +0 -24
  65. package/dist/strategies/strategy-selector.d.ts +0 -8
  66. package/dist/strategies/strategy-selector.js +0 -79
  67. package/dist/streaming.d.ts +0 -7
  68. package/dist/types.d.ts +0 -226
  69. package/dist/types.js +0 -5
  70. package/dist/utils.d.ts +0 -8
  71. package/dist/utils.js +0 -52
package/dist/api.js DELETED
@@ -1,498 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getMeta = void 0;
4
- exports.callAi = callAi;
5
- const strategies_1 = require("./strategies");
6
- const response_metadata_1 = require("./response-metadata");
7
- Object.defineProperty(exports, "getMeta", { enumerable: true, get: function () { return response_metadata_1.getMeta; } });
8
- const key_management_1 = require("./key-management");
9
- const error_handling_1 = require("./error-handling");
10
- const api_core_1 = require("./api-core");
11
- const non_streaming_1 = require("./non-streaming");
12
- const streaming_1 = require("./streaming");
13
- // Import package version for debugging
14
- // eslint-disable-next-line @typescript-eslint/no-var-requires
15
- const PACKAGE_VERSION = require("../package.json").version;
16
- // Default fallback model when the primary model fails or is unavailable
17
- const FALLBACK_MODEL = "openrouter/auto";
18
- /**
19
- * Make an AI API call with the given options
20
- * @param prompt User prompt as string or an array of message objects
21
- * @param options Configuration options including optional schema for structured output
22
- * @returns A Promise that resolves to the complete response string when streaming is disabled,
23
- * or a Promise that resolves to an AsyncGenerator when streaming is enabled.
24
- * The AsyncGenerator yields partial responses as they arrive.
25
- */
26
- function callAi(prompt, options = {}) {
27
- // Check if we need to force streaming based on model strategy
28
- const schemaStrategy = (0, strategies_1.chooseSchemaStrategy)(options.model, options.schema || null);
29
- // We no longer set a default maxTokens
30
- // Will only include max_tokens in the request if explicitly set by the user
31
- // Handle special case: Claude with tools requires streaming
32
- if (!options.stream && schemaStrategy.shouldForceStream) {
33
- // Buffer streaming results into a single response
34
- return bufferStreamingResults(prompt, options);
35
- }
36
- // Handle normal non-streaming mode
37
- if (options.stream !== true) {
38
- return callAINonStreaming(prompt, options);
39
- }
40
- // Handle streaming mode - return a Promise that resolves to an AsyncGenerator
41
- // but also supports legacy non-awaited usage for backward compatibility
42
- const streamPromise = (async () => {
43
- // Do setup and validation before returning the generator
44
- const { endpoint, requestOptions, model, schemaStrategy } = prepareRequestParams(prompt, { ...options, stream: true });
45
- // Use either explicit debug option or global debug flag
46
- const debug = options.debug || key_management_1.globalDebug;
47
- if (debug) {
48
- console.log(`[callAi:${PACKAGE_VERSION}] Making fetch request to: ${endpoint}`);
49
- console.log(`[callAi:${PACKAGE_VERSION}] With model: ${model}`);
50
- console.log(`[callAi:${PACKAGE_VERSION}] Request headers:`, JSON.stringify(requestOptions.headers));
51
- }
52
- let response;
53
- try {
54
- response = await fetch(endpoint, requestOptions);
55
- if (options.debug) {
56
- console.log(`[callAi:${PACKAGE_VERSION}] Fetch completed with status:`, response.status, response.statusText);
57
- // Log all headers
58
- console.log(`[callAi:${PACKAGE_VERSION}] Response headers:`);
59
- response.headers.forEach((value, name) => {
60
- console.log(`[callAi:${PACKAGE_VERSION}] ${name}: ${value}`);
61
- });
62
- // Clone response for diagnostic purposes only
63
- const diagnosticResponse = response.clone();
64
- try {
65
- // Try to get the response as text for debugging
66
- const responseText = await diagnosticResponse.text();
67
- console.log(`[callAi:${PACKAGE_VERSION}] First 500 chars of response body:`, responseText.substring(0, 500) +
68
- (responseText.length > 500 ? "..." : ""));
69
- }
70
- catch (e) {
71
- console.log(`[callAi:${PACKAGE_VERSION}] Could not read response body for diagnostics:`, e);
72
- }
73
- }
74
- }
75
- catch (fetchError) {
76
- if (options.debug) {
77
- console.error(`[callAi:${PACKAGE_VERSION}] Network error during fetch:`, fetchError);
78
- }
79
- throw fetchError; // Re-throw network errors
80
- }
81
- // Explicitly check for HTTP error status and log extensively if debug is enabled
82
- // Safe access to headers in case of mock environments
83
- const contentType = response?.headers?.get?.("content-type") || "";
84
- if (options.debug) {
85
- console.log(`[callAi:${PACKAGE_VERSION}] Response.ok =`, response.ok);
86
- console.log(`[callAi:${PACKAGE_VERSION}] Response.status =`, response.status);
87
- console.log(`[callAi:${PACKAGE_VERSION}] Response.statusText =`, response.statusText);
88
- console.log(`[callAi:${PACKAGE_VERSION}] Response.type =`, response.type);
89
- console.log(`[callAi:${PACKAGE_VERSION}] Content-Type =`, contentType);
90
- }
91
- // Browser-compatible error handling - must check BOTH status code AND content-type
92
- // Some browsers will report status 200 for SSE streams even when server returns 400
93
- const hasHttpError = !response.ok || response.status >= 400;
94
- const hasJsonError = contentType.includes("application/json");
95
- if (hasHttpError || hasJsonError) {
96
- if (options.debug) {
97
- console.log(`[callAi:${PACKAGE_VERSION}] ⚠️ Error detected - HTTP Status: ${response.status}, Content-Type: ${contentType}`);
98
- }
99
- // Handle the error with fallback model if appropriate
100
- if (!options.skipRetry) {
101
- const clonedResponse = response.clone();
102
- let isInvalidModel = false;
103
- try {
104
- // Check if this is an invalid model error
105
- const modelCheckResult = await (0, error_handling_1.checkForInvalidModelError)(clonedResponse, model, options.debug);
106
- isInvalidModel = modelCheckResult.isInvalidModel;
107
- if (isInvalidModel) {
108
- if (options.debug) {
109
- console.log(`[callAi:${PACKAGE_VERSION}] Retrying with fallback model: ${FALLBACK_MODEL}`);
110
- }
111
- // Retry with fallback model
112
- return (await callAi(prompt, {
113
- ...options,
114
- model: FALLBACK_MODEL,
115
- }));
116
- }
117
- }
118
- catch (modelCheckError) {
119
- console.error(`[callAi:${PACKAGE_VERSION}] Error during model check:`, modelCheckError);
120
- // Continue with normal error handling
121
- }
122
- }
123
- // Extract error details from response
124
- try {
125
- // Try to get error details from the response body
126
- const errorBody = await response.text();
127
- if (options.debug) {
128
- console.log(`[callAi:${PACKAGE_VERSION}] Error body:`, errorBody);
129
- }
130
- try {
131
- // Try to parse JSON error
132
- const errorJson = JSON.parse(errorBody);
133
- if (options.debug) {
134
- console.log(`[callAi:${PACKAGE_VERSION}] Parsed error:`, errorJson);
135
- }
136
- // Extract message from OpenRouter error format
137
- let errorMessage = "";
138
- // Handle common error formats
139
- if (errorJson.error &&
140
- typeof errorJson.error === "object" &&
141
- errorJson.error.message) {
142
- // OpenRouter/OpenAI format: { error: { message: "..." } }
143
- errorMessage = errorJson.error.message;
144
- }
145
- else if (errorJson.error && typeof errorJson.error === "string") {
146
- // Simple error format: { error: "..." }
147
- errorMessage = errorJson.error;
148
- }
149
- else if (errorJson.message) {
150
- // Generic format: { message: "..." }
151
- errorMessage = errorJson.message;
152
- }
153
- else {
154
- // Fallback with status details
155
- errorMessage = `API returned ${response.status}: ${response.statusText}`;
156
- }
157
- // Add status details to error message if not already included
158
- if (!errorMessage.includes(response.status.toString())) {
159
- errorMessage = `${errorMessage} (Status: ${response.status})`;
160
- }
161
- if (options.debug) {
162
- console.log(`[callAi:${PACKAGE_VERSION}] Extracted error message:`, errorMessage);
163
- }
164
- // Create error with standard format
165
- const error = new Error(errorMessage);
166
- // Add useful metadata
167
- error.status = response.status;
168
- error.statusText = response.statusText;
169
- error.details = errorJson;
170
- error.contentType = contentType;
171
- throw error;
172
- }
173
- catch (jsonError) {
174
- // If JSON parsing fails, extract a useful message from the raw error body
175
- if (options.debug) {
176
- console.log(`[callAi:${PACKAGE_VERSION}] JSON parse error:`, jsonError);
177
- }
178
- // Try to extract a useful message even from non-JSON text
179
- let errorMessage = "";
180
- // Check if it's a plain text error message
181
- if (errorBody && errorBody.trim().length > 0) {
182
- // Limit length for readability
183
- errorMessage =
184
- errorBody.length > 100
185
- ? errorBody.substring(0, 100) + "..."
186
- : errorBody;
187
- }
188
- else {
189
- errorMessage = `API error: ${response.status} ${response.statusText}`;
190
- }
191
- // Add status details if not already included
192
- if (!errorMessage.includes(response.status.toString())) {
193
- errorMessage = `${errorMessage} (Status: ${response.status})`;
194
- }
195
- if (options.debug) {
196
- console.log(`[callAi:${PACKAGE_VERSION}] Extracted text error message:`, errorMessage);
197
- }
198
- const error = new Error(errorMessage);
199
- error.status = response.status;
200
- error.statusText = response.statusText;
201
- error.details = errorBody;
202
- error.contentType = contentType;
203
- throw error;
204
- }
205
- }
206
- catch (responseError) {
207
- if (responseError instanceof Error) {
208
- // Re-throw if it's already properly formatted
209
- throw responseError;
210
- }
211
- // Fallback error
212
- const error = new Error(`API returned ${response.status}: ${response.statusText}`);
213
- error.status = response.status;
214
- error.statusText = response.statusText;
215
- error.contentType = contentType;
216
- throw error;
217
- }
218
- }
219
- // Only if response is OK, create and return the streaming generator
220
- if (options.debug) {
221
- console.log(`[callAi:${PACKAGE_VERSION}] Response OK, creating streaming generator`);
222
- }
223
- return (0, streaming_1.createStreamingGenerator)(response, options, schemaStrategy, model);
224
- })();
225
- // For backward compatibility with v0.6.x where users didn't await the result
226
- if (process.env.NODE_ENV !== "production") {
227
- if (options.debug) {
228
- console.warn(`[callAi:${PACKAGE_VERSION}] No await found - using legacy streaming pattern. This will be removed in a future version and may cause issues with certain models.`);
229
- }
230
- }
231
- // Create a proxy object that acts both as a Promise and an AsyncGenerator for backward compatibility
232
- // @ts-ignore - We're deliberately implementing a proxy with dual behavior
233
- return (0, api_core_1.createBackwardCompatStreamingProxy)(streamPromise);
234
- }
235
- /**
236
- * Buffer streaming results into a single response for cases where
237
- * we need to use streaming internally but the caller requested non-streaming
238
- */
239
- async function bufferStreamingResults(prompt, options) {
240
- // Create a copy of options with streaming enabled
241
- const streamingOptions = {
242
- ...options,
243
- stream: true,
244
- };
245
- try {
246
- // Get streaming generator
247
- const generator = (await callAi(prompt, streamingOptions));
248
- // For Claude JSON responses, take only the last chunk (the final processed result)
249
- // For all other cases, concatenate chunks as before
250
- const isClaudeJson = /claude/.test(options.model || "") && options.schema;
251
- if (isClaudeJson) {
252
- // For Claude with JSON schema, we only want the last yielded value
253
- // which will be the complete, properly processed JSON
254
- let lastChunk = "";
255
- for await (const chunk of generator) {
256
- // Replace the last chunk entirely instead of concatenating
257
- lastChunk = chunk;
258
- }
259
- return lastChunk;
260
- }
261
- else {
262
- // For all other cases, concatenate chunks
263
- let result = "";
264
- for await (const chunk of generator) {
265
- result += chunk;
266
- }
267
- return result;
268
- }
269
- }
270
- catch (error) {
271
- // Handle errors with standard API error handling
272
- await (0, error_handling_1.handleApiError)(error, "Buffered streaming", options.debug, {
273
- apiKey: options.apiKey,
274
- endpoint: options.endpoint,
275
- skipRefresh: options.skipRefresh,
276
- refreshToken: options.refreshToken,
277
- updateRefreshToken: options.updateRefreshToken,
278
- });
279
- // If we get here, key was refreshed successfully, retry the operation with the new key
280
- // Retry with the refreshed key
281
- return bufferStreamingResults(prompt, {
282
- ...options,
283
- apiKey: key_management_1.keyStore.current || undefined, // Use the refreshed key from keyStore
284
- });
285
- }
286
- // This line should never be reached, but it satisfies the linter by ensuring
287
- // all code paths return a value
288
- throw new Error("Unexpected code path in bufferStreamingResults");
289
- }
290
- /**
291
- * Standardized API error handler
292
- */
293
- // createBackwardCompatStreamingProxy is imported from api-core.ts
294
- // handleApiError is imported from error-handling.ts
295
- // checkForInvalidModelError is imported from error-handling.ts
296
- /**
297
- * Prepare request parameters common to both streaming and non-streaming calls
298
- */
299
- function prepareRequestParams(prompt, options) {
300
- // First try to get the API key from options or window globals
301
- let apiKey = options.apiKey ||
302
- key_management_1.keyStore.current || // Try keyStore first in case it was refreshed in a previous call
303
- (typeof window !== "undefined" ? window.CALLAI_API_KEY : null);
304
- const schema = options.schema || null;
305
- // If no API key exists, we won't throw immediately. We'll continue and let handleApiError
306
- // attempt to fetch a key if needed. This will be handled later in the call chain.
307
- // Select the appropriate strategy based on model and schema
308
- const schemaStrategy = (0, strategies_1.chooseSchemaStrategy)(options.model, schema);
309
- const model = schemaStrategy.model;
310
- // Get custom chat API origin if set
311
- const customChatOrigin = options.chatUrl ||
312
- (typeof window !== "undefined" ? window.CALLAI_CHAT_URL : null) ||
313
- (typeof process !== "undefined" && process.env
314
- ? process.env.CALLAI_CHAT_URL
315
- : null);
316
- // Use custom origin or default OpenRouter URL
317
- const endpoint = options.endpoint ||
318
- (customChatOrigin
319
- ? `${customChatOrigin}/api/v1/chat/completions`
320
- : "https://openrouter.ai/api/v1/chat/completions");
321
- // Handle both string prompts and message arrays for backward compatibility
322
- const messages = Array.isArray(prompt)
323
- ? prompt
324
- : [{ role: "user", content: prompt }];
325
- // Common parameters for both streaming and non-streaming
326
- const requestParams = {
327
- model,
328
- messages,
329
- stream: options.stream !== undefined ? options.stream : false,
330
- };
331
- // Only include temperature if explicitly set
332
- if (options.temperature !== undefined) {
333
- requestParams.temperature = options.temperature;
334
- }
335
- // Only include top_p if explicitly set
336
- if (options.topP !== undefined) {
337
- requestParams.top_p = options.topP;
338
- }
339
- // Only include max_tokens if explicitly set
340
- if (options.maxTokens !== undefined) {
341
- requestParams.max_tokens = options.maxTokens;
342
- }
343
- // Add optional parameters if specified
344
- if (options.stop) {
345
- // Handle both single string and array of stop sequences
346
- requestParams.stop = Array.isArray(options.stop)
347
- ? options.stop
348
- : [options.stop];
349
- }
350
- // Add response_format parameter for models that support JSON output
351
- if (options.responseFormat === "json") {
352
- requestParams.response_format = { type: "json_object" };
353
- }
354
- // Add schema structure if provided (for function calling/JSON mode)
355
- if (schema) {
356
- // Apply schema-specific parameters using the selected strategy
357
- Object.assign(requestParams, schemaStrategy.prepareRequest(schema, messages));
358
- }
359
- // HTTP headers for the request
360
- const headers = {
361
- Authorization: `Bearer ${apiKey}`,
362
- "Content-Type": "application/json",
363
- "HTTP-Referer": options.referer || "https://vibes.diy",
364
- "X-Title": options.title || "Vibes",
365
- };
366
- // Add any additional headers
367
- if (options.headers) {
368
- Object.assign(headers, options.headers);
369
- }
370
- // Build the requestOptions object for fetch
371
- const requestOptions = {
372
- method: "POST",
373
- headers: {
374
- ...headers,
375
- "Content-Type": "application/json",
376
- },
377
- body: JSON.stringify(requestParams),
378
- };
379
- // If we don't have an API key, throw a clear error that can be caught and handled
380
- // by the error handling system to trigger key fetching
381
- if (!apiKey) {
382
- throw new Error("API key is required. Provide it via options.apiKey or set window.CALLAI_API_KEY");
383
- }
384
- // Debug logging for request payload
385
- if (options.debug) {
386
- console.log(`[callAi-prepareRequest:raw] Endpoint: ${endpoint}`);
387
- console.log(`[callAi-prepareRequest:raw] Model: ${model}`);
388
- console.log(`[callAi-prepareRequest:raw] Payload:`, JSON.stringify(requestParams));
389
- }
390
- return { apiKey, model, endpoint, requestOptions, schemaStrategy };
391
- }
392
- /**
393
- * Internal implementation for non-streaming API calls
394
- */
395
- async function callAINonStreaming(prompt, options = {}, isRetry = false) {
396
- try {
397
- // Start timing for metadata
398
- const startTime = Date.now();
399
- // Create metadata object
400
- const meta = {
401
- model: options.model || "unknown",
402
- timing: {
403
- startTime: startTime,
404
- },
405
- };
406
- const { endpoint, requestOptions, model, schemaStrategy } = prepareRequestParams(prompt, options);
407
- const response = await fetch(endpoint, requestOptions);
408
- // We don't store the raw Response object in metadata anymore
409
- // Handle HTTP errors, with potential fallback for invalid model
410
- if (!response.ok || response.status >= 400) {
411
- const { isInvalidModel } = await (0, error_handling_1.checkForInvalidModelError)(response, model, options.debug);
412
- if (isInvalidModel) {
413
- // Retry with fallback model
414
- return callAINonStreaming(prompt, { ...options, model: FALLBACK_MODEL }, true);
415
- }
416
- // Create a proper error object with the status code preserved
417
- const error = new Error(`HTTP error! Status: ${response.status}`);
418
- // Add status code as a property of the error object
419
- error.status = response.status;
420
- error.statusCode = response.status; // Add statusCode for compatibility with different error patterns
421
- throw error;
422
- }
423
- let result;
424
- // For Claude, use text() instead of json() to avoid potential hanging
425
- if (/claude/i.test(model)) {
426
- try {
427
- result = await (0, non_streaming_1.extractClaudeResponse)(response);
428
- }
429
- catch (error) {
430
- (0, error_handling_1.handleApiError)(error, "Claude API response processing failed", options.debug);
431
- }
432
- }
433
- else {
434
- result = await response.json();
435
- }
436
- // Debug logging for raw API response
437
- if (options.debug) {
438
- console.log(`[callAi-nonStreaming:raw] Response:`, JSON.stringify(result));
439
- }
440
- // Handle error responses
441
- if (result.error) {
442
- if (options.debug) {
443
- console.error("API returned an error:", result.error);
444
- }
445
- // If it's a model error and not already a retry, try with fallback
446
- if (!isRetry &&
447
- !options.skipRetry &&
448
- result.error.message &&
449
- result.error.message.toLowerCase().includes("not a valid model")) {
450
- if (options.debug) {
451
- console.warn(`Model ${model} error, retrying with ${FALLBACK_MODEL}`);
452
- }
453
- return callAINonStreaming(prompt, { ...options, model: FALLBACK_MODEL }, true);
454
- }
455
- return JSON.stringify({
456
- error: result.error,
457
- message: result.error.message || "API returned an error",
458
- });
459
- }
460
- // Extract content from the response
461
- const content = (0, non_streaming_1.extractContent)(result, schemaStrategy);
462
- // Store the raw response data for user access
463
- if (result) {
464
- // Store the parsed JSON result from the API call
465
- meta.rawResponse = result;
466
- }
467
- // Update model info
468
- meta.model = model;
469
- // Update timing info
470
- if (meta.timing) {
471
- meta.timing.endTime = Date.now();
472
- meta.timing.duration = meta.timing.endTime - meta.timing.startTime;
473
- }
474
- // Process the content based on model type
475
- const processedContent = schemaStrategy.processResponse(content);
476
- // Box the string for WeakMap storage
477
- const boxed = (0, response_metadata_1.boxString)(processedContent);
478
- response_metadata_1.responseMetadata.set(boxed, meta);
479
- return processedContent;
480
- }
481
- catch (error) {
482
- await (0, error_handling_1.handleApiError)(error, "Non-streaming API call", options.debug, {
483
- apiKey: options.apiKey,
484
- endpoint: options.endpoint,
485
- skipRefresh: options.skipRefresh,
486
- refreshToken: options.refreshToken,
487
- updateRefreshToken: options.updateRefreshToken,
488
- });
489
- // If we get here, key was refreshed successfully, retry the operation with the new key
490
- // Retry with the refreshed key
491
- return callAINonStreaming(prompt, {
492
- ...options,
493
- apiKey: key_management_1.keyStore.current || undefined, // Use the refreshed key from keyStore
494
- }, true); // Set isRetry to true
495
- }
496
- // This line will never be reached, but it satisfies the linter
497
- throw new Error("Unexpected code path in callAINonStreaming");
498
- }
package/dist/image.d.ts DELETED
@@ -1,12 +0,0 @@
1
- /**
2
- * Image generation API implementation for call-ai
3
- * Integration with custom image generation API
4
- */
5
- import { ImageGenOptions, ImageResponse } from "./types";
6
- /**
7
- * Generate images using a custom API that mimics OpenAI's image generation capabilities
8
- * @param prompt Text prompt describing the image to generate
9
- * @param options Configuration options for the image generation request
10
- * @returns A Promise that resolves to the image response containing base64 encoded image data
11
- */
12
- export declare function imageGen(prompt: string, options?: ImageGenOptions): Promise<ImageResponse>;
package/dist/index.d.ts DELETED
@@ -1,7 +0,0 @@
1
- /**
2
- * call-ai: A lightweight library for making AI API calls
3
- */
4
- export * from "./types";
5
- export { callAi, getMeta } from "./api";
6
- export { callAi as callAI } from "./api";
7
- export { imageGen } from "./image";
package/dist/index.js DELETED
@@ -1,32 +0,0 @@
1
- "use strict";
2
- /**
3
- * call-ai: A lightweight library for making AI API calls
4
- */
5
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- var desc = Object.getOwnPropertyDescriptor(m, k);
8
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
- desc = { enumerable: true, get: function() { return m[k]; } };
10
- }
11
- Object.defineProperty(o, k2, desc);
12
- }) : (function(o, m, k, k2) {
13
- if (k2 === undefined) k2 = k;
14
- o[k2] = m[k];
15
- }));
16
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
17
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
18
- };
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.imageGen = exports.callAI = exports.getMeta = exports.callAi = void 0;
21
- // Export public types
22
- __exportStar(require("./types"), exports);
23
- // Export API functions
24
- var api_1 = require("./api");
25
- Object.defineProperty(exports, "callAi", { enumerable: true, get: function () { return api_1.callAi; } });
26
- Object.defineProperty(exports, "getMeta", { enumerable: true, get: function () { return api_1.getMeta; } });
27
- // Backward compatibility for callAI (uppercase AI)
28
- var api_2 = require("./api");
29
- Object.defineProperty(exports, "callAI", { enumerable: true, get: function () { return api_2.callAi; } });
30
- // Export image generation function
31
- var image_1 = require("./image");
32
- Object.defineProperty(exports, "imageGen", { enumerable: true, get: function () { return image_1.imageGen; } });
@@ -1,43 +0,0 @@
1
- /**
2
- * Key management functionality for call-ai
3
- */
4
- declare const keyStore: {
5
- current: string | null;
6
- refreshEndpoint: string | null;
7
- refreshToken: string | null;
8
- isRefreshing: boolean;
9
- lastRefreshAttempt: number;
10
- metadata: Record<string, any>;
11
- };
12
- declare let globalDebug: boolean;
13
- /**
14
- * Initialize key store with environment variables
15
- */
16
- declare function initKeyStore(): void;
17
- /**
18
- * Check if an error indicates we need a new API key
19
- * @param error The error to check
20
- * @param debug Whether to log debug information
21
- * @returns True if the error suggests we need a new key
22
- */
23
- declare function isNewKeyError(error: any, debug?: boolean): boolean;
24
- /**
25
- * Refreshes the API key by calling the specified endpoint
26
- * @param currentKey The current API key (may be null for initial key request)
27
- * @param endpoint The endpoint to call for key refresh
28
- * @param refreshToken Authentication token for the refresh endpoint
29
- * @returns Object containing the API key and topup flag
30
- */
31
- declare function refreshApiKey(currentKey: string | null, endpoint: string | null, refreshToken: string | null, debug?: boolean): Promise<{
32
- apiKey: string;
33
- topup: boolean;
34
- }>;
35
- /**
36
- * Helper function to extract hash from key (implementation depends on how you store metadata)
37
- */
38
- declare function getHashFromKey(key: string): string | null;
39
- /**
40
- * Helper function to store key metadata for future reference
41
- */
42
- declare function storeKeyMetadata(data: any): void;
43
- export { keyStore, globalDebug, initKeyStore, isNewKeyError, refreshApiKey, getHashFromKey, storeKeyMetadata, };