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