foliko 1.0.72 → 1.0.74

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.
@@ -0,0 +1,643 @@
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
+ - ✅ `IntentClassificationSchema` - 意图识别 Zod Schema
54
+ - ✅ `TaskStructuredSchema` - 任务结构化解析 Schema
55
+ - ✅ `SummarySchema` - 摘要生成 Schema
56
+ - ✅ `_classifyIntent()` - 意图分类方法
57
+ - ✅ `_parseStructuredTask()` - 任务结构化解析方法
58
+ - ✅ `_summarizeMessages()` - 智能摘要方法(使用结构化输出)
59
+ - ✅ `configureIntentClassification()` - 意图识别配置方法
60
+ - ✅ `getLastIntent()` - 获取上次意图识别结果
61
+ - ✅ `getCacheStatus()` - 缓存状态查询
62
+
63
+ **收益**:
64
+ - 输出类型安全,减少解析错误
65
+ - 支持智能意图路由
66
+ - 为任务分解提供结构化基础
67
+ - 可根据意图自动调整 `maxSteps`
68
+
69
+ ---
70
+
71
+ #### ✅ 2.2 Prompt Caching 集成 **[已完成]**
72
+
73
+ **现状**:使用 tiktoken 手动计算 token,未利用 AI SDK 原生缓存
74
+
75
+ **优化位置**:`src/core/agent-chat.js`
76
+
77
+ **已实现功能**:
78
+ - ✅ `_supportsPromptCache()` - 检测模型是否支持 Prompt Caching
79
+ - ✅ `_buildSystemPrompt()` - 构建可缓存的系统提示
80
+ - ✅ `_applyPromptCacheToMessages()` - 应用缓存标记到消息
81
+ - ✅ `_getSystemPrompt()` - 获取缓存的系统提示
82
+ - ✅ `configurePromptCache()` - Prompt Cache 配置方法
83
+ - ✅ `getCacheStatus()` - 缓存状态查询
84
+
85
+ **收益**:
86
+ - 降低 30-50% token 消耗
87
+ - 加快响应速度
88
+ - 减少 API 调用成本
89
+ - 支持模型自动检测
90
+
91
+ ---
92
+
93
+ ### 🟡 【中优先级】
94
+
95
+ #### 2.3 流式响应增强 - `smoothStream` / `streamObject`
96
+
97
+ **现状**:流式使用 `stream` 但未使用平滑输出
98
+
99
+ **优化位置**:`src/core/agent-chat.js`
100
+
101
+ **建议修改**:
102
+
103
+ ```javascript
104
+ // 2.3.1 平滑流式输出
105
+ async *chatStream(message, options = {}) {
106
+ // ...
107
+
108
+ const result = await framework.runWithContext(context, async () => {
109
+ return agent.stream({
110
+ messages,
111
+ ...this.providerOptions,
112
+ ...smoothStream({
113
+ delayInMs: 14 // 14ms 平滑间隔
114
+ })
115
+ })
116
+ })
117
+
118
+ // ...
119
+ }
120
+
121
+ // 2.3.2 结构化流式输出 - 新增方法
122
+ async *streamStructured(message, schema, options = {}) {
123
+ const { streamObject } = require('ai')
124
+
125
+ const { partialObjectStream } = await streamObject({
126
+ model: this._aiClient,
127
+ schema,
128
+ prompt: message,
129
+ ...smoothStream({ delayInMs: 14 })
130
+ })
131
+
132
+ for await (const partialObject of partialObjectStream) {
133
+ yield { type: 'partial', data: partialObject }
134
+ }
135
+ }
136
+ ```
137
+
138
+ **收益**:
139
+ - 更流畅的实时输出体验
140
+ - 支持部分对象流式渲染
141
+
142
+ ---
143
+
144
+ #### 2.4 推理模型支持 - o1/o3/R1
145
+
146
+ **现状**:未针对推理模型配置
147
+
148
+ **优化位置**:`src/core/provider.js` 和 `src/core/agent-chat.js`
149
+
150
+ **建议修改**:
151
+
152
+ ```javascript
153
+ // 2.4.1 provider.js - 新增推理模型配置
154
+ const REASONING_MODELS = {
155
+ 'o1-mini': { type: 'reasoning', supportsTools: false, maxTokens: 25000 },
156
+ 'o1-preview': { type: 'reasoning', supportsTools: false, maxTokens: 25000 },
157
+ 'o3-mini': { type: 'reasoning', supportsTools: false, maxTokens: 100000 },
158
+ 'deepseek-r1': { type: 'reasoning', supportsTools: true, maxTokens: 64000 },
159
+ 'deepseek-r1-distill-qwen-32b': { type: 'reasoning', supportsTools: true, maxTokens: 32000 }
160
+ }
161
+
162
+ // 2.4.2 agent-chat.js - 根据模型类型调整配置
163
+ _getAgentConfig() {
164
+ const modelId = this.model.toLowerCase()
165
+
166
+ // 检测是否是推理模型
167
+ const isReasoningModel = Object.keys(REASONING_MODELS)
168
+ .some(name => modelId.includes(name))
169
+
170
+ if (isReasoningModel) {
171
+ const config = REASONING_MODELS[Object.keys(REASONING_MODELS)
172
+ .find(name => modelId.includes(name))]
173
+
174
+ return {
175
+ // 推理模型通常不需要 system prompt
176
+ includeSystemInMessages: false,
177
+ // 推理模型不支持工具或需要特殊处理
178
+ supportsTools: config.supportsTools,
179
+ // 增大 maxTokens
180
+ maxTokens: config.maxTokens
181
+ }
182
+ }
183
+
184
+ return {
185
+ includeSystemInMessages: true,
186
+ supportsTools: true,
187
+ maxTokens: 8192
188
+ }
189
+ }
190
+ ```
191
+
192
+ **收益**:
193
+ - 支持 o1/o3/DeepSeek R1 等推理模型
194
+ - 自动适配推理模型的特殊配置
195
+ - 优化推理任务的性能
196
+
197
+ ---
198
+
199
+ #### 2.5 中间件系统
200
+
201
+ **现状**:缺乏统一的中间件机制
202
+
203
+ **优化位置**:新增 `src/middleware/ai-middleware.js`
204
+
205
+ **建议新增**:
206
+
207
+ ```javascript
208
+ // src/middleware/ai-middleware.js
209
+ const {
210
+ extractReasoningMiddleware,
211
+ defaultSettingsMiddleware,
212
+ withTelemetry
213
+ } = require('ai')
214
+
215
+ /**
216
+ * 创建 AI 中间件
217
+ */
218
+ function createAIMiddleware(options = {}) {
219
+ const middlewares = []
220
+
221
+ // 1. 推理提取中间件
222
+ if (options.extractReasoning !== false) {
223
+ middlewares.push(extractReasoningMiddleware({
224
+ tagName: 'thinking',
225
+ onChunk: (chunk) => {
226
+ options.onReasoning?.(chunk)
227
+ }
228
+ }))
229
+ }
230
+
231
+ // 2. 默认设置中间件
232
+ middlewares.push(defaultSettingsMiddleware({
233
+ settings: {
234
+ [options.defaultModel]: {
235
+ temperature: options.temperature || 0.7,
236
+ maxTokens: options.maxTokens || 8192
237
+ }
238
+ }
239
+ }))
240
+
241
+ // 3. 遥测中间件
242
+ if (options.telemetry) {
243
+ middlewares.push(withTelemetry({
244
+ serviceName: 'foliko-agent',
245
+ metadata: {
246
+ version: options.version,
247
+ sessionId: options.sessionId
248
+ }
249
+ }))
250
+ }
251
+
252
+ return middlewares
253
+ }
254
+
255
+ /**
256
+ * 创建日志中间件(自定义)
257
+ */
258
+ function createLoggingMiddleware() {
259
+ return {
260
+ async wrapModel(model, { doStream }) {
261
+ return {
262
+ doStream: async (prompt, options) => {
263
+ const startTime = Date.now()
264
+ console.log('[AI] Request started:', {
265
+ promptLength: typeof prompt === 'string' ? prompt.length : 'array'
266
+ })
267
+
268
+ try {
269
+ const result = await doStream()
270
+ const duration = Date.now() - startTime
271
+ console.log('[AI] Request completed:', { duration })
272
+ return result
273
+ } catch (error) {
274
+ console.error('[AI] Request failed:', error.message)
275
+ throw error
276
+ }
277
+ }
278
+ }
279
+ }
280
+ }
281
+ }
282
+
283
+ module.exports = {
284
+ createAIMiddleware,
285
+ createLoggingMiddleware
286
+ }
287
+ ```
288
+
289
+ **收益**:
290
+ - 统一的日志、监控、遥测
291
+ - 推理过程可追踪
292
+ - 支持自定义中间件扩展
293
+
294
+ ---
295
+
296
+ #### 2.6 Embeddings 支持
297
+
298
+ **现状**:未实现嵌入功能
299
+
300
+ **优化位置**:新增到 `src/plugins/ai-plugin.js` 或创建新文件
301
+
302
+ **建议新增**:
303
+
304
+ ```javascript
305
+ // src/plugins/embeddings-plugin.js 或在 ai-plugin.js 中新增
306
+ const { embed, embedMany } = require('ai')
307
+
308
+ class AIPlugin extends Plugin {
309
+ // ... 现有代码
310
+
311
+ /**
312
+ * 获取嵌入模型
313
+ */
314
+ getEmbeddingModel() {
315
+ if (this._embeddingModel) return this._embeddingModel
316
+
317
+ const embeddingModelId = this._getEmbeddingModelId()
318
+ this._embeddingModel = this._embeddingProvider.textEmbeddingModel(embeddingModelId)
319
+
320
+ return this._embeddingModel
321
+ }
322
+
323
+ _getEmbeddingModelId() {
324
+ const provider = this.config.provider?.toLowerCase()
325
+ const modelMap = {
326
+ 'openai': 'text-embedding-3-small',
327
+ 'deepseek': 'deepseek-embed',
328
+ 'ollama': 'nomic-embed-text'
329
+ }
330
+ return modelMap[provider] || 'text-embedding-3-small'
331
+ }
332
+
333
+ /**
334
+ * 嵌入单个文本
335
+ */
336
+ async embedText(text) {
337
+ const { embedding } = await embed({
338
+ model: this.getEmbeddingModel(),
339
+ value: text
340
+ })
341
+ return embedding
342
+ }
343
+
344
+ /**
345
+ * 批量嵌入
346
+ */
347
+ async embedTexts(texts) {
348
+ const { embeddings } = await embedMany({
349
+ model: this.getEmbeddingModel(),
350
+ values: texts
351
+ })
352
+ return embeddings
353
+ }
354
+ }
355
+ ```
356
+
357
+ **收益**:
358
+ - 支持 RAG 知识库构建
359
+ - 语义搜索基础
360
+ - 文本相似度计算
361
+
362
+ ---
363
+
364
+ ### 🟢 【低优先级】
365
+
366
+ #### 2.7 错误处理增强
367
+
368
+ **现状**:基础错误捕获
369
+
370
+ **优化位置**:`src/core/agent-chat.js`
371
+
372
+ **建议修改**:
373
+
374
+ ```javascript
375
+ // 2.7.1 新增错误类型导入
376
+ const {
377
+ AI_APICallError,
378
+ AI_RetryableError,
379
+ AI_NoSuchModelError,
380
+ AIInvalidPromptError
381
+ } = require('ai')
382
+
383
+ // 2.7.2 增强错误处理
384
+ async chat(message, options = {}) {
385
+ try {
386
+ // ... 现有代码
387
+ } catch (error) {
388
+ if (error instanceof AI_APICallError) {
389
+ switch (error.statusCode) {
390
+ case 400:
391
+ throw new Error(`无效请求: ${error.message}`)
392
+ case 401:
393
+ throw new Error('API 密钥无效或已过期')
394
+ case 429:
395
+ throw new Error('请求频率超限,请稍后重试')
396
+ case 500:
397
+ case 502:
398
+ case 503:
399
+ throw new Error(`AI 服务暂时不可用: ${error.message}`)
400
+ default:
401
+ throw error
402
+ }
403
+ } else if (error instanceof AI_NoSuchModelError) {
404
+ throw new Error(`模型 ${this.model} 不存在或不可用`)
405
+ } else if (error instanceof AIInvalidPromptError) {
406
+ throw new Error(`提示词无效: ${error.message}`)
407
+ }
408
+ throw error
409
+ }
410
+ }
411
+
412
+ // 2.7.3 重试装饰器
413
+ async withRetry(fn, maxRetries = 3, delayMs = 1000) {
414
+ for (let i = 0; i < maxRetries; i++) {
415
+ try {
416
+ return await fn()
417
+ } catch (error) {
418
+ if (i === maxRetries - 1) throw error
419
+ if (!this._isRetryable(error)) throw error
420
+
421
+ console.log(`[AgentChat] Retry ${i + 1}/${maxRetries} after ${delayMs}ms`)
422
+ await new Promise(r => setTimeout(r, delayMs))
423
+ delayMs *= 2 // 指数退避
424
+ }
425
+ }
426
+ }
427
+
428
+ _isRetryable(error) {
429
+ if (error instanceof AI_APICallError) {
430
+ return [429, 500, 502, 503].includes(error.statusCode)
431
+ }
432
+ return false
433
+ }
434
+ ```
435
+
436
+ **收益**:
437
+ - 更健壮的错误恢复
438
+ - 用户友好的错误提示
439
+ - 自动重试机制
440
+
441
+ ---
442
+
443
+ #### 2.8 MCP Elicitation 支持
444
+
445
+ **现状**:使用 MCP 但未支持用户确认
446
+
447
+ **优化位置**:`src/executors/mcp-executor.js`
448
+
449
+ **建议修改**:
450
+
451
+ ```javascript
452
+ // 2.8.1 新增 MCP Elicitation 支持
453
+ async connect() {
454
+ // ... 现有代码
455
+
456
+ // 启用 Elicitation(用户确认)
457
+ if (this.client && typeof this.client.requestConfirmation === 'function') {
458
+ this._enableElicitation = true
459
+ }
460
+ }
461
+
462
+ // 2.8.2 工具调用时请求确认
463
+ async executeToolWithConfirmation(toolName, args) {
464
+ if (!this._enableElicitation) {
465
+ return this.executeTool(toolName, args)
466
+ }
467
+
468
+ // 发送确认请求给用户
469
+ const confirmed = await this._requestUserConfirmation({
470
+ toolName,
471
+ args,
472
+ description: this._getToolDescription(toolName)
473
+ })
474
+
475
+ if (!confirmed) {
476
+ return { error: 'User rejected tool execution' }
477
+ }
478
+
479
+ return this.executeTool(toolName, args)
480
+ }
481
+ ```
482
+
483
+ **收益**:
484
+ - 用户可控制工具执行
485
+ - 提高安全性
486
+ - 支持敏感操作确认
487
+
488
+ ---
489
+
490
+ ## 三、优化优先级汇总
491
+
492
+ | 优先级 | 优化项 | 状态 | 收益 | 影响范围 |
493
+ |--------|--------|------|------|----------|
494
+ | 🔴 高 | `generateObject` 意图识别 | ✅ 已完成 | 类型安全、智能路由 | `agent-chat.js` |
495
+ | 🔴 高 | Prompt Caching | ✅ 已完成 | 降低30% token消耗 | `agent-chat.js` |
496
+ | 🟡 中 | `smoothStream` 流式增强 | 待做 | 更流畅体验 | `agent-chat.js` |
497
+ | 🟡 中 | 推理模型支持 | 待做 | o1/R1 优化 | `provider.js`, `agent-chat.js` |
498
+ | 🟡 中 | 中间件系统 | 待做 | 统一监控/日志 | 新建 `middleware/` |
499
+ | 🟡 中 | Embeddings | 待做 | RAG 基础 | `ai-plugin.js` |
500
+ | 🟢 低 | 错误处理增强 | 待做 | 更健壮 | `agent-chat.js` |
501
+ | 🟢 低 | MCP Elicitation | 待做 | 用户控制 | `mcp-executor.js` |
502
+
503
+ ---
504
+
505
+ ## 四、实施路线图
506
+
507
+ ### 第一阶段(立即可做)- ✅ 已完成
508
+
509
+ ```
510
+ ✅ generateObject 意图识别
511
+ └── 在 agent-chat.js 新增 _classifyIntent() 方法
512
+ └── 新增 IntentClassificationSchema, TaskStructuredSchema, SummarySchema
513
+ └── 新增 configureIntentClassification(), getLastIntent(), getCacheStatus()
514
+
515
+ ✅ Prompt Caching 集成
516
+ └── 在 _buildSystemPrompt() 中使用缓存机制
517
+ └── 新增 _supportsPromptCache(), _applyPromptCacheToMessages()
518
+ └── 新增 configurePromptCache() 配置方法
519
+ ```
520
+
521
+ ### 第二阶段(1周内)
522
+
523
+ ```
524
+ 📦 smoothStream 流式增强
525
+ └── 在 stream() 中添加 smoothStream 配置
526
+
527
+ 📦 推理模型支持
528
+ └── 在 provider.js 新增 REASONING_MODELS 配置
529
+
530
+ 📦 错误处理增强
531
+ └── 使用 AI SDK 错误类型替换基础 catch
532
+ ```
533
+
534
+ ### 第三阶段(长期)
535
+
536
+ ```
537
+ 📦 中间件系统
538
+ └── 新建 src/middleware/ai-middleware.js
539
+
540
+ 📦 Embeddings 支持
541
+ └── 在 ai-plugin.js 新增 embedText/embedTexts 方法
542
+
543
+ 📦 MCP Elicitation
544
+ └── 在 mcp-executor.js 新增用户确认机制
545
+ ```
546
+
547
+ ---
548
+
549
+ ## 五、新增配置选项
550
+
551
+ ### 意图识别配置
552
+
553
+ ```javascript
554
+ const agent = new AgentChatHandler(agent, {
555
+ // 意图识别(默认开启)
556
+ enableIntentClassification: true,
557
+ // 可选:用于意图识别的专用模型
558
+ intentModel: openai('gpt-4o-mini')
559
+ })
560
+
561
+ // 运行时配置
562
+ agent.configureIntentClassification({
563
+ enabled: true,
564
+ model: openai('gpt-4o-mini')
565
+ })
566
+
567
+ // 获取上次意图识别结果
568
+ const intent = agent.getLastIntent()
569
+ // { intent: 'create', confidence: 0.95, entities: [...], suggestedTools: [...] }
570
+ ```
571
+
572
+ ### Prompt Caching 配置
573
+
574
+ ```javascript
575
+ const agent = new AgentChatHandler(agent, {
576
+ // Prompt Caching(默认开启)
577
+ enablePromptCache: true,
578
+ // 缓存有效期(默认 1 小时)
579
+ cacheMaxAgeMs: 1000 * 60 * 60
580
+ })
581
+
582
+ // 运行时配置
583
+ agent.configurePromptCache({
584
+ enabled: true,
585
+ maxAgeMs: 1000 * 60 * 30 // 30 分钟
586
+ })
587
+
588
+ // 查看缓存状态
589
+ const status = agent.getCacheStatus()
590
+ // { promptCache: { enabled: true, supported: true, ... }, intentClassification: {...} }
591
+ ```
592
+
593
+ ### chat() / chatStream() 返回值变化
594
+
595
+ ```javascript
596
+ // chat() 返回值新增 intent 字段
597
+ const result = await agent.chat("帮我创建一个文件")
598
+ // { success: true, message: "...", stepCount: 3, intent: { intent: 'create', confidence: 0.9, ... } }
599
+
600
+ // chatStream() 支持接收 intent 事件
601
+ for await (const chunk of agent.chatStream("查询天气")) {
602
+ if (chunk.type === 'intent') {
603
+ console.log('意图:', chunk.intent) // { intent: 'query', confidence: 0.95, ... }
604
+ }
605
+ }
606
+
607
+ // 监听意图识别事件
608
+ agent.on('intent-classified', ({ message, intent }) => {
609
+ console.log(`消息 "${message}" 被识别为: ${intent.intent}`)
610
+ })
611
+
612
+ agent.on('intent-detected', ({ message, intent }) => {
613
+ console.log(`流式模式检测到意图: ${intent.intent}`)
614
+ })
615
+ ```
616
+
617
+ ---
618
+
619
+ ## 六、需要安装的包
620
+
621
+ ```bash
622
+ # 基础已安装
623
+ npm install ai @ai-sdk/openai @ai-sdk/anthropic
624
+
625
+ # 可能需要添加(根据需求)
626
+ npm install @ai-sdk/google # Gemini 模型支持
627
+ npm install @ai-sdk/deepseek # DeepSeek 模型支持
628
+ npm install @ai-sdk/amazon-bedrock # AWS Bedrock 支持
629
+ ```
630
+
631
+ ---
632
+
633
+ ## 七、参考资料
634
+
635
+ - [AI SDK 官方文档](https://ai-sdk.dev/docs/getting-started)
636
+ - [AI SDK Cookbook](https://ai-sdk.dev/cookbook)
637
+ - [AI SDK API Reference](https://ai-sdk.dev/docs/api-reference)
638
+
639
+ ---
640
+
641
+ *文档生成时间:2025-01-25*
642
+ *基于 AI SDK v6 版本分析*
643
+ *高优先级优化完成时间:2025-01-26*
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foliko",
3
- "version": "1.0.72",
3
+ "version": "1.0.74",
4
4
  "description": "简约的插件化 Agent 框架",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -85,17 +85,16 @@ class FileSystemPlugin extends Plugin {
85
85
  // 读取文件
86
86
  framework.registerTool({
87
87
  name: 'read_file',
88
- description: '读取文件内容',
88
+ description: '读取文件内容。path 是必填参数。',
89
89
  inputSchema: z.object({
90
- path: z.string().optional().describe('文件路径'),
91
- filePath: z.string().optional().describe('文件路径(同path)'),
92
- encoding: z.enum(['utf8', 'base64', 'binary']).optional().describe('文件编码,默认 utf8'),
90
+ path: z.string().describe('文件路径(必须)'),
93
91
  lines: z.number().optional().describe('只读取前 N 行')
94
92
  }),
95
93
  execute: async (args, framework) => {
96
- const filePath = args.path || args.filePath
97
- const encoding = args.encoding || 'utf8'
98
- const lines = args.lines
94
+ const { path: filePath, lines } = args
95
+ if (!filePath) {
96
+ return { success: false, error: 'path 是必填参数' }
97
+ }
99
98
  try {
100
99
  if (!fs.existsSync(filePath)) {
101
100
  return { success: false, error: '文件不存在' }
@@ -110,7 +109,7 @@ class FileSystemPlugin extends Plugin {
110
109
  const allLines = fileContent.split('\n')
111
110
  content = allLines.slice(0, lines).join('\n')
112
111
  } else {
113
- content = fs.readFileSync(filePath, encoding)
112
+ content = fs.readFileSync(filePath, 'utf8')
114
113
  }
115
114
  return {
116
115
  success: true,
@@ -128,22 +127,22 @@ class FileSystemPlugin extends Plugin {
128
127
  // 写入文件
129
128
  framework.registerTool({
130
129
  name: 'write_file',
131
- description: '创建或写入文件内容',
130
+ description: '创建或写入文件内容。content 是要写入的文本内容。',
132
131
  inputSchema: z.object({
133
- path: z.string().optional().describe('文件路径'),
134
- filePath: z.string().optional().describe('文件路径(同path)'),
135
- content: z.string().describe('文件内容')
132
+ path: z.string().describe('文件路径(必须)'),
133
+ content: z.string().describe('文件内容(必须)')
136
134
  }),
137
135
  execute: async (args, framework) => {
138
- const filePath = args.path || args.filePath
139
- const content = args.content
140
- const encoding = args.encoding || 'utf8'
136
+ const { path: filePath, content } = args
137
+ if (!filePath || !content) {
138
+ return { success: false, error: 'path 和 content 都是必填参数' }
139
+ }
141
140
  try {
142
141
  const dir = path.dirname(filePath)
143
142
  if (!fs.existsSync(dir)) {
144
143
  fs.mkdirSync(dir, { recursive: true })
145
144
  }
146
- fs.writeFileSync(filePath, content, encoding)
145
+ fs.writeFileSync(filePath, content, 'utf8')
147
146
  return { success: true, message: `文件已写入: ${filePath}`, filePath, size: content.length }
148
147
  } catch (error) {
149
148
  return { success: false, error: error.message }
@@ -44,7 +44,7 @@ class AgentChatHandler extends EventEmitter {
44
44
  this._systemPrompt = config.systemPrompt || 'You are a helpful assistant.'
45
45
  this._messages = []
46
46
  this._tools = new Map()
47
- this._maxSteps = 10
47
+ this._maxSteps = 5 // 降低默认步骤数,减少上下文消耗
48
48
 
49
49
  // 上下文压缩配置:根据模型自动设置限制
50
50
  const modelKey = Object.keys(MODEL_CONTEXT_LIMITS).find(k =>
@@ -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(args, this.agent.framework)
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
package/src/core/agent.js CHANGED
@@ -29,7 +29,8 @@ class Agent extends EventEmitter {
29
29
  this.baseURL = config.baseURL
30
30
  this.provider = config.provider || 'deepseek'
31
31
  this.providerOptions = config.providerOptions || {}
32
- this.providerOptions.maxOutputTokens=8192
32
+ this.providerOptions.maxOutputTokens = 8192
33
+ this.providerOptions.temperature = 0.3 // 降低 temperature 减少生成错误 JSON 的概率
33
34
  // 原始 system prompt
34
35
  this._originalPrompt = config.systemPrompt || '你是一个智能助手。当用户提出问题或任务时,你会主动分析需求,选择合适的工具来获取信息或执行操作。你善于将复杂任务拆解为多个步骤,通过工具协作完成。'
35
36
 
@@ -30,6 +30,10 @@ const DEFAULT_PROVIDERS = {
30
30
  anthropic: {
31
31
  name: 'Anthropic',
32
32
  baseURL: 'https://api.anthropic.com/v1'
33
+ },
34
+ minimax: {
35
+ name: 'MiniMax',
36
+ baseURL: 'https://api.minimaxi.com/v1'
33
37
  }
34
38
  }
35
39