@apicity/openai 0.1.0-alpha.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.
@@ -0,0 +1,735 @@
1
+ import { OpenAiError, } from "./types.js";
2
+ import { OpenAiChatRequestSchema, OpenAiEmbeddingRequestSchema, OpenAiFileUploadRequestSchema, OpenAiImageEditRequestSchema, OpenAiImageGenerationRequestSchema, OpenAiImageVariationRequestSchema, OpenAiModerationRequestSchema, OpenAiSpeechRequestSchema, OpenAiTranscribeRequestSchema, OpenAiTranslateRequestSchema, OpenAiBatchCreateRequestSchema, OpenAiResponseRequestSchema, OpenAiResponseCompactRequestSchema, OpenAiResponseInputTokensRequestSchema, OpenAiFineTuningJobCreateRequestSchema, OpenAiCheckpointPermissionCreateRequestSchema, } from "./zod.js";
3
+ import { attachExamples } from "./example.js";
4
+ export function textPart(text) {
5
+ return { type: "text", text };
6
+ }
7
+ export function imageUrlPart(url, detail) {
8
+ return {
9
+ type: "image_url",
10
+ image_url: { url, ...(detail ? { detail } : {}) },
11
+ };
12
+ }
13
+ export function imageBase64Part(base64, mediaType, detail) {
14
+ return imageUrlPart(`data:${mediaType};base64,${base64}`, detail);
15
+ }
16
+ export function firstContent(response) {
17
+ return response.choices[0]?.message?.content ?? "";
18
+ }
19
+ export function openai(opts) {
20
+ const baseURL = opts.baseURL ?? "https://api.openai.com/v1";
21
+ const doFetch = opts.fetch ?? fetch;
22
+ const timeout = opts.timeout ?? 30000;
23
+ async function makeRequest(path, init, signal) {
24
+ const controller = new AbortController();
25
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
26
+ if (signal) {
27
+ signal.addEventListener("abort", () => controller.abort());
28
+ }
29
+ try {
30
+ const res = await doFetch(`${baseURL}${path}`, {
31
+ method: "POST",
32
+ headers: {
33
+ Authorization: `Bearer ${opts.apiKey}`,
34
+ ...init.headers,
35
+ },
36
+ body: init.body,
37
+ signal: controller.signal,
38
+ });
39
+ clearTimeout(timeoutId);
40
+ if (!res.ok) {
41
+ let message = `OpenAI API error: ${res.status}`;
42
+ let body = null;
43
+ try {
44
+ body = await res.json();
45
+ if (typeof body === "object" && body !== null && "error" in body) {
46
+ const err = body.error;
47
+ if (err?.message) {
48
+ message = `OpenAI API error ${res.status}: ${err.message}`;
49
+ }
50
+ }
51
+ }
52
+ catch {
53
+ // ignore parse errors
54
+ }
55
+ throw new OpenAiError(message, res.status, body);
56
+ }
57
+ return (await res.json());
58
+ }
59
+ catch (error) {
60
+ clearTimeout(timeoutId);
61
+ if (error instanceof OpenAiError)
62
+ throw error;
63
+ throw new OpenAiError(`OpenAI request failed: ${error}`, 500);
64
+ }
65
+ }
66
+ function jsonRequest(body) {
67
+ return {
68
+ headers: { "Content-Type": "application/json" },
69
+ body: JSON.stringify(body),
70
+ };
71
+ }
72
+ async function makeBinaryRequest(path, init, signal) {
73
+ const controller = new AbortController();
74
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
75
+ if (signal) {
76
+ signal.addEventListener("abort", () => controller.abort());
77
+ }
78
+ try {
79
+ const res = await doFetch(`${baseURL}${path}`, {
80
+ method: "POST",
81
+ headers: {
82
+ Authorization: `Bearer ${opts.apiKey}`,
83
+ ...init.headers,
84
+ },
85
+ body: init.body,
86
+ signal: controller.signal,
87
+ });
88
+ clearTimeout(timeoutId);
89
+ if (!res.ok) {
90
+ let message = `OpenAI API error: ${res.status}`;
91
+ let body = null;
92
+ try {
93
+ body = await res.json();
94
+ if (typeof body === "object" && body !== null && "error" in body) {
95
+ const err = body.error;
96
+ if (err?.message) {
97
+ message = `OpenAI API error ${res.status}: ${err.message}`;
98
+ }
99
+ }
100
+ }
101
+ catch {
102
+ // ignore parse errors
103
+ }
104
+ throw new OpenAiError(message, res.status, body);
105
+ }
106
+ return await res.arrayBuffer();
107
+ }
108
+ catch (error) {
109
+ clearTimeout(timeoutId);
110
+ if (error instanceof OpenAiError)
111
+ throw error;
112
+ throw new OpenAiError(`OpenAI request failed: ${error}`, 500);
113
+ }
114
+ }
115
+ async function makeGetRequest(path, query, signal) {
116
+ const controller = new AbortController();
117
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
118
+ if (signal) {
119
+ signal.addEventListener("abort", () => controller.abort());
120
+ }
121
+ const params = new URLSearchParams();
122
+ if (query) {
123
+ for (const [key, value] of Object.entries(query)) {
124
+ if (value === undefined)
125
+ continue;
126
+ if (Array.isArray(value)) {
127
+ for (const v of value) {
128
+ params.append(`${key}[]`, v);
129
+ }
130
+ }
131
+ else {
132
+ params.append(key, String(value));
133
+ }
134
+ }
135
+ }
136
+ const qs = params.toString();
137
+ const url = `${baseURL}${path}${qs ? `?${qs}` : ""}`;
138
+ try {
139
+ const res = await doFetch(url, {
140
+ method: "GET",
141
+ headers: {
142
+ Authorization: `Bearer ${opts.apiKey}`,
143
+ },
144
+ signal: controller.signal,
145
+ });
146
+ clearTimeout(timeoutId);
147
+ if (!res.ok) {
148
+ let message = `OpenAI API error: ${res.status}`;
149
+ let body = null;
150
+ try {
151
+ body = await res.json();
152
+ if (typeof body === "object" && body !== null && "error" in body) {
153
+ const err = body.error;
154
+ if (err?.message) {
155
+ message = `OpenAI API error ${res.status}: ${err.message}`;
156
+ }
157
+ }
158
+ }
159
+ catch {
160
+ // ignore parse errors
161
+ }
162
+ throw new OpenAiError(message, res.status, body);
163
+ }
164
+ return (await res.json());
165
+ }
166
+ catch (error) {
167
+ clearTimeout(timeoutId);
168
+ if (error instanceof OpenAiError)
169
+ throw error;
170
+ throw new OpenAiError(`OpenAI request failed: ${error}`, 500);
171
+ }
172
+ }
173
+ async function makeEmptyPostRequest(path, signal) {
174
+ const controller = new AbortController();
175
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
176
+ if (signal) {
177
+ signal.addEventListener("abort", () => controller.abort());
178
+ }
179
+ try {
180
+ const res = await doFetch(`${baseURL}${path}`, {
181
+ method: "POST",
182
+ headers: {
183
+ Authorization: `Bearer ${opts.apiKey}`,
184
+ },
185
+ signal: controller.signal,
186
+ });
187
+ clearTimeout(timeoutId);
188
+ if (!res.ok) {
189
+ let message = `OpenAI API error: ${res.status}`;
190
+ let body = null;
191
+ try {
192
+ body = await res.json();
193
+ if (typeof body === "object" && body !== null && "error" in body) {
194
+ const err = body.error;
195
+ if (err?.message) {
196
+ message = `OpenAI API error ${res.status}: ${err.message}`;
197
+ }
198
+ }
199
+ }
200
+ catch {
201
+ // ignore parse errors
202
+ }
203
+ throw new OpenAiError(message, res.status, body);
204
+ }
205
+ return (await res.json());
206
+ }
207
+ catch (error) {
208
+ clearTimeout(timeoutId);
209
+ if (error instanceof OpenAiError)
210
+ throw error;
211
+ throw new OpenAiError(`OpenAI request failed: ${error}`, 500);
212
+ }
213
+ }
214
+ async function makeDeleteRequest(path, signal) {
215
+ const controller = new AbortController();
216
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
217
+ if (signal) {
218
+ signal.addEventListener("abort", () => controller.abort());
219
+ }
220
+ try {
221
+ const res = await doFetch(`${baseURL}${path}`, {
222
+ method: "DELETE",
223
+ headers: {
224
+ Authorization: `Bearer ${opts.apiKey}`,
225
+ },
226
+ signal: controller.signal,
227
+ });
228
+ clearTimeout(timeoutId);
229
+ if (!res.ok) {
230
+ let message = `OpenAI API error: ${res.status}`;
231
+ let body = null;
232
+ try {
233
+ body = await res.json();
234
+ if (typeof body === "object" && body !== null && "error" in body) {
235
+ const err = body.error;
236
+ if (err?.message) {
237
+ message = `OpenAI API error ${res.status}: ${err.message}`;
238
+ }
239
+ }
240
+ }
241
+ catch {
242
+ // ignore parse errors
243
+ }
244
+ throw new OpenAiError(message, res.status, body);
245
+ }
246
+ return (await res.json());
247
+ }
248
+ catch (error) {
249
+ clearTimeout(timeoutId);
250
+ if (error instanceof OpenAiError)
251
+ throw error;
252
+ throw new OpenAiError(`OpenAI request failed: ${error}`, 500);
253
+ }
254
+ }
255
+ async function makeGetTextRequest(path, signal) {
256
+ const controller = new AbortController();
257
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
258
+ if (signal) {
259
+ signal.addEventListener("abort", () => controller.abort());
260
+ }
261
+ const url = `${baseURL}${path}`;
262
+ try {
263
+ const res = await doFetch(url, {
264
+ method: "GET",
265
+ headers: {
266
+ Authorization: `Bearer ${opts.apiKey}`,
267
+ },
268
+ signal: controller.signal,
269
+ });
270
+ clearTimeout(timeoutId);
271
+ if (!res.ok) {
272
+ let message = `OpenAI API error: ${res.status}`;
273
+ let body = null;
274
+ try {
275
+ body = await res.json();
276
+ if (typeof body === "object" && body !== null && "error" in body) {
277
+ const err = body.error;
278
+ if (err?.message) {
279
+ message = `OpenAI API error ${res.status}: ${err.message}`;
280
+ }
281
+ }
282
+ }
283
+ catch {
284
+ // ignore parse errors
285
+ }
286
+ throw new OpenAiError(message, res.status, body);
287
+ }
288
+ return await res.text();
289
+ }
290
+ catch (error) {
291
+ clearTimeout(timeoutId);
292
+ if (error instanceof OpenAiError)
293
+ throw error;
294
+ throw new OpenAiError(`OpenAI request failed: ${error}`, 500);
295
+ }
296
+ }
297
+ // POST v1 namespace
298
+ const postV1 = {
299
+ chat: {
300
+ // POST https://api.openai.com/v1/chat/completions/{id}
301
+ // Docs: https://platform.openai.com/docs/api-reference
302
+ completions: Object.assign(async (reqOrId, reqOrSignal, signal) => {
303
+ // Overload: update stored completion (POST /chat/completions/{id})
304
+ if (typeof reqOrId === "string") {
305
+ const id = reqOrId;
306
+ const req = reqOrSignal;
307
+ const actualSignal = signal;
308
+ return makeRequest(`/chat/completions/${encodeURIComponent(id)}`, jsonRequest(req), actualSignal);
309
+ }
310
+ // Default: create chat completion (POST /chat/completions)
311
+ return makeRequest("/chat/completions", jsonRequest(reqOrId), reqOrSignal);
312
+ }, {
313
+ schema: OpenAiChatRequestSchema,
314
+ }),
315
+ },
316
+ audio: {
317
+ // POST https://api.openai.com/v1/audio/speech
318
+ // Docs: https://platform.openai.com/docs/api-reference
319
+ speech: Object.assign(async (req, signal) => {
320
+ return makeBinaryRequest("/audio/speech", jsonRequest(req), signal);
321
+ }, {
322
+ schema: OpenAiSpeechRequestSchema,
323
+ }),
324
+ // POST https://api.openai.com/v1/audio/transcriptions
325
+ // Docs: https://platform.openai.com/docs/api-reference
326
+ transcriptions: Object.assign(async (req, signal) => {
327
+ const form = new FormData();
328
+ form.append("file", req.file);
329
+ form.append("model", req.model);
330
+ if (req.response_format !== undefined)
331
+ form.append("response_format", req.response_format);
332
+ if (req.language !== undefined)
333
+ form.append("language", req.language);
334
+ if (req.prompt !== undefined)
335
+ form.append("prompt", req.prompt);
336
+ if (req.temperature !== undefined)
337
+ form.append("temperature", String(req.temperature));
338
+ return makeRequest("/audio/transcriptions", { headers: {}, body: form }, signal);
339
+ }, {
340
+ schema: OpenAiTranscribeRequestSchema,
341
+ }),
342
+ // POST https://api.openai.com/v1/audio/translations
343
+ // Docs: https://platform.openai.com/docs/api-reference
344
+ translations: Object.assign(async (req, signal) => {
345
+ const form = new FormData();
346
+ form.append("file", req.file);
347
+ form.append("model", req.model);
348
+ if (req.response_format !== undefined)
349
+ form.append("response_format", req.response_format);
350
+ if (req.prompt !== undefined)
351
+ form.append("prompt", req.prompt);
352
+ if (req.temperature !== undefined)
353
+ form.append("temperature", String(req.temperature));
354
+ return makeRequest("/audio/translations", { headers: {}, body: form }, signal);
355
+ }, {
356
+ schema: OpenAiTranslateRequestSchema,
357
+ }),
358
+ },
359
+ // POST https://api.openai.com/v1/embeddings
360
+ // Docs: https://platform.openai.com/docs/api-reference
361
+ embeddings: Object.assign(async (req, signal) => {
362
+ return makeRequest("/embeddings", jsonRequest(req), signal);
363
+ }, {
364
+ schema: OpenAiEmbeddingRequestSchema,
365
+ }),
366
+ images: {
367
+ // POST https://api.openai.com/v1/images/generations
368
+ // Docs: https://platform.openai.com/docs/api-reference
369
+ generations: Object.assign(async (req, signal) => {
370
+ return makeRequest("/images/generations", jsonRequest({ moderation: "low", ...req }), signal);
371
+ }, {
372
+ schema: OpenAiImageGenerationRequestSchema,
373
+ }),
374
+ // POST https://api.openai.com/v1/images/edits
375
+ // Docs: https://platform.openai.com/docs/api-reference
376
+ edits: Object.assign(async (req, signal) => {
377
+ const form = new FormData();
378
+ if (Array.isArray(req.image)) {
379
+ for (const img of req.image) {
380
+ form.append("image", img);
381
+ }
382
+ }
383
+ else {
384
+ form.append("image", req.image);
385
+ }
386
+ form.append("prompt", req.prompt);
387
+ if (req.mask !== undefined)
388
+ form.append("mask", req.mask);
389
+ if (req.model !== undefined)
390
+ form.append("model", req.model);
391
+ if (req.n !== undefined)
392
+ form.append("n", String(req.n));
393
+ if (req.size !== undefined)
394
+ form.append("size", req.size);
395
+ if (req.quality !== undefined)
396
+ form.append("quality", req.quality);
397
+ if (req.output_format !== undefined)
398
+ form.append("output_format", req.output_format);
399
+ if (req.response_format !== undefined)
400
+ form.append("response_format", req.response_format);
401
+ if (req.background !== undefined)
402
+ form.append("background", req.background);
403
+ if (req.input_fidelity !== undefined)
404
+ form.append("input_fidelity", req.input_fidelity);
405
+ if (req.output_compression !== undefined)
406
+ form.append("output_compression", String(req.output_compression));
407
+ if (req.user !== undefined)
408
+ form.append("user", req.user);
409
+ return makeRequest("/images/edits", { headers: {}, body: form }, signal);
410
+ }, {
411
+ schema: OpenAiImageEditRequestSchema,
412
+ }),
413
+ // POST https://api.openai.com/v1/images/variations
414
+ // Docs: https://platform.openai.com/docs/api-reference
415
+ variations: Object.assign(async (req, signal) => {
416
+ const form = new FormData();
417
+ form.append("image", req.image);
418
+ if (req.model !== undefined)
419
+ form.append("model", req.model);
420
+ if (req.n !== undefined)
421
+ form.append("n", String(req.n));
422
+ if (req.response_format !== undefined)
423
+ form.append("response_format", req.response_format);
424
+ if (req.size !== undefined)
425
+ form.append("size", req.size);
426
+ if (req.user !== undefined)
427
+ form.append("user", req.user);
428
+ return makeRequest("/images/variations", { headers: {}, body: form }, signal);
429
+ }, {
430
+ schema: OpenAiImageVariationRequestSchema,
431
+ }),
432
+ },
433
+ // POST https://api.openai.com/v1/files
434
+ // Docs: https://platform.openai.com/docs/api-reference
435
+ files: Object.assign(async (req, signal) => {
436
+ const form = new FormData();
437
+ form.append("file", req.file);
438
+ form.append("purpose", req.purpose);
439
+ if (req.expires_after !== undefined) {
440
+ form.append("expires_after", JSON.stringify(req.expires_after));
441
+ }
442
+ return makeRequest("/files", { headers: {}, body: form }, signal);
443
+ }, {
444
+ schema: OpenAiFileUploadRequestSchema,
445
+ }),
446
+ // POST https://api.openai.com/v1/moderations
447
+ // Docs: https://platform.openai.com/docs/api-reference
448
+ moderations: Object.assign(async (req, signal) => {
449
+ return makeRequest("/moderations", jsonRequest(req), signal);
450
+ }, {
451
+ schema: OpenAiModerationRequestSchema,
452
+ }),
453
+ // POST https://api.openai.com/v1/responses
454
+ // Docs: https://platform.openai.com/docs/api-reference
455
+ responses: Object.assign(async (req, signal) => {
456
+ return makeRequest("/responses", jsonRequest(req), signal);
457
+ }, {
458
+ schema: OpenAiResponseRequestSchema,
459
+ // POST https://api.openai.com/v1/responses/compact
460
+ // Docs: https://platform.openai.com/docs/api-reference
461
+ compact: Object.assign(async (req, signal) => {
462
+ return makeRequest("/responses/compact", jsonRequest(req), signal);
463
+ }, {
464
+ schema: OpenAiResponseCompactRequestSchema,
465
+ }),
466
+ // POST https://api.openai.com/v1/responses/input_tokens
467
+ // Docs: https://platform.openai.com/docs/api-reference
468
+ inputTokens: Object.assign(async (req, signal) => {
469
+ return makeRequest("/responses/input_tokens", jsonRequest(req), signal);
470
+ }, {
471
+ schema: OpenAiResponseInputTokensRequestSchema,
472
+ }),
473
+ // POST https://api.openai.com/v1/responses/{id}/cancel
474
+ // Docs: https://platform.openai.com/docs/api-reference
475
+ cancel: Object.assign(async (id, signal) => {
476
+ return makeEmptyPostRequest(`/responses/${encodeURIComponent(id)}/cancel`, signal);
477
+ }, {}),
478
+ }),
479
+ // POST https://api.openai.com/v1/batches
480
+ // Docs: https://platform.openai.com/docs/api-reference
481
+ batches: Object.assign(async (req, signal) => {
482
+ return makeRequest("/batches", jsonRequest(req), signal);
483
+ }, {
484
+ schema: OpenAiBatchCreateRequestSchema,
485
+ // POST https://api.openai.com/v1/batches/{id}/cancel
486
+ // Docs: https://platform.openai.com/docs/api-reference
487
+ cancel: Object.assign(async (id, signal) => {
488
+ return makeEmptyPostRequest(`/batches/${encodeURIComponent(id)}/cancel`, signal);
489
+ }, {}),
490
+ }),
491
+ fineTuning: {
492
+ // POST https://api.openai.com/v1/fine_tuning/jobs
493
+ // Docs: https://platform.openai.com/docs/api-reference
494
+ jobs: Object.assign(async (req, signal) => {
495
+ return makeRequest("/fine_tuning/jobs", jsonRequest(req), signal);
496
+ }, {
497
+ schema: OpenAiFineTuningJobCreateRequestSchema,
498
+ // POST https://api.openai.com/v1/fine_tuning/jobs/{id}/cancel
499
+ // Docs: https://platform.openai.com/docs/api-reference
500
+ cancel: Object.assign(async (id, signal) => {
501
+ return makeEmptyPostRequest(`/fine_tuning/jobs/${encodeURIComponent(id)}/cancel`, signal);
502
+ }, {}),
503
+ // POST https://api.openai.com/v1/fine_tuning/jobs/{id}/pause
504
+ // Docs: https://platform.openai.com/docs/api-reference
505
+ pause: Object.assign(async (id, signal) => {
506
+ return makeEmptyPostRequest(`/fine_tuning/jobs/${encodeURIComponent(id)}/pause`, signal);
507
+ }, {}),
508
+ // POST https://api.openai.com/v1/fine_tuning/jobs/{id}/resume
509
+ // Docs: https://platform.openai.com/docs/api-reference
510
+ resume: Object.assign(async (id, signal) => {
511
+ return makeEmptyPostRequest(`/fine_tuning/jobs/${encodeURIComponent(id)}/resume`, signal);
512
+ }, {}),
513
+ }),
514
+ checkpoints: {
515
+ // POST https://api.openai.com/v1/fine_tuning/checkpoints/{checkpoint}/permissions
516
+ // Docs: https://platform.openai.com/docs/api-reference
517
+ permissions: Object.assign(async (checkpoint, req, signal) => {
518
+ return makeRequest(`/fine_tuning/checkpoints/${encodeURIComponent(checkpoint)}/permissions`, jsonRequest(req), signal);
519
+ }, {
520
+ schema: OpenAiCheckpointPermissionCreateRequestSchema,
521
+ }),
522
+ },
523
+ },
524
+ };
525
+ // GET v1 namespace
526
+ const getV1 = {
527
+ chat: {
528
+ // GET https://api.openai.com/v1/chat/completions/{idOrOpts}
529
+ // Docs: https://platform.openai.com/docs/api-reference
530
+ completions: Object.assign(async (idOrOpts, signal) => {
531
+ if (typeof idOrOpts === "string") {
532
+ // GET /chat/completions/{id}
533
+ return makeGetRequest(`/chat/completions/${encodeURIComponent(idOrOpts)}`, undefined, signal);
534
+ }
535
+ // GET /chat/completions (list)
536
+ const query = {};
537
+ if (idOrOpts?.after)
538
+ query.after = idOrOpts.after;
539
+ if (idOrOpts?.limit !== undefined)
540
+ query.limit = String(idOrOpts.limit);
541
+ if (idOrOpts?.order)
542
+ query.order = idOrOpts.order;
543
+ if (idOrOpts?.metadata) {
544
+ for (const [k, v] of Object.entries(idOrOpts.metadata)) {
545
+ query[`metadata[${k}]`] = v;
546
+ }
547
+ }
548
+ return makeGetRequest("/chat/completions", query, signal);
549
+ }, {
550
+ // GET https://api.openai.com/v1/chat/completions/{id}/messages
551
+ // Docs: https://platform.openai.com/docs/api-reference
552
+ messages: async (id, opts, signal) => {
553
+ const query = {};
554
+ if (opts?.after)
555
+ query.after = opts.after;
556
+ if (opts?.limit !== undefined)
557
+ query.limit = String(opts.limit);
558
+ if (opts?.order)
559
+ query.order = opts.order;
560
+ return makeGetRequest(`/chat/completions/${encodeURIComponent(id)}/messages`, query, signal);
561
+ },
562
+ }),
563
+ },
564
+ // GET https://api.openai.com/v1/files/{idOrOpts}
565
+ // Docs: https://platform.openai.com/docs/api-reference
566
+ files: Object.assign(async (idOrOpts, signal) => {
567
+ if (typeof idOrOpts === "string") {
568
+ // GET /files/{id}
569
+ return makeGetRequest(`/files/${encodeURIComponent(idOrOpts)}`, undefined, signal);
570
+ }
571
+ // GET /files (list)
572
+ const query = {};
573
+ if (idOrOpts?.purpose !== undefined)
574
+ query.purpose = idOrOpts.purpose;
575
+ if (idOrOpts?.limit !== undefined)
576
+ query.limit = String(idOrOpts.limit);
577
+ if (idOrOpts?.order !== undefined)
578
+ query.order = idOrOpts.order;
579
+ if (idOrOpts?.after !== undefined)
580
+ query.after = idOrOpts.after;
581
+ return makeGetRequest("/files", query, signal);
582
+ }, {
583
+ // GET https://api.openai.com/v1/files/{id}/content
584
+ // Docs: https://platform.openai.com/docs/api-reference
585
+ content: async (id, signal) => {
586
+ return makeGetTextRequest(`/files/${encodeURIComponent(id)}/content`, signal);
587
+ },
588
+ }),
589
+ // GET https://api.openai.com/v1/models/{id}
590
+ // Docs: https://platform.openai.com/docs/api-reference
591
+ models: Object.assign(async (id, signal) => {
592
+ if (typeof id === "string") {
593
+ // GET /models/{id}
594
+ return makeGetRequest(`/models/${encodeURIComponent(id)}`, undefined, signal);
595
+ }
596
+ // GET /models (list)
597
+ return makeGetRequest("/models", undefined, typeof id === "object" ? id : signal // Handle signal as first param
598
+ );
599
+ }, {}),
600
+ // GET https://api.openai.com/v1/responses/{id}
601
+ // Docs: https://platform.openai.com/docs/api-reference
602
+ responses: Object.assign(async (id, opts, signal) => {
603
+ return makeGetRequest(`/responses/${encodeURIComponent(id)}`, {
604
+ include: opts?.include,
605
+ stream: opts?.stream,
606
+ }, signal);
607
+ }, {
608
+ // GET https://api.openai.com/v1/responses/{id}/input_items
609
+ // Docs: https://platform.openai.com/docs/api-reference
610
+ inputItems: async (id, opts, signal) => {
611
+ return makeGetRequest(`/responses/${encodeURIComponent(id)}/input_items`, {
612
+ after: opts?.after,
613
+ limit: opts?.limit !== undefined ? String(opts.limit) : undefined,
614
+ order: opts?.order,
615
+ include: opts?.include,
616
+ }, signal);
617
+ },
618
+ }),
619
+ // GET https://api.openai.com/v1/batches/{idOrOpts}
620
+ // Docs: https://platform.openai.com/docs/api-reference
621
+ batches: Object.assign(async (idOrOpts, signal) => {
622
+ if (typeof idOrOpts === "string") {
623
+ // GET /batches/{id}
624
+ return makeGetRequest(`/batches/${encodeURIComponent(idOrOpts)}`, undefined, signal);
625
+ }
626
+ // GET /batches (list)
627
+ return makeGetRequest("/batches", {
628
+ after: idOrOpts?.after,
629
+ limit: idOrOpts?.limit !== undefined
630
+ ? String(idOrOpts.limit)
631
+ : undefined,
632
+ }, signal);
633
+ }, {}),
634
+ fineTuning: {
635
+ // GET https://api.openai.com/v1/fine_tuning/jobs/{idOrOpts}
636
+ // Docs: https://platform.openai.com/docs/api-reference
637
+ jobs: Object.assign(async (idOrOpts, signal) => {
638
+ if (typeof idOrOpts === "string") {
639
+ // GET /fine_tuning/jobs/{id}
640
+ return makeGetRequest(`/fine_tuning/jobs/${encodeURIComponent(idOrOpts)}`, undefined, signal);
641
+ }
642
+ // GET /fine_tuning/jobs (list)
643
+ const query = {};
644
+ const opts = idOrOpts;
645
+ if (opts?.after)
646
+ query.after = opts.after;
647
+ if (opts?.limit !== undefined)
648
+ query.limit = String(opts.limit);
649
+ if (opts?.metadata) {
650
+ for (const [k, v] of Object.entries(opts.metadata)) {
651
+ query[`metadata[${k}]`] = v;
652
+ }
653
+ }
654
+ return makeGetRequest("/fine_tuning/jobs", query, signal);
655
+ }, {
656
+ // GET https://api.openai.com/v1/fine_tuning/jobs/{id}/events
657
+ // Docs: https://platform.openai.com/docs/api-reference
658
+ events: async (id, opts, signal) => {
659
+ const query = {};
660
+ if (opts?.after)
661
+ query.after = opts.after;
662
+ if (opts?.limit !== undefined)
663
+ query.limit = String(opts.limit);
664
+ return makeGetRequest(`/fine_tuning/jobs/${encodeURIComponent(id)}/events`, query, signal);
665
+ },
666
+ // GET https://api.openai.com/v1/fine_tuning/jobs/{id}/checkpoints
667
+ // Docs: https://platform.openai.com/docs/api-reference
668
+ checkpoints: async (id, opts, signal) => {
669
+ const query = {};
670
+ if (opts?.after)
671
+ query.after = opts.after;
672
+ if (opts?.limit !== undefined)
673
+ query.limit = String(opts.limit);
674
+ return makeGetRequest(`/fine_tuning/jobs/${encodeURIComponent(id)}/checkpoints`, query, signal);
675
+ },
676
+ }),
677
+ checkpoints: {
678
+ // GET https://api.openai.com/v1/fine_tuning/checkpoints/{checkpoint}/permissions
679
+ // Docs: https://platform.openai.com/docs/api-reference
680
+ permissions: async (checkpoint, opts, signal) => {
681
+ const query = {};
682
+ if (opts?.after)
683
+ query.after = opts.after;
684
+ if (opts?.limit !== undefined)
685
+ query.limit = String(opts.limit);
686
+ if (opts?.order)
687
+ query.order = opts.order;
688
+ if (opts?.project_id)
689
+ query.project_id = opts.project_id;
690
+ return makeGetRequest(`/fine_tuning/checkpoints/${encodeURIComponent(checkpoint)}/permissions`, query, signal);
691
+ },
692
+ },
693
+ },
694
+ };
695
+ // DELETE v1 namespace
696
+ const deleteV1 = {
697
+ chat: {
698
+ // DELETE https://api.openai.com/v1/chat/completions/{id}
699
+ // Docs: https://platform.openai.com/docs/api-reference
700
+ completions: async (id, signal) => {
701
+ return makeDeleteRequest(`/chat/completions/${encodeURIComponent(id)}`, signal);
702
+ },
703
+ },
704
+ // DELETE https://api.openai.com/v1/files/{id}
705
+ // Docs: https://platform.openai.com/docs/api-reference
706
+ files: async (id, signal) => {
707
+ return makeDeleteRequest(`/files/${encodeURIComponent(id)}`, signal);
708
+ },
709
+ // DELETE https://api.openai.com/v1/models/{id}
710
+ // Docs: https://platform.openai.com/docs/api-reference
711
+ models: async (id, signal) => {
712
+ return makeDeleteRequest(`/models/${encodeURIComponent(id)}`, signal);
713
+ },
714
+ // DELETE https://api.openai.com/v1/responses/{id}
715
+ // Docs: https://platform.openai.com/docs/api-reference
716
+ responses: async (id, signal) => {
717
+ return makeDeleteRequest(`/responses/${encodeURIComponent(id)}`, signal);
718
+ },
719
+ fineTuning: {
720
+ checkpoints: {
721
+ // DELETE https://api.openai.com/v1/fine_tuning/checkpoints/{checkpoint}/permissions/{permissionId}
722
+ // Docs: https://platform.openai.com/docs/api-reference
723
+ permissions: async (checkpoint, permissionId, signal) => {
724
+ return makeDeleteRequest(`/fine_tuning/checkpoints/${encodeURIComponent(checkpoint)}/permissions/${encodeURIComponent(permissionId)}`, signal);
725
+ },
726
+ },
727
+ },
728
+ };
729
+ return attachExamples({
730
+ post: { v1: postV1 },
731
+ get: { v1: getV1 },
732
+ delete: { v1: deleteV1 },
733
+ });
734
+ }
735
+ //# sourceMappingURL=openai.js.map