@opentiny/next-sdk 0.1.15-beta.1 → 0.1.15
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/agent/AgentModelProvider.ts +1 -490
- package/agent/type.ts +2 -8
- package/dist/WebMcpClient.d.ts +26 -165
- package/dist/WebMcpServer.d.ts +147 -36
- package/dist/agent/AgentModelProvider.d.ts +1 -35
- package/dist/agent/type.d.ts +2 -8
- package/dist/index.es.dev.js +11175 -14893
- package/dist/index.es.js +18206 -20985
- package/dist/index.js +320 -2411
- package/dist/index.umd.dev.js +11200 -14918
- package/dist/index.umd.js +71 -111
- package/dist/{mcpsdk@1.24.3.dev.js → mcpsdk@1.23.0.dev.js} +6652 -8271
- package/dist/{mcpsdk@1.24.3.es.dev.js → mcpsdk@1.23.0.es.dev.js} +6641 -8260
- package/dist/mcpsdk@1.23.0.es.js +15584 -0
- package/dist/mcpsdk@1.23.0.js +43 -0
- package/dist/transport/ExtensionPageServerTransport.d.ts +2 -1
- package/dist/webagent.dev.js +19914 -23355
- package/dist/webagent.es.dev.js +19889 -23330
- package/dist/webagent.es.js +15583 -18140
- package/dist/webagent.js +65 -105
- package/dist/webmcp-full.dev.js +7263 -8880
- package/dist/webmcp-full.es.dev.js +7261 -8878
- package/dist/webmcp-full.es.js +9267 -10421
- package/dist/webmcp-full.js +32 -32
- package/dist/webmcp.dev.js +22 -14
- package/dist/webmcp.es.dev.js +20 -12
- package/dist/webmcp.es.js +179 -172
- package/dist/webmcp.js +1 -1
- package/dist/zod@3.25.76.dev.js +32 -30
- package/dist/zod@3.25.76.es.dev.js +30 -28
- package/dist/zod@3.25.76.es.js +145 -143
- package/dist/zod@3.25.76.js +1 -1
- package/package.json +8 -9
- package/transport/ExtensionPageServerTransport.ts +4 -2
- package/agent/utils/generateReActPrompt.ts +0 -55
- package/agent/utils/parseReActAction.ts +0 -34
- package/dist/agent/utils/generateReActPrompt.d.ts +0 -9
- package/dist/agent/utils/parseReActAction.d.ts +0 -14
- package/dist/mcpsdk@1.24.3.es.js +0 -16781
- package/dist/mcpsdk@1.24.3.js +0 -43
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import { streamText, stepCountIs, generateText, StreamTextResult } from 'ai'
|
|
2
|
-
import {
|
|
3
|
-
experimental_MCPClientConfig as MCPClientConfig,
|
|
4
|
-
experimental_createMCPClient as createMCPClient
|
|
5
|
-
} from '@ai-sdk/mcp'
|
|
2
|
+
import { experimental_MCPClientConfig as MCPClientConfig, experimental_createMCPClient as createMCPClient } from 'ai'
|
|
6
3
|
import type { ToolSet } from 'ai'
|
|
7
4
|
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
|
|
8
5
|
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
|
|
@@ -15,8 +12,6 @@ import { ExtensionClientTransport } from '../transport/ExtensionClientTransport'
|
|
|
15
12
|
import { MessageChannelTransport } from '@opentiny/next'
|
|
16
13
|
import { WebMcpClient } from '../WebMcpClient'
|
|
17
14
|
import { getAISDKTools } from './utils/getAISDKTools'
|
|
18
|
-
import { generateReActToolsPrompt } from './utils/generateReActPrompt'
|
|
19
|
-
import { parseReActAction } from './utils/parseReActAction'
|
|
20
15
|
|
|
21
16
|
export const AIProviderFactories = {
|
|
22
17
|
['openai']: createOpenAI,
|
|
@@ -48,8 +43,6 @@ export class AgentModelProvider {
|
|
|
48
43
|
onClientDisconnected?: (serverName: string, reason?: string) => void
|
|
49
44
|
/** 缓存 ai-sdk response 中的 多轮会话的上下文 */
|
|
50
45
|
messages: any[] = []
|
|
51
|
-
/** 是否使用 ReAct 模式(通过提示词而非 function calling 进行工具调用) */
|
|
52
|
-
useReActMode: boolean = false
|
|
53
46
|
|
|
54
47
|
constructor({ llmConfig, mcpServers }: IAgentModelProviderOption) {
|
|
55
48
|
if (!llmConfig) {
|
|
@@ -77,9 +70,6 @@ export class AgentModelProvider {
|
|
|
77
70
|
} else {
|
|
78
71
|
throw new Error('Either llmConfig.llm or llmConfig.providerType must be provided')
|
|
79
72
|
}
|
|
80
|
-
|
|
81
|
-
// 读取 ReAct 模式配置
|
|
82
|
-
this.useReActMode = (llmConfig as any).useReActMode ?? false
|
|
83
73
|
}
|
|
84
74
|
|
|
85
75
|
/** 创建一个 ai-sdk的 mcpClient, 创建失败则返回 null */
|
|
@@ -110,7 +100,6 @@ export class AgentModelProvider {
|
|
|
110
100
|
{ name: 'mcp-web-client', version: '1.0.0' },
|
|
111
101
|
{ capabilities: { roots: { listChanged: true }, sampling: {}, elicitation: {} } }
|
|
112
102
|
)
|
|
113
|
-
// @ts-ignore transport 已经在前面的条件分支中转换为 Transport 实例,类型系统无法正确推断
|
|
114
103
|
await client.connect(transport)
|
|
115
104
|
|
|
116
105
|
//@ts-ignore
|
|
@@ -295,488 +284,10 @@ export class AgentModelProvider {
|
|
|
295
284
|
return toolsResult
|
|
296
285
|
}
|
|
297
286
|
|
|
298
|
-
/** 生成 ReAct 模式的系统提示词(包含工具描述) */
|
|
299
|
-
private _generateReActSystemPrompt(tools: ToolSet, modelName: string, baseSystemPrompt?: string): string {
|
|
300
|
-
// 统一使用 XML 格式的 ReAct 提示词(所有 ReAct 模式都使用相同格式)
|
|
301
|
-
const toolsPrompt = generateReActToolsPrompt(tools)
|
|
302
|
-
|
|
303
|
-
if (baseSystemPrompt) {
|
|
304
|
-
return `${baseSystemPrompt}${toolsPrompt}`
|
|
305
|
-
}
|
|
306
|
-
return `你是一个智能助手,可以通过调用工具来完成任务。\n${toolsPrompt}`
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
/** 执行 ReAct 模式下的工具调用 */
|
|
310
|
-
private async _executeReActToolCall(
|
|
311
|
-
toolName: string,
|
|
312
|
-
args: any,
|
|
313
|
-
tools: ToolSet
|
|
314
|
-
): Promise<{ success: boolean; result?: any; error?: string }> {
|
|
315
|
-
const tool = tools[toolName]
|
|
316
|
-
if (!tool) {
|
|
317
|
-
return { success: false, error: `工具 ${toolName} 不存在` }
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
try {
|
|
321
|
-
const toolInfo = tool as any
|
|
322
|
-
const executeFn = toolInfo.execute || toolInfo.call
|
|
323
|
-
if (typeof executeFn !== 'function') {
|
|
324
|
-
return { success: false, error: `工具 ${toolName} 没有可执行的函数` }
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
const result = await executeFn(args, {})
|
|
328
|
-
return { success: true, result }
|
|
329
|
-
} catch (error: any) {
|
|
330
|
-
const errorMsg = error?.message || String(error) || '工具执行失败'
|
|
331
|
-
return { success: false, error: errorMsg }
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
/** ReAct 模式的对话实现 */
|
|
336
|
-
private async _chatReAct(
|
|
337
|
-
chatMethod: ChatMethodFn,
|
|
338
|
-
{ model, maxSteps = 5, ...options }: Parameters<typeof generateText>[0] & { maxSteps?: number; message?: string }
|
|
339
|
-
): Promise<any> {
|
|
340
|
-
if (!this.llm) {
|
|
341
|
-
throw new Error('LLM is not initialized')
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
await this.initClientsAndTools()
|
|
345
|
-
|
|
346
|
-
// 合并所有可用工具
|
|
347
|
-
const allTools = this._tempMergeTools(options.tools) as ToolSet
|
|
348
|
-
const toolNames = Object.keys(allTools)
|
|
349
|
-
|
|
350
|
-
// 如果没有工具,回退到普通模式
|
|
351
|
-
if (toolNames.length === 0) {
|
|
352
|
-
return this._chat(chatMethod, { model, maxSteps, ...options })
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
// 准备消息历史
|
|
356
|
-
let currentMessages: any[] = []
|
|
357
|
-
if (options.message && !options.messages) {
|
|
358
|
-
currentMessages.push({ role: 'user', content: options.message })
|
|
359
|
-
} else if (options.messages) {
|
|
360
|
-
currentMessages = [...options.messages]
|
|
361
|
-
} else {
|
|
362
|
-
currentMessages = [...this.messages]
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
// 确保 model 是字符串类型(ReAct 模式下 model 应该是模型名称字符串)
|
|
366
|
-
const modelName = typeof model === 'string' ? model : (model as any)?.modelId || 'default-model'
|
|
367
|
-
|
|
368
|
-
// 生成包含工具描述的系统提示词
|
|
369
|
-
const systemPrompt = this._generateReActSystemPrompt(allTools, modelName, options.system as string)
|
|
370
|
-
|
|
371
|
-
const systemMessage = { role: 'system', content: systemPrompt }
|
|
372
|
-
|
|
373
|
-
// 确保第一条消息是系统提示词
|
|
374
|
-
const messagesWithSystem =
|
|
375
|
-
currentMessages[0]?.role === 'system' ? currentMessages : [systemMessage, ...currentMessages]
|
|
376
|
-
|
|
377
|
-
// 判断是否为流式输出
|
|
378
|
-
const isStream = chatMethod === streamText
|
|
379
|
-
|
|
380
|
-
if (isStream) {
|
|
381
|
-
// 流式输出模式:创建一个包装的流
|
|
382
|
-
return this._chatReActStream(messagesWithSystem, allTools, modelName, maxSteps, options)
|
|
383
|
-
} else {
|
|
384
|
-
// 非流式输出模式:循环对话直到完成
|
|
385
|
-
return this._chatReActNonStream(messagesWithSystem, allTools, modelName, maxSteps, options)
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
/**
|
|
390
|
-
* 检查消息内容是否包含图片
|
|
391
|
-
* @param content 消息内容
|
|
392
|
-
* @returns 是否包含图片
|
|
393
|
-
*/
|
|
394
|
-
private _messageHasImage(content: any): boolean {
|
|
395
|
-
if (!content) return false
|
|
396
|
-
|
|
397
|
-
// 如果 content 是数组,检查是否有 image 类型的项
|
|
398
|
-
if (Array.isArray(content)) {
|
|
399
|
-
return content.some((item) => item && item.type === 'image')
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
return false
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
/**
|
|
406
|
-
* 从消息中移除图片,但保留文本内容
|
|
407
|
-
* @param message 原始消息
|
|
408
|
-
* @returns 移除图片后的消息(如果只有图片没有文本,返回 null)
|
|
409
|
-
*/
|
|
410
|
-
private _removeImageFromMessage(message: any): any | null {
|
|
411
|
-
if (!message || !message.content) {
|
|
412
|
-
return null
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
// 如果 content 不是数组,直接返回(没有图片)
|
|
416
|
-
if (!Array.isArray(message.content)) {
|
|
417
|
-
return message
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
// 过滤掉图片类型的内容,保留文本
|
|
421
|
-
const textContent = message.content.filter((item: any) => item && item.type !== 'image')
|
|
422
|
-
|
|
423
|
-
// 如果过滤后没有内容,返回 null
|
|
424
|
-
if (textContent.length === 0) {
|
|
425
|
-
return null
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
// 返回只包含文本的消息副本
|
|
429
|
-
return {
|
|
430
|
-
...message,
|
|
431
|
-
content: textContent
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
/**
|
|
436
|
-
* 构建用于模型调用的消息列表(magentic-ui 风格)
|
|
437
|
-
* 策略:保留所有文本消息,仅限制图片数量(类似 magentic-ui 的 maybe_remove_old_screenshots)
|
|
438
|
-
*
|
|
439
|
-
* @param systemMessage 系统提示词
|
|
440
|
-
* @param allMessages 所有消息历史(包括初始消息和后续对话)
|
|
441
|
-
* @param maxImages 最多保留的图片数量(默认3张)
|
|
442
|
-
* @returns 构建好的消息列表
|
|
443
|
-
*/
|
|
444
|
-
private _buildMessagesForModel(systemMessage: any | null, allMessages: any[], maxImages: number = 3): any[] {
|
|
445
|
-
const messages: any[] = []
|
|
446
|
-
|
|
447
|
-
// 1. 添加系统提示词
|
|
448
|
-
if (systemMessage) {
|
|
449
|
-
messages.push(systemMessage)
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
// 2. 保留所有文本消息,但限制图片数量
|
|
453
|
-
// 从后往前遍历,优先保留最新的图片
|
|
454
|
-
let imageCount = 0
|
|
455
|
-
const processedMessages: any[] = []
|
|
456
|
-
|
|
457
|
-
for (let i = allMessages.length - 1; i >= 0; i--) {
|
|
458
|
-
const msg = allMessages[i]
|
|
459
|
-
|
|
460
|
-
// 检查消息是否包含图片
|
|
461
|
-
const hasImage = this._messageHasImage(msg.content)
|
|
462
|
-
|
|
463
|
-
if (hasImage) {
|
|
464
|
-
if (imageCount < maxImages) {
|
|
465
|
-
// 图片数量未超限,保留完整消息
|
|
466
|
-
processedMessages.unshift(msg)
|
|
467
|
-
imageCount++
|
|
468
|
-
} else {
|
|
469
|
-
// 图片数量超限,移除图片但保留文本(如果有)
|
|
470
|
-
const textOnly = this._removeImageFromMessage(msg)
|
|
471
|
-
if (textOnly) {
|
|
472
|
-
processedMessages.unshift(textOnly)
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
} else {
|
|
476
|
-
// 非图片消息:全部保留
|
|
477
|
-
processedMessages.unshift(msg)
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
messages.push(...processedMessages)
|
|
482
|
-
|
|
483
|
-
return messages
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
/** ReAct 模式非流式对话 */
|
|
487
|
-
private async _chatReActNonStream(
|
|
488
|
-
messages: any[],
|
|
489
|
-
tools: ToolSet,
|
|
490
|
-
model: string,
|
|
491
|
-
maxSteps: number,
|
|
492
|
-
options: any
|
|
493
|
-
): Promise<any> {
|
|
494
|
-
// 保存完整的消息历史(用于最终返回和传递给模型)
|
|
495
|
-
let fullMessageHistory = [...messages]
|
|
496
|
-
// 提取系统提示词(第一条消息)
|
|
497
|
-
const systemMessage = messages[0]?.role === 'system' ? messages[0] : null
|
|
498
|
-
// 提取所有非系统消息
|
|
499
|
-
const allUserMessages = systemMessage ? messages.slice(1) : messages
|
|
500
|
-
|
|
501
|
-
let stepCount = 0
|
|
502
|
-
// 配置:最多保留的图片数量(默认3张,类似 magentic-ui)
|
|
503
|
-
const maxImages = (options as any).maxImages ?? 3
|
|
504
|
-
|
|
505
|
-
while (stepCount < maxSteps) {
|
|
506
|
-
stepCount++
|
|
507
|
-
|
|
508
|
-
// 构建用于模型调用的消息列表(magentic-ui 风格:保留所有文本,限制图片)
|
|
509
|
-
const messagesForModel = this._buildMessagesForModel(systemMessage, allUserMessages, maxImages)
|
|
510
|
-
|
|
511
|
-
// 调用 LLM(ReAct 模式下不传递 tools,因为工具调用通过提示词实现)
|
|
512
|
-
// 参考 magentic-ui:保留所有文本历史(上下文完整),仅限制图片数量(优化 token)
|
|
513
|
-
const { tools: _, ...restOptions } = options
|
|
514
|
-
const result = await generateText({
|
|
515
|
-
// @ts-ignore ProviderV2 是所有llm的父类,在每一个具体的llm类都有一个选择model的函数用法
|
|
516
|
-
model: this.llm(model),
|
|
517
|
-
messages: messagesForModel,
|
|
518
|
-
...restOptions
|
|
519
|
-
})
|
|
520
|
-
|
|
521
|
-
const assistantMessage = result.text
|
|
522
|
-
// 添加到所有消息和完整历史
|
|
523
|
-
const assistantMsg = { role: 'assistant', content: assistantMessage }
|
|
524
|
-
allUserMessages.push(assistantMsg)
|
|
525
|
-
fullMessageHistory.push(assistantMsg)
|
|
526
|
-
|
|
527
|
-
// 解析工具调用
|
|
528
|
-
const action = parseReActAction(assistantMessage, tools)
|
|
529
|
-
|
|
530
|
-
if (!action) {
|
|
531
|
-
// 没有工具调用,返回最终结果
|
|
532
|
-
this.messages = fullMessageHistory
|
|
533
|
-
return {
|
|
534
|
-
text: assistantMessage,
|
|
535
|
-
response: { messages: fullMessageHistory }
|
|
536
|
-
}
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
// 执行工具调用
|
|
540
|
-
const toolResult = await this._executeReActToolCall(action.toolName, action.arguments, tools)
|
|
541
|
-
|
|
542
|
-
// 统一使用 XML 格式的 Observation
|
|
543
|
-
const resultString = toolResult.success ? JSON.stringify(toolResult.result) : `工具执行失败 - ${toolResult.error}`
|
|
544
|
-
const observation = `<tool_response>\n${resultString}\n</tool_response>`
|
|
545
|
-
|
|
546
|
-
// 添加到所有消息和完整历史
|
|
547
|
-
const observationMessage = {
|
|
548
|
-
role: 'user',
|
|
549
|
-
content: observation
|
|
550
|
-
}
|
|
551
|
-
allUserMessages.push(observationMessage)
|
|
552
|
-
fullMessageHistory.push(observationMessage)
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
// 达到最大步数,返回最后一条消息
|
|
556
|
-
this.messages = fullMessageHistory
|
|
557
|
-
const lastMessage = fullMessageHistory[fullMessageHistory.length - 2]?.content || ''
|
|
558
|
-
return {
|
|
559
|
-
text: lastMessage,
|
|
560
|
-
response: { messages: fullMessageHistory }
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
/** ReAct 模式流式对话 */
|
|
565
|
-
private _chatReActStream(messages: any[], tools: ToolSet, model: string, maxSteps: number, options: any): any {
|
|
566
|
-
// 保存 this 引用,以便在异步生成器中使用
|
|
567
|
-
const self = this
|
|
568
|
-
// @ts-ignore ProviderV2 是所有llm的父类,在每一个具体的llm类都有一个选择model的函数用法
|
|
569
|
-
const llmModel = this.llm(model)
|
|
570
|
-
|
|
571
|
-
// 创建一个 Promise 来跟踪流完成状态,用于触发 onFinish
|
|
572
|
-
let streamCompleteResolver: (value: any) => void
|
|
573
|
-
let streamCompleteRejecter: (error: any) => void
|
|
574
|
-
const streamCompletePromise = new Promise((resolve, reject) => {
|
|
575
|
-
streamCompleteResolver = resolve
|
|
576
|
-
streamCompleteRejecter = reject
|
|
577
|
-
})
|
|
578
|
-
|
|
579
|
-
// 创建一个异步生成器来模拟流式输出
|
|
580
|
-
const stream = new ReadableStream({
|
|
581
|
-
async start(controller) {
|
|
582
|
-
// 保存完整的消息历史(用于最终返回和传递给模型)
|
|
583
|
-
let fullMessageHistory = [...messages]
|
|
584
|
-
// 提取系统提示词(第一条消息)
|
|
585
|
-
const systemMessage = messages[0]?.role === 'system' ? messages[0] : null
|
|
586
|
-
// 提取所有非系统消息
|
|
587
|
-
const allUserMessages = systemMessage ? messages.slice(1) : [...messages]
|
|
588
|
-
|
|
589
|
-
let stepCount = 0
|
|
590
|
-
let accumulatedText = ''
|
|
591
|
-
// 配置:最多保留的图片数量(默认3张,类似 magentic-ui)
|
|
592
|
-
const maxImages = (options as any).maxImages ?? 3
|
|
593
|
-
|
|
594
|
-
try {
|
|
595
|
-
while (stepCount < maxSteps) {
|
|
596
|
-
stepCount++
|
|
597
|
-
|
|
598
|
-
// 构建用于模型调用的消息列表(magentic-ui 风格:保留所有文本,限制图片)
|
|
599
|
-
const messagesForModel = self._buildMessagesForModel(systemMessage, allUserMessages, maxImages)
|
|
600
|
-
|
|
601
|
-
// 移除 tools 选项,ReAct 模式下不传递 tools
|
|
602
|
-
const { tools: _, ...restOptions } = options
|
|
603
|
-
// 调用流式 LLM
|
|
604
|
-
// 参考 magentic-ui:保留所有文本历史(上下文完整),仅限制图片数量(优化 token)
|
|
605
|
-
delete restOptions.system
|
|
606
|
-
const result = await streamText({
|
|
607
|
-
...restOptions,
|
|
608
|
-
model: llmModel,
|
|
609
|
-
messages: messagesForModel
|
|
610
|
-
})
|
|
611
|
-
|
|
612
|
-
// 收集流式输出
|
|
613
|
-
let assistantText = ''
|
|
614
|
-
for await (const part of result.fullStream) {
|
|
615
|
-
if (part.type === 'text-delta') {
|
|
616
|
-
assistantText += part.text || ''
|
|
617
|
-
// 转发文本增量
|
|
618
|
-
controller.enqueue({
|
|
619
|
-
type: 'text-delta',
|
|
620
|
-
text: part.text
|
|
621
|
-
})
|
|
622
|
-
} else if (part.type === 'text-start') {
|
|
623
|
-
controller.enqueue({ type: 'text-start' })
|
|
624
|
-
} else if (part.type === 'text-end') {
|
|
625
|
-
// 暂时不关闭,等待检查是否有工具调用
|
|
626
|
-
} else {
|
|
627
|
-
// 转发其他类型的事件
|
|
628
|
-
controller.enqueue(part)
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
accumulatedText += assistantText
|
|
633
|
-
// 添加到所有消息和完整历史
|
|
634
|
-
const assistantMsg = { role: 'assistant', content: accumulatedText }
|
|
635
|
-
allUserMessages.push(assistantMsg)
|
|
636
|
-
fullMessageHistory.push(assistantMsg)
|
|
637
|
-
|
|
638
|
-
// 解析工具调用
|
|
639
|
-
const action = parseReActAction(accumulatedText, tools)
|
|
640
|
-
|
|
641
|
-
if (!action) {
|
|
642
|
-
// 没有工具调用,结束流
|
|
643
|
-
controller.enqueue({ type: 'text-end' })
|
|
644
|
-
controller.close()
|
|
645
|
-
self.messages = fullMessageHistory
|
|
646
|
-
// 触发 onFinish 回调
|
|
647
|
-
streamCompleteResolver({ messages: fullMessageHistory })
|
|
648
|
-
return
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
// 特殊处理: computer 工具的 terminate 操作
|
|
652
|
-
if (action.toolName === 'computer' && action.arguments?.action === 'terminate') {
|
|
653
|
-
// 视为对话结束
|
|
654
|
-
controller.enqueue({ type: 'text-end' })
|
|
655
|
-
controller.close()
|
|
656
|
-
self.messages = fullMessageHistory
|
|
657
|
-
streamCompleteResolver({ messages: fullMessageHistory })
|
|
658
|
-
return
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
// 发送工具调用开始事件(符合 tiny-robot 格式)
|
|
662
|
-
const toolCallId = `react-${Date.now()}`
|
|
663
|
-
controller.enqueue({
|
|
664
|
-
type: 'tool-input-start',
|
|
665
|
-
id: toolCallId,
|
|
666
|
-
toolName: action.toolName
|
|
667
|
-
})
|
|
668
|
-
|
|
669
|
-
// 发送工具调用参数(显示调用中状态)
|
|
670
|
-
const argsString = JSON.stringify(action.arguments, null, 2)
|
|
671
|
-
controller.enqueue({
|
|
672
|
-
type: 'tool-input-delta',
|
|
673
|
-
id: toolCallId,
|
|
674
|
-
delta: argsString
|
|
675
|
-
})
|
|
676
|
-
|
|
677
|
-
// 执行工具调用
|
|
678
|
-
const toolResult = await self._executeReActToolCall(action.toolName, action.arguments, tools)
|
|
679
|
-
|
|
680
|
-
// 如果结果包含 screenshot,先提取出来,避免 JSON stringify 导致过大
|
|
681
|
-
let screenshot = undefined
|
|
682
|
-
let resultData = toolResult.result
|
|
683
|
-
if (
|
|
684
|
-
toolResult.success &&
|
|
685
|
-
toolResult.result &&
|
|
686
|
-
typeof toolResult.result === 'object' &&
|
|
687
|
-
toolResult.result.screenshot
|
|
688
|
-
) {
|
|
689
|
-
screenshot = toolResult.result.screenshot
|
|
690
|
-
const { screenshot: _, ...rest } = toolResult.result
|
|
691
|
-
resultData = rest
|
|
692
|
-
}
|
|
693
|
-
|
|
694
|
-
// 构造 Observation 文本(统一使用 XML 格式)
|
|
695
|
-
let observationText = ''
|
|
696
|
-
|
|
697
|
-
if (toolResult.success) {
|
|
698
|
-
// 尝试从 resultData 中提取纯文本信息
|
|
699
|
-
if (
|
|
700
|
-
resultData &&
|
|
701
|
-
Array.isArray(resultData.content) &&
|
|
702
|
-
resultData.content.length > 0 &&
|
|
703
|
-
resultData.content[0].text
|
|
704
|
-
) {
|
|
705
|
-
observationText = resultData.content[0].text
|
|
706
|
-
} else {
|
|
707
|
-
observationText = JSON.stringify(resultData)
|
|
708
|
-
}
|
|
709
|
-
} else {
|
|
710
|
-
observationText = `工具执行失败 - ${toolResult.error}`
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
// 统一使用 XML 格式的 Observation,如果有截图,添加验证提示
|
|
714
|
-
let finalObservation = `<tool_response>\n${observationText}\n</tool_response>`
|
|
715
|
-
|
|
716
|
-
if (screenshot) {
|
|
717
|
-
finalObservation += `\n请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
// 发送工具结果(符合 tiny-robot 格式,给 UI 展示用的,不包含 base64 防止卡顿)
|
|
721
|
-
controller.enqueue({
|
|
722
|
-
type: 'tool-result',
|
|
723
|
-
toolCallId: toolCallId,
|
|
724
|
-
result: finalObservation
|
|
725
|
-
})
|
|
726
|
-
|
|
727
|
-
// 添加工具结果到消息历史(ReAct 模式下,工具结果作为 user 消息添加)
|
|
728
|
-
const observationMessage = screenshot
|
|
729
|
-
? {
|
|
730
|
-
role: 'user',
|
|
731
|
-
content: [
|
|
732
|
-
{ type: 'text', text: finalObservation },
|
|
733
|
-
{ type: 'image', image: screenshot }
|
|
734
|
-
]
|
|
735
|
-
}
|
|
736
|
-
: {
|
|
737
|
-
role: 'user',
|
|
738
|
-
content: finalObservation
|
|
739
|
-
}
|
|
740
|
-
|
|
741
|
-
// 添加到所有消息和完整历史
|
|
742
|
-
allUserMessages.push(observationMessage)
|
|
743
|
-
fullMessageHistory.push(observationMessage)
|
|
744
|
-
|
|
745
|
-
// 重置累积文本,准备下一轮
|
|
746
|
-
accumulatedText = ''
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
// 达到最大步数
|
|
750
|
-
controller.enqueue({ type: 'text-end' })
|
|
751
|
-
controller.close()
|
|
752
|
-
self.messages = fullMessageHistory
|
|
753
|
-
// 触发 onFinish 回调
|
|
754
|
-
streamCompleteResolver({ messages: fullMessageHistory })
|
|
755
|
-
} catch (error: any) {
|
|
756
|
-
controller.error(error)
|
|
757
|
-
streamCompleteRejecter(error)
|
|
758
|
-
}
|
|
759
|
-
}
|
|
760
|
-
})
|
|
761
|
-
|
|
762
|
-
// 返回一个类似 streamText 的结果对象
|
|
763
|
-
// response Promise 需要在流结束时 resolve,这样才能触发 onFinish 回调
|
|
764
|
-
return {
|
|
765
|
-
fullStream: stream,
|
|
766
|
-
response: streamCompletePromise
|
|
767
|
-
}
|
|
768
|
-
}
|
|
769
|
-
|
|
770
287
|
private async _chat(
|
|
771
288
|
chatMethod: ChatMethodFn,
|
|
772
289
|
{ model, maxSteps = 5, ...options }: Parameters<typeof generateText>[0] & { maxSteps?: number; message?: string }
|
|
773
290
|
): Promise<any> {
|
|
774
|
-
// 如果启用 ReAct 模式,使用 ReAct 实现
|
|
775
|
-
if (this.useReActMode) {
|
|
776
|
-
return this._chatReAct(chatMethod, { model, maxSteps, ...options })
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
// 否则使用原有的 function calling 模式
|
|
780
291
|
if (!this.llm) {
|
|
781
292
|
throw new Error('LLM is not initialized')
|
|
782
293
|
}
|
package/agent/type.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
|
+
export type { experimental_MCPClient as MCPClient } from 'ai'
|
|
1
2
|
import type { ProviderV2 } from '@ai-sdk/provider'
|
|
2
|
-
import type {
|
|
3
|
-
|
|
4
|
-
// 从 MCPClientConfig 中提取 transport 类型
|
|
5
|
-
export type MCPTransport = MCPClientConfig['transport']
|
|
3
|
+
import type { MCPTransport } from 'ai'
|
|
6
4
|
|
|
7
5
|
type ProviderFactory = 'openai' | 'deepseek' | ((options: any) => ProviderV2)
|
|
8
6
|
|
|
@@ -15,8 +13,6 @@ type LlmFactoryConfig = {
|
|
|
15
13
|
providerType: ProviderFactory
|
|
16
14
|
/** 互斥:当使用 providerType 分支时不允许传入 llm */
|
|
17
15
|
llm?: never
|
|
18
|
-
/** 是否使用 ReAct 模式(通过提示词而非 function calling 进行工具调用),默认为 false */
|
|
19
|
-
useReActMode?: boolean
|
|
20
16
|
}
|
|
21
17
|
|
|
22
18
|
type LlmInstanceConfig = {
|
|
@@ -26,8 +22,6 @@ type LlmInstanceConfig = {
|
|
|
26
22
|
apiKey?: never
|
|
27
23
|
baseURL?: never
|
|
28
24
|
providerType?: never
|
|
29
|
-
/** 是否使用 ReAct 模式(通过提示词而非 function calling 进行工具调用),默认为 false */
|
|
30
|
-
useReActMode?: boolean
|
|
31
25
|
}
|
|
32
26
|
|
|
33
27
|
/** 代理模型提供器的大语言配置对象, 通过 XOR 表达二选一 */
|