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