This repository was archived by the owner on Jun 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathopenai.ts
More file actions
962 lines (879 loc) · 30.2 KB
/
Copy pathopenai.ts
File metadata and controls
962 lines (879 loc) · 30.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
/**
* OpenAI model provider implementation.
*
* This module provides integration with OpenAI's Chat Completions API,
* supporting streaming responses, tool use, and configurable model parameters.
*
* @see https://platform.openai.com/docs/api-reference/chat/create
*/
import OpenAI, { type ClientOptions } from 'openai'
import { Model } from '../models/model.js'
import type { BaseModelConfig, StreamOptions } from '../models/model.js'
import type { Message } from '../types/messages.js'
import type { ImageBlock, DocumentBlock, MediaFormats } from '../types/media.js'
import { encodeBase64 } from '../types/media.js'
import type { ModelStreamEvent } from '../models/streaming.js'
import { ContextWindowOverflowError } from '../errors.js'
import type { ChatCompletionContentPartText } from 'openai/resources/index.mjs'
import { logger } from '../logging/logger.js'
/**
* Browser-compatible MIME type lookup.
* Maps file extensions to MIME types without using Node.js path module.
*/
const mimeTypeLookup = (format: string): string | false => {
const mimeTypes: Record<MediaFormats, string> = {
// Video
mkv: 'video/x-matroska',
mov: 'video/quicktime',
mp4: 'application/mp4',
webm: 'video/webm',
flv: 'video/x-flv',
mpeg: 'video/mpeg',
mpg: 'video/mpeg',
wmv: 'video/x-ms-wmv',
'3gp': 'video/3gpp',
// Images
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
gif: 'image/gif',
webp: 'image/webp',
// Documents
pdf: 'application/pdf',
csv: 'text/csv',
doc: 'application/msword',
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
xls: 'application/vnd.ms-excel',
txt: 'text/plain',
json: 'application/json',
xml: 'application/xml',
html: 'text/html',
md: 'text/markdown',
}
return mimeTypes[format.toLowerCase() as MediaFormats] || false
}
const DEFAULT_OPENAI_MODEL_ID = 'gpt-4o'
/**
* Error message patterns that indicate context window overflow.
* Used to detect when input exceeds the model's context window.
*
* @see https://platform.openai.com/docs/guides/error-codes
*/
const OPENAI_CONTEXT_WINDOW_OVERFLOW_PATTERNS = [
'maximum context length',
'context_length_exceeded',
'too many tokens',
'context length',
]
/**
* Type representing an OpenAI streaming chat choice.
* Used for type-safe handling of streaming responses.
*/
type OpenAIChatChoice = {
delta?: {
role?: string
content?: string
tool_calls?: Array<{
index: number
id?: string
type?: string
function?: {
name?: string
arguments?: string
}
}>
}
finish_reason?: string
index: number
}
/**
* Configuration interface for OpenAI model provider.
*
* Extends BaseModelConfig with OpenAI-specific configuration options
* for model parameters and request settings.
*
* @example
* ```typescript
* const config: OpenAIModelConfig = {
* modelId: 'gpt-4o',
* temperature: 0.7,
* maxTokens: 1024
* }
* ```
*/
export interface OpenAIModelConfig extends BaseModelConfig {
/**
* OpenAI model identifier (e.g., gpt-4o, gpt-3.5-turbo).
*/
modelId?: string
/**
* Controls randomness in generation.
*
* @see https://platform.openai.com/docs/api-reference/chat/create#chat-create-temperature
*/
temperature?: number
/**
* Maximum number of tokens to generate in the completion.
*
* @see https://platform.openai.com/docs/api-reference/chat/create#chat-create-max_completion_tokens
*/
maxTokens?: number
/**
* Controls diversity via nucleus sampling.
*
* @see https://platform.openai.com/docs/api-reference/chat/create#chat-create-top_p
*/
topP?: number
/**
* Reduces repetition of token sequences (-2.0 to 2.0).
*/
frequencyPenalty?: number
/**
* Encourages the model to talk about new topics (-2.0 to 2.0).
*/
presencePenalty?: number
/**
* Additional parameters to pass through to the OpenAI API.
* This field provides forward compatibility for any new parameters
* that OpenAI introduces. All properties in this object will be
* spread into the API request.
*
* @example
* ```typescript
* // Pass stop sequences
* { params: { stop: ['END', 'STOP'] } }
*
* // Pass any future OpenAI parameters
* { params: { newParameter: 'value' } }
* ```
*/
params?: Record<string, unknown>
}
/**
* Options interface for creating an OpenAIModel instance.
*/
export interface OpenAIModelOptions extends OpenAIModelConfig {
/**
* OpenAI API key (falls back to OPENAI_API_KEY environment variable).
*/
apiKey?: string
/**
* Pre-configured OpenAI client instance.
* If provided, this client will be used instead of creating a new one.
*/
client?: OpenAI
/**
* Additional OpenAI client configuration.
* Only used if client is not provided.
*/
clientConfig?: ClientOptions
}
/**
* OpenAI model provider implementation.
*
* Implements the Model interface for OpenAI using the Chat Completions API.
* Supports streaming responses, tool use, and comprehensive configuration.
*
* @example
* ```typescript
* const provider = new OpenAIModel({
* apiKey: 'sk-...',
* modelId: 'gpt-4o',
* temperature: 0.7,
* maxTokens: 1024
* })
*
* const messages: Message[] = [
* { role: 'user', content: [{ type: 'textBlock', text: 'Hello!' }] }
* ]
*
* for await (const event of provider.stream(messages)) {
* if (event.type === 'modelContentBlockDeltaEvent' && event.delta.type === 'textDelta') {
* process.stdout.write(event.delta.text)
* }
* }
* ```
*/
export class OpenAIModel extends Model<OpenAIModelConfig> {
private _config: OpenAIModelConfig
private _client: OpenAI
/**
* Creates a new OpenAIModel instance.
*
* @param options - Configuration for model and client (modelId is required)
*
* @example
* ```typescript
* // Minimal configuration with API key and model ID
* const provider = new OpenAIModel({
* modelId: 'gpt-4o',
* apiKey: 'sk-...'
* })
*
* // With additional model configuration
* const provider = new OpenAIModel({
* modelId: 'gpt-4o',
* apiKey: 'sk-...',
* temperature: 0.8,
* maxTokens: 2048
* })
*
* // Using environment variable for API key
* const provider = new OpenAIModel({
* modelId: 'gpt-3.5-turbo'
* })
*
* // Using a pre-configured client instance
* const client = new OpenAI({ apiKey: 'sk-...', timeout: 60000 })
* const provider = new OpenAIModel({
* modelId: 'gpt-4o',
* client
* })
* ```
*/
constructor(options?: OpenAIModelOptions) {
super()
const { apiKey, client, clientConfig, ...modelConfig } = options || {}
// Initialize model config
this._config = modelConfig
// Use provided client or create a new one
if (client) {
this._client = client
} else {
// Check if API key is available when creating a new client
// In browsers, apiKey must be provided directly
// In Node.js, can use OPENAI_API_KEY environment variable as fallback
const hasEnvKey =
typeof process !== 'undefined' && typeof process.env !== 'undefined' && process.env.OPENAI_API_KEY
if (!apiKey && !hasEnvKey && !clientConfig?.apiKey) {
throw new Error(
"OpenAI API key is required. Provide it via the 'apiKey' option or set the OPENAI_API_KEY environment variable."
)
}
// Initialize OpenAI client
// Only include apiKey if explicitly provided, otherwise let client use env var
this._client = new OpenAI({
...(apiKey ? { apiKey } : {}),
...clientConfig,
})
}
}
/**
* Updates the model configuration.
* Merges the provided configuration with existing settings.
*
* @param modelConfig - Configuration object with model-specific settings to update
*
* @example
* ```typescript
* // Update temperature and maxTokens
* provider.updateConfig({
* temperature: 0.9,
* maxTokens: 2048
* })
* ```
*/
updateConfig(modelConfig: OpenAIModelConfig): void {
this._config = { ...this._config, ...modelConfig }
}
/**
* Retrieves the current model configuration.
*
* @returns The current configuration object
*
* @example
* ```typescript
* const config = provider.getConfig()
* console.log(config.modelId)
* ```
*/
getConfig(): OpenAIModelConfig {
return this._config
}
/**
* Streams a conversation with the OpenAI model.
* Returns an async iterable that yields streaming events as they occur.
*
* @param messages - Array of conversation messages
* @param options - Optional streaming configuration
* @returns Async iterable of streaming events
*
* @throws \{ContextWindowOverflowError\} When input exceeds the model's context window
*
* @example
* ```typescript
* const provider = new OpenAIModel({ modelId: 'gpt-4o', apiKey: 'sk-...' })
* const messages: Message[] = [
* { role: 'user', content: [{ type: 'textBlock', text: 'What is 2+2?' }] }
* ]
*
* for await (const event of provider.stream(messages)) {
* if (event.type === 'modelContentBlockDeltaEvent' && event.delta.type === 'textDelta') {
* process.stdout.write(event.delta.text)
* }
* }
* ```
*
* @example
* ```typescript
* // With tool use
* const options: StreamOptions = {
* systemPrompt: 'You are a helpful assistant',
* toolSpecs: [calculatorTool]
* }
*
* for await (const event of provider.stream(messages, options)) {
* if (event.type === 'modelMessageStopEvent' && event.stopReason === 'toolUse') {
* console.log('Model wants to use a tool')
* }
* }
* ```
*/
async *stream(messages: Message[], options?: StreamOptions): AsyncIterable<ModelStreamEvent> {
// Validate messages array is not empty
if (!messages || messages.length === 0) {
throw new Error('At least one message is required')
}
try {
// Format the request
const request = this._formatRequest(messages, options)
// Create streaming request with usage tracking
const stream = await this._client.chat.completions.create(request)
// Track streaming state (Use mutable object for proper state tracking)
const streamState = {
messageStarted: false,
textContentBlockStarted: false,
}
// Track active tool calls for stop events
const activeToolCalls = new Map<number, boolean>()
// Buffer usage to emit before message stop
let bufferedUsage: {
type: 'modelMetadataEvent'
usage: {
inputTokens: number
outputTokens: number
totalTokens: number
}
} | null = null
// Process streaming response
for await (const chunk of stream) {
if (!chunk.choices || chunk.choices.length === 0) {
// Handle usage chunk (no choices)
// Buffer usage to emit before message stop
if (chunk.usage) {
bufferedUsage = {
type: 'modelMetadataEvent',
usage: {
inputTokens: chunk.usage.prompt_tokens ?? 0,
outputTokens: chunk.usage.completion_tokens ?? 0,
totalTokens: chunk.usage.total_tokens ?? 0,
},
}
}
continue
}
// Map chunk to SDK events
const events = this._mapOpenAIChunkToSDKEvents(chunk, streamState, activeToolCalls)
for (const event of events) {
// Emit buffered usage before message stop
if (event.type === 'modelMessageStopEvent' && bufferedUsage) {
yield bufferedUsage
bufferedUsage = null
}
yield event
}
}
// Emit any remaining buffered usage
if (bufferedUsage) {
yield bufferedUsage
}
} catch (error) {
const err = error as Error
// Check for context window overflow using simple pattern matching
if (OPENAI_CONTEXT_WINDOW_OVERFLOW_PATTERNS.some((pattern) => err.message?.toLowerCase().includes(pattern))) {
throw new ContextWindowOverflowError(err.message)
}
// Re-throw other errors unchanged
throw err
}
}
/**
* Formats a request for the OpenAI Chat Completions API.
*
* @param messages - Conversation messages
* @param options - Stream options
* @returns Formatted OpenAI request
*/
private _formatRequest(
messages: Message[],
options?: StreamOptions
): OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming {
// Start with required fields
const request: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = {
model: this._config.modelId ?? DEFAULT_OPENAI_MODEL_ID,
messages: [] as OpenAI.Chat.Completions.ChatCompletionMessageParam[],
stream: true,
stream_options: { include_usage: true },
}
// Handle system prompt (string or array format)
if (options?.systemPrompt !== undefined) {
if (typeof options.systemPrompt === 'string') {
// String path: validate and add as-is
if (options.systemPrompt.trim().length > 0) {
request.messages.push({
role: 'system',
content: options.systemPrompt,
})
}
} else if (Array.isArray(options.systemPrompt) && options.systemPrompt.length > 0) {
// Array path: extract text blocks and warn about cache points
const textBlocks: string[] = []
let hasCachePoints = false
let hasGuardContent = false
for (const block of options.systemPrompt) {
if (block.type === 'textBlock') {
textBlocks.push(block.text)
} else if (block.type === 'cachePointBlock') {
hasCachePoints = true
} else if (block.type === 'guardContentBlock') {
hasGuardContent = true
}
}
if (hasCachePoints) {
logger.warn('cache points are not supported in openai system prompts, ignoring cache points')
}
if (hasGuardContent) {
logger.warn('guard content is not supported in openai system prompts, removing guard content block')
}
if (textBlocks.length > 0) {
request.messages.push({
role: 'system',
content: textBlocks.join(''),
})
}
}
}
// Add formatted messages
const formattedMessages = this._formatMessages(messages)
request.messages.push(...formattedMessages)
// Add model configuration parameters
if (this._config.temperature !== undefined) {
request.temperature = this._config.temperature
}
if (this._config.maxTokens !== undefined) {
request.max_completion_tokens = this._config.maxTokens
}
if (this._config.topP !== undefined) {
request.top_p = this._config.topP
}
if (this._config.frequencyPenalty !== undefined) {
request.frequency_penalty = this._config.frequencyPenalty
}
if (this._config.presencePenalty !== undefined) {
request.presence_penalty = this._config.presencePenalty
}
// Add tool specifications with validation
if (options?.toolSpecs && options.toolSpecs.length > 0) {
request.tools = options.toolSpecs.map((spec) => {
if (!spec.name || !spec.description) {
throw new Error('Tool specification must have both name and description')
}
return {
type: 'function' as const,
function: {
name: spec.name,
description: spec.description,
parameters: spec.inputSchema as Record<string, unknown>,
},
}
})
// Add tool choice if specified
if (options.toolChoice) {
if ('auto' in options.toolChoice) {
request.tool_choice = 'auto'
} else if ('any' in options.toolChoice) {
request.tool_choice = 'required'
} else if ('tool' in options.toolChoice) {
request.tool_choice = {
type: 'function',
function: { name: options.toolChoice.tool.name },
}
}
}
}
// Spread params object last for forward compatibility
if (this._config.params) {
Object.assign(request, this._config.params)
}
// Validate n parameter (number of completions) - only n=1 supported for streaming
if ('n' in request && request.n !== undefined && request.n !== null && request.n > 1) {
throw new Error('Streaming with n > 1 is not supported')
}
return request
}
/**
* Formats messages for OpenAI API.
* Handles splitting tool results into separate messages.
*
* @param messages - SDK messages
* @returns OpenAI-formatted messages
*/
private _formatMessages(messages: Message[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] {
const openAIMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = []
for (const message of messages) {
if (message.role === 'user') {
// Separate tool results from other content
const toolResults = message.content.filter((b) => b.type === 'toolResultBlock')
const otherContent = message.content.filter((b) => b.type !== 'toolResultBlock')
// Add non-tool-result content as user message
if (otherContent.length > 0) {
const contentParts: OpenAI.Chat.Completions.ChatCompletionContentPart[] = []
for (const block of otherContent) {
switch (block.type) {
case 'textBlock': {
contentParts.push({
type: 'text',
text: block.text,
})
break
}
case 'imageBlock': {
const imageBlock = block as ImageBlock
switch (imageBlock.source.type) {
case 'imageSourceUrl': {
contentParts.push({
type: 'image_url',
image_url: {
url: imageBlock.source.url,
},
})
break
}
case 'imageSourceBytes': {
const base64 = encodeBase64(String.fromCharCode(...imageBlock.source.bytes))
const mimeType = mimeTypeLookup(imageBlock.format) || `image/${imageBlock.format}`
contentParts.push({
type: 'image_url',
image_url: {
url: `data:${mimeType};base64,${base64}`,
},
})
break
}
default: {
console.warn(
`OpenAI ChatCompletions API does not support image block type: ${imageBlock.source.type}.`
)
break
}
}
break
}
case 'documentBlock': {
const docBlock = block as DocumentBlock
switch (docBlock.source.type) {
case 'documentSourceBytes': {
const mimeType = mimeTypeLookup(docBlock.format) || `application/${docBlock.format}`
const base64 = encodeBase64(String.fromCharCode(...docBlock.source.bytes))
const file: OpenAI.Chat.Completions.ChatCompletionContentPart.File = {
type: 'file',
file: {
file_data: `data:${mimeType};base64,${base64}`,
filename: docBlock.name,
},
}
contentParts.push(file)
break
}
case 'documentSourceText': {
// Text documents can be added directly
console.warn(
'OpenAI does not support text document sources directly. Converting this text document to string content.'
)
contentParts.push({
type: 'text',
text: docBlock.source.text,
})
break
}
case 'documentSourceContentBlock': {
// Push each content block as a content part
contentParts.push(
...docBlock.source.content.map<ChatCompletionContentPartText>((block) => {
return {
type: 'text',
text: block.text,
}
})
)
break
}
default: {
console.warn(
`OpenAI ChatCompletions API only supports text content in user messages. Skipping document block type: ${docBlock.source.type}.`
)
break
}
}
break
}
default: {
console.warn(`OpenAI ChatCompletions API does not support content type: ${block.type}.`)
break
}
}
}
// Validate content is not empty before adding
if (contentParts.length > 0) {
openAIMessages.push({
role: 'user',
content: contentParts,
})
}
}
// Add each tool result as separate tool message
// OpenAI only supports text content in tool result messages, not JSON
for (const toolResult of toolResults) {
if (toolResult.type === 'toolResultBlock') {
// Format tool result content - convert all to text string
// Note: OpenAI tool messages only accept string content (not structured JSON)
const contentText = toolResult.content
.map((c) => {
if (c.type === 'textBlock') {
return c.text
} else if (c.type === 'jsonBlock') {
try {
return JSON.stringify(c.json)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
const dataPreview =
typeof c.json === 'object' && c.json !== null
? `object with keys: ${Object.keys(c.json).slice(0, 5).join(', ')}`
: typeof c.json
return `[JSON Serialization Error: ${error.message}. Data type: ${dataPreview}]`
}
}
return ''
})
.join('')
// Validate content is not empty
if (!contentText || contentText.trim().length === 0) {
throw new Error(
`Tool result for toolUseId "${toolResult.toolUseId}" has empty content. ` +
'OpenAI requires tool messages to have non-empty content.'
)
}
// Prepend error indicator if status is error
const finalContent = toolResult.status === 'error' ? `[ERROR] ${contentText}` : contentText
openAIMessages.push({
role: 'tool',
tool_call_id: toolResult.toolUseId,
content: finalContent,
})
}
}
} else {
// Handle assistant messages
const toolUseCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = []
// Use array + join pattern for efficient string concatenation
const textParts: string[] = []
for (const block of message.content) {
switch (block.type) {
case 'textBlock': {
textParts.push(block.text)
break
}
case 'toolUseBlock': {
try {
toolUseCalls.push({
id: block.toolUseId,
type: 'function',
function: {
name: block.name,
arguments: JSON.stringify(block.input),
},
})
} catch (error: unknown) {
if (error instanceof Error) {
throw new Error(`Failed to serialize tool input for "${block.name}`, error)
}
throw error
}
break
}
case 'reasoningBlock': {
if (block.text) {
console.warn('Reasoning blocks are not supported by OpenAI Chat Completions API. Converting to text.')
textParts.push(block.text)
}
break
}
default: {
console.warn(
`OpenAI ChatCompletions API does not support ${block.type} content in assistant messages. Skipping this block.`
)
}
}
}
// Trim text content to avoid whitespace-only messages
const textContent = textParts.join('').trim()
const assistantMessage: OpenAI.Chat.Completions.ChatCompletionAssistantMessageParam = {
role: 'assistant',
content: textContent,
}
if (toolUseCalls.length > 0) {
assistantMessage.tool_calls = toolUseCalls
}
// Only add if message has content or tool calls
if (textContent.length > 0 || toolUseCalls.length > 0) {
openAIMessages.push(assistantMessage)
}
}
}
return openAIMessages
}
/**
* Converts a snake_case string to camelCase.
* Used for mapping OpenAI stop reasons to SDK format.
*
* @param str - Snake case string (e.g., 'content_filter')
* @returns Camel case string (e.g., 'contentFilter')
*
* @example
* ```typescript
* _snakeToCamel('context_length_exceeded') // => 'contextLengthExceeded'
* _snakeToCamel('tool_calls') // => 'toolCalls'
* ```
*/
private _snakeToCamel(str: string): string {
return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
}
/**
* Maps an OpenAI chunk to SDK streaming events.
*
* @param chunk - OpenAI chunk
* @param streamState - Mutable state object tracking message and content block state
* @param activeToolCalls - Map tracking active tool calls by index
* @returns Array of SDK streaming events
*/
private _mapOpenAIChunkToSDKEvents(
chunk: { choices: unknown[] },
streamState: { messageStarted: boolean; textContentBlockStarted: boolean },
activeToolCalls: Map<number, boolean>
): ModelStreamEvent[] {
const events: ModelStreamEvent[] = []
// Validate choices array has at least one element
if (!chunk.choices || chunk.choices.length === 0) {
return events
}
const choice = chunk.choices[0]
// Validate choice is an object
if (!choice || typeof choice !== 'object') {
logger.warn(`choice=<${choice}> | invalid choice format in openai chunk`)
return events
}
// Process first choice (OpenAI typically returns one choice in streaming)
const typedChoice = choice as OpenAIChatChoice
if (!typedChoice.delta && !typedChoice.finish_reason) {
return events
}
const delta = typedChoice.delta
// Handle message start (role appears) - update mutable state
if (delta?.role && !streamState.messageStarted) {
streamState.messageStarted = true
events.push({
type: 'modelMessageStartEvent',
role: delta.role as 'user' | 'assistant',
})
}
// Handle text content delta and start event
if (delta?.content && delta.content.length > 0) {
// Emit start event on first text delta
if (!streamState.textContentBlockStarted) {
streamState.textContentBlockStarted = true
events.push({
type: 'modelContentBlockStartEvent',
})
}
events.push({
type: 'modelContentBlockDeltaEvent',
delta: {
type: 'textDelta',
text: delta.content,
},
})
}
// Handle tool calls
if (delta?.tool_calls && delta.tool_calls.length > 0) {
for (const toolCall of delta.tool_calls) {
// Validate tool call index
if (toolCall.index === undefined || typeof toolCall.index !== 'number') {
logger.warn(`tool_call=<${JSON.stringify(toolCall)}> | received tool call with invalid index`)
continue
}
// If tool call has id and name, it's the start of a new tool call
if (toolCall.id && toolCall.function?.name) {
events.push({
type: 'modelContentBlockStartEvent',
start: {
type: 'toolUseStart',
name: toolCall.function.name,
toolUseId: toolCall.id,
},
})
// Track active tool calls
activeToolCalls.set(toolCall.index, true)
}
// If tool call has arguments, it's a delta
if (toolCall.function?.arguments) {
events.push({
type: 'modelContentBlockDeltaEvent',
delta: {
type: 'toolUseInputDelta',
input: toolCall.function.arguments,
},
})
}
}
}
// Handle finish reason (message stop)
if (typedChoice.finish_reason) {
// Emit stop event for text content if it was started
if (streamState.textContentBlockStarted) {
events.push({
type: 'modelContentBlockStopEvent',
})
streamState.textContentBlockStarted = false
}
// Emit stop events for all active tool calls and delete during iteration
for (const [index] of activeToolCalls) {
events.push({
type: 'modelContentBlockStopEvent',
})
activeToolCalls.delete(index)
}
// Map OpenAI stop reason to SDK stop reason
const stopReasonMap: Record<string, string> = {
stop: 'endTurn',
tool_calls: 'toolUse',
length: 'maxTokens',
content_filter: 'contentFiltered',
}
// Log unknown stop reasons
let stopReason = stopReasonMap[typedChoice.finish_reason]
if (!stopReason) {
const fallbackReason = this._snakeToCamel(typedChoice.finish_reason)
logger.warn(
`finish_reason=<${typedChoice.finish_reason}>, fallback=<${fallbackReason}> | unknown openai stop reason, using camelCase conversion as fallback`
)
stopReason = fallbackReason
}
events.push({
type: 'modelMessageStopEvent',
stopReason,
})
}
return events
}
}