-
Notifications
You must be signed in to change notification settings - Fork 649
Expand file tree
/
Copy pathopenAICompatibleProvider.ts
More file actions
2011 lines (1824 loc) · 76.2 KB
/
openAICompatibleProvider.ts
File metadata and controls
2011 lines (1824 loc) · 76.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
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { EMBEDDING_TEST_KEY, isNormalized } from '@/utils/vector'
import {
LLM_PROVIDER,
LLMResponse,
MODEL_META,
MCPToolDefinition,
LLMCoreStreamEvent,
ModelConfig,
ChatMessage,
LLM_EMBEDDING_ATTRS,
IConfigPresenter
} from '@shared/presenter'
import { createStreamEvent } from '@shared/types/core/llm-events'
import { BaseLLMProvider, SUMMARY_TITLES_PROMPT } from '../baseProvider'
import OpenAI, { AzureOpenAI } from 'openai'
import {
ChatCompletionContentPart,
ChatCompletionContentPartText,
ChatCompletionMessage,
ChatCompletionMessageParam
} from 'openai/resources'
import { presenter } from '@/presenter'
import { eventBus, SendTarget } from '@/eventbus'
import { NOTIFICATION_EVENTS } from '@/events'
import { jsonrepair } from 'jsonrepair'
import { app } from 'electron'
import path from 'path'
import fs from 'fs'
import sharp from 'sharp'
import { proxyConfig } from '../../proxyConfig'
import { modelCapabilities } from '../../configPresenter/modelCapabilities'
import { ProxyAgent } from 'undici'
const OPENAI_REASONING_MODELS = [
'o4-mini',
'o1-pro',
'o3',
'o3-pro',
'o3-mini',
'o3-preview',
'o1-mini',
'o1-pro',
'o1-preview',
'o1',
'gpt-5',
'gpt-5-mini',
'gpt-5-nano',
'gpt-5-chat'
]
const OPENAI_IMAGE_GENERATION_MODELS = ['gpt-4o-all', 'gpt-4o-image']
const OPENAI_IMAGE_GENERATION_MODEL_PREFIXES = ['dall-e-', 'gpt-image-']
const isOpenAIImageGenerationModel = (modelId: string): boolean =>
OPENAI_IMAGE_GENERATION_MODELS.includes(modelId) ||
OPENAI_IMAGE_GENERATION_MODEL_PREFIXES.some((prefix) => modelId.startsWith(prefix))
// Add supported image size constants
const SUPPORTED_IMAGE_SIZES = {
SQUARE: '1024x1024',
LANDSCAPE: '1536x1024',
PORTRAIT: '1024x1536'
} as const
// Add list of models with configurable sizes
const SIZE_CONFIGURABLE_MODELS = ['gpt-image-1', 'gpt-4o-image', 'gpt-4o-all']
export class OpenAICompatibleProvider extends BaseLLMProvider {
protected openai!: OpenAI
protected isNoModelsApi: boolean = false
// Add blacklist of providers that don't support OpenAI standard interface
private static readonly NO_MODELS_API_LIST: string[] = []
constructor(provider: LLM_PROVIDER, configPresenter: IConfigPresenter) {
super(provider, configPresenter)
this.createOpenAIClient()
if (OpenAICompatibleProvider.NO_MODELS_API_LIST.includes(this.provider.id.toLowerCase())) {
this.isNoModelsApi = true
}
this.init()
}
private supportsEffortParameter(modelId: string): boolean {
return modelCapabilities.supportsReasoningEffort(this.provider.id, modelId)
}
private supportsVerbosityParameter(modelId: string): boolean {
return modelCapabilities.supportsVerbosity(this.provider.id, modelId)
}
protected createOpenAIClient(): void {
// Get proxy configuration
const proxyUrl = proxyConfig.getProxyUrl()
const fetchOptions: { dispatcher?: ProxyAgent } = {}
if (proxyUrl) {
console.log(`[OpenAI Compatible Provider] Using proxy: ${proxyUrl}`)
const proxyAgent = new ProxyAgent(proxyUrl)
fetchOptions.dispatcher = proxyAgent
}
// Check if this is official OpenAI or Azure OpenAI
const isOfficialOpenAI = this.isOfficialOpenAIService()
const isAzureOpenAI = this.provider.id === 'azure-openai'
// Only use custom fetch for third-party services to avoid triggering 403
// Keep original behavior for official OpenAI and Azure OpenAI for best compatibility
const shouldUseCleanFetch = !isOfficialOpenAI && !isAzureOpenAI
const customFetch = shouldUseCleanFetch ? this.createCleanFetch() : undefined
if (isAzureOpenAI) {
try {
const apiVersion = this.configPresenter.getSetting<string>('azureApiVersion')
const azureConfig: any = {
apiKey: this.provider.apiKey,
baseURL: this.provider.baseUrl,
apiVersion: apiVersion || '2024-02-01',
defaultHeaders: {
...this.defaultHeaders
}
}
// Use fetchOptions for proxy (original behavior for Azure)
if (fetchOptions.dispatcher) {
azureConfig.fetchOptions = fetchOptions
}
this.openai = new AzureOpenAI(azureConfig)
} catch (e) {
console.warn('create azure openai failed', e)
}
} else {
const openaiConfig: any = {
apiKey: this.provider.apiKey,
baseURL: this.provider.baseUrl,
defaultHeaders: {
...this.defaultHeaders
}
}
if (customFetch) {
// Third-party service: use custom fetch to avoid 403
openaiConfig.fetch = customFetch
// Also apply proxy via fetchOptions for third-party services
if (fetchOptions.dispatcher) {
openaiConfig.fetchOptions = fetchOptions
}
console.log(
`[OpenAI Compatible Provider] Using custom fetch for third-party service: ${this.provider.baseUrl}`
)
} else {
// Official OpenAI: use original behavior with fetchOptions
if (fetchOptions.dispatcher) {
openaiConfig.fetchOptions = fetchOptions
}
console.log(`[OpenAI Compatible Provider] Using original fetch for official OpenAI`)
}
this.openai = new OpenAI(openaiConfig)
}
}
/**
* Check if this is the official OpenAI service by provider ID
*/
private isOfficialOpenAIService(): boolean {
return this.provider.id === 'openai'
}
/**
* Creates a custom fetch function that removes OpenAI SDK headers that may trigger 403
* This ensures all OpenAI SDK requests (including streaming) use clean headers
*/
private createCleanFetch() {
return async (url: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
// Create a copy of init to avoid modifying the original
const cleanInit = { ...init }
if (cleanInit.headers) {
// Convert headers to a plain object for easier manipulation
const headers = new Headers(cleanInit.headers)
const cleanHeaders: Record<string, string> = {}
// Only keep essential headers, remove SDK-specific ones that trigger 403
const allowedHeaders = [
'authorization',
'content-type',
'accept',
'http-referer',
'x-title'
]
headers.forEach((value, key) => {
const lowerKey = key.toLowerCase()
// Keep only allowed headers and avoid X-Stainless-* headers
if (
allowedHeaders.includes(lowerKey) ||
(!lowerKey.startsWith('x-stainless-') &&
!lowerKey.includes('user-agent') &&
!lowerKey.includes('openai-'))
) {
cleanHeaders[key] = value
}
})
// Ensure we have Authorization header
if (!cleanHeaders['Authorization'] && !cleanHeaders['authorization']) {
cleanHeaders['Authorization'] = `Bearer ${this.provider.apiKey}`
}
// Add our default headers
Object.assign(cleanHeaders, this.defaultHeaders)
cleanInit.headers = cleanHeaders
}
// Use regular fetch - proxy is already handled by OpenAI SDK's fetchOptions
return fetch(url, cleanInit)
}
}
public onProxyResolved(): void {
this.createOpenAIClient()
}
// Implement abstract method fetchProviderModels from BaseLLMProvider
protected async fetchProviderModels(options?: { timeout: number }): Promise<MODEL_META[]> {
// Check if provider is in blacklist
if (this.isNoModelsApi) {
// console.log(`Provider ${this.provider.name} does not support OpenAI models API`)
return this.models
}
return this.fetchOpenAIModels(options)
}
protected async fetchOpenAIModels(options?: { timeout: number }): Promise<MODEL_META[]> {
// Now using the clean fetch function via OpenAI SDK
const response = await this.openai.models.list(options)
return response.data.map((model) => ({
id: model.id,
name: model.id,
group: 'default',
providerId: this.provider.id,
isCustom: false,
contextLength: 4096,
maxTokens: 2048
}))
}
/**
* User messages: Upper layer will insert image_url based on whether vision exists
* Assistant messages: Need to judge and convert images to correct context, as models can be switched
* Tool calls and tool responses:
* - If supportsFunctionCall=true: Use standard OpenAI format (tool_calls + role:tool)
* - If supportsFunctionCall=false: Convert to mock user messages with function_call_record format
* @param messages - Chat messages array
* @param supportsFunctionCall - Whether the model supports native function calling
* @returns Formatted messages for OpenAI API
*/
protected formatMessages(
messages: ChatMessage[],
supportsFunctionCall: boolean = false
): ChatCompletionMessageParam[] {
// console.log('formatMessages', messages)
const result: ChatCompletionMessageParam[] = []
// Track pending tool calls for non-FC models (to pair with tool responses)
const pendingToolCalls: Map<
string,
{ name: string; arguments: string; assistantContent?: string }
> = new Map()
const pendingToolCallOrder: string[] = []
// Track expected tool_call_ids for native function calling models
const pendingNativeToolCallIds: string[] = []
const pendingNativeToolCallSet: Set<string> = new Set()
const serializeContent = (content: unknown): string => {
if (content === undefined) return ''
if (typeof content === 'string') return content
return JSON.stringify(content)
}
const enqueueNativeToolCallId = (toolCallId?: string) => {
if (!toolCallId) return
pendingNativeToolCallIds.push(toolCallId)
pendingNativeToolCallSet.add(toolCallId)
}
const consumeNativeToolCallId = (preferredId?: string): string | undefined => {
if (preferredId && pendingNativeToolCallSet.has(preferredId)) {
pendingNativeToolCallSet.delete(preferredId)
const idx = pendingNativeToolCallIds.indexOf(preferredId)
if (idx !== -1) pendingNativeToolCallIds.splice(idx, 1)
return preferredId
}
while (pendingNativeToolCallIds.length > 0) {
const candidate = pendingNativeToolCallIds.shift()
if (!candidate) continue
if (!pendingNativeToolCallSet.has(candidate)) continue
pendingNativeToolCallSet.delete(candidate)
return candidate
}
return undefined
}
const snapshotPendingNativeToolCallIds = () =>
pendingNativeToolCallIds.filter((id) => pendingNativeToolCallSet.has(id))
const removePendingMockToolCallId = (toolCallId: string) => {
pendingToolCalls.delete(toolCallId)
const idx = pendingToolCallOrder.indexOf(toolCallId)
if (idx !== -1) pendingToolCallOrder.splice(idx, 1)
}
const getPendingMockToolCallEntries = () =>
pendingToolCallOrder
.map((id) => {
const meta = pendingToolCalls.get(id)
if (!meta) return undefined
return { id, meta }
})
.filter(
(
entry
): entry is {
id: string
meta: { name: string; arguments: string; assistantContent?: string }
} => Boolean(entry)
)
const pushMockToolResponse = (
toolCallId: string,
pendingCall: { name: string; arguments: string; assistantContent?: string },
responseContent: string
) => {
let argsObj
try {
argsObj =
typeof pendingCall.arguments === 'string'
? JSON.parse(pendingCall.arguments)
: pendingCall.arguments
} catch {
argsObj = {}
}
const mockRecord = {
function_call_record: {
name: pendingCall.name,
arguments: argsObj,
response: responseContent
}
}
result.push({
role: 'user',
content: `<function_call>${JSON.stringify(mockRecord)}</function_call>`
} as ChatCompletionMessageParam)
removePendingMockToolCallId(toolCallId)
}
for (let i = 0; i < messages.length; i++) {
const msg = messages[i]
// Handle basic message structure
const baseMessage: Partial<ChatCompletionMessageParam> = {
role: msg.role as 'system' | 'user' | 'assistant' | 'tool'
}
// Handle content conversion to string for non-user messages
if (msg.content !== undefined && msg.role !== 'user') {
if (typeof msg.content === 'string') {
baseMessage.content = msg.content
} else if (Array.isArray(msg.content)) {
// Handle multimodal content arrays
const textParts: string[] = []
for (const part of msg.content) {
if (part.type === 'text' && part.text) {
textParts.push(part.text)
}
if (part.type === 'image_url' && part.image_url?.url) {
textParts.push(`image: ${part.image_url.url}`)
}
}
baseMessage.content = textParts.join('\n')
}
}
// Handle user messages (keep multimodal content structure)
if (msg.role === 'user') {
if (typeof msg.content === 'string') {
baseMessage.content = msg.content
} else if (Array.isArray(msg.content)) {
baseMessage.content = msg.content as ChatCompletionContentPart[]
}
result.push(baseMessage as ChatCompletionMessageParam)
continue
}
// Handle assistant messages with tool_calls
if (msg.role === 'assistant' && msg.tool_calls && msg.tool_calls.length > 0) {
const reasoningContent = (msg as any).reasoning_content as string | undefined
if (supportsFunctionCall) {
// Standard OpenAI format - preserve tool_calls structure
const normalizedToolCalls = msg.tool_calls.map((toolCall) => {
const toolCallId = toolCall.id || `tool-${Date.now()}-${Math.random()}`
enqueueNativeToolCallId(toolCallId)
return {
...toolCall,
id: toolCallId
}
})
result.push({
role: 'assistant',
content: baseMessage.content || null,
tool_calls: normalizedToolCalls,
...(reasoningContent !== undefined ? { reasoning_content: reasoningContent } : {})
} as ChatCompletionMessageParam)
} else {
// Mock format: Store tool calls and assistant content, wait for tool responses
// First add the assistant message if it has content
if (baseMessage.content) {
result.push({
role: 'assistant',
content: baseMessage.content,
...(reasoningContent !== undefined ? { reasoning_content: reasoningContent } : {})
} as ChatCompletionMessageParam)
}
// Store tool calls for pairing with responses
for (const toolCall of msg.tool_calls) {
const toolCallId = toolCall.id || `tool-${Date.now()}-${Math.random()}`
pendingToolCalls.set(toolCallId, {
name: toolCall.function?.name || 'unknown',
arguments:
typeof toolCall.function?.arguments === 'string'
? toolCall.function.arguments
: JSON.stringify(toolCall.function?.arguments || {}),
assistantContent: baseMessage.content as string | undefined
})
pendingToolCallOrder.push(toolCallId)
}
}
continue
}
// Handle tool messages
if (msg.role === 'tool') {
if (supportsFunctionCall) {
const serializedContent = serializeContent(msg.content)
const pendingIds = snapshotPendingNativeToolCallIds()
if (pendingIds.length > 1 && serializedContent) {
const splitParts = this.splitMergedToolContent(serializedContent, pendingIds.length)
if (splitParts && splitParts.length === pendingIds.length) {
splitParts.forEach((part, index) => {
const toolCallId = pendingIds[index]
if (!toolCallId) return
consumeNativeToolCallId(toolCallId)
result.push({
role: 'tool',
content: part,
tool_call_id: toolCallId
} as ChatCompletionMessageParam)
})
continue
}
}
let resolvedToolCallId = msg.tool_call_id
if (resolvedToolCallId && pendingNativeToolCallSet.has(resolvedToolCallId)) {
consumeNativeToolCallId(resolvedToolCallId)
} else if (!resolvedToolCallId) {
resolvedToolCallId = consumeNativeToolCallId()
}
result.push({
role: 'tool',
content: serializedContent,
tool_call_id: resolvedToolCallId || msg.tool_call_id || ''
} as ChatCompletionMessageParam)
} else {
// Mock format: Create user message with function_call_record
const serializedContent = serializeContent(msg.content)
const pendingEntries = getPendingMockToolCallEntries()
if (pendingEntries.length > 1 && serializedContent) {
const splitParts = this.splitMergedToolContent(serializedContent, pendingEntries.length)
if (splitParts && splitParts.length === pendingEntries.length) {
splitParts.forEach((part, index) => {
const entry = pendingEntries[index]
pushMockToolResponse(entry.id, entry.meta, part)
})
continue
}
}
let toolCallId = msg.tool_call_id || ''
if (!toolCallId && pendingEntries.length > 0) {
toolCallId = pendingEntries[0].id
}
const pendingCall = toolCallId ? pendingToolCalls.get(toolCallId) : undefined
if (toolCallId && pendingCall) {
pushMockToolResponse(toolCallId, pendingCall, serializedContent)
} else {
// Fallback: tool response without matching call, still format as user message
const mockRecord = {
function_call_record: {
name: 'unknown',
arguments: {},
response: serializedContent
}
}
result.push({
role: 'user',
content: `<function_call>${JSON.stringify(mockRecord)}</function_call>`
} as ChatCompletionMessageParam)
}
}
continue
}
// Handle other messages (system, assistant without tool_calls)
if (msg.role === 'assistant') {
const reasoningContent = (msg as any).reasoning_content as string | undefined
if (reasoningContent !== undefined) {
;(baseMessage as any).reasoning_content = reasoningContent
}
}
result.push(baseMessage as ChatCompletionMessageParam)
}
return result
}
/**
* Some upstream MCP layers merge multiple tool responses into a single assistant message when
* `pendingIds.length > 1`; this is outside of the standard OpenAI tool_call flow, so we attempt
* to recover individual payloads by trying several splitting heuristics. Supported formats
* include JSON arrays of strings, delimiter blocks formed by lines of three or more hyphens/equals/asterisks,
* blank-line separation, and repeated header markers. Each strategy is attempted in order so we
* favor structured formats first and fall back to progressively looser parsing when strict
* patterns fail.
*/
private splitMergedToolContent(content: string, expectedParts: number): string[] | null {
if (!content || expectedParts <= 1) return null
const trimmed = content.trim()
if (!trimmed) return null
const strategies: Array<() => string[] | null> = [
() => this.trySplitJsonArray(trimmed, expectedParts),
() => this.trySplitByDelimiter(trimmed, /\n-{3,}\n+/g, expectedParts),
() => this.trySplitByDelimiter(trimmed, /\n={3,}\n+/g, expectedParts),
() => this.trySplitByDelimiter(trimmed, /\n\*{3,}\n+/g, expectedParts),
() => this.trySplitByDelimiter(trimmed, /\n\s*\n+/g, expectedParts),
() => this.trySplitByHeaderRepeats(trimmed, expectedParts)
]
for (const strategy of strategies) {
const parts = strategy()
if (parts) {
return parts
}
}
return null
}
private trySplitJsonArray(content: string, expectedParts: number): string[] | null {
if (!content.startsWith('[')) return null
try {
const parsed = JSON.parse(content)
if (Array.isArray(parsed) && parsed.length === expectedParts) {
return parsed.map((entry) => (typeof entry === 'string' ? entry : JSON.stringify(entry)))
}
} catch {
return null
}
return null
}
private trySplitByDelimiter(
content: string,
delimiter: RegExp,
expectedParts: number
): string[] | null {
const parts = content
.split(delimiter)
.map((part) => part.trim())
.filter((part) => part.length > 0)
if (parts.length === expectedParts) {
return parts
}
return null
}
private trySplitByHeaderRepeats(content: string, expectedParts: number): string[] | null {
const headerRegex = /(?:^|\n)([-*]?\s*[A-Za-z][A-Za-z0-9\s,'"-]{0,80}?:)/g
const matches = [...content.matchAll(headerRegex)]
if (matches.length === 0) {
return null
}
const grouped = new Map<string, number[]>()
for (const match of matches) {
const rawHeader = match[1]
if (!rawHeader) continue
const normalized = rawHeader.replace(/\d+/g, '').trim().toLowerCase()
if (!normalized || normalized.length < 3) continue
const startIndex = (match.index ?? 0) + (match[0].startsWith('\n') ? 1 : 0)
if (!grouped.has(normalized)) {
grouped.set(normalized, [])
}
grouped.get(normalized)!.push(startIndex)
}
for (const [, indices] of grouped) {
if (indices.length === expectedParts) {
const segments: string[] = []
for (let i = 0; i < indices.length; i++) {
const start = indices[i]
const end = i + 1 < indices.length ? indices[i + 1] : content.length
const segment = content.slice(start, end).trim()
if (!segment) {
return null
}
segments.push(segment)
}
if (segments.length === expectedParts) {
return segments
}
}
}
if (matches.length === expectedParts) {
const segments: string[] = []
for (let i = 0; i < matches.length; i++) {
const match = matches[i]
const start = (match.index ?? 0) + (match[0].startsWith('\n') ? 1 : 0)
const end =
i + 1 < matches.length ? (matches[i + 1].index ?? content.length) : content.length
const segment = content.slice(start, end).trim()
if (!segment) {
return null
}
segments.push(segment)
}
if (segments.length === expectedParts) {
return segments
}
}
return null
}
// OpenAI completion method
protected async openAICompletion(
messages: ChatMessage[],
modelId?: string,
temperature?: number,
maxTokens?: number
): Promise<LLMResponse> {
if (!this.isInitialized) {
throw new Error('Provider not initialized')
}
if (!modelId) {
throw new Error('Model ID is required')
}
// Check if model supports function calling
const modelConfig = this.configPresenter.getModelConfig(modelId, this.provider.id)
const supportsFunctionCall = modelConfig?.functionCall || false
const requestParams: OpenAI.Chat.ChatCompletionCreateParams = {
messages: this.formatMessages(messages, supportsFunctionCall),
model: modelId,
stream: false,
temperature: temperature,
...(modelId.startsWith('o1') ||
modelId.startsWith('o3') ||
modelId.startsWith('o4') ||
modelId.includes('gpt-4.1') ||
modelId.includes('gpt-5')
? { max_completion_tokens: maxTokens }
: { max_tokens: maxTokens })
}
OPENAI_REASONING_MODELS.forEach((noTempId) => {
if (modelId.startsWith(noTempId)) {
delete requestParams.temperature
}
})
const completion = await this.openai.chat.completions.create(requestParams)
const message = completion.choices[0].message as ChatCompletionMessage & {
reasoning_content?: string
}
const resultResp: LLMResponse = {
content: ''
}
// Handle native reasoning_content
if (message.reasoning_content) {
resultResp.reasoning_content = message.reasoning_content
resultResp.content = message.content || ''
return resultResp
}
// Handle <think> tags
if (message.content) {
const content = message.content.trimStart()
if (content.includes('<think>')) {
const thinkStart = content.indexOf('<think>')
const thinkEnd = content.indexOf('</think>')
if (thinkEnd > thinkStart) {
// 提取 reasoning_content
resultResp.reasoning_content = content.substring(thinkStart + 7, thinkEnd).trim()
// 合并 <think> 前后的普通内容
const beforeThink = content.substring(0, thinkStart).trim()
const afterThink = content.substring(thinkEnd + 8).trim()
resultResp.content = [beforeThink, afterThink].filter(Boolean).join('\n')
} else {
// 如果没有找到配对的结束标签,将所有内容作为普通内容
resultResp.content = message.content
}
} else {
// 没有 think 标签,所有内容作为普通内容
resultResp.content = message.content
}
}
return resultResp
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 处理图片生成模型请求的内部方法。
* @param messages 聊天消息数组。
* @param modelId 模型ID。
* @returns AsyncGenerator<LLMCoreStreamEvent> 流式事件。
*/
private async *handleImgGeneration(
messages: ChatMessage[],
modelId: string
): AsyncGenerator<LLMCoreStreamEvent> {
// 获取最后几条消息,检查是否有图片
let prompt = ''
const imageUrls: string[] = []
// 获取最后的用户消息内容作为提示词
const lastUserMessage = messages.findLast((m) => m.role === 'user')
if (lastUserMessage?.content) {
if (typeof lastUserMessage.content === 'string') {
prompt = lastUserMessage.content
} else if (Array.isArray(lastUserMessage.content)) {
// 处理多模态内容,提取文本
const textParts: string[] = []
for (const part of lastUserMessage.content) {
if (part.type === 'text' && part.text) {
textParts.push(part.text)
}
}
prompt = textParts.join('\n')
}
}
// 检查最后几条消息中是否有图片
// 通常我们只需要检查最后两条消息:最近的用户消息和最近的助手消息
const lastMessages = messages.slice(-2)
for (const message of lastMessages) {
if (message.content) {
if (Array.isArray(message.content)) {
for (const part of message.content) {
if (part.type === 'image_url' && part.image_url?.url) {
imageUrls.push(part.image_url.url)
}
}
}
}
}
if (!prompt) {
console.error('[handleImgGeneration] Could not extract prompt for image generation.')
yield createStreamEvent.error('Could not extract prompt for image generation.')
yield createStreamEvent.stop('error')
return
}
try {
let result: OpenAI.Images.ImagesResponse
if (imageUrls.length > 0) {
// 使用 images.edit 接口处理带有图片的请求
let imageBuffer: Buffer
if (imageUrls[0].startsWith('imgcache://')) {
const filePath = imageUrls[0].slice('imgcache://'.length)
const fullPath = path.join(app.getPath('userData'), 'images', filePath)
imageBuffer = fs.readFileSync(fullPath)
} else {
const imageResponse = await fetch(imageUrls[0])
const imageBlob = await imageResponse.blob()
imageBuffer = Buffer.from(await imageBlob.arrayBuffer())
}
// 创建临时文件
const imagePath = `/tmp/openai_image_${Date.now()}.png`
await new Promise<void>((resolve, reject) => {
fs.writeFile(imagePath, imageBuffer, (err: Error | null) => {
if (err) {
reject(err)
} else {
resolve()
}
})
})
// 使用文件路径创建 Readable 流
const imageFile = fs.createReadStream(imagePath)
const params: OpenAI.Images.ImageEditParams = {
model: modelId,
image: imageFile,
prompt: prompt,
n: 1
}
// 如果是支持尺寸配置的模型,检测图片尺寸并设置合适的参数
if (SIZE_CONFIGURABLE_MODELS.includes(modelId)) {
try {
const metadata = await sharp(imageBuffer).metadata()
if (metadata.width && metadata.height) {
const aspectRatio = metadata.width / metadata.height
// 根据宽高比选择最接近的尺寸
if (Math.abs(aspectRatio - 1) < 0.1) {
// 接近正方形
params.size = SUPPORTED_IMAGE_SIZES.SQUARE
} else if (aspectRatio > 1) {
// 横向图片
params.size = SUPPORTED_IMAGE_SIZES.LANDSCAPE
} else {
// 纵向图片
params.size = SUPPORTED_IMAGE_SIZES.PORTRAIT
}
} else {
// 如果无法获取宽高,使用默认参数
params.size = '1024x1536'
}
params.quality = 'high'
} catch (error) {
console.warn(
'[handleImgGeneration] Failed to detect image dimensions, using default size:',
error
)
// 检测失败时使用默认参数
params.size = '1024x1536'
params.quality = 'high'
}
}
result = await this.openai.images.edit(params)
// 清理临时文件
try {
fs.unlinkSync(imagePath)
} catch (e) {
console.error('[handleImgGeneration] Failed to delete temporary file:', e)
}
} else {
// 使用原来的 images.generate 接口处理没有图片的请求
console.log(
`[handleImgGeneration] Generating image with model ${modelId} and prompt: "${prompt}"`
)
const params: OpenAI.Images.ImageGenerateParams = {
model: modelId,
prompt: prompt,
n: 1,
response_format: 'b64_json' // 请求 base64 格式
}
if (modelId === 'gpt-image-1' || modelId === 'gpt-4o-image' || modelId === 'gpt-4o-all') {
params.size = '1024x1536'
params.quality = 'high'
}
result = await this.openai.images.generate(params, {
timeout: 300_000
})
}
if (result.data && (result.data[0]?.url || result.data[0]?.b64_json)) {
// 使用devicePresenter缓存图片URL
try {
let imageUrl: string = ''
if (result.data[0]?.b64_json) {
// 处理 base64 数据
const base64Data = result.data[0].b64_json
// 直接使用 devicePresenter 缓存 base64 数据
imageUrl = await presenter.devicePresenter.cacheImage(
base64Data.startsWith('data:image/png;base64,')
? base64Data
: 'data:image/png;base64,' + base64Data
)
} else {
// 原有的 URL 处理逻辑
imageUrl = result.data[0]?.url || ''
imageUrl = await presenter.devicePresenter.cacheImage(imageUrl)
}
// 返回缓存后的URL
yield createStreamEvent.imageData({ data: imageUrl, mimeType: 'deepchat/image-url' })
// 处理 usage 信息
if (result.usage) {
yield createStreamEvent.usage({
prompt_tokens: result.usage.input_tokens || 0,
completion_tokens: result.usage.output_tokens || 0,
total_tokens: result.usage.total_tokens || 0
})
}
yield createStreamEvent.stop('complete')
} catch (cacheError) {
// 缓存失败时降级为使用原始URL
console.warn(
'[handleImgGeneration] Failed to cache image, using original data/URL:',
cacheError
)
yield createStreamEvent.imageData({
data: result.data[0]?.url || result.data[0]?.b64_json || '',
mimeType: result.data[0]?.url ? 'deepchat/image-url' : 'deepchat/image-base64'
})
yield createStreamEvent.stop('complete')
}
} else {
console.error('[handleImgGeneration] No image data received from API.', result)
yield createStreamEvent.error('No image data received from API.')
yield createStreamEvent.stop('error')
}
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error)
console.error('[handleImgGeneration] Error during image generation:', errorMessage)
yield createStreamEvent.error(`Image generation failed: ${errorMessage}`)
yield createStreamEvent.stop('error')
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 处理 OpenAI 聊天补全模型请求的内部方法。
* @param messages 聊天消息数组。
* @param modelId 模型ID。
* @param modelConfig 模型配置。
* @param temperature 温度参数。
* @param maxTokens 最大 token 数。
* @param mcpTools MCP 工具定义数组。
* @returns AsyncGenerator<LLMCoreStreamEvent> 流式事件。
*/
private async *handleChatCompletion(
messages: ChatMessage[],
modelId: string,
modelConfig: ModelConfig,
temperature: number,
maxTokens: number,
mcpTools: MCPToolDefinition[]
): AsyncGenerator<LLMCoreStreamEvent> {
//-----------------------------------------------------------------------------------------------------
// 为 OpenAI 聊天补全准备消息和工具
const tools = mcpTools || []
const supportsFunctionCall = modelConfig?.functionCall || false // 判断是否支持原生函数调用
let processedMessages = [
...this.formatMessages(messages, supportsFunctionCall)
] as ChatCompletionMessageParam[]
// 如果不支持原生函数调用但存在工具,则准备非原生函数调用提示
if (tools.length > 0 && !supportsFunctionCall) {
processedMessages = this.prepareFunctionCallPrompt(processedMessages, tools)
}
// 如果支持原生函数调用,则转换工具定义为 OpenAI 格式
const apiTools =
tools.length > 0 && supportsFunctionCall
? await presenter.mcpPresenter.mcpToolsToOpenAITools(tools, this.provider.id)
: undefined
// 构建请求参数
const requestParams: OpenAI.Chat.ChatCompletionCreateParams = {
messages: processedMessages,
model: modelId,
stream: true,