foliko 1.0.72 → 1.0.73
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/docs/ai-sdk-optimization.md +636 -0
- package/package.json +1 -1
- package/src/core/agent-chat.js +43 -4
- package/src/core/provider.js +4 -0
|
@@ -0,0 +1,636 @@
|
|
|
1
|
+
# AI SDK v6 优化报告 - Foliko 项目
|
|
2
|
+
|
|
3
|
+
> 本报告基于 [AI SDK v6 文档](https://ai-sdk.dev/docs/getting-started) 和 [Cookbook](https://ai-sdk.dev/cookbook) 分析,为 Foliko 项目提供具体的优化建议。
|
|
4
|
+
|
|
5
|
+
## 一、项目当前 AI SDK 使用分析
|
|
6
|
+
|
|
7
|
+
### 1.1 已集成的 AI SDK 组件
|
|
8
|
+
|
|
9
|
+
| 组件 | 版本 | 用途 |
|
|
10
|
+
|------|------|------|
|
|
11
|
+
| `ai` | 6.0.116 | 核心 SDK |
|
|
12
|
+
| `@ai-sdk/openai` | 3.0.41 | OpenAI Provider |
|
|
13
|
+
| `@ai-sdk/anthropic` | 3.0.58 | Anthropic Provider |
|
|
14
|
+
| `@ai-sdk/openai-compatible` | 2.0.35 | 兼容 Provider |
|
|
15
|
+
| `@ai-sdk/mcp` | 1.0.25 | MCP 集成 |
|
|
16
|
+
| `zod` | 3.24.0 | Schema 验证 |
|
|
17
|
+
| `tiktoken` | 1.0.22 | Token 计数 |
|
|
18
|
+
|
|
19
|
+
### 1.2 当前使用的 AI SDK 功能
|
|
20
|
+
|
|
21
|
+
```javascript
|
|
22
|
+
// ✅ 已使用
|
|
23
|
+
- ToolLoopAgent (工具调用循环)
|
|
24
|
+
- generateText (上下文总结)
|
|
25
|
+
- streamText 架构
|
|
26
|
+
- 基础 Provider 配置
|
|
27
|
+
- Zod schema (工具参数)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### 1.3 相关文件位置
|
|
31
|
+
|
|
32
|
+
| 功能 | 文件位置 | 用途 |
|
|
33
|
+
|------|---------|------|
|
|
34
|
+
| `ToolLoopAgent` | `src/core/agent-chat.js` | 工具调用循环 |
|
|
35
|
+
| `generateText` | `src/core/agent-chat.js` | 上下文总结、工具结果压缩 |
|
|
36
|
+
| `@ai-sdk/mcp` | `src/executors/mcp-executor.js` | MCP 服务器集成 |
|
|
37
|
+
| `Zod` | 全局 | 工具参数 schema |
|
|
38
|
+
| `tiktoken` | `src/core/agent-chat.js` | Token 计数、上下文压缩 |
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## 二、优化建议
|
|
43
|
+
|
|
44
|
+
### 🔴 【高优先级】
|
|
45
|
+
|
|
46
|
+
#### 2.1 结构化输出 - `generateObject` / `streamObject`
|
|
47
|
+
|
|
48
|
+
**现状**:项目使用 `generateText` 进行总结,但未使用结构化输出
|
|
49
|
+
|
|
50
|
+
**优化位置**:`src/core/agent-chat.js`
|
|
51
|
+
|
|
52
|
+
**建议新增**:
|
|
53
|
+
|
|
54
|
+
```javascript
|
|
55
|
+
// 2.1.1 意图识别
|
|
56
|
+
async _classifyIntent(message) {
|
|
57
|
+
const { generateObject } = require('ai')
|
|
58
|
+
|
|
59
|
+
const { object } = await generateObject({
|
|
60
|
+
model: this._aiClient,
|
|
61
|
+
schema: z.object({
|
|
62
|
+
intent: z.enum([
|
|
63
|
+
'create', 'read', 'update', 'delete',
|
|
64
|
+
'query', 'execute', 'explain', 'unknown'
|
|
65
|
+
]),
|
|
66
|
+
confidence: z.number().min(0).max(1),
|
|
67
|
+
entities: z.array(z.object({
|
|
68
|
+
name: z.string(),
|
|
69
|
+
type: z.string(),
|
|
70
|
+
value: z.any()
|
|
71
|
+
})).optional(),
|
|
72
|
+
suggestedTools: z.array(z.string()).optional()
|
|
73
|
+
}),
|
|
74
|
+
prompt: `分析用户消息的意图:${message}`
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
return object
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// 2.1.2 结构化任务解析
|
|
81
|
+
async _parseStructuredTask(message) {
|
|
82
|
+
const { generateObject } = require('ai')
|
|
83
|
+
|
|
84
|
+
const { object } = await generateObject({
|
|
85
|
+
model: this._aiClient,
|
|
86
|
+
schema: z.object({
|
|
87
|
+
taskType: z.enum(['simple', 'multi-step', 'parallel', 'conditional']),
|
|
88
|
+
steps: z.array(z.object({
|
|
89
|
+
action: z.string(),
|
|
90
|
+
tool: z.string().optional(),
|
|
91
|
+
parameters: z.record(z.any()).optional(),
|
|
92
|
+
dependsOn: z.array(z.number()).optional()
|
|
93
|
+
})),
|
|
94
|
+
estimatedComplexity: z.number().min(1).max(10)
|
|
95
|
+
}),
|
|
96
|
+
prompt: `将任务分解为结构化步骤:${message}`
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
return object
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
**收益**:
|
|
104
|
+
- 输出类型安全,减少解析错误
|
|
105
|
+
- 支持智能意图路由
|
|
106
|
+
- 为任务分解提供结构化基础
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
#### 2.2 Prompt Caching 集成
|
|
111
|
+
|
|
112
|
+
**现状**:使用 tiktoken 手动计算 token,未利用 AI SDK 原生缓存
|
|
113
|
+
|
|
114
|
+
**优化位置**:`src/core/agent-chat.js`
|
|
115
|
+
|
|
116
|
+
**建议修改**:
|
|
117
|
+
|
|
118
|
+
```javascript
|
|
119
|
+
// 2.2.1 新增导入
|
|
120
|
+
const { cachePrompt, smoothStream } = require('ai')
|
|
121
|
+
|
|
122
|
+
// 2.2.2 修改 _buildSystemPrompt - 添加缓存标记
|
|
123
|
+
_buildSystemPrompt() {
|
|
124
|
+
const parts = []
|
|
125
|
+
parts.push(this._originalPrompt)
|
|
126
|
+
// ... 其他部分
|
|
127
|
+
|
|
128
|
+
// 使用 cachePrompt 标记可缓存内容
|
|
129
|
+
const cacheableContent = parts.join('\n\n')
|
|
130
|
+
this._cachedSystemPrompt = cachePrompt(cacheableContent, {
|
|
131
|
+
cachePrefix: `system-${this.agent.name}`,
|
|
132
|
+
maxAgeMs: 1000 * 60 * 60 // 1小时
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
return this._cachedSystemPrompt
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// 2.2.3 在 chat() 中使用缓存
|
|
139
|
+
async chat(message, options = {}) {
|
|
140
|
+
// ...
|
|
141
|
+
|
|
142
|
+
// 使用缓存的 system prompt
|
|
143
|
+
const cachedSystem = this._cachedSystemPrompt || this._systemPrompt
|
|
144
|
+
|
|
145
|
+
const agent = new ToolLoopAgent({
|
|
146
|
+
model: this._aiClient,
|
|
147
|
+
instructions: cachedSystem, // 使用缓存版本
|
|
148
|
+
tools: tools,
|
|
149
|
+
stopWhen: (step) => step.stepCount >= maxSteps
|
|
150
|
+
})
|
|
151
|
+
}
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
**收益**:
|
|
155
|
+
- 降低 30-50% token 消耗
|
|
156
|
+
- 加快响应速度
|
|
157
|
+
- 减少 API 调用成本
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
### 🟡 【中优先级】
|
|
162
|
+
|
|
163
|
+
#### 2.3 流式响应增强 - `smoothStream` / `streamObject`
|
|
164
|
+
|
|
165
|
+
**现状**:流式使用 `stream` 但未使用平滑输出
|
|
166
|
+
|
|
167
|
+
**优化位置**:`src/core/agent-chat.js`
|
|
168
|
+
|
|
169
|
+
**建议修改**:
|
|
170
|
+
|
|
171
|
+
```javascript
|
|
172
|
+
// 2.3.1 平滑流式输出
|
|
173
|
+
async *chatStream(message, options = {}) {
|
|
174
|
+
// ...
|
|
175
|
+
|
|
176
|
+
const result = await framework.runWithContext(context, async () => {
|
|
177
|
+
return agent.stream({
|
|
178
|
+
messages,
|
|
179
|
+
...this.providerOptions,
|
|
180
|
+
...smoothStream({
|
|
181
|
+
delayInMs: 14 // 14ms 平滑间隔
|
|
182
|
+
})
|
|
183
|
+
})
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
// ...
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// 2.3.2 结构化流式输出 - 新增方法
|
|
190
|
+
async *streamStructured(message, schema, options = {}) {
|
|
191
|
+
const { streamObject } = require('ai')
|
|
192
|
+
|
|
193
|
+
const { partialObjectStream } = await streamObject({
|
|
194
|
+
model: this._aiClient,
|
|
195
|
+
schema,
|
|
196
|
+
prompt: message,
|
|
197
|
+
...smoothStream({ delayInMs: 14 })
|
|
198
|
+
})
|
|
199
|
+
|
|
200
|
+
for await (const partialObject of partialObjectStream) {
|
|
201
|
+
yield { type: 'partial', data: partialObject }
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
**收益**:
|
|
207
|
+
- 更流畅的实时输出体验
|
|
208
|
+
- 支持部分对象流式渲染
|
|
209
|
+
|
|
210
|
+
---
|
|
211
|
+
|
|
212
|
+
#### 2.4 推理模型支持 - o1/o3/R1
|
|
213
|
+
|
|
214
|
+
**现状**:未针对推理模型配置
|
|
215
|
+
|
|
216
|
+
**优化位置**:`src/core/provider.js` 和 `src/core/agent-chat.js`
|
|
217
|
+
|
|
218
|
+
**建议修改**:
|
|
219
|
+
|
|
220
|
+
```javascript
|
|
221
|
+
// 2.4.1 provider.js - 新增推理模型配置
|
|
222
|
+
const REASONING_MODELS = {
|
|
223
|
+
'o1-mini': { type: 'reasoning', supportsTools: false, maxTokens: 25000 },
|
|
224
|
+
'o1-preview': { type: 'reasoning', supportsTools: false, maxTokens: 25000 },
|
|
225
|
+
'o3-mini': { type: 'reasoning', supportsTools: false, maxTokens: 100000 },
|
|
226
|
+
'deepseek-r1': { type: 'reasoning', supportsTools: true, maxTokens: 64000 },
|
|
227
|
+
'deepseek-r1-distill-qwen-32b': { type: 'reasoning', supportsTools: true, maxTokens: 32000 }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// 2.4.2 agent-chat.js - 根据模型类型调整配置
|
|
231
|
+
_getAgentConfig() {
|
|
232
|
+
const modelId = this.model.toLowerCase()
|
|
233
|
+
|
|
234
|
+
// 检测是否是推理模型
|
|
235
|
+
const isReasoningModel = Object.keys(REASONING_MODELS)
|
|
236
|
+
.some(name => modelId.includes(name))
|
|
237
|
+
|
|
238
|
+
if (isReasoningModel) {
|
|
239
|
+
const config = REASONING_MODELS[Object.keys(REASONING_MODELS)
|
|
240
|
+
.find(name => modelId.includes(name))]
|
|
241
|
+
|
|
242
|
+
return {
|
|
243
|
+
// 推理模型通常不需要 system prompt
|
|
244
|
+
includeSystemInMessages: false,
|
|
245
|
+
// 推理模型不支持工具或需要特殊处理
|
|
246
|
+
supportsTools: config.supportsTools,
|
|
247
|
+
// 增大 maxTokens
|
|
248
|
+
maxTokens: config.maxTokens
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return {
|
|
253
|
+
includeSystemInMessages: true,
|
|
254
|
+
supportsTools: true,
|
|
255
|
+
maxTokens: 8192
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
**收益**:
|
|
261
|
+
- 支持 o1/o3/DeepSeek R1 等推理模型
|
|
262
|
+
- 自动适配推理模型的特殊配置
|
|
263
|
+
- 优化推理任务的性能
|
|
264
|
+
|
|
265
|
+
---
|
|
266
|
+
|
|
267
|
+
#### 2.5 中间件系统
|
|
268
|
+
|
|
269
|
+
**现状**:缺乏统一的中间件机制
|
|
270
|
+
|
|
271
|
+
**优化位置**:新增 `src/middleware/ai-middleware.js`
|
|
272
|
+
|
|
273
|
+
**建议新增**:
|
|
274
|
+
|
|
275
|
+
```javascript
|
|
276
|
+
// src/middleware/ai-middleware.js
|
|
277
|
+
const {
|
|
278
|
+
extractReasoningMiddleware,
|
|
279
|
+
defaultSettingsMiddleware,
|
|
280
|
+
withTelemetry
|
|
281
|
+
} = require('ai')
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* 创建 AI 中间件
|
|
285
|
+
*/
|
|
286
|
+
function createAIMiddleware(options = {}) {
|
|
287
|
+
const middlewares = []
|
|
288
|
+
|
|
289
|
+
// 1. 推理提取中间件
|
|
290
|
+
if (options.extractReasoning !== false) {
|
|
291
|
+
middlewares.push(extractReasoningMiddleware({
|
|
292
|
+
tagName: 'thinking',
|
|
293
|
+
onChunk: (chunk) => {
|
|
294
|
+
options.onReasoning?.(chunk)
|
|
295
|
+
}
|
|
296
|
+
}))
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// 2. 默认设置中间件
|
|
300
|
+
middlewares.push(defaultSettingsMiddleware({
|
|
301
|
+
settings: {
|
|
302
|
+
[options.defaultModel]: {
|
|
303
|
+
temperature: options.temperature || 0.7,
|
|
304
|
+
maxTokens: options.maxTokens || 8192
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}))
|
|
308
|
+
|
|
309
|
+
// 3. 遥测中间件
|
|
310
|
+
if (options.telemetry) {
|
|
311
|
+
middlewares.push(withTelemetry({
|
|
312
|
+
serviceName: 'foliko-agent',
|
|
313
|
+
metadata: {
|
|
314
|
+
version: options.version,
|
|
315
|
+
sessionId: options.sessionId
|
|
316
|
+
}
|
|
317
|
+
}))
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return middlewares
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* 创建日志中间件(自定义)
|
|
325
|
+
*/
|
|
326
|
+
function createLoggingMiddleware() {
|
|
327
|
+
return {
|
|
328
|
+
async wrapModel(model, { doStream }) {
|
|
329
|
+
return {
|
|
330
|
+
doStream: async (prompt, options) => {
|
|
331
|
+
const startTime = Date.now()
|
|
332
|
+
console.log('[AI] Request started:', {
|
|
333
|
+
promptLength: typeof prompt === 'string' ? prompt.length : 'array'
|
|
334
|
+
})
|
|
335
|
+
|
|
336
|
+
try {
|
|
337
|
+
const result = await doStream()
|
|
338
|
+
const duration = Date.now() - startTime
|
|
339
|
+
console.log('[AI] Request completed:', { duration })
|
|
340
|
+
return result
|
|
341
|
+
} catch (error) {
|
|
342
|
+
console.error('[AI] Request failed:', error.message)
|
|
343
|
+
throw error
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
module.exports = {
|
|
352
|
+
createAIMiddleware,
|
|
353
|
+
createLoggingMiddleware
|
|
354
|
+
}
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
**收益**:
|
|
358
|
+
- 统一的日志、监控、遥测
|
|
359
|
+
- 推理过程可追踪
|
|
360
|
+
- 支持自定义中间件扩展
|
|
361
|
+
|
|
362
|
+
---
|
|
363
|
+
|
|
364
|
+
#### 2.6 Embeddings 支持
|
|
365
|
+
|
|
366
|
+
**现状**:未实现嵌入功能
|
|
367
|
+
|
|
368
|
+
**优化位置**:新增到 `src/plugins/ai-plugin.js` 或创建新文件
|
|
369
|
+
|
|
370
|
+
**建议新增**:
|
|
371
|
+
|
|
372
|
+
```javascript
|
|
373
|
+
// src/plugins/embeddings-plugin.js 或在 ai-plugin.js 中新增
|
|
374
|
+
const { embed, embedMany } = require('ai')
|
|
375
|
+
|
|
376
|
+
class AIPlugin extends Plugin {
|
|
377
|
+
// ... 现有代码
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* 获取嵌入模型
|
|
381
|
+
*/
|
|
382
|
+
getEmbeddingModel() {
|
|
383
|
+
if (this._embeddingModel) return this._embeddingModel
|
|
384
|
+
|
|
385
|
+
const embeddingModelId = this._getEmbeddingModelId()
|
|
386
|
+
this._embeddingModel = this._embeddingProvider.textEmbeddingModel(embeddingModelId)
|
|
387
|
+
|
|
388
|
+
return this._embeddingModel
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
_getEmbeddingModelId() {
|
|
392
|
+
const provider = this.config.provider?.toLowerCase()
|
|
393
|
+
const modelMap = {
|
|
394
|
+
'openai': 'text-embedding-3-small',
|
|
395
|
+
'deepseek': 'deepseek-embed',
|
|
396
|
+
'ollama': 'nomic-embed-text'
|
|
397
|
+
}
|
|
398
|
+
return modelMap[provider] || 'text-embedding-3-small'
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* 嵌入单个文本
|
|
403
|
+
*/
|
|
404
|
+
async embedText(text) {
|
|
405
|
+
const { embedding } = await embed({
|
|
406
|
+
model: this.getEmbeddingModel(),
|
|
407
|
+
value: text
|
|
408
|
+
})
|
|
409
|
+
return embedding
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* 批量嵌入
|
|
414
|
+
*/
|
|
415
|
+
async embedTexts(texts) {
|
|
416
|
+
const { embeddings } = await embedMany({
|
|
417
|
+
model: this.getEmbeddingModel(),
|
|
418
|
+
values: texts
|
|
419
|
+
})
|
|
420
|
+
return embeddings
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
**收益**:
|
|
426
|
+
- 支持 RAG 知识库构建
|
|
427
|
+
- 语义搜索基础
|
|
428
|
+
- 文本相似度计算
|
|
429
|
+
|
|
430
|
+
---
|
|
431
|
+
|
|
432
|
+
### 🟢 【低优先级】
|
|
433
|
+
|
|
434
|
+
#### 2.7 错误处理增强
|
|
435
|
+
|
|
436
|
+
**现状**:基础错误捕获
|
|
437
|
+
|
|
438
|
+
**优化位置**:`src/core/agent-chat.js`
|
|
439
|
+
|
|
440
|
+
**建议修改**:
|
|
441
|
+
|
|
442
|
+
```javascript
|
|
443
|
+
// 2.7.1 新增错误类型导入
|
|
444
|
+
const {
|
|
445
|
+
AI_APICallError,
|
|
446
|
+
AI_RetryableError,
|
|
447
|
+
AI_NoSuchModelError,
|
|
448
|
+
AIInvalidPromptError
|
|
449
|
+
} = require('ai')
|
|
450
|
+
|
|
451
|
+
// 2.7.2 增强错误处理
|
|
452
|
+
async chat(message, options = {}) {
|
|
453
|
+
try {
|
|
454
|
+
// ... 现有代码
|
|
455
|
+
} catch (error) {
|
|
456
|
+
if (error instanceof AI_APICallError) {
|
|
457
|
+
switch (error.statusCode) {
|
|
458
|
+
case 400:
|
|
459
|
+
throw new Error(`无效请求: ${error.message}`)
|
|
460
|
+
case 401:
|
|
461
|
+
throw new Error('API 密钥无效或已过期')
|
|
462
|
+
case 429:
|
|
463
|
+
throw new Error('请求频率超限,请稍后重试')
|
|
464
|
+
case 500:
|
|
465
|
+
case 502:
|
|
466
|
+
case 503:
|
|
467
|
+
throw new Error(`AI 服务暂时不可用: ${error.message}`)
|
|
468
|
+
default:
|
|
469
|
+
throw error
|
|
470
|
+
}
|
|
471
|
+
} else if (error instanceof AI_NoSuchModelError) {
|
|
472
|
+
throw new Error(`模型 ${this.model} 不存在或不可用`)
|
|
473
|
+
} else if (error instanceof AIInvalidPromptError) {
|
|
474
|
+
throw new Error(`提示词无效: ${error.message}`)
|
|
475
|
+
}
|
|
476
|
+
throw error
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// 2.7.3 重试装饰器
|
|
481
|
+
async withRetry(fn, maxRetries = 3, delayMs = 1000) {
|
|
482
|
+
for (let i = 0; i < maxRetries; i++) {
|
|
483
|
+
try {
|
|
484
|
+
return await fn()
|
|
485
|
+
} catch (error) {
|
|
486
|
+
if (i === maxRetries - 1) throw error
|
|
487
|
+
if (!this._isRetryable(error)) throw error
|
|
488
|
+
|
|
489
|
+
console.log(`[AgentChat] Retry ${i + 1}/${maxRetries} after ${delayMs}ms`)
|
|
490
|
+
await new Promise(r => setTimeout(r, delayMs))
|
|
491
|
+
delayMs *= 2 // 指数退避
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
_isRetryable(error) {
|
|
497
|
+
if (error instanceof AI_APICallError) {
|
|
498
|
+
return [429, 500, 502, 503].includes(error.statusCode)
|
|
499
|
+
}
|
|
500
|
+
return false
|
|
501
|
+
}
|
|
502
|
+
```
|
|
503
|
+
|
|
504
|
+
**收益**:
|
|
505
|
+
- 更健壮的错误恢复
|
|
506
|
+
- 用户友好的错误提示
|
|
507
|
+
- 自动重试机制
|
|
508
|
+
|
|
509
|
+
---
|
|
510
|
+
|
|
511
|
+
#### 2.8 MCP Elicitation 支持
|
|
512
|
+
|
|
513
|
+
**现状**:使用 MCP 但未支持用户确认
|
|
514
|
+
|
|
515
|
+
**优化位置**:`src/executors/mcp-executor.js`
|
|
516
|
+
|
|
517
|
+
**建议修改**:
|
|
518
|
+
|
|
519
|
+
```javascript
|
|
520
|
+
// 2.8.1 新增 MCP Elicitation 支持
|
|
521
|
+
async connect() {
|
|
522
|
+
// ... 现有代码
|
|
523
|
+
|
|
524
|
+
// 启用 Elicitation(用户确认)
|
|
525
|
+
if (this.client && typeof this.client.requestConfirmation === 'function') {
|
|
526
|
+
this._enableElicitation = true
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// 2.8.2 工具调用时请求确认
|
|
531
|
+
async executeToolWithConfirmation(toolName, args) {
|
|
532
|
+
if (!this._enableElicitation) {
|
|
533
|
+
return this.executeTool(toolName, args)
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// 发送确认请求给用户
|
|
537
|
+
const confirmed = await this._requestUserConfirmation({
|
|
538
|
+
toolName,
|
|
539
|
+
args,
|
|
540
|
+
description: this._getToolDescription(toolName)
|
|
541
|
+
})
|
|
542
|
+
|
|
543
|
+
if (!confirmed) {
|
|
544
|
+
return { error: 'User rejected tool execution' }
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
return this.executeTool(toolName, args)
|
|
548
|
+
}
|
|
549
|
+
```
|
|
550
|
+
|
|
551
|
+
**收益**:
|
|
552
|
+
- 用户可控制工具执行
|
|
553
|
+
- 提高安全性
|
|
554
|
+
- 支持敏感操作确认
|
|
555
|
+
|
|
556
|
+
---
|
|
557
|
+
|
|
558
|
+
## 三、优化优先级汇总
|
|
559
|
+
|
|
560
|
+
| 优先级 | 优化项 | 收益 | 影响范围 | 工作量 |
|
|
561
|
+
|--------|--------|------|----------|--------|
|
|
562
|
+
| 🔴 高 | `generateObject` 意图识别 | 类型安全、智能路由 | `agent-chat.js` | 1天 |
|
|
563
|
+
| 🔴 高 | Prompt Caching | 降低30% token消耗 | `agent-chat.js` | 0.5天 |
|
|
564
|
+
| 🟡 中 | `smoothStream` 流式增强 | 更流畅体验 | `agent-chat.js` | 0.5天 |
|
|
565
|
+
| 🟡 中 | 推理模型支持 | o1/R1 优化 | `provider.js`, `agent-chat.js` | 1天 |
|
|
566
|
+
| 🟡 中 | 中间件系统 | 统一监控/日志 | 新建 `middleware/` | 2天 |
|
|
567
|
+
| 🟡 中 | Embeddings | RAG 基础 | `ai-plugin.js` | 1天 |
|
|
568
|
+
| 🟢 低 | 错误处理增强 | 更健壮 | `agent-chat.js` | 0.5天 |
|
|
569
|
+
| 🟢 低 | MCP Elicitation | 用户控制 | `mcp-executor.js` | 1天 |
|
|
570
|
+
|
|
571
|
+
---
|
|
572
|
+
|
|
573
|
+
## 四、实施路线图
|
|
574
|
+
|
|
575
|
+
### 第一阶段(立即可做)
|
|
576
|
+
|
|
577
|
+
```
|
|
578
|
+
✅ generateObject 意图识别
|
|
579
|
+
└── 在 agent-chat.js 新增 _classifyIntent() 方法
|
|
580
|
+
|
|
581
|
+
✅ Prompt Caching 集成
|
|
582
|
+
└── 在 _buildSystemPrompt() 中使用 cachePrompt()
|
|
583
|
+
```
|
|
584
|
+
|
|
585
|
+
### 第二阶段(1周内)
|
|
586
|
+
|
|
587
|
+
```
|
|
588
|
+
📦 smoothStream 流式增强
|
|
589
|
+
└── 在 stream() 中添加 smoothStream 配置
|
|
590
|
+
|
|
591
|
+
📦 推理模型支持
|
|
592
|
+
└── 在 provider.js 新增 REASONING_MODELS 配置
|
|
593
|
+
|
|
594
|
+
📦 错误处理增强
|
|
595
|
+
└── 使用 AI SDK 错误类型替换基础 catch
|
|
596
|
+
```
|
|
597
|
+
|
|
598
|
+
### 第三阶段(长期)
|
|
599
|
+
|
|
600
|
+
```
|
|
601
|
+
📦 中间件系统
|
|
602
|
+
└── 新建 src/middleware/ai-middleware.js
|
|
603
|
+
|
|
604
|
+
📦 Embeddings 支持
|
|
605
|
+
└── 在 ai-plugin.js 新增 embedText/embedTexts 方法
|
|
606
|
+
|
|
607
|
+
📦 MCP Elicitation
|
|
608
|
+
└── 在 mcp-executor.js 新增用户确认机制
|
|
609
|
+
```
|
|
610
|
+
|
|
611
|
+
---
|
|
612
|
+
|
|
613
|
+
## 五、需要安装的包
|
|
614
|
+
|
|
615
|
+
```bash
|
|
616
|
+
# 基础已安装
|
|
617
|
+
npm install ai @ai-sdk/openai @ai-sdk/anthropic
|
|
618
|
+
|
|
619
|
+
# 可能需要添加(根据需求)
|
|
620
|
+
npm install @ai-sdk/google # Gemini 模型支持
|
|
621
|
+
npm install @ai-sdk/deepseek # DeepSeek 模型支持
|
|
622
|
+
npm install @ai-sdk/amazon-bedrock # AWS Bedrock 支持
|
|
623
|
+
```
|
|
624
|
+
|
|
625
|
+
---
|
|
626
|
+
|
|
627
|
+
## 六、参考资料
|
|
628
|
+
|
|
629
|
+
- [AI SDK 官方文档](https://ai-sdk.dev/docs/getting-started)
|
|
630
|
+
- [AI SDK Cookbook](https://ai-sdk.dev/cookbook)
|
|
631
|
+
- [AI SDK API Reference](https://ai-sdk.dev/docs/api-reference)
|
|
632
|
+
|
|
633
|
+
---
|
|
634
|
+
|
|
635
|
+
*文档生成时间:2025-01-25*
|
|
636
|
+
*基于 AI SDK v6 版本分析*
|
package/package.json
CHANGED
package/src/core/agent-chat.js
CHANGED
|
@@ -626,14 +626,17 @@ ${truncatedContent}${truncatedNote}
|
|
|
626
626
|
name: toolName,
|
|
627
627
|
description: toolDef.description || '',
|
|
628
628
|
execute: async (args) => {
|
|
629
|
+
// 清理参数:移除 undefined、function 等无效值
|
|
630
|
+
const cleanedArgs = this._cleanToolArgs(args)
|
|
631
|
+
|
|
629
632
|
// 执行工具
|
|
630
|
-
this.emit('tool-call', { name: toolName, args })
|
|
633
|
+
this.emit('tool-call', { name: toolName, args: cleanedArgs })
|
|
631
634
|
try {
|
|
632
|
-
const result = await toolDef.execute(
|
|
633
|
-
this.emit('tool-result', { name: toolName, args, result })
|
|
635
|
+
const result = await toolDef.execute(cleanedArgs, this.agent.framework)
|
|
636
|
+
this.emit('tool-result', { name: toolName, args: cleanedArgs, result })
|
|
634
637
|
return result
|
|
635
638
|
} catch (err) {
|
|
636
|
-
this.emit('tool-error', { name: toolName, args, error: err.message })
|
|
639
|
+
this.emit('tool-error', { name: toolName, args: cleanedArgs, error: err.message })
|
|
637
640
|
return { error: err.message }
|
|
638
641
|
}
|
|
639
642
|
}
|
|
@@ -653,6 +656,42 @@ ${truncatedContent}${truncatedNote}
|
|
|
653
656
|
return tools
|
|
654
657
|
}
|
|
655
658
|
|
|
659
|
+
/**
|
|
660
|
+
* 清理工具参数,移除无效值
|
|
661
|
+
* @param {Object} args - 原始参数
|
|
662
|
+
* @returns {Object} 清理后的参数
|
|
663
|
+
* @private
|
|
664
|
+
*/
|
|
665
|
+
_cleanToolArgs(args) {
|
|
666
|
+
if (!args || typeof args !== 'object') {
|
|
667
|
+
return {}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
const cleaned = {}
|
|
671
|
+
for (const [key, value] of Object.entries(args)) {
|
|
672
|
+
// 跳过 undefined、function、symbol 等无效值
|
|
673
|
+
if (value === undefined || value === null) {
|
|
674
|
+
continue
|
|
675
|
+
}
|
|
676
|
+
if (typeof value === 'function' || typeof value === 'symbol') {
|
|
677
|
+
continue
|
|
678
|
+
}
|
|
679
|
+
// 递归清理嵌套对象
|
|
680
|
+
if (typeof value === 'object' && !Array.isArray(value)) {
|
|
681
|
+
cleaned[key] = this._cleanToolArgs(value)
|
|
682
|
+
} else if (Array.isArray(value)) {
|
|
683
|
+
cleaned[key] = value.map(item =>
|
|
684
|
+
typeof item === 'object' && item !== null
|
|
685
|
+
? this._cleanToolArgs(item)
|
|
686
|
+
: item
|
|
687
|
+
).filter(item => item !== undefined && typeof item !== 'function')
|
|
688
|
+
} else {
|
|
689
|
+
cleaned[key] = value
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
return cleaned
|
|
693
|
+
}
|
|
694
|
+
|
|
656
695
|
/**
|
|
657
696
|
* 清理消息格式
|
|
658
697
|
* @private
|