-
Notifications
You must be signed in to change notification settings - Fork 649
Expand file tree
/
Copy pathollamaProvider.ts
More file actions
1191 lines (1085 loc) · 39.6 KB
/
ollamaProvider.ts
File metadata and controls
1191 lines (1085 loc) · 39.6 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 {
LLM_PROVIDER,
LLMResponse,
MODEL_META,
OllamaModel,
ProgressResponse,
MCPToolDefinition,
ModelConfig,
LLMCoreStreamEvent,
ChatMessage,
LLM_EMBEDDING_ATTRS
} from '@shared/presenter'
import { BaseLLMProvider, SUMMARY_TITLES_PROMPT } from '../baseProvider'
import { ConfigPresenter } from '../../configPresenter'
import { Ollama, Message, ShowResponse } from 'ollama'
import { presenter } from '@/presenter'
import { EMBEDDING_TEST_KEY, isNormalized } from '@/utils/vector'
// 定义 Ollama 工具类型
interface OllamaTool {
type: 'function'
function: {
name: string
description: string
parameters: {
type: 'object'
properties: {
[key: string]: {
type: string
description: string
enum?: string[]
}
}
required: string[]
}
}
}
export class OllamaProvider extends BaseLLMProvider {
private ollama: Ollama
constructor(provider: LLM_PROVIDER, configPresenter: ConfigPresenter) {
super(provider, configPresenter)
if (this.provider.apiKey) {
this.ollama = new Ollama({
host: this.provider.baseUrl,
headers: { Authorization: `Bearer ${this.provider.apiKey}` }
})
} else {
this.ollama = new Ollama({
host: this.provider.baseUrl
})
}
this.init()
}
// 基础 Provider 功能实现
protected async fetchProviderModels(): Promise<MODEL_META[]> {
try {
console.log('Ollama service check', this.ollama, this.provider)
// 获取 Ollama 本地已安装的模型列表
const ollamaModels = await this.listModels()
// 将 Ollama 模型格式转换为应用程序的 MODEL_META 格式
return ollamaModels.map((model) => ({
id: model.name,
name: model.name,
providerId: this.provider.id,
contextLength: 8192, // 默认值,可以根据实际模型信息调整
maxTokens: 2048, // 添加必需的 maxTokens 字段
isCustom: false,
group: model.details?.family || 'default',
description: `${model.details?.parameter_size || ''} ${model.details?.family || ''} model`
}))
} catch (error) {
console.error('Failed to fetch Ollama models:', error)
return []
}
}
// 辅助方法:格式化消息
private formatMessages(messages: ChatMessage[]): Message[] {
return messages.map((msg) => {
if (typeof msg.content === 'string') {
return {
role: msg.role,
content: msg.content
}
} else {
// 分离文本和图片内容
const text =
msg.content && Array.isArray(msg.content)
? msg.content
.filter((c) => c.type === 'text')
.map((c) => c.text)
.join('\n')
: ''
const images =
msg.content && Array.isArray(msg.content)
? (msg.content
.filter((c) => c.type === 'image_url')
.map((c) => c.image_url?.url)
.filter(Boolean) as string[])
: []
return {
role: msg.role,
content: text,
...(images.length > 0 && { images })
}
}
})
}
public async check(): Promise<{ isOk: boolean; errorMsg: string | null }> {
try {
// 尝试获取模型列表来检查 Ollama 服务是否可用
await this.ollama.list()
return { isOk: true, errorMsg: null }
} catch (error) {
console.error('Ollama service check failed:', error)
return {
isOk: false,
errorMsg: `无法连接到 Ollama 服务: ${(error as Error).message}`
}
}
}
public async summaryTitles(messages: ChatMessage[], modelId: string): Promise<string> {
try {
const prompt = `${SUMMARY_TITLES_PROMPT}\n\n${messages.map((m) => `${m.role}: ${m.content}`).join('\n')}`
const response = await this.ollama.generate({
model: modelId,
prompt: prompt,
options: {
temperature: 0.3,
num_predict: 30
}
})
return response.response.trim()
} catch (error) {
console.error('Failed to generate title with Ollama:', error)
return '新对话'
}
}
public async completions(
messages: ChatMessage[],
modelId: string,
temperature?: number,
maxTokens?: number
): Promise<LLMResponse> {
try {
const response = await this.ollama.chat({
model: modelId,
messages: this.formatMessages(messages),
options: {
temperature: temperature || 0.7,
num_predict: maxTokens
}
})
const resultResp: LLMResponse = {
content: ''
}
// Ollama可能不提供完整的token计数
if (response.prompt_eval_count !== undefined || response.eval_count !== undefined) {
resultResp.totalUsage = {
prompt_tokens: response.prompt_eval_count || 0,
completion_tokens: response.eval_count || 0,
total_tokens: (response.prompt_eval_count || 0) + (response.eval_count || 0)
}
}
// 处理 thinking 字段
const content = response.message?.content || ''
const thinking = response.message?.thinking || ''
if (thinking) {
resultResp.reasoning_content = thinking
resultResp.content = content
}
// 处理<think>标签(其他模型)
else 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 = content
}
} else {
// 没有特殊格式,所有内容作为普通内容
resultResp.content = content
}
return resultResp
} catch (error) {
console.error('Ollama completions failed:', error)
throw error
}
}
public async summaries(
text: string,
modelId: string,
temperature?: number,
maxTokens?: number
): Promise<LLMResponse> {
try {
const prompt = `请对以下内容进行总结:\n\n${text}`
const response = await this.ollama.generate({
model: modelId,
prompt: prompt,
options: {
temperature: temperature || 0.5,
num_predict: maxTokens
}
})
return {
content: response.response,
reasoning_content: undefined
}
} catch (error) {
console.error('Ollama summaries failed:', error)
throw error
}
}
public async generateText(
prompt: string,
modelId: string,
temperature?: number,
maxTokens?: number
): Promise<LLMResponse> {
try {
const response = await this.ollama.generate({
model: modelId,
prompt: prompt,
options: {
temperature: temperature || 0.7,
num_predict: maxTokens
}
})
return {
content: response.response,
reasoning_content: undefined
}
} catch (error) {
console.error('Ollama generate text failed:', error)
throw error
}
}
public async suggestions(
context: string,
modelId: string,
temperature?: number,
maxTokens?: number
): Promise<string[]> {
try {
const prompt = `基于以下上下文,生成5个可能的后续问题或建议:\n\n${context}`
const response = await this.ollama.generate({
model: modelId,
prompt: prompt,
options: {
temperature: temperature || 0.8,
num_predict: maxTokens || 200
}
})
// 简单处理返回的文本,按行分割,并过滤掉空行
return response.response
.split('\n')
.map((line) => line.trim())
.filter((line) => line && line.length > 0)
.slice(0, 5) // 最多返回5个建议
} catch (error) {
console.error('Ollama suggestions failed:', error)
return []
}
}
private async attachModelInfo(model: OllamaModel): Promise<OllamaModel> {
const showResponse = await this.showModelInfo(model.name)
const info = showResponse.model_info
const family = model.details.family
const context_length = info?.[family + '.context_length'] ?? 4096
const embedding_length = info?.[family + '.embedding_length'] ?? 512
const capabilities = showResponse.capabilities ?? ['chat']
// Merge customConfig properties to model
return {
...model,
model_info: {
context_length,
embedding_length
},
capabilities
}
}
// Ollama 特有的模型管理功能
public async listModels(): Promise<OllamaModel[]> {
try {
const response = await this.ollama.list()
const models = response.models as unknown as OllamaModel[]
// FIXME: Merge model properties, optimize after ollama list API is improved
return await Promise.all(models.map(async (model) => this.attachModelInfo(model)))
} catch (error) {
console.error('Failed to list Ollama models:', (error as Error).message)
return []
}
}
public async listRunningModels(): Promise<OllamaModel[]> {
try {
const response = await this.ollama.ps()
const runningModels = response.models as unknown as OllamaModel[]
// FIXME: Merge model properties, optimize after ollama list API is improved
return await Promise.all(runningModels.map(async (model) => this.attachModelInfo(model)))
} catch (error) {
console.error('Failed to list running Ollama models:', (error as Error).message)
return []
}
}
public async pullModel(
modelName: string,
onProgress?: (progress: ProgressResponse) => void
): Promise<boolean> {
try {
const stream = await this.ollama.pull({
model: modelName,
insecure: true,
stream: true
})
for await (const chunk of stream) {
if (onProgress) {
onProgress(chunk as ProgressResponse)
}
}
return true
} catch (error) {
console.error(`Failed to pull Ollama model ${modelName}:`, (error as Error).message)
return false
}
}
public async deleteModel(modelName: string): Promise<boolean> {
try {
await this.ollama.delete({
model: modelName
})
return true
} catch (error) {
console.error(`Failed to delete Ollama model ${modelName}:`, (error as Error).message)
return false
}
}
public async showModelInfo(modelName: string): Promise<ShowResponse> {
try {
const response = await this.ollama.show({
model: modelName
})
return response
} catch (error) {
console.error(`Failed to show Ollama model info for ${modelName}:`, (error as Error).message)
throw error
}
}
// 辅助方法:将 MCP 工具转换为 Ollama 工具格式
private async convertToOllamaTools(mcpTools: MCPToolDefinition[]): Promise<OllamaTool[]> {
const openAITools = await presenter.mcpPresenter.mcpToolsToOpenAITools(
mcpTools,
this.provider.id
)
return openAITools.map((rawTool) => {
const tool = rawTool as unknown as {
function: {
name: string
description?: string
parameters: { properties: Record<string, unknown>; required?: string[] }
}
}
const properties = tool.function.parameters.properties || {}
const convertedProperties: Record<
string,
{ type: string; description: string; enum?: string[] }
> = {}
for (const [key, value] of Object.entries(properties)) {
if (typeof value === 'object' && value !== null) {
const param = value as { type: unknown; description: unknown; enum?: string[] }
convertedProperties[key] = {
type: String(param.type || 'string'),
description: String(param.description || ''),
...(param.enum ? { enum: param.enum } : {})
}
}
}
return {
type: 'function' as const,
function: {
name: tool.function.name,
description: tool.function.description || '',
parameters: {
type: 'object' as const,
properties: convertedProperties,
required: tool.function.parameters.required || []
}
}
}
})
}
// 实现BaseLLMProvider抽象方法 - 核心流处理
async *coreStream(
messages: ChatMessage[],
modelId: string,
modelConfig: ModelConfig,
temperature: number,
maxTokens: number,
mcpTools: MCPToolDefinition[]
): AsyncGenerator<LLMCoreStreamEvent> {
if (!modelId) throw new Error('Model ID is required')
// Ollama 不需要图片生成分支,直接处理聊天完成
yield* this.handleChatCompletion(
messages,
modelId,
modelConfig,
temperature,
maxTokens,
mcpTools
)
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 处理 Ollama 聊天补全模型请求的内部方法。
* @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> {
try {
const tools = mcpTools || []
const supportsFunctionCall = modelConfig?.functionCall || false
let processedMessages = this.formatMessages(messages)
// 工具参数准备
let ollamaTools: OllamaTool[] | undefined = undefined
if (tools.length > 0) {
if (supportsFunctionCall) {
// 支持原生函数调用,转换工具定义
ollamaTools = await this.convertToOllamaTools(tools)
} else {
// 不支持原生函数调用,使用提示词包装
processedMessages = this.prepareFunctionCallPrompt(processedMessages, tools)
// Ollama对于非原生支持通常情况下也不需要传递tools参数
ollamaTools = undefined
}
}
// Ollama聊天参数
const chatParams = {
model: modelId,
messages: processedMessages,
options: {
temperature: temperature || 0.7,
num_predict: maxTokens
},
stream: true as const,
...(modelConfig?.reasoningEffort && { reasoning_effort: modelConfig.reasoningEffort }),
...(supportsFunctionCall && ollamaTools && ollamaTools.length > 0
? { tools: ollamaTools }
: {})
}
// 创建流
const stream = await this.ollama.chat(chatParams)
// --- 状态变量 ---
type TagState = 'none' | 'start' | 'inside' | 'end'
let thinkState: TagState = 'none'
let funcState: TagState = 'none'
let pendingBuffer = '' // 用于标签匹配和潜在文本输出的缓冲区
let thinkBuffer = '' // 思考内容缓冲区
let funcCallBuffer = '' // 非原生函数调用内容的缓冲区
let codeBlockBuffer = '' // 代码块内容的缓冲区
const thinkStartMarker = '<think>'
const thinkEndMarker = '</think>'
const funcStartMarker = '<function_call>'
const funcEndMarker = '</function_call>'
// 代码块标记变体
const codeBlockMarkers = [
'```tool_code',
'```tool',
'``` tool_code',
'``` tool',
'```function_call',
'``` function_call'
]
const codeBlockEndMarker = '```'
let isInCodeBlock = false
// 用于跟踪原生工具调用
const nativeToolCalls: Record<
string,
{ name: string; arguments: string; completed?: boolean }
> = {}
let stopReason: LLMCoreStreamEvent['stop_reason'] = 'complete'
let toolUseDetected = false
let usage:
| {
prompt_tokens: number
completion_tokens: number
total_tokens: number
}
| undefined = undefined
// --- 流处理循环 ---
for await (const chunk of stream) {
// 处理使用统计
if (chunk.prompt_eval_count !== undefined || chunk.eval_count !== undefined) {
usage = {
prompt_tokens: chunk.prompt_eval_count || 0,
completion_tokens: chunk.eval_count || 0,
total_tokens: (chunk.prompt_eval_count || 0) + (chunk.eval_count || 0)
}
}
// 处理原生工具调用
if (
supportsFunctionCall &&
chunk.message?.tool_calls &&
chunk.message.tool_calls.length > 0
) {
toolUseDetected = true
for (const toolCall of chunk.message.tool_calls) {
const toolId = toolCall.function?.name || `ollama-tool-${Date.now()}`
if (!nativeToolCalls[toolId]) {
nativeToolCalls[toolId] = {
name: toolCall.function?.name || '',
arguments: JSON.stringify(toolCall.function?.arguments || {})
}
// 发送工具调用开始事件
yield {
type: 'tool_call_start',
tool_call_id: toolId,
tool_call_name: toolCall.function?.name || ''
}
// 发送工具调用参数块事件
yield {
type: 'tool_call_chunk',
tool_call_id: toolId,
tool_call_arguments_chunk: JSON.stringify(toolCall.function?.arguments || {})
}
// 发送工具调用结束事件
yield {
type: 'tool_call_end',
tool_call_id: toolId,
tool_call_arguments_complete: JSON.stringify(toolCall.function?.arguments || {})
}
}
}
stopReason = 'tool_use'
continue
}
// 处理 thinking 字段
const currentThinking = chunk.message?.thinking || ''
if (currentThinking) {
yield { type: 'reasoning', reasoning_content: currentThinking }
}
// 获取当前内容
const currentContent = chunk.message?.content || ''
if (!currentContent) continue
// 逐字符处理
for (const char of currentContent) {
pendingBuffer += char
let processedChar = false // 标记字符是否被状态逻辑处理
// --- 处理代码块 ---
if (isInCodeBlock) {
codeBlockBuffer += char
// 检查代码块结束
if (codeBlockBuffer.endsWith(codeBlockEndMarker)) {
isInCodeBlock = false
const codeContent = codeBlockBuffer
.substring(0, codeBlockBuffer.length - codeBlockEndMarker.length)
.trim()
try {
// 尝试解析JSON
let parsedCall
try {
// 移除可能的语言标识和开头的空白
const cleanContent = codeContent.replace(/^tool_code\s*/i, '').trim()
parsedCall = JSON.parse(cleanContent)
} catch {
// 尝试修复通用JSON格式问题
const cleanContent = codeContent.replace(/^tool_code\s*/i, '').trim()
const repaired = cleanContent
.replace(/,\s*}/g, '}') // 移除对象末尾的逗号
.replace(/,\s*\]/g, ']') // 移除数组末尾的逗号
.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2":') // 确保所有键都有双引号
parsedCall = JSON.parse(repaired)
}
// 提取函数名和参数
let functionName, functionArgs
if (parsedCall.function_call && typeof parsedCall.function_call === 'object') {
functionName = parsedCall.function_call.name
functionArgs = parsedCall.function_call.arguments
} else if (parsedCall.name && parsedCall.arguments !== undefined) {
functionName = parsedCall.name
functionArgs = parsedCall.arguments
} else if (
parsedCall.function &&
typeof parsedCall.function === 'object' &&
parsedCall.function.name
) {
functionName = parsedCall.function.name
functionArgs = parsedCall.function.arguments
} else {
throw new Error('无法从代码块中识别函数调用格式')
}
// 确保参数是字符串
if (typeof functionArgs !== 'string') {
functionArgs = JSON.stringify(functionArgs)
}
// 生成唯一ID
const id = parsedCall.id || `ollama-tool-${Date.now()}`
// 发送工具调用
toolUseDetected = true
yield {
type: 'tool_call_start',
tool_call_id: id,
tool_call_name: functionName
}
yield {
type: 'tool_call_chunk',
tool_call_id: id,
tool_call_arguments_chunk: functionArgs
}
yield {
type: 'tool_call_end',
tool_call_id: id,
tool_call_arguments_complete: functionArgs
}
stopReason = 'tool_use'
} catch {
// 解析失败,将内容作为普通文本输出
yield {
type: 'text',
content: '```tool_code\n' + codeContent + '\n```'
}
}
// 重置状态和缓冲区
codeBlockBuffer = ''
pendingBuffer = ''
processedChar = true
}
continue
}
if (usage) {
yield { type: 'usage', usage }
}
// --- 思考标签处理 ---
if (thinkState === 'inside') {
if (pendingBuffer.endsWith(thinkEndMarker)) {
thinkState = 'none'
if (thinkBuffer) {
yield { type: 'reasoning', reasoning_content: thinkBuffer }
thinkBuffer = ''
}
pendingBuffer = ''
processedChar = true
} else if (thinkEndMarker.startsWith(pendingBuffer)) {
thinkState = 'end'
processedChar = true
} else if (pendingBuffer.length >= thinkEndMarker.length) {
const charsToYield = pendingBuffer.slice(0, -thinkEndMarker.length + 1)
if (charsToYield) {
thinkBuffer += charsToYield
yield { type: 'reasoning', reasoning_content: charsToYield }
}
pendingBuffer = pendingBuffer.slice(-thinkEndMarker.length + 1)
if (thinkEndMarker.startsWith(pendingBuffer)) {
thinkState = 'end'
} else {
thinkBuffer += pendingBuffer
yield { type: 'reasoning', reasoning_content: pendingBuffer }
pendingBuffer = ''
thinkState = 'inside'
}
processedChar = true
} else {
thinkBuffer += char
yield { type: 'reasoning', reasoning_content: char }
pendingBuffer = ''
processedChar = true
}
} else if (thinkState === 'end') {
if (pendingBuffer.endsWith(thinkEndMarker)) {
thinkState = 'none'
if (thinkBuffer) {
yield { type: 'reasoning', reasoning_content: thinkBuffer }
thinkBuffer = ''
}
pendingBuffer = ''
processedChar = true
} else if (!thinkEndMarker.startsWith(pendingBuffer)) {
const failedTagChars = pendingBuffer
thinkBuffer += failedTagChars
yield { type: 'reasoning', reasoning_content: failedTagChars }
pendingBuffer = ''
thinkState = 'inside'
processedChar = true
} else {
processedChar = true
}
}
// --- 函数调用标签处理 ---
else if (
!supportsFunctionCall &&
tools.length > 0 &&
(funcState === 'inside' || funcState === 'end')
) {
processedChar = true // 假设已处理,除非下面的逻辑改变状态
if (funcState === 'inside') {
if (pendingBuffer.endsWith(funcEndMarker)) {
funcState = 'none'
funcCallBuffer += pendingBuffer.slice(0, -funcEndMarker.length)
pendingBuffer = ''
toolUseDetected = true
const parsedCalls = this.parseFunctionCalls(
`${funcStartMarker}${funcCallBuffer}${funcEndMarker}`,
`non-native-${this.provider.id}`
)
for (const parsedCall of parsedCalls) {
yield {
type: 'tool_call_start',
tool_call_id: parsedCall.id,
tool_call_name: parsedCall.function.name
}
yield {
type: 'tool_call_chunk',
tool_call_id: parsedCall.id,
tool_call_arguments_chunk: parsedCall.function.arguments
}
yield {
type: 'tool_call_end',
tool_call_id: parsedCall.id,
tool_call_arguments_complete: parsedCall.function.arguments
}
}
funcCallBuffer = ''
} else if (funcEndMarker.startsWith(pendingBuffer)) {
funcState = 'end'
} else if (pendingBuffer.length >= funcEndMarker.length) {
const charsToAdd = pendingBuffer.slice(0, -funcEndMarker.length + 1)
funcCallBuffer += charsToAdd
pendingBuffer = pendingBuffer.slice(-funcEndMarker.length + 1)
if (funcEndMarker.startsWith(pendingBuffer)) {
funcState = 'end'
} else {
funcCallBuffer += pendingBuffer
pendingBuffer = ''
funcState = 'inside'
}
} else {
funcCallBuffer += char
pendingBuffer = ''
}
} else {
// funcState === 'end'
if (pendingBuffer.endsWith(funcEndMarker)) {
funcState = 'none'
pendingBuffer = ''
toolUseDetected = true
const parsedCalls = this.parseFunctionCalls(
`${funcStartMarker}${funcCallBuffer}${funcEndMarker}`,
`non-native-${this.provider.id}`
)
for (const parsedCall of parsedCalls) {
yield {
type: 'tool_call_start',
tool_call_id: parsedCall.id,
tool_call_name: parsedCall.function.name
}
yield {
type: 'tool_call_chunk',
tool_call_id: parsedCall.id,
tool_call_arguments_chunk: parsedCall.function.arguments
}
yield {
type: 'tool_call_end',
tool_call_id: parsedCall.id,
tool_call_arguments_complete: parsedCall.function.arguments
}
}
funcCallBuffer = ''
} else if (!funcEndMarker.startsWith(pendingBuffer)) {
funcCallBuffer += pendingBuffer
pendingBuffer = ''
funcState = 'inside'
}
}
}
// --- 处理一般文本/标签检测(当不在任何标签内时)---
if (!processedChar) {
let potentialThink = thinkStartMarker.startsWith(pendingBuffer)
let potentialFunc =
!supportsFunctionCall && tools.length > 0 && funcStartMarker.startsWith(pendingBuffer)
const matchedThink = pendingBuffer.endsWith(thinkStartMarker)
const matchedFunc =
!supportsFunctionCall && tools.length > 0 && pendingBuffer.endsWith(funcStartMarker)
// 检查代码块标记
let codeBlockDetected = false
for (const marker of codeBlockMarkers) {
if (pendingBuffer.endsWith(marker)) {
codeBlockDetected = true
break
}
}
// --- 首先处理完整匹配 ---
if (matchedThink) {
const textBefore = pendingBuffer.slice(0, -thinkStartMarker.length)
if (textBefore) {
yield { type: 'text', content: textBefore }
}
thinkState = 'inside'
funcState = 'none' // 重置其他状态
pendingBuffer = ''
} else if (matchedFunc) {
const textBefore = pendingBuffer.slice(0, -funcStartMarker.length)
if (textBefore) {
yield { type: 'text', content: textBefore }
}
funcState = 'inside'
thinkState = 'none' // 重置其他状态
pendingBuffer = ''
} else if (codeBlockDetected) {
// 找到代码块开始标记,提取前面的文本
let markerText = ''
for (const marker of codeBlockMarkers) {
if (pendingBuffer.endsWith(marker)) {
markerText = marker
break
}
}
const textBefore = pendingBuffer.slice(0, -markerText.length)
if (textBefore) {
yield { type: 'text', content: textBefore }
}
isInCodeBlock = true
codeBlockBuffer = ''
pendingBuffer = ''
}
// --- 处理部分匹配(继续累积)---
else if (potentialThink || potentialFunc) {
// 如果可能匹配任一标签,只保留缓冲区并等待更多字符
thinkState = potentialThink ? 'start' : 'none'
funcState = potentialFunc ? 'start' : 'none'
}
// --- 处理不匹配/失败 ---
else if (pendingBuffer.length > 0) {
// 缓冲区不以'<'开头,或以'<'开头但不再匹配任何标签的开始
const charToYield = pendingBuffer[0]
yield { type: 'text', content: charToYield }
pendingBuffer = pendingBuffer.slice(1)
// 使用缩短的缓冲区立即重新评估潜在匹配
potentialThink =
pendingBuffer.length > 0 && thinkStartMarker.startsWith(pendingBuffer)
potentialFunc =
pendingBuffer.length > 0 &&
!supportsFunctionCall &&
tools.length > 0 &&
funcStartMarker.startsWith(pendingBuffer)
thinkState = potentialThink ? 'start' : 'none'
funcState = potentialFunc ? 'start' : 'none'
}
}
} // 字符循环结束
} // 块循环结束
// --- 完成处理 ---
// 输出缓冲区中剩余的文本
if (pendingBuffer) {
// 根据最终状态决定如何输出
if (thinkState === 'inside' || thinkState === 'end') {
yield { type: 'reasoning', reasoning_content: pendingBuffer }
thinkBuffer += pendingBuffer
} else if (funcState === 'inside' || funcState === 'end') {
// 将剩余内容添加到函数缓冲区 - 稍后处理
funcCallBuffer += pendingBuffer
} else {
yield { type: 'text', content: pendingBuffer }
}
pendingBuffer = ''
}
// 处理不完整的非原生函数调用
if (funcCallBuffer) {
const potentialContent = `${funcStartMarker}${funcCallBuffer}`
try {
const parsedCalls = this.parseFunctionCalls(
potentialContent,
`non-native-incomplete-${this.provider.id}`
)
if (parsedCalls.length > 0) {
toolUseDetected = true
for (const parsedCall of parsedCalls) {
yield {
type: 'tool_call_start',
tool_call_id: parsedCall.id + '-incomplete',
tool_call_name: parsedCall.function.name
}
yield {
type: 'tool_call_chunk',
tool_call_id: parsedCall.id + '-incomplete',
tool_call_arguments_chunk: parsedCall.function.arguments
}
yield {
type: 'tool_call_end',
tool_call_id: parsedCall.id + '-incomplete',
tool_call_arguments_complete: parsedCall.function.arguments
}
}
} else {
// 如果解析失败或没有结果,将缓冲区作为文本输出
yield { type: 'text', content: potentialContent }
}
} catch (e) {
console.error('解析不完整的函数调用缓冲区时出错:', e)
yield { type: 'text', content: potentialContent }