@aeye/openai 0.3.10 → 0.7.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 CHANGED
@@ -1,921 +1,1076 @@
1
- # @aeye/openai
2
-
3
- OpenAI provider for the @aeye (AI TypeScript) framework. This package provides a comprehensive integration with OpenAI's API, supporting the full range of capabilities including chat completions, image generation, speech synthesis, transcription, and embeddings.
4
-
5
- ## Features
6
-
7
- - **Chat Completions**: Support for GPT-4, GPT-4 Turbo, GPT-3.5 Turbo, and other chat models
8
- - **Vision**: GPT-4 Vision (GPT-4V) for image understanding
9
- - **Reasoning Models**: o1, o1-mini, o3-mini for advanced reasoning tasks
10
- - **Image Generation**: DALL-E 2 and DALL-E 3 for creating images from text
11
- - **Speech-to-Text**: Whisper models for audio transcription
12
- - **Text-to-Speech**: TTS models for voice synthesis
13
- - **Embeddings**: Text embeddings for semantic search and similarity
14
- - **Function Calling**: Tool/function calling with automatic schema conversion
15
- - **Structured Outputs**: JSON mode and schema-based structured outputs
16
- - **Streaming**: Real-time streaming responses for chat completions
17
- - **Multi-modal**: Support for text, images, audio, and files in conversations
18
- - **Extensible**: Base class for OpenAI-compatible providers (Azure OpenAI, OpenRouter, etc.)
19
-
20
- ## Installation
21
-
22
- ```bash
23
- npm install @aeye/openai @aeye/ai @aeye/core openai zod
24
- ```
25
-
26
- ## Quick Start
27
-
28
- ```typescript
29
- import { OpenAIProvider } from '@aeye/openai';
30
-
31
- // Create provider instance
32
- const provider = new OpenAIProvider({
33
- apiKey: process.env.OPENAI_API_KEY!,
34
- });
35
-
36
- // Create executor
37
- const executor = provider.createExecutor();
38
-
39
- // Make a request
40
- const response = await executor(
41
- {
42
- messages: [
43
- { role: 'user', content: 'Tell me a joke about TypeScript' }
44
- ]
45
- },
46
- {},
47
- { model: 'gpt-4' }
48
- );
49
-
50
- console.log(response.content);
51
- ```
52
-
53
- ## Configuration
54
-
55
- ### Basic Configuration
56
-
57
- ```typescript
58
- import { OpenAIProvider, OpenAIConfig } from '@aeye/openai';
59
-
60
- const config: OpenAIConfig = {
61
- apiKey: process.env.OPENAI_API_KEY!,
62
- organization: 'org-123456', // Optional: for multi-org accounts
63
- };
64
-
65
- const provider = new OpenAIProvider(config);
66
- ```
67
-
68
- ### Custom Base URL (for Azure OpenAI or compatible APIs)
69
-
70
- ```typescript
71
- const provider = new OpenAIProvider({
72
- apiKey: process.env.AZURE_API_KEY!,
73
- baseURL: 'https://your-resource.openai.azure.com/openai/deployments/your-deployment',
74
- });
75
- ```
76
-
77
- ## Usage Examples
78
-
79
- ### Chat Completions
80
-
81
- #### Basic Chat
82
-
83
- ```typescript
84
- const executor = provider.createExecutor();
85
-
86
- const response = await executor(
87
- {
88
- messages: [
89
- { role: 'system', content: 'You are a helpful assistant.' },
90
- { role: 'user', content: 'What is the capital of France?' }
91
- ],
92
- temperature: 0.7,
93
- maxTokens: 150,
94
- },
95
- {},
96
- { model: 'gpt-4' }
97
- );
98
-
99
- console.log(response.content);
100
- console.log('Tokens used:', response.usage.totalTokens);
101
- ```
102
-
103
- #### Streaming Chat
104
-
105
- ```typescript
106
- const streamer = provider.createStreamer();
107
-
108
- for await (const chunk of streamer(
109
- {
110
- messages: [
111
- { role: 'user', content: 'Write a short story about a robot' }
112
- ]
113
- },
114
- {},
115
- { model: 'gpt-4' }
116
- )) {
117
- if (chunk.content) {
118
- process.stdout.write(chunk.content);
119
- }
120
- }
121
- ```
122
-
123
- #### Multi-turn Conversation
124
-
125
- ```typescript
126
- const conversation = [
127
- { role: 'system' as const, content: 'You are a helpful assistant.' },
128
- { role: 'user' as const, content: 'What is TypeScript?' },
129
- ];
130
-
131
- // First response
132
- let response = await executor(
133
- { messages: conversation },
134
- {},
135
- { model: 'gpt-4' }
136
- );
137
-
138
- conversation.push({ role: 'assistant', content: response.content });
139
- conversation.push({ role: 'user', content: 'Can you give me an example?' });
140
-
141
- // Second response
142
- response = await executor(
143
- { messages: conversation },
144
- {},
145
- { model: 'gpt-4' }
146
- );
147
- ```
148
-
149
- ### Vision (GPT-4V)
150
-
151
- #### Analyze an Image
152
-
153
- ```typescript
154
- const response = await executor(
155
- {
156
- messages: [
157
- {
158
- role: 'user',
159
- content: [
160
- { type: 'text', content: 'What is in this image?' },
161
- {
162
- type: 'image',
163
- content: 'https://example.com/image.jpg',
164
- // Or use base64: content: 'data:image/jpeg;base64,/9j/4AAQ...'
165
- }
166
- ]
167
- }
168
- ]
169
- },
170
- {},
171
- { model: 'gpt-4-vision-preview' }
172
- );
173
- ```
174
-
175
- #### Multiple Images
176
-
177
- ```typescript
178
- const response = await executor(
179
- {
180
- messages: [
181
- {
182
- role: 'user',
183
- content: [
184
- { type: 'text', content: 'Compare these two images' },
185
- { type: 'image', content: 'https://example.com/image1.jpg' },
186
- { type: 'image', content: 'https://example.com/image2.jpg' }
187
- ]
188
- }
189
- ]
190
- },
191
- {},
192
- { model: 'gpt-4-vision-preview' }
193
- );
194
- ```
195
-
196
- ### Function Calling
197
-
198
- #### Define and Use Tools
199
-
200
- ```typescript
201
- import z from 'zod';
202
-
203
- const response = await executor(
204
- {
205
- messages: [
206
- { role: 'user', content: 'What is the weather like in San Francisco?' }
207
- ],
208
- tools: [
209
- {
210
- name: 'get_current_weather',
211
- description: 'Get the current weather in a given location',
212
- parameters: z.object({
213
- location: z.string().describe('The city and state, e.g., San Francisco, CA'),
214
- unit: z.enum(['celsius', 'fahrenheit']).optional(),
215
- }),
216
- }
217
- ],
218
- toolChoice: 'auto', // Can be 'auto', 'required', 'none', or { tool: 'tool_name' }
219
- },
220
- {},
221
- { model: 'gpt-4' }
222
- );
223
-
224
- if (response.toolCalls) {
225
- for (const toolCall of response.toolCalls) {
226
- console.log('Tool:', toolCall.name);
227
- console.log('Arguments:', JSON.parse(toolCall.arguments));
228
-
229
- // Execute the function and send result back
230
- const functionResult = await getWeather(JSON.parse(toolCall.arguments));
231
-
232
- const finalResponse = await executor(
233
- {
234
- messages: [
235
- { role: 'user', content: 'What is the weather like in San Francisco?' },
236
- { role: 'assistant', content: '', toolCalls: [toolCall] },
237
- {
238
- role: 'tool',
239
- content: JSON.stringify(functionResult),
240
- toolCallId: toolCall.id,
241
- }
242
- ]
243
- },
244
- {},
245
- { model: 'gpt-4' }
246
- );
247
- }
248
- }
249
- ```
250
-
251
- #### Force Specific Tool
252
-
253
- ```typescript
254
- const response = await executor(
255
- {
256
- messages: [
257
- { role: 'user', content: 'Get the weather for Boston' }
258
- ],
259
- tools: [
260
- {
261
- name: 'get_weather',
262
- description: 'Get weather information',
263
- parameters: z.object({
264
- location: z.string(),
265
- }),
266
- }
267
- ],
268
- toolChoice: { tool: 'get_weather' }, // Force this specific tool
269
- },
270
- {},
271
- { model: 'gpt-4' }
272
- );
273
- ```
274
-
275
- ### Structured Outputs
276
-
277
- #### JSON Mode
278
-
279
- ```typescript
280
- const response = await executor(
281
- {
282
- messages: [
283
- {
284
- role: 'user',
285
- content: 'List three famous scientists and their main contributions in JSON format'
286
- }
287
- ],
288
- responseFormat: 'json', // Ensures valid JSON output
289
- },
290
- {},
291
- { model: 'gpt-4' }
292
- );
293
-
294
- const scientists = JSON.parse(response.content);
295
- ```
296
-
297
- #### Schema-based Structured Output
298
-
299
- ```typescript
300
- import z from 'zod';
301
-
302
- const PersonSchema = z.object({
303
- name: z.string(),
304
- age: z.number(),
305
- occupation: z.string(),
306
- hobbies: z.array(z.string()),
307
- });
308
-
309
- const response = await executor(
310
- {
311
- messages: [
312
- {
313
- role: 'user',
314
- content: 'Generate a profile for a fictional software engineer'
315
- }
316
- ],
317
- responseFormat: PersonSchema, // Strict schema enforcement
318
- },
319
- {},
320
- { model: 'gpt-4' }
321
- );
322
-
323
- // Response is guaranteed to match the schema
324
- const person = JSON.parse(response.content);
325
- console.log(person.name, person.age); // Type-safe
326
- ```
327
-
328
- ### Image Generation (DALL-E)
329
-
330
- #### Generate with DALL-E 3
331
-
332
- ```typescript
333
- const imageResponse = await provider.generateImage(
334
- {
335
- prompt: 'A serene landscape with mountains and a lake at sunset',
336
- model: 'dall-e-3',
337
- size: '1024x1024',
338
- quality: 'hd', // 'standard' or 'hd'
339
- style: 'vivid', // 'vivid' or 'natural'
340
- n: 1,
341
- },
342
- {}
343
- );
344
-
345
- console.log('Generated image URL:', imageResponse.images[0].url);
346
- console.log('Revised prompt:', imageResponse.images[0].revisedPrompt);
347
- ```
348
-
349
- #### Generate Multiple Images with DALL-E 2
350
-
351
- ```typescript
352
- const imageResponse = await provider.generateImage(
353
- {
354
- prompt: 'A cute robot playing with a puppy',
355
- model: 'dall-e-2',
356
- size: '512x512',
357
- n: 3, // Generate 3 variations
358
- },
359
- {}
360
- );
361
-
362
- imageResponse.images.forEach((img, i) => {
363
- console.log(`Image ${i + 1}:`, img.url);
364
- });
365
- ```
366
-
367
- #### Get Base64 Image Data
368
-
369
- ```typescript
370
- const imageResponse = await provider.generateImage(
371
- {
372
- prompt: 'A futuristic city skyline',
373
- model: 'dall-e-3',
374
- responseFormat: 'b64_json', // Get base64 instead of URL
375
- },
376
- {}
377
- );
378
-
379
- const base64Image = imageResponse.images[0].b64_json;
380
- // Save or process the base64 data
381
- ```
382
-
383
- ### Speech Synthesis (TTS)
384
-
385
- #### Generate Speech
386
-
387
- ```typescript
388
- import fs from 'fs';
389
-
390
- const speechResponse = await provider.generateSpeech(
391
- {
392
- text: 'Hello! This is a text-to-speech example using OpenAI.',
393
- model: 'tts-1', // or 'tts-1-hd' for higher quality
394
- voice: 'alloy', // alloy, echo, fable, onyx, nova, shimmer
395
- speed: 1.0, // 0.25 to 4.0
396
- responseFormat: 'mp3', // mp3, opus, aac, flac, wav, pcm
397
- },
398
- {}
399
- );
400
-
401
- // Save to file
402
- fs.writeFileSync('output.mp3', speechResponse.audioBuffer);
403
- console.log('Audio saved to output.mp3');
404
- ```
405
-
406
- #### Different Voices
407
-
408
- ```typescript
409
- const voices = ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'];
410
-
411
- for (const voice of voices) {
412
- const response = await provider.generateSpeech(
413
- {
414
- text: `This is the ${voice} voice speaking.`,
415
- voice,
416
- model: 'tts-1',
417
- },
418
- {}
419
- );
420
-
421
- fs.writeFileSync(`voice_${voice}.mp3`, response.audioBuffer);
422
- }
423
- ```
424
-
425
- ### Transcription (Whisper)
426
-
427
- #### Transcribe Audio File
428
-
429
- ```typescript
430
- import fs from 'fs';
431
-
432
- const audioBuffer = fs.readFileSync('audio.mp3');
433
-
434
- const transcription = await provider.transcribe(
435
- {
436
- audio: audioBuffer,
437
- model: 'whisper-1',
438
- language: 'en', // Optional: ISO-639-1 language code
439
- prompt: 'This is a podcast about AI and technology', // Optional: context
440
- },
441
- {}
442
- );
443
-
444
- console.log('Transcription:', transcription.text);
445
- ```
446
-
447
- #### Transcribe with Timestamps
448
-
449
- ```typescript
450
- const transcription = await provider.transcribe(
451
- {
452
- audio: audioBuffer,
453
- model: 'whisper-1',
454
- responseFormat: 'verbose_json',
455
- timestampGranularities: ['word', 'segment'],
456
- },
457
- {}
458
- );
459
-
460
- console.log('Full text:', transcription.text);
461
- console.log('Language:', transcription.language);
462
- console.log('Duration:', transcription.duration);
463
-
464
- // Word-level timestamps
465
- transcription.words?.forEach(word => {
466
- console.log(`${word.word}: ${word.start}s - ${word.end}s`);
467
- });
468
-
469
- // Segment-level timestamps
470
- transcription.segments?.forEach(segment => {
471
- console.log(`${segment.text}: ${segment.start}s - ${segment.end}s`);
472
- });
473
- ```
474
-
475
- #### Different Output Formats
476
-
477
- ```typescript
478
- // Plain text
479
- const text = await provider.transcribe(
480
- { audio: audioBuffer, responseFormat: 'text' },
481
- {}
482
- );
483
-
484
- // SRT subtitles
485
- const srt = await provider.transcribe(
486
- { audio: audioBuffer, responseFormat: 'srt' },
487
- {}
488
- );
489
-
490
- // VTT subtitles
491
- const vtt = await provider.transcribe(
492
- { audio: audioBuffer, responseFormat: 'vtt' },
493
- {}
494
- );
495
- ```
496
-
497
- ### Embeddings
498
-
499
- #### Generate Embeddings
500
-
501
- ```typescript
502
- const embeddingResponse = await provider.embed(
503
- {
504
- texts: [
505
- 'The quick brown fox jumps over the lazy dog',
506
- 'Machine learning is a subset of artificial intelligence',
507
- 'OpenAI develops advanced AI models'
508
- ],
509
- model: 'text-embedding-3-small', // or 'text-embedding-3-large'
510
- },
511
- {}
512
- );
513
-
514
- embeddingResponse.embeddings.forEach((item, i) => {
515
- console.log(`Embedding ${i}:`, item.embedding.length, 'dimensions');
516
- });
517
-
518
- console.log('Tokens used:', embeddingResponse.usage?.text?.input);
519
- ```
520
-
521
- #### Custom Dimensions (for smaller embeddings)
522
-
523
- ```typescript
524
- const embeddingResponse = await provider.embed(
525
- {
526
- texts: ['Some text to embed'],
527
- model: 'text-embedding-3-large',
528
- dimensions: 256, // Reduce from default 3072 to 256
529
- },
530
- {}
531
- );
532
- ```
533
-
534
- #### Calculate Similarity
535
-
536
- ```typescript
537
- function cosineSimilarity(a: number[], b: number[]): number {
538
- const dotProduct = a.reduce((sum, val, i) => sum + val * b[i], 0);
539
- const magnitudeA = Math.sqrt(a.reduce((sum, val) => sum + val * val, 0));
540
- const magnitudeB = Math.sqrt(b.reduce((sum, val) => sum + val * val, 0));
541
- return dotProduct / (magnitudeA * magnitudeB);
542
- }
543
-
544
- const response = await provider.embed(
545
- {
546
- texts: [
547
- 'I love programming in TypeScript',
548
- 'TypeScript is my favorite language',
549
- 'I enjoy cooking Italian food'
550
- ],
551
- model: 'text-embedding-3-small',
552
- },
553
- {}
554
- );
555
-
556
- const [emb1, emb2, emb3] = response.embeddings.map(e => e.embedding);
557
-
558
- console.log('Similarity 1-2:', cosineSimilarity(emb1, emb2)); // High similarity
559
- console.log('Similarity 1-3:', cosineSimilarity(emb1, emb3)); // Low similarity
560
- ```
561
-
562
- ### Reasoning Models (o1, o3-mini)
563
-
564
- #### Using o1 Models
565
-
566
- The o1 and o3-mini models use extended thinking to solve complex problems.
567
-
568
- ```typescript
569
- const response = await executor(
570
- {
571
- messages: [
572
- {
573
- role: 'user',
574
- content: 'Solve this logic puzzle: There are 100 doors, all closed. You make 100 passes. On pass 1, toggle all doors. On pass 2, toggle every 2nd door. On pass 3, toggle every 3rd door, etc. Which doors are open after 100 passes?'
575
- }
576
- ],
577
- // Note: o1 models don't support temperature or system messages
578
- },
579
- {},
580
- { model: 'o1-preview' } // or 'o1-mini', 'o3-mini'
581
- );
582
-
583
- console.log('Reasoning:', response.reasoning); // Internal reasoning process
584
- console.log('Answer:', response.content);
585
- ```
586
-
587
- **Important**: o1 models have different capabilities:
588
- - No system messages support (use user messages instead)
589
- - No temperature control (model uses internal reasoning)
590
- - No streaming support
591
- - Extended processing time for complex problems
592
-
593
- ### Advanced Features
594
-
595
- #### Abort Requests
596
-
597
- ```typescript
598
- const controller = new AbortController();
599
-
600
- // Set timeout
601
- setTimeout(() => controller.abort(), 5000);
602
-
603
- try {
604
- const response = await executor(
605
- { messages: [{ role: 'user', content: 'Tell me a long story' }] },
606
- {},
607
- { model: 'gpt-4' },
608
- controller.signal
609
- );
610
- } catch (error) {
611
- if (error.name === 'AbortError') {
612
- console.log('Request was aborted');
613
- }
614
- }
615
- ```
616
-
617
- #### List Available Models
618
-
619
- ```typescript
620
- const models = await provider.listModels();
621
-
622
- models.forEach(model => {
623
- console.log(`${model.id}: ${model.capabilities}`);
624
- console.log(` Context window: ${model.contextWindow}`);
625
- console.log(` Pricing: $${model.pricing.text.input}/1M input tokens`);
626
- });
627
- ```
628
-
629
- #### Check Provider Health
630
-
631
- ```typescript
632
- const isHealthy = await provider.checkHealth();
633
- console.log('OpenAI API is', isHealthy ? 'accessible' : 'not accessible');
634
- ```
635
-
636
- #### Default Metadata
637
-
638
- ```typescript
639
- // Set default metadata for all requests
640
- provider.defaultMetadata = {
641
- model: 'gpt-4',
642
- user: 'user-123',
643
- };
644
-
645
- // Now model is automatically set
646
- const response = await executor(
647
- { messages: [{ role: 'user', content: 'Hello' }] },
648
- {}
649
- // No need to pass { model: 'gpt-4' }
650
- );
651
- ```
652
-
653
- ## Extending for Custom Providers
654
-
655
- The `OpenAIProvider` class can be extended to support OpenAI-compatible APIs like Azure OpenAI, OpenRouter, or custom deployments.
656
-
657
- ### Example: Custom Provider
658
-
659
- ```typescript
660
- import { OpenAIProvider, OpenAIConfig } from '@aeye/openai';
661
- import OpenAI from 'openai';
662
-
663
- interface CustomConfig extends OpenAIConfig {
664
- customOption?: string;
665
- }
666
-
667
- class CustomProvider extends OpenAIProvider<CustomConfig> {
668
- readonly name = 'custom-provider';
669
-
670
- protected createClient(config: CustomConfig): OpenAI {
671
- return new OpenAI({
672
- apiKey: config.apiKey,
673
- baseURL: 'https://api.custom-provider.com/v1',
674
- defaultHeaders: {
675
- 'X-Custom-Header': config.customOption || '',
676
- },
677
- });
678
- }
679
-
680
- protected customizeChatParams(params: any, config: CustomConfig, request: any) {
681
- // Add custom parameters
682
- return {
683
- ...params,
684
- custom_param: config.customOption,
685
- };
686
- }
687
- }
688
-
689
- // Use the custom provider
690
- const customProvider = new CustomProvider({
691
- apiKey: process.env.CUSTOM_API_KEY!,
692
- customOption: 'value',
693
- });
694
- ```
695
-
696
- ### Example: Azure OpenAI
697
-
698
- ```typescript
699
- class AzureOpenAIProvider extends OpenAIProvider {
700
- readonly name = 'azure-openai';
701
-
702
- protected createClient(config: OpenAIConfig): OpenAI {
703
- return new OpenAI({
704
- apiKey: config.apiKey,
705
- baseURL: config.baseURL, // Azure endpoint
706
- defaultQuery: { 'api-version': '2024-02-01' },
707
- });
708
- }
709
- }
710
-
711
- const azureProvider = new AzureOpenAIProvider({
712
- apiKey: process.env.AZURE_OPENAI_KEY!,
713
- baseURL: 'https://your-resource.openai.azure.com/openai/deployments/your-deployment',
714
- });
715
- ```
716
-
717
- ## Configuration Options
718
-
719
- ### OpenAIConfig
720
-
721
- | Property | Type | Required | Description |
722
- |----------|------|----------|-------------|
723
- | `apiKey` | `string` | Yes | OpenAI API key |
724
- | `baseURL` | `string` | No | Custom base URL for API endpoint |
725
- | `organization` | `string` | No | OpenAI organization ID |
726
-
727
- ### Request Parameters
728
-
729
- #### Chat Completion Request
730
-
731
- | Parameter | Type | Description |
732
- |-----------|------|-------------|
733
- | `messages` | `Message[]` | Array of conversation messages |
734
- | `temperature` | `number` | Sampling temperature (0-2) |
735
- | `topP` | `number` | Nucleus sampling parameter |
736
- | `maxTokens` | `number` | Maximum tokens to generate |
737
- | `stop` | `string \| string[]` | Stop sequences |
738
- | `tools` | `Tool[]` | Function definitions for tool calling |
739
- | `toolChoice` | `'auto' \| 'required' \| 'none' \| { tool: string }` | Tool selection mode |
740
- | `responseFormat` | `'text' \| 'json' \| ZodSchema` | Response format constraint |
741
-
742
- #### Image Generation Request
743
-
744
- | Parameter | Type | Description |
745
- |-----------|------|-------------|
746
- | `prompt` | `string` | Text description of desired image |
747
- | `model` | `string` | Model to use (dall-e-2, dall-e-3) |
748
- | `size` | `string` | Image size (512x512, 1024x1024, etc.) |
749
- | `quality` | `'standard' \| 'hd'` | Image quality (DALL-E 3 only) |
750
- | `style` | `'vivid' \| 'natural'` | Image style (DALL-E 3 only) |
751
- | `n` | `number` | Number of images to generate |
752
- | `responseFormat` | `'url' \| 'b64_json'` | Response format |
753
-
754
- #### Transcription Request
755
-
756
- | Parameter | Type | Description |
757
- |-----------|------|-------------|
758
- | `audio` | `Buffer \| string \| Blob` | Audio file to transcribe |
759
- | `model` | `string` | Model to use (whisper-1) |
760
- | `language` | `string` | ISO-639-1 language code |
761
- | `prompt` | `string` | Context for better accuracy |
762
- | `responseFormat` | `'json' \| 'text' \| 'srt' \| 'vtt' \| 'verbose_json'` | Output format |
763
- | `timestampGranularities` | `('word' \| 'segment')[]` | Timestamp detail level |
764
- | `temperature` | `number` | Sampling temperature |
765
-
766
- #### Speech Synthesis Request
767
-
768
- | Parameter | Type | Description |
769
- |-----------|------|-------------|
770
- | `text` | `string` | Text to convert to speech |
771
- | `model` | `string` | Model to use (tts-1, tts-1-hd) |
772
- | `voice` | `string` | Voice ID (alloy, echo, fable, onyx, nova, shimmer) |
773
- | `speed` | `number` | Playback speed (0.25-4.0) |
774
- | `responseFormat` | `'mp3' \| 'opus' \| 'aac' \| 'flac' \| 'wav' \| 'pcm'` | Audio format |
775
-
776
- #### Embedding Request
777
-
778
- | Parameter | Type | Description |
779
- |-----------|------|-------------|
780
- | `texts` | `string[]` | Texts to embed |
781
- | `model` | `string` | Model to use (text-embedding-3-small, text-embedding-3-large, text-embedding-ada-002) |
782
- | `dimensions` | `number` | Output dimensions (embedding-3 models only) |
783
- | `encodingFormat` | `'float' \| 'base64'` | Encoding format |
784
-
785
- ## Error Handling
786
-
787
- The provider throws specific error types for different failure scenarios:
788
-
789
- ```typescript
790
- import { ProviderError, RateLimitError, ProviderAuthError } from '@aeye/openai';
791
-
792
- try {
793
- const response = await executor(
794
- { messages: [{ role: 'user', content: 'Hello' }] },
795
- {},
796
- { model: 'gpt-4' }
797
- );
798
- } catch (error) {
799
- if (error instanceof RateLimitError) {
800
- console.error('Rate limit exceeded');
801
- if (error.retryAfter) {
802
- console.log(`Retry after ${error.retryAfter} seconds`);
803
- }
804
- } else if (error instanceof ProviderAuthError) {
805
- console.error('Authentication failed - check your API key');
806
- } else if (error instanceof ProviderError) {
807
- console.error(`Provider error: ${error.message}`);
808
- console.error('Original error:', error.cause);
809
- }
810
- }
811
- ```
812
-
813
- ### Error Types
814
-
815
- - **`ProviderError`**: Base error for all provider-related errors
816
- - **`ProviderAuthError`**: Authentication/authorization failures
817
- - **`RateLimitError`**: Rate limit exceeded (includes `retryAfter` if available)
818
- - **`ProviderRateLimitError`**: Specialized rate limit error
819
- - **`ProviderQuotaError`**: Quota/usage limit exceeded
820
-
821
- ## API Reference
822
-
823
- ### OpenAIProvider
824
-
825
- Main provider class implementing the @aeye Provider interface.
826
-
827
- **Constructor**: `new OpenAIProvider(config: OpenAIConfig)`
828
-
829
- **Methods**:
830
- - `listModels(config?: TConfig): Promise<ModelInfo[]>` - List available models
831
- - `checkHealth(config?: TConfig): Promise<boolean>` - Check API health
832
- - `createExecutor<TContext, TMetadata>(config?: TConfig): Executor` - Create chat executor
833
- - `createStreamer<TContext, TMetadata>(config?: TConfig): Streamer` - Create streaming executor
834
- - `generateImage<TContext>(request, ctx, config?): Promise<ImageGenerationResponse>` - Generate images
835
- - `transcribe<TContext>(request, ctx, config?): Promise<TranscriptionResponse>` - Transcribe audio
836
- - `generateSpeech<TContext>(request, ctx, config?): Promise<SpeechResponse>` - Generate speech
837
- - `embed<TContext>(request, ctx, config?): Promise<EmbeddingResponse>` - Generate embeddings
838
-
839
- **Protected Methods** (for extending):
840
- - `createClient(config): OpenAI` - Create OpenAI client
841
- - `convertModel(model): ModelInfo` - Convert model format
842
- - `convertMessages(request): OpenAI.ChatCompletionMessageParam[]` - Convert messages
843
- - `convertTools(request): OpenAI.ChatCompletionTool[]` - Convert tools
844
- - `convertToolChoice(request): OpenAI.ChatCompletionToolChoiceOption` - Convert tool choice
845
- - `convertResponseFormat(request): ResponseFormat` - Convert response format
846
- - `customizeChatParams(params, config, request)` - Customize chat params
847
- - `customizeImageParams(params, config)` - Customize image params
848
- - `customizeTranscriptionParams(params, config)` - Customize transcription params
849
- - `customizeSpeechParams(params, config)` - Customize speech params
850
- - `customizeEmbeddingParams(params, config)` - Customize embedding params
851
-
852
- ## Model Support
853
-
854
- ### Chat Models
855
-
856
- - **GPT-4 Turbo**: `gpt-4-turbo`, `gpt-4-turbo-preview`
857
- - **GPT-4**: `gpt-4`, `gpt-4-0613`, `gpt-4-32k`
858
- - **GPT-4 Vision**: `gpt-4-vision-preview`, `gpt-4-turbo-2024-04-09`
859
- - **GPT-3.5 Turbo**: `gpt-3.5-turbo`, `gpt-3.5-turbo-16k`
860
- - **Reasoning**: `o1-preview`, `o1-mini`, `o3-mini`
861
-
862
- ### Image Models
863
-
864
- - **DALL-E 3**: `dall-e-3`
865
- - **DALL-E 2**: `dall-e-2`
866
-
867
- ### Audio Models
868
-
869
- - **Whisper**: `whisper-1`
870
- - **TTS**: `tts-1`, `tts-1-hd`
871
-
872
- ### Embedding Models
873
-
874
- - **Embedding v3**: `text-embedding-3-small`, `text-embedding-3-large`
875
- - **Embedding v2**: `text-embedding-ada-002`
876
-
877
- ## Best Practices
878
-
879
- 1. **API Key Security**: Never hardcode API keys. Use environment variables or secure key management.
880
-
881
- 2. **Error Handling**: Always wrap API calls in try-catch blocks and handle rate limits gracefully.
882
-
883
- 3. **Streaming for Long Responses**: Use streaming for better user experience with lengthy responses.
884
-
885
- 4. **Token Management**: Monitor token usage to control costs. Use `maxTokens` to limit response length.
886
-
887
- 5. **Model Selection**: Choose the appropriate model for your use case:
888
- - GPT-4 for complex tasks requiring high accuracy
889
- - GPT-3.5 Turbo for simpler tasks and faster responses
890
- - o1/o3-mini for reasoning-heavy problems
891
-
892
- 6. **Function Calling**: Use structured schemas with Zod for type-safe function definitions.
893
-
894
- 7. **Retry Logic**: Implement exponential backoff for rate limit errors.
895
-
896
- 8. **Context Window**: Be aware of model context limits and truncate messages if needed.
897
-
898
- ## Related Packages
899
-
900
- - **[@aeye/core](../core)**: Core @aeye framework types and interfaces
901
- - **[@aeye/ai](../ai)**: AI abstractions and utilities
902
- - **[@aeye/anthropic](../anthropic)**: Anthropic Claude provider
903
- - **[@aeye/openrouter](../openrouter)**: OpenRouter multi-provider gateway
904
-
905
- ## License
906
-
907
- GPL-3.0
908
-
909
- ## Contributing
910
-
911
- Contributions are welcome! Please see the main [@aeye repository](https://github.com/ClickerMonkey/aeye) for contribution guidelines.
912
-
913
- ## Support
914
-
915
- For issues and questions:
916
- - GitHub Issues: https://github.com/ClickerMonkey/aeye/issues
917
- - Documentation: https://github.com/ClickerMonkey/aeye
918
-
919
- ## Changelog
920
-
921
- See [CHANGELOG.md](CHANGELOG.md) for version history and updates.
1
+ # @aeye/openai
2
+
3
+ OpenAI provider for the @aeye (AI TypeScript) framework. This package provides a comprehensive integration with OpenAI's API, supporting the full range of capabilities including chat completions, image generation, speech synthesis, transcription, and embeddings.
4
+
5
+ ## Features
6
+
7
+ - **Chat**: GPT-5.x, GPT-6, GPT-4.1 and other chat models, through Chat Completions or the Responses API
8
+ - **Vision**: Image and file (PDF) understanding
9
+ - **Reasoning**: Efforts `none` through `max`, reasoning summaries, and encrypted reasoning carried across turns
10
+ - **Hosted Tools**: Web search, file search, code interpreter, image generation, and remote MCP servers run by OpenAI
11
+ - **Image Generation**: GPT Image (`gpt-image-2` by default) for generating and editing images
12
+ - **Speech-to-Text**: `gpt-transcribe`, diarization with known speakers, and Whisper
13
+ - **Text-to-Speech**: TTS models with built-in or custom voices
14
+ - **Audio Output**: Spoken answers from audio-capable chat models
15
+ - **Embeddings**: Text embeddings for semantic search and similarity
16
+ - **Decisions**: Probabilities, choices, and scores from `/v1/decisions` (`gpt-6-luna`)
17
+ - **Batches**: Chat requests as one batch at about half the price
18
+ - **Function Calling**: Tool/function calling with automatic schema conversion, free-text and grammar tools, tool search, async tools, and allowed tools
19
+ - **Structured Outputs**: JSON mode and schema-based structured outputs
20
+ - **Streaming**: Real-time streaming responses for chat completions
21
+ - **Multi-modal**: Support for text, images, audio, and files in conversations
22
+ - **Extensible**: Base class for OpenAI-compatible providers (Azure OpenAI, OpenRouter, etc.)
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ npm install @aeye/openai @aeye/ai @aeye/core openai zod
28
+ ```
29
+
30
+ Requires Node >= 22 and the `openai` SDK v7.
31
+
32
+ ## Quick Start
33
+
34
+ ```typescript
35
+ import { OpenAIProvider } from '@aeye/openai';
36
+
37
+ // Create provider instance
38
+ const provider = new OpenAIProvider({
39
+ apiKey: process.env.OPENAI_API_KEY!,
40
+ });
41
+
42
+ // Create executor
43
+ const executor = provider.createExecutor();
44
+
45
+ // Make a request
46
+ const response = await executor(
47
+ {
48
+ messages: [
49
+ { role: 'user', content: 'Tell me a joke about TypeScript' }
50
+ ]
51
+ },
52
+ {},
53
+ { model: 'gpt-5.4-mini' }
54
+ );
55
+
56
+ console.log(response.content);
57
+ ```
58
+
59
+ ## Configuration
60
+
61
+ ### Basic Configuration
62
+
63
+ ```typescript
64
+ import { OpenAIProvider, OpenAIConfig } from '@aeye/openai';
65
+
66
+ const config: OpenAIConfig = {
67
+ apiKey: process.env.OPENAI_API_KEY!,
68
+ organization: 'org-123456', // Optional: for multi-org accounts
69
+ };
70
+
71
+ const provider = new OpenAIProvider(config);
72
+ ```
73
+
74
+ ### Chat Completions or Responses API
75
+
76
+ ```typescript
77
+ const provider = new OpenAIProvider({
78
+ apiKey: process.env.OPENAI_API_KEY!,
79
+ api: 'auto', // 'auto' (default) | 'chat' | 'responses'
80
+ });
81
+ ```
82
+
83
+ With `'auto'`, chat uses Chat Completions unless the model is Responses-only (codex, pre-5.6 pro models, deep-research, computer-use), the request has `hostedTools`, a tool sets `format`, `defer`, or `async`, `reason` sets `mode`, `summary`, or `context`, or the request has tools and a reasoning `effort` other than `none`. Through Responses, reasoning comes back encrypted (unless `store` is on) and is replayed on later turns.
84
+
85
+ ### Custom Base URL (for Azure OpenAI or compatible APIs)
86
+
87
+ ```typescript
88
+ const provider = new OpenAIProvider({
89
+ apiKey: process.env.AZURE_API_KEY!,
90
+ baseURL: 'https://your-resource.openai.azure.com/openai/deployments/your-deployment',
91
+ });
92
+ ```
93
+
94
+ ## Usage Examples
95
+
96
+ ### Chat Completions
97
+
98
+ #### Basic Chat
99
+
100
+ ```typescript
101
+ const executor = provider.createExecutor();
102
+
103
+ const response = await executor(
104
+ {
105
+ messages: [
106
+ { role: 'system', content: 'You are a helpful assistant.' },
107
+ { role: 'user', content: 'What is the capital of France?' }
108
+ ],
109
+ temperature: 0.7,
110
+ maxTokens: 150,
111
+ },
112
+ {},
113
+ { model: 'gpt-5.4-mini' }
114
+ );
115
+
116
+ console.log(response.content);
117
+ console.log('Tokens used:', response.usage.totalTokens);
118
+ ```
119
+
120
+ #### Streaming Chat
121
+
122
+ ```typescript
123
+ const streamer = provider.createStreamer();
124
+
125
+ for await (const chunk of streamer(
126
+ {
127
+ messages: [
128
+ { role: 'user', content: 'Write a short story about a robot' }
129
+ ]
130
+ },
131
+ {},
132
+ { model: 'gpt-5.4-mini' }
133
+ )) {
134
+ if (chunk.content) {
135
+ process.stdout.write(chunk.content);
136
+ }
137
+ }
138
+ ```
139
+
140
+ #### Multi-turn Conversation
141
+
142
+ ```typescript
143
+ const conversation = [
144
+ { role: 'system' as const, content: 'You are a helpful assistant.' },
145
+ { role: 'user' as const, content: 'What is TypeScript?' },
146
+ ];
147
+
148
+ // First response
149
+ let response = await executor(
150
+ { messages: conversation },
151
+ {},
152
+ { model: 'gpt-5.4-mini' }
153
+ );
154
+
155
+ conversation.push({ role: 'assistant', content: response.content });
156
+ conversation.push({ role: 'user', content: 'Can you give me an example?' });
157
+
158
+ // Second response
159
+ response = await executor(
160
+ { messages: conversation },
161
+ {},
162
+ { model: 'gpt-5.4-mini' }
163
+ );
164
+ ```
165
+
166
+ ### Vision
167
+
168
+ #### Analyze an Image
169
+
170
+ ```typescript
171
+ const response = await executor(
172
+ {
173
+ messages: [
174
+ {
175
+ role: 'user',
176
+ content: [
177
+ { type: 'text', content: 'What is in this image?' },
178
+ {
179
+ type: 'image',
180
+ content: 'https://example.com/image.jpg',
181
+ // Or use base64: content: 'data:image/jpeg;base64,/9j/4AAQ...'
182
+ }
183
+ ]
184
+ }
185
+ ]
186
+ },
187
+ {},
188
+ { model: 'gpt-5.4-mini' }
189
+ );
190
+ ```
191
+
192
+ #### Multiple Images
193
+
194
+ ```typescript
195
+ const response = await executor(
196
+ {
197
+ messages: [
198
+ {
199
+ role: 'user',
200
+ content: [
201
+ { type: 'text', content: 'Compare these two images' },
202
+ { type: 'image', content: 'https://example.com/image1.jpg' },
203
+ { type: 'image', content: 'https://example.com/image2.jpg' }
204
+ ]
205
+ }
206
+ ]
207
+ },
208
+ {},
209
+ { model: 'gpt-5.4-mini' }
210
+ );
211
+ ```
212
+
213
+ ### Function Calling
214
+
215
+ #### Define and Use Tools
216
+
217
+ ```typescript
218
+ import z from 'zod';
219
+
220
+ const response = await executor(
221
+ {
222
+ messages: [
223
+ { role: 'user', content: 'What is the weather like in San Francisco?' }
224
+ ],
225
+ tools: [
226
+ {
227
+ name: 'get_current_weather',
228
+ description: 'Get the current weather in a given location',
229
+ parameters: z.object({
230
+ location: z.string().describe('The city and state, e.g., San Francisco, CA'),
231
+ unit: z.enum(['celsius', 'fahrenheit']).optional(),
232
+ }),
233
+ }
234
+ ],
235
+ toolChoice: 'auto', // 'auto', 'required', 'none', { tool: 'tool_name' }, or { allowed: ['tool_name'], required? }
236
+ },
237
+ {},
238
+ { model: 'gpt-5.4-mini' }
239
+ );
240
+
241
+ if (response.toolCalls) {
242
+ for (const toolCall of response.toolCalls) {
243
+ console.log('Tool:', toolCall.name);
244
+ console.log('Arguments:', JSON.parse(toolCall.arguments));
245
+
246
+ // Execute the function and send result back
247
+ const functionResult = await getWeather(JSON.parse(toolCall.arguments));
248
+
249
+ const finalResponse = await executor(
250
+ {
251
+ messages: [
252
+ { role: 'user', content: 'What is the weather like in San Francisco?' },
253
+ { role: 'assistant', content: '', toolCalls: [toolCall] },
254
+ {
255
+ role: 'tool',
256
+ content: JSON.stringify(functionResult),
257
+ toolCallId: toolCall.id,
258
+ }
259
+ ]
260
+ },
261
+ {},
262
+ { model: 'gpt-5.4-mini' }
263
+ );
264
+ }
265
+ }
266
+ ```
267
+
268
+ #### Force Specific Tool
269
+
270
+ ```typescript
271
+ const response = await executor(
272
+ {
273
+ messages: [
274
+ { role: 'user', content: 'Get the weather for Boston' }
275
+ ],
276
+ tools: [
277
+ {
278
+ name: 'get_weather',
279
+ description: 'Get weather information',
280
+ parameters: z.object({
281
+ location: z.string(),
282
+ }),
283
+ }
284
+ ],
285
+ toolChoice: { tool: 'get_weather' }, // Force this specific tool
286
+ },
287
+ {},
288
+ { model: 'gpt-5.4-mini' }
289
+ );
290
+ ```
291
+
292
+ ### Structured Outputs
293
+
294
+ #### JSON Mode
295
+
296
+ ```typescript
297
+ const response = await executor(
298
+ {
299
+ messages: [
300
+ {
301
+ role: 'user',
302
+ content: 'List three famous scientists and their main contributions in JSON format'
303
+ }
304
+ ],
305
+ responseFormat: 'json', // Ensures valid JSON output
306
+ },
307
+ {},
308
+ { model: 'gpt-5.4-mini' }
309
+ );
310
+
311
+ const scientists = JSON.parse(response.content);
312
+ ```
313
+
314
+ #### Schema-based Structured Output
315
+
316
+ ```typescript
317
+ import z from 'zod';
318
+
319
+ const PersonSchema = z.object({
320
+ name: z.string(),
321
+ age: z.number(),
322
+ occupation: z.string(),
323
+ hobbies: z.array(z.string()),
324
+ });
325
+
326
+ const response = await executor(
327
+ {
328
+ messages: [
329
+ {
330
+ role: 'user',
331
+ content: 'Generate a profile for a fictional software engineer'
332
+ }
333
+ ],
334
+ responseFormat: PersonSchema, // Strict schema enforcement
335
+ },
336
+ {},
337
+ { model: 'gpt-5.4-mini' }
338
+ );
339
+
340
+ // Response is guaranteed to match the schema
341
+ const person = JSON.parse(response.content);
342
+ console.log(person.name, person.age); // Type-safe
343
+ ```
344
+
345
+ A schema that fits OpenAI's strict dialect is sent with `strict: true`. One that doesn't (nested more than 10 levels, for example) goes non-strict, and through the Responses API it is marked `strict: false`, since Responses treats an unflagged `json_schema` as strict.
346
+
347
+ ### Image Generation (GPT Image)
348
+
349
+ #### Generate an Image
350
+
351
+ ```typescript
352
+ const imageResponse = await provider.generateImage(
353
+ {
354
+ prompt: 'A serene landscape with mountains and a lake at sunset',
355
+ model: 'gpt-image-2', // the default
356
+ size: '1024x1024', // or 'auto'; other sizes snap to the nearest the model supports
357
+ quality: 'high', // 'auto' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' (per model)
358
+ outputFormat: 'webp', // 'png' | 'jpeg' | 'webp'
359
+ outputCompression: 80, // 0-100, for jpeg and webp
360
+ background: 'transparent',
361
+ n: 1,
362
+ },
363
+ {}
364
+ );
365
+
366
+ const base64Image = imageResponse.images[0].b64_json;
367
+ ```
368
+
369
+ #### Edit with Reference Images
370
+
371
+ ```typescript
372
+ const edited = await provider.editImage(
373
+ {
374
+ prompt: 'Put the product from the second image on the table in the first',
375
+ image: fs.readFileSync('room.png'), // source image
376
+ references: [fs.readFileSync('product.png')], // more input images
377
+ mask: fs.readFileSync('mask.png'), // optional, over the source image
378
+ inputFidelity: 'high', // keep input details closely
379
+ },
380
+ {}
381
+ );
382
+ ```
383
+
384
+ Usage reports the quality and size actually produced, so per-image pricing applies; GPT Image 2 and later report output image tokens in `usage.image.tokens`.
385
+
386
+ ### Speech Synthesis (TTS)
387
+
388
+ #### Generate Speech
389
+
390
+ ```typescript
391
+ import fs from 'fs';
392
+ import { Readable } from 'stream';
393
+
394
+ const speechResponse = await provider.generateSpeech(
395
+ {
396
+ text: 'Hello! This is a text-to-speech example using OpenAI.',
397
+ model: 'gpt-4o-mini-tts', // the default
398
+ voice: 'alloy', // any built-in voice name or a custom voice id
399
+ instructions: 'Speak warmly and a little slowly.',
400
+ speed: 1.0, // 0.25 to 4.0
401
+ responseFormat: 'mp3', // mp3, opus, aac, flac, wav, pcm
402
+ },
403
+ {}
404
+ );
405
+
406
+ // Save to file
407
+ Readable.fromWeb(speechResponse.audio).pipe(fs.createWriteStream('output.mp3'));
408
+ console.log('Audio saved to output.mp3');
409
+ ```
410
+
411
+ #### Different Voices
412
+
413
+ ```typescript
414
+ const voices = ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'];
415
+
416
+ for (const voice of voices) {
417
+ const response = await provider.generateSpeech(
418
+ {
419
+ text: `This is the ${voice} voice speaking.`,
420
+ voice,
421
+ model: 'gpt-4o-mini-tts',
422
+ },
423
+ {}
424
+ );
425
+
426
+ Readable.fromWeb(response.audio).pipe(fs.createWriteStream(`voice_${voice}.mp3`));
427
+ }
428
+ ```
429
+
430
+ ### Transcription
431
+
432
+ #### Transcribe Audio File
433
+
434
+ ```typescript
435
+ import fs from 'fs';
436
+
437
+ const audioBuffer = fs.readFileSync('audio.mp3');
438
+
439
+ const transcription = await provider.transcribe(
440
+ {
441
+ audio: audioBuffer,
442
+ model: 'gpt-transcribe', // the default
443
+ language: 'en', // Optional: ISO-639-1 language code
444
+ prompt: 'This is a podcast about AI and technology', // Optional: context
445
+ },
446
+ {}
447
+ );
448
+
449
+ console.log('Transcription:', transcription.text);
450
+ ```
451
+
452
+ #### Transcribe with Timestamps
453
+
454
+ ```typescript
455
+ const transcription = await provider.transcribe(
456
+ {
457
+ audio: audioBuffer,
458
+ model: 'whisper-1',
459
+ responseFormat: 'verbose_json',
460
+ timestampGranularities: ['word', 'segment'],
461
+ },
462
+ {}
463
+ );
464
+
465
+ console.log('Full text:', transcription.text);
466
+
467
+ // Segment-level timestamps
468
+ transcription.segments?.forEach(segment => {
469
+ console.log(`${segment.text}: ${segment.start}s - ${segment.end}s`);
470
+ });
471
+ ```
472
+
473
+ #### Speaker Diarization
474
+
475
+ ```typescript
476
+ const transcription = await provider.transcribe(
477
+ {
478
+ audio: fs.readFileSync('meeting.mp3'),
479
+ model: 'gpt-4o-transcribe-diarize',
480
+ responseFormat: 'diarized_json',
481
+ knownSpeakers: [
482
+ { name: 'Alice', audio: fs.readFileSync('alice.wav') },
483
+ { name: 'Bob', audio: fs.readFileSync('bob.wav') },
484
+ ],
485
+ },
486
+ {}
487
+ );
488
+
489
+ transcription.segments?.forEach(segment => {
490
+ console.log(`${segment.speaker}: ${segment.text}`);
491
+ });
492
+ ```
493
+
494
+ #### Different Output Formats
495
+
496
+ ```typescript
497
+ // Plain text
498
+ const text = await provider.transcribe(
499
+ { audio: audioBuffer, responseFormat: 'text' },
500
+ {}
501
+ );
502
+
503
+ // SRT subtitles
504
+ const srt = await provider.transcribe(
505
+ { audio: audioBuffer, responseFormat: 'srt' },
506
+ {}
507
+ );
508
+
509
+ // VTT subtitles
510
+ const vtt = await provider.transcribe(
511
+ { audio: audioBuffer, responseFormat: 'vtt' },
512
+ {}
513
+ );
514
+ ```
515
+
516
+ ### Embeddings
517
+
518
+ #### Generate Embeddings
519
+
520
+ ```typescript
521
+ const embeddingResponse = await provider.embed(
522
+ {
523
+ texts: [
524
+ 'The quick brown fox jumps over the lazy dog',
525
+ 'Machine learning is a subset of artificial intelligence',
526
+ 'OpenAI develops advanced AI models'
527
+ ],
528
+ model: 'text-embedding-3-small', // or 'text-embedding-3-large'
529
+ },
530
+ {}
531
+ );
532
+
533
+ embeddingResponse.embeddings.forEach((item, i) => {
534
+ console.log(`Embedding ${i}:`, item.embedding.length, 'dimensions');
535
+ });
536
+
537
+ console.log('Tokens used:', embeddingResponse.usage?.text?.input);
538
+ ```
539
+
540
+ #### Custom Dimensions (for smaller embeddings)
541
+
542
+ ```typescript
543
+ const embeddingResponse = await provider.embed(
544
+ {
545
+ texts: ['Some text to embed'],
546
+ model: 'text-embedding-3-large',
547
+ dimensions: 256, // Reduce from default 3072 to 256
548
+ },
549
+ {}
550
+ );
551
+ ```
552
+
553
+ #### Calculate Similarity
554
+
555
+ ```typescript
556
+ function cosineSimilarity(a: number[], b: number[]): number {
557
+ const dotProduct = a.reduce((sum, val, i) => sum + val * b[i], 0);
558
+ const magnitudeA = Math.sqrt(a.reduce((sum, val) => sum + val * val, 0));
559
+ const magnitudeB = Math.sqrt(b.reduce((sum, val) => sum + val * val, 0));
560
+ return dotProduct / (magnitudeA * magnitudeB);
561
+ }
562
+
563
+ const response = await provider.embed(
564
+ {
565
+ texts: [
566
+ 'I love programming in TypeScript',
567
+ 'TypeScript is my favorite language',
568
+ 'I enjoy cooking Italian food'
569
+ ],
570
+ model: 'text-embedding-3-small',
571
+ },
572
+ {}
573
+ );
574
+
575
+ const [emb1, emb2, emb3] = response.embeddings.map(e => e.embedding);
576
+
577
+ console.log('Similarity 1-2:', cosineSimilarity(emb1, emb2)); // High similarity
578
+ console.log('Similarity 1-3:', cosineSimilarity(emb1, emb3)); // Low similarity
579
+ ```
580
+
581
+ ### Reasoning
582
+
583
+ ```typescript
584
+ const response = await executor(
585
+ {
586
+ messages: [
587
+ {
588
+ role: 'user',
589
+ content: 'Solve this logic puzzle: There are 100 doors, all closed. You make 100 passes. On pass 1, toggle all doors. On pass 2, toggle every 2nd door. On pass 3, toggle every 3rd door, etc. Which doors are open after 100 passes?'
590
+ }
591
+ ],
592
+ reason: {
593
+ effort: 'high', // 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'
594
+ summary: 'auto', // a readable summary (uses the Responses API)
595
+ },
596
+ },
597
+ {},
598
+ { model: 'gpt-5.5' }
599
+ );
600
+
601
+ console.log('Reasoning:', response.reasoning?.content);
602
+ console.log('Answer:', response.content);
603
+ ```
604
+
605
+ - The effort is clamped to the model's accepted efforts when its `ModelInfo.reasoningEfforts` lists them.
606
+ - `mode`, `summary`, or `context`, or an effort other than `none` with tools, send the request to the Responses API. There, reasoning comes back encrypted (`openai-responses-v1` details) unless `store` is on; keep the assistant message's `reasoning` in the conversation and it is replayed on the next turn.
607
+ - `reason.maxTokens` and `reason.exclude` are not used by OpenAI.
608
+ - Only reasoning OpenAI produced (`reasoning.provider` is `'openai'`, or unset) is replayed; reasoning relayed by OpenRouter or made on Bedrock is left out, since OpenAI can't decrypt it.
609
+ - An assistant turn of only tool calls is sent with no content rather than an empty text part.
610
+
611
+ ### Hosted Tools
612
+
613
+ Tools OpenAI runs itself go in `hostedTools` and use the Responses API:
614
+
615
+ ```typescript
616
+ const response = await executor(
617
+ {
618
+ messages: [{ role: 'user', content: 'Summarize this week\'s TypeScript news.' }],
619
+ hostedTools: [
620
+ { type: 'web_search', allowedDomains: ['devblogs.microsoft.com'] },
621
+ { type: 'code_interpreter' },
622
+ { type: 'file_search', vectorStoreIds: ['vs_123'], maxResults: 5 },
623
+ { type: 'mcp', label: 'docs', url: 'https://example.com/mcp', allowedTools: ['search'] },
624
+ { type: 'image_generation' },
625
+ ],
626
+ },
627
+ {},
628
+ { model: 'gpt-5.4-mini' }
629
+ );
630
+
631
+ console.log(response.citations); // [{ url, title, start, end }]
632
+ console.log(response.usage?.tools); // { web_search: 1, ... }
633
+ ```
634
+
635
+ `web_fetch` is not available on OpenAI (web search fetches pages itself), and web search can only allow domains, not block them (`blockedDomains` is rejected). Images from `image_generation` come back on `response.images`.
636
+
637
+ ### Audio Output
638
+
639
+ ```typescript
640
+ const response = await executor(
641
+ {
642
+ messages: [{ role: 'user', content: 'Say hello in French.' }],
643
+ modalities: ['text', 'audio'],
644
+ audio: { voice: 'alloy', format: 'mp3' }, // streaming defaults to pcm
645
+ },
646
+ {},
647
+ { model: 'gpt-audio-1.5' }
648
+ );
649
+
650
+ console.log(response.audio?.transcript); // response.audio.data is base64
651
+ ```
652
+
653
+ ### Other Request Options
654
+
655
+ - `seed`, `verbosity` (`'low' | 'medium' | 'high'`), `serviceTier` (`'auto' | 'default' | 'flex' | 'fast' | 'scale'`), and `metadata` are passed through. Chat Completions sends `metadata` only when `store` is on.
656
+ - `moderate: true` runs inline moderation (`omni-moderation-latest`); verdicts come back on `response.moderation`.
657
+ - Content parts take `cacheBreakpoint` (a prompt cache breakpoint), `detail` for images, and `name` for files.
658
+ - `response.serviceTier` reports the tier used (`priority` reads as `fast`).
659
+
660
+ ### Tool Features
661
+
662
+ - `toolChoice: { allowed: [...], required? }` is sent as `allowed_tools` on both APIs: every tool is still sent (keeping the prompt cacheable), but only the allowed ones may be called.
663
+ - A tool with `format: { type: 'text' }` or `format: { type: 'grammar', syntax: 'lark' | 'regex', definition }` is a Responses custom tool: the model writes free text, constrained by the grammar, and it arrives as `{ input }` arguments (`TEXT_TOOL_SCHEMA` from `@aeye/core`). With `api: 'chat'` it is a one-field function whose description carries the grammar.
664
+ - `defer: true` sends the tool with `defer_loading` and adds the hosted `tool_search` tool, so it is loaded only when the model searches for it.
665
+ - `async: true` marks an async tool; the model keeps working while it runs.
666
+
667
+ ```typescript
668
+ import { TEXT_TOOL_SCHEMA } from '@aeye/core';
669
+
670
+ const response = await executor(
671
+ {
672
+ messages: [{ role: 'user', content: 'How many orders did customer 42 place?' }],
673
+ tools: [{
674
+ name: 'sql',
675
+ description: 'Run a read-only SQL query',
676
+ parameters: TEXT_TOOL_SCHEMA,
677
+ format: { type: 'grammar', syntax: 'regex', definition: 'SELECT [^;]+;' },
678
+ }],
679
+ },
680
+ {},
681
+ { model: 'gpt-5.4-mini' }
682
+ );
683
+
684
+ console.log(response.toolCalls?.[0]?.arguments); // {"input":"SELECT COUNT(*) FROM orders WHERE customer_id = 42;"}
685
+ ```
686
+
687
+ ### Decisions
688
+
689
+ Typed answers from `/v1/decisions` (default model `gpt-6-luna`, or `defaultModels.decision`), through `ai.decide`:
690
+
691
+ ```typescript
692
+ import { AI } from '@aeye/ai';
693
+
694
+ const ai = AI.with().providers({ openai: provider }).create();
695
+
696
+ const { answers } = await ai.decide.get({
697
+ input: 'I was charged twice for my order.',
698
+ questions: {
699
+ billing: { type: 'predicate', instructions: 'Is this a billing problem?' },
700
+ urgency: { type: 'score', instructions: 'How urgent is it?', levels: ['Can wait', 'This week', 'Now'] },
701
+ },
702
+ });
703
+ ```
704
+
705
+ Decisions report through the `decide` hooks.
706
+
707
+ ### Batches
708
+
709
+ `ai.batch` uploads chat requests as a JSONL file and runs them as one batch with a 24 hour window, at about half the price. Results come back in request order; a failed request has `error`.
710
+
711
+ ```typescript
712
+ const job = await ai.batch.submit(
713
+ questions.map(question => ({ messages: [{ role: 'user', content: question }] })),
714
+ { metadata: { model: 'gpt-5.4-mini' } },
715
+ );
716
+
717
+ const done = await ai.batch.wait(job, {});
718
+ done.results?.forEach(result => console.log(result.response?.content ?? result.error));
719
+ ```
720
+
721
+ ### Advanced Features
722
+
723
+ #### Abort Requests
724
+
725
+ ```typescript
726
+ const controller = new AbortController();
727
+
728
+ // Set timeout
729
+ setTimeout(() => controller.abort(), 5000);
730
+
731
+ try {
732
+ const response = await executor(
733
+ { messages: [{ role: 'user', content: 'Tell me a long story' }] },
734
+ {},
735
+ { model: 'gpt-5.4-mini' },
736
+ controller.signal
737
+ );
738
+ } catch (error) {
739
+ if (error.name === 'AbortError') {
740
+ console.log('Request was aborted');
741
+ }
742
+ }
743
+ ```
744
+
745
+ #### List Available Models
746
+
747
+ ```typescript
748
+ const models = await provider.listModels();
749
+
750
+ models.forEach(model => {
751
+ console.log(`${model.id}: ${model.capabilities}`);
752
+ console.log(` Context window: ${model.contextWindow}`);
753
+ console.log(` Pricing: $${model.pricing.text.input}/1M input tokens`);
754
+ });
755
+ ```
756
+
757
+ #### Check Provider Health
758
+
759
+ ```typescript
760
+ const isHealthy = await provider.checkHealth();
761
+ console.log('OpenAI API is', isHealthy ? 'accessible' : 'not accessible');
762
+ ```
763
+
764
+ #### Default Metadata
765
+
766
+ ```typescript
767
+ // Set default metadata for all requests
768
+ provider.defaultMetadata = {
769
+ model: 'gpt-5.4-mini',
770
+ user: 'user-123',
771
+ };
772
+
773
+ // Now model is automatically set
774
+ const response = await executor(
775
+ { messages: [{ role: 'user', content: 'Hello' }] },
776
+ {}
777
+ // No need to pass { model: 'gpt-5.4-mini' }
778
+ );
779
+ ```
780
+
781
+ ## Extending for Custom Providers
782
+
783
+ The `OpenAIProvider` class can be extended to support OpenAI-compatible APIs like Azure OpenAI, OpenRouter, or custom deployments.
784
+
785
+ ### Example: Custom Provider
786
+
787
+ ```typescript
788
+ import type { Request } from '@aeye/core';
789
+ import { OpenAIProvider, OpenAIConfig } from '@aeye/openai';
790
+ import OpenAI from 'openai';
791
+
792
+ interface CustomConfig extends OpenAIConfig {
793
+ customOption?: string;
794
+ }
795
+
796
+ class CustomProvider extends OpenAIProvider<CustomConfig> {
797
+ readonly name = 'custom-provider';
798
+
799
+ protected createClient(config: CustomConfig): OpenAI {
800
+ return new OpenAI({
801
+ apiKey: config.apiKey,
802
+ baseURL: 'https://api.custom-provider.com/v1',
803
+ defaultHeaders: {
804
+ 'X-Custom-Header': config.customOption || '',
805
+ },
806
+ });
807
+ }
808
+
809
+ protected augmentChatRequest<TParams extends OpenAI.Chat.ChatCompletionCreateParams>(
810
+ params: TParams,
811
+ request: Request,
812
+ config: CustomConfig,
813
+ ) {
814
+ // Add custom parameters (mutate in place)
815
+ Object.assign(params, { custom_param: config.customOption });
816
+ }
817
+ }
818
+
819
+ // Use the custom provider
820
+ const customProvider = new CustomProvider({
821
+ apiKey: process.env.CUSTOM_API_KEY!,
822
+ customOption: 'value',
823
+ });
824
+ ```
825
+
826
+ ### Example: Azure OpenAI
827
+
828
+ ```typescript
829
+ class AzureOpenAIProvider extends OpenAIProvider {
830
+ readonly name = 'azure-openai';
831
+
832
+ protected createClient(config: OpenAIConfig): OpenAI {
833
+ return new OpenAI({
834
+ apiKey: config.apiKey,
835
+ baseURL: config.baseURL, // Azure endpoint
836
+ defaultQuery: { 'api-version': '2024-02-01' },
837
+ });
838
+ }
839
+ }
840
+
841
+ const azureProvider = new AzureOpenAIProvider({
842
+ apiKey: process.env.AZURE_OPENAI_KEY!,
843
+ baseURL: 'https://your-resource.openai.azure.com/openai/deployments/your-deployment',
844
+ });
845
+ ```
846
+
847
+ ## Configuration Options
848
+
849
+ ### OpenAIConfig
850
+
851
+ | Property | Type | Required | Description |
852
+ |----------|------|----------|-------------|
853
+ | `apiKey` | `string` | Yes | OpenAI API key |
854
+ | `baseURL` | `string` | No | Custom base URL for API endpoint |
855
+ | `organization` | `string` | No | OpenAI organization ID |
856
+ | `project` | `string` | No | OpenAI project ID |
857
+ | `store` | `boolean` | No | Let OpenAI store requests (default `false`) |
858
+ | `api` | `'auto' \| 'chat' \| 'responses'` | No | Which API chat uses (default `'auto'`) |
859
+ | `retry` / `retryEvents` | `RetryConfig` / `RetryEvents` | No | Retry behavior and events |
860
+ | `hooks` | `OpenAIHooks` | No | `beforeRequest` / `afterRequest` / `onError` for `chat`, `responses`, `imageGenerate`, `imageEdit`, `transcribe`, `speech`, `embed`, `rerank`, `decide` |
861
+ | `defaultModels` | `object` | No | Per-operation defaults; built in: `gpt-image-2` (generate, edit), `gpt-5.4-mini` (image analysis), `gpt-transcribe`, `gpt-4o-mini-tts`, `text-embedding-3-small`, `gpt-6-luna` (decision); `rerank` has no OpenAI default |
862
+
863
+ ### Request Parameters
864
+
865
+ #### Chat Completion Request
866
+
867
+ | Parameter | Type | Description |
868
+ |-----------|------|-------------|
869
+ | `messages` | `Message[]` | Array of conversation messages |
870
+ | `temperature` | `number` | Sampling temperature (0-2) |
871
+ | `topP` | `number` | Nucleus sampling parameter |
872
+ | `maxTokens` | `number` | Maximum tokens to generate |
873
+ | `stop` | `string \| string[]` | Stop sequences |
874
+ | `tools` | `Tool[]` | Function definitions for tool calling |
875
+ | `toolsOneAtATime` | `boolean` | Sends `parallel_tool_calls: false`. Otherwise Chat Completions leaves the parameter out (parallel calls are the default, and o3 rejects the parameter) |
876
+ | `toolChoice` | `'auto' \| 'required' \| 'none' \| { tool: string } \| { allowed: string[]; required?: boolean }` | Tool selection mode |
877
+ | `responseFormat` | `'text' \| 'json' \| ZodSchema` | Response format constraint |
878
+ | `reason` | `Reason` | `{ effort, summary, mode, context }` |
879
+ | `seed` / `verbosity` / `serviceTier` / `metadata` | | Passed through |
880
+ | `modalities` / `audio` | | Audio output |
881
+ | `hostedTools` | `HostedTool[]` | Tools OpenAI runs (Responses API) |
882
+ | `moderate` | `boolean` | Inline moderation |
883
+
884
+ #### Image Generation Request
885
+
886
+ | Parameter | Type | Description |
887
+ |-----------|------|-------------|
888
+ | `prompt` | `string` | Text description of desired image |
889
+ | `model` | `string` | GPT Image model (default gpt-image-2) |
890
+ | `size` | `string` | `WIDTHxHEIGHT` or `'auto'`; snaps to the model's sizes |
891
+ | `quality` | `'auto' \| 'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max'` | Image quality (models accept subsets) |
892
+ | `background` | `'transparent' \| 'opaque' \| 'auto'` | Background |
893
+ | `outputFormat` | `'png' \| 'jpeg' \| 'webp'` | Encoding |
894
+ | `outputCompression` | `number` | 0-100, for jpeg and webp |
895
+ | `moderation` | `'auto' \| 'low'` | Moderation strictness (generate) |
896
+ | `references` / `mask` / `inputFidelity` | | Extra input images, mask, and detail preservation (edit) |
897
+ | `n` | `number` | Number of images to generate |
898
+ | `streamCount` | `number` | Partial images to stream |
899
+
900
+ #### Transcription Request
901
+
902
+ | Parameter | Type | Description |
903
+ |-----------|------|-------------|
904
+ | `audio` | `Buffer \| string \| Blob` | Audio file to transcribe |
905
+ | `model` | `string` | Model to use (default gpt-transcribe) |
906
+ | `language` | `string` | ISO-639-1 language code |
907
+ | `prompt` | `string` | Context for better accuracy |
908
+ | `responseFormat` | `'json' \| 'text' \| 'srt' \| 'vtt' \| 'verbose_json' \| 'diarized_json'` | Output format |
909
+ | `knownSpeakers` | `{ name, audio }[]` | Reference clips for diarization |
910
+ | `timestampGranularities` | `('word' \| 'segment')[]` | Timestamp detail level |
911
+ | `temperature` | `number` | Sampling temperature |
912
+
913
+ #### Speech Synthesis Request
914
+
915
+ | Parameter | Type | Description |
916
+ |-----------|------|-------------|
917
+ | `text` | `string` | Text to convert to speech |
918
+ | `model` | `string` | Model to use (default gpt-4o-mini-tts) |
919
+ | `voice` | `string` | Built-in voice name or custom voice id (default alloy) |
920
+ | `instructions` | `string` | Style instructions |
921
+ | `speed` | `number` | Playback speed (0.25-4.0) |
922
+ | `responseFormat` | `'mp3' \| 'opus' \| 'aac' \| 'flac' \| 'wav' \| 'pcm'` | Audio format |
923
+
924
+ #### Embedding Request
925
+
926
+ | Parameter | Type | Description |
927
+ |-----------|------|-------------|
928
+ | `texts` | `string[]` | Texts to embed |
929
+ | `model` | `string` | Model to use (text-embedding-3-small, text-embedding-3-large, text-embedding-ada-002) |
930
+ | `dimensions` | `number` | Output dimensions (embedding-3 models only) |
931
+ | `encodingFormat` | `'float' \| 'base64'` | Encoding format |
932
+
933
+ ## Error Handling
934
+
935
+ The provider throws specific error types for different failure scenarios:
936
+
937
+ ```typescript
938
+ import { ProviderError, RateLimitError, ProviderAuthError } from '@aeye/openai';
939
+
940
+ try {
941
+ const response = await executor(
942
+ { messages: [{ role: 'user', content: 'Hello' }] },
943
+ {},
944
+ { model: 'gpt-5.4-mini' }
945
+ );
946
+ } catch (error) {
947
+ if (error instanceof RateLimitError) {
948
+ console.error('Rate limit exceeded');
949
+ if (error.retryAfter) {
950
+ console.log(`Retry after ${error.retryAfter} seconds`);
951
+ }
952
+ } else if (error instanceof ProviderAuthError) {
953
+ console.error('Authentication failed - check your API key');
954
+ } else if (error instanceof ProviderError) {
955
+ console.error(`Provider error: ${error.message}`);
956
+ console.error('Original error:', error.cause);
957
+ }
958
+ }
959
+ ```
960
+
961
+ ### Error Types
962
+
963
+ - **`ProviderError`**: Base error for all provider-related errors
964
+ - **`ProviderAuthError`**: Authentication/authorization failures
965
+ - **`RateLimitError`**: Rate limit exceeded (includes `retryAfter` if available)
966
+ - **`ProviderRateLimitError`**: Specialized rate limit error
967
+ - **`ProviderQuotaError`**: Quota/usage limit exceeded
968
+
969
+ ## API Reference
970
+
971
+ ### OpenAIProvider
972
+
973
+ Main provider class implementing the @aeye Provider interface.
974
+
975
+ **Constructor**: `new OpenAIProvider(config: OpenAIConfig)`
976
+
977
+ **Methods**:
978
+ - `listModels(config?: TConfig): Promise<ModelInfo[]>` - List available models
979
+ - `checkHealth(config?: TConfig): Promise<boolean>` - Check API health
980
+ - `createExecutor<TContext, TMetadata>(config?: TConfig): Executor` - Create chat executor
981
+ - `createStreamer<TContext, TMetadata>(config?: TConfig): Streamer` - Create streaming executor
982
+ - `generateImage<TContext>(request, ctx, config?): Promise<ImageGenerationResponse>` - Generate images
983
+ - `editImage<TContext>(request, ctx, config?): Promise<ImageGenerationResponse>` - Edit images
984
+ - `transcribe<TContext>(request, ctx, config?): Promise<TranscriptionResponse>` - Transcribe audio
985
+ - `speech(request, ctx, config?): Promise<SpeechResponse>` - Generate speech
986
+ - `embed<TContext>(request, ctx, config?): Promise<EmbeddingResponse>` - Generate embeddings
987
+ - `decide(request, ctx, config?): Promise<DecisionResponse>` - Answer decision questions
988
+ - `submitBatch(requests, ctx, config?): Promise<BatchJob>` / `getBatch(job, ctx, config?): Promise<BatchJob>` - Run and read batches
989
+
990
+ **Protected Methods** (for extending):
991
+ - `createClient(config): OpenAI` - Create OpenAI client
992
+ - `convertModel(model): ModelInfo` - Convert model format
993
+ - `convertMessages(request): OpenAI.ChatCompletionMessageParam[]` - Convert messages
994
+ - `convertTools(request): OpenAI.ChatCompletionTool[]` - Convert tools
995
+ - `convertToolChoice(request): OpenAI.ChatCompletionToolChoiceOption` - Convert tool choice
996
+ - `convertResponseFormat(request): ResponseFormat` - Convert response format
997
+ - `augmentChatRequest(params, request, config)` - Add to Chat Completions params (mutate in place)
998
+ - `chatHeaders(params)` - Extra HTTP headers for a Chat Completions request (none by default; OpenRouter adds a feature flag here)
999
+ - `augmentChatMessage(chatMessage, message, config)` / `augmentChatContent(...)` - Add to converted messages and content parts
1000
+ - `augmentChatResponse(completion, response, config)` / `augmentChatChunk(chunk, ...)` - Read extra fields from responses and chunks
1001
+ - `augmentImageGenerateRequest?` / `augmentImageEditRequest?` / `augmentTranscriptionRequest?` / `augmentSpeechRequest?` / `augmentEmbeddingRequest?` `(params, request, config)` - Optional hooks to add to those params
1002
+ - `usesResponses(request, modelId, config, model?)` - Whether a chat request goes to the Responses API
1003
+ - `createBatch(batch, run)` / `retrieveBatch(job, run)` - Submit and read batches (OpenRouter overrides these for inline batches)
1004
+ - `send(op, run, request, params, call)` / `finish(op, run, request, params, response)` - Run an API call with retries inside the operation's `beforeRequest` / `onError` hooks, then report its response to `afterRequest` (OpenRouter's `rerank` and `decide` use these)
1005
+
1006
+ ## Model Support
1007
+
1008
+ ### Chat Models
1009
+
1010
+ - **GPT-6**: `gpt-6-luna`, `gpt-6-sol`, `gpt-6-astra`, `gpt-6.1-sol`, `gpt-6.1-terra`
1011
+ - **GPT-5.x**: `gpt-5.6-*`, `gpt-5.5`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.4-nano`, `chat-latest`
1012
+ - **Pro and codex** (Responses API): `gpt-5.5-pro`, `gpt-5.4-pro`, `gpt-5.3-codex`
1013
+ - **GPT-4.1 / GPT-4o** (retiring): `gpt-4.1`, `gpt-4.1-mini`, `gpt-4o`, `gpt-4o-mini`
1014
+ - **Audio**: `gpt-audio-1.5`
1015
+
1016
+ ### Image Models
1017
+
1018
+ - **GPT Image**: `gpt-image-2`, `gpt-image-2.5-*`
1019
+
1020
+ ### Audio Models
1021
+
1022
+ - **Transcription**: `gpt-transcribe`, `gpt-4o-transcribe`, `gpt-4o-transcribe-diarize`, `whisper-1`
1023
+ - **TTS**: `gpt-4o-mini-tts`, `tts-1`, `tts-1-hd`
1024
+
1025
+ The `@aeye/models` registry records each model's `retiresAt` date; retired models are never selected.
1026
+
1027
+ ### Embedding Models
1028
+
1029
+ - **Embedding v3**: `text-embedding-3-small`, `text-embedding-3-large`
1030
+ - **Embedding v2**: `text-embedding-ada-002`
1031
+
1032
+ ## Best Practices
1033
+
1034
+ 1. **API Key Security**: Never hardcode API keys. Use environment variables or secure key management.
1035
+
1036
+ 2. **Error Handling**: Always wrap API calls in try-catch blocks and handle rate limits gracefully.
1037
+
1038
+ 3. **Streaming for Long Responses**: Use streaming for better user experience with lengthy responses.
1039
+
1040
+ 4. **Token Management**: Monitor token usage to control costs. Use `maxTokens` to limit response length.
1041
+
1042
+ 5. **Model Selection**: Choose the appropriate model for your use case:
1043
+ - GPT-6 or GPT-5.5 for complex tasks requiring high accuracy
1044
+ - `gpt-5.4-mini` / `gpt-5.4-nano` for simpler tasks and faster responses
1045
+ - A higher `reason.effort` for reasoning-heavy problems
1046
+
1047
+ 6. **Function Calling**: Use structured schemas with Zod for type-safe function definitions.
1048
+
1049
+ 7. **Retry Logic**: Implement exponential backoff for rate limit errors.
1050
+
1051
+ 8. **Context Window**: Be aware of model context limits and truncate messages if needed.
1052
+
1053
+ ## Related Packages
1054
+
1055
+ - **[@aeye/core](../core)**: Core @aeye framework types and interfaces
1056
+ - **[@aeye/ai](../ai)**: AI abstractions and utilities
1057
+ - **[@aeye/anthropic](../anthropic)**: Anthropic Claude provider
1058
+ - **[@aeye/openrouter](../openrouter)**: OpenRouter multi-provider gateway
1059
+
1060
+ ## License
1061
+
1062
+ GPL-3.0
1063
+
1064
+ ## Contributing
1065
+
1066
+ Contributions are welcome! Please see the main [@aeye repository](https://github.com/ClickerMonkey/aeye) for contribution guidelines.
1067
+
1068
+ ## Support
1069
+
1070
+ For issues and questions:
1071
+ - GitHub Issues: https://github.com/ClickerMonkey/aeye/issues
1072
+ - Documentation: https://github.com/ClickerMonkey/aeye
1073
+
1074
+ ## Changelog
1075
+
1076
+ See [CHANGELOG.md](CHANGELOG.md) for version history and updates.