@nickyzj2023/ai 1.6.4 → 1.7.0
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/README.md +21 -8
- package/dist/cli.mjs +36 -15
- package/dist/index.d.mts +16 -4
- package/dist/index.mjs +2 -2
- package/dist/{mcp-BBjcb8es.mjs → mcp-C22GzADk.mjs} +37 -8
- package/dist/{src-BtaIXKLo.mjs → src-C1ARVH43.mjs} +120 -46
- package/dist/tools/mcp.d.mts +9 -2
- package/dist/tools/mcp.mjs +2 -2
- package/dist/{types--dXFoUow.d.mts → types-Bwc1Oqk3.d.mts} +57 -12
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -31,7 +31,7 @@ import { loadMCPTools } from "@nickyzj2023/ai/mcp";
|
|
|
31
31
|
const model = defineModel({
|
|
32
32
|
baseUrl: "https://api.deepseek.com/v1",
|
|
33
33
|
apiKey: process.env.APIKEY,
|
|
34
|
-
model: "deepseek-
|
|
34
|
+
model: "deepseek-flash",
|
|
35
35
|
});
|
|
36
36
|
|
|
37
37
|
const tools = [
|
|
@@ -49,18 +49,31 @@ const tools = [
|
|
|
49
49
|
}
|
|
50
50
|
})),
|
|
51
51
|
// 自定义工具
|
|
52
|
-
defineTool("
|
|
53
|
-
const error = new Error(`模型保持沉默,理由:${reason}`);
|
|
54
|
-
error.name = "skipReply";
|
|
55
|
-
throw error;
|
|
56
|
-
}),
|
|
52
|
+
defineTool("square", "把一个数字平方", { num: {type: "number", description: "一个数字"} }, ({ num }) => num ** 2),
|
|
57
53
|
];
|
|
58
54
|
|
|
59
|
-
const messages = [{ role: "user", content: "
|
|
55
|
+
const messages = [{ role: "user", content: "查询上海天气" }];
|
|
60
56
|
|
|
61
|
-
|
|
57
|
+
// Agent层的用法(推荐)
|
|
58
|
+
// 流式传输,思考/回复内容会逐token输出,工具调用会收集完模型的调用请求后一次性执行完
|
|
59
|
+
for await (const e of runAgent(model, messages, { tools, stream: true })) {
|
|
62
60
|
console.log(e);
|
|
63
61
|
}
|
|
62
|
+
// 默认的非流式,result事件包含了最终的reasoning/content/usage等信息
|
|
63
|
+
for await (const e of runAgent(model, messages, { tools })) {
|
|
64
|
+
if (e.type === "result") console.log(e.content);
|
|
65
|
+
else if (e.type === "error") console.log(e.message);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// LLM层的用法(Agent用的就是它们,stream/nonStream函数只对模型的响应事件做了转发)
|
|
69
|
+
// 流式传输,和runAgent + stream:true没啥区别
|
|
70
|
+
for await (const e of stream(model, messages, tools)) {
|
|
71
|
+
console.log(e);
|
|
72
|
+
}
|
|
73
|
+
// 非流式,直接拿到最终结果
|
|
74
|
+
const result = await nonStream(model, messages, tools);
|
|
75
|
+
console.log(result.content, result.usage);
|
|
76
|
+
|
|
64
77
|
```
|
|
65
78
|
|
|
66
79
|
### 在终端里使用
|
package/dist/cli.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { i as runAgent, n as get_weather_default, r as get_time_default } from "./src-
|
|
1
|
+
import { a as humanizeNumber, i as runAgent, n as get_weather_default, r as get_time_default } from "./src-C1ARVH43.mjs";
|
|
2
2
|
import { a as listModels, t as defineModel } from "./helper-DJw58Gmz.mjs";
|
|
3
|
-
import { n as loadMCPTools } from "./mcp-
|
|
3
|
+
import { n as listMcpToolNames, r as loadMCPTools } from "./mcp-C22GzADk.mjs";
|
|
4
4
|
import { compactStr, extractErrorMessage, isObject, to } from "@nickyzj2023/utils";
|
|
5
5
|
import readline from "node:readline";
|
|
6
6
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
@@ -99,8 +99,16 @@ const askMcpServer = async (current) => {
|
|
|
99
99
|
console.log("headers解析失败,已回退到原先的值");
|
|
100
100
|
}
|
|
101
101
|
let ignoredToolNames = current?.ignoredToolNames;
|
|
102
|
-
const
|
|
103
|
-
if (
|
|
102
|
+
const [error, toolNames = []] = await to(listMcpToolNames(url, headers ? { headers } : void 0));
|
|
103
|
+
if (error) console.log(`获取工具列表失败:${extractErrorMessage(error)}`);
|
|
104
|
+
else {
|
|
105
|
+
console.log("该服务器提供的工具:");
|
|
106
|
+
toolNames.forEach((toolName, i) => {
|
|
107
|
+
console.log(`${i + 1}. ${toolName}`);
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
const ignoredInput = (await ask(`忽略的工具(名称或序号,用逗号分隔,也支持1-5这样的连续序号) [当前为${current?.ignoredToolNames?.join(",") ?? "无"}]: `)).trim();
|
|
111
|
+
if (ignoredInput) ignoredToolNames = parseIgnoredToolNames(ignoredInput, toolNames);
|
|
104
112
|
return {
|
|
105
113
|
name,
|
|
106
114
|
type,
|
|
@@ -120,6 +128,23 @@ const pickByIndex = (input, names) => {
|
|
|
120
128
|
return Number.isInteger(index) ? names[index] : void 0;
|
|
121
129
|
};
|
|
122
130
|
/**
|
|
131
|
+
* 解析“忽略的工具”输入:名称、单个序号、序号段(如1-5,9-12),均可逗号混用
|
|
132
|
+
* @param input 用户输入
|
|
133
|
+
* @param toolNames 该服务器的工具名列表,序号按列表顺序(从1开始)换算
|
|
134
|
+
* @returns 去重后的工具名;越界序号以及无意义的重复会被丢弃
|
|
135
|
+
*/
|
|
136
|
+
const parseIgnoredToolNames = (input, toolNames) => {
|
|
137
|
+
const picked = input.split(",").map((item) => item.trim()).filter(Boolean).flatMap((item) => {
|
|
138
|
+
const range = /^(\d+)\s*-\s*(\d+)$/.exec(item);
|
|
139
|
+
if (!range) return /^\d+$/.test(item) ? [toolNames[Number(item) - 1]] : [item];
|
|
140
|
+
const start = Number(range[1]);
|
|
141
|
+
const end = Number(range[2]);
|
|
142
|
+
if (start > end) return [];
|
|
143
|
+
return Array.from({ length: end - start + 1 }, (_, i) => toolNames[start + i - 1]);
|
|
144
|
+
}).filter((name) => Boolean(name));
|
|
145
|
+
return [...new Set(picked)];
|
|
146
|
+
};
|
|
147
|
+
/**
|
|
123
148
|
* MCP配置菜单:列出现有服务器,数字键编辑、a键添加、d键删除、回车或q结束
|
|
124
149
|
*/
|
|
125
150
|
const configMcp = async (mcpServers) => {
|
|
@@ -299,16 +324,6 @@ const readClipboardImage = async () => {
|
|
|
299
324
|
}
|
|
300
325
|
};
|
|
301
326
|
//#endregion
|
|
302
|
-
//#region src/utils/internalHelper.ts
|
|
303
|
-
const formatter = new Intl.NumberFormat("en-US", {
|
|
304
|
-
notation: "compact",
|
|
305
|
-
maximumFractionDigits: 1
|
|
306
|
-
});
|
|
307
|
-
/** 把数字转换成千分位 */
|
|
308
|
-
const humanizeNumber = (number) => {
|
|
309
|
-
return formatter.format(number);
|
|
310
|
-
};
|
|
311
|
-
//#endregion
|
|
312
327
|
//#region src/interfaces/tui.ts
|
|
313
328
|
var TUI = class {
|
|
314
329
|
rl = null;
|
|
@@ -449,6 +464,9 @@ var TUI = class {
|
|
|
449
464
|
case "tool_call":
|
|
450
465
|
this.printToolCall(event.name, event.args);
|
|
451
466
|
break;
|
|
467
|
+
case "result":
|
|
468
|
+
this.printContent(event.content);
|
|
469
|
+
break;
|
|
452
470
|
case "tool_result":
|
|
453
471
|
this.printToolResult(event.name, event.result);
|
|
454
472
|
break;
|
|
@@ -543,7 +561,10 @@ const startChat = async (prompt) => {
|
|
|
543
561
|
get_time_default,
|
|
544
562
|
...await mcpLoading
|
|
545
563
|
];
|
|
546
|
-
for await (const e of runAgent(model, messages,
|
|
564
|
+
for await (const e of runAgent(model, messages, {
|
|
565
|
+
tools,
|
|
566
|
+
stream: true
|
|
567
|
+
})) tui.render(e);
|
|
547
568
|
});
|
|
548
569
|
tui.start(prompt);
|
|
549
570
|
};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { _ as ToolDefinition, a as ContentPart, c as Message, d as NonStreamEvent, f as NonStreamResult, g as ToolCall, h as TextContent, i as ChatCompletionsResponse, l as Modality, m as StreamEvent, n as AudioContent, o as FinishReason, p as RunAgentOptions, r as ChatCompletionsChunk, s as ImageContent, t as AgentEvent, u as Model, v as Usage, y as VideoContent } from "./types-Bwc1Oqk3.mjs";
|
|
2
2
|
//#region src/agent.d.ts
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Agent循环
|
|
5
|
+
* @param options.stream 是否流式输出,默认false(每轮推送一个result事件)
|
|
6
|
+
*/
|
|
7
|
+
declare function runAgent(model: Model, messages: Message[], options?: RunAgentOptions): AsyncGenerator<AgentEvent>;
|
|
4
8
|
//#endregion
|
|
5
9
|
//#region src/llm.d.ts
|
|
6
10
|
/**
|
|
@@ -8,7 +12,15 @@ declare function runAgent(model: Model, messages: Message[], tools: ToolDefiniti
|
|
|
8
12
|
*/
|
|
9
13
|
declare function stream(model: Model, messages: Message[], tools?: ToolDefinition[], options?: Omit<RequestInit, "body"> & {
|
|
10
14
|
body?: Record<string, unknown>;
|
|
11
|
-
}): AsyncGenerator<
|
|
15
|
+
}): AsyncGenerator<StreamEvent>;
|
|
16
|
+
/**
|
|
17
|
+
* 非流式请求模型,一次性拿到完整回复
|
|
18
|
+
* @remarks 与stream()共享同一套请求/解析规则,区别在于不做SSE解析
|
|
19
|
+
* @throws 请求失败(含状态码非2xx)、取消(signal.abort)时抛出异常
|
|
20
|
+
*/
|
|
21
|
+
declare function nonStream(model: Model, messages: Message[], tools?: ToolDefinition[], options?: Omit<RequestInit, "body"> & {
|
|
22
|
+
body?: Record<string, unknown>;
|
|
23
|
+
}): Promise<NonStreamResult>;
|
|
12
24
|
//#endregion
|
|
13
25
|
//#region src/tools/get-time.d.ts
|
|
14
26
|
declare const _default: ToolDefinition;
|
|
@@ -153,4 +165,4 @@ declare const listModels: (baseUrl: string, apiKey?: string) => Promise<string[]
|
|
|
153
165
|
*/
|
|
154
166
|
declare const estimateTokens: (messages?: Message[]) => number;
|
|
155
167
|
//#endregion
|
|
156
|
-
export { type AgentEvent, type AudioContent, type ChatCompletionsChunk, type
|
|
168
|
+
export { type AgentEvent, type AudioContent, type ChatCompletionsChunk, type ChatCompletionsResponse, type ContentPart, type FinishReason, type ImageContent, type Message, type Modality, type Model, type NonStreamEvent, type NonStreamResult, type RunAgentOptions, type StreamEvent, type TextContent, type ToolCall, type ToolDefinition, type Usage, type VideoContent, compact, defineModel, defineTool, estimateTextTokens, estimateTokens, _default as getTime, _default$1 as getWeather, listModels, nonStream, runAgent, stream };
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as runAgent, n as get_weather_default, o as nonStream, r as get_time_default, s as stream, t as compact } from "./src-C1ARVH43.mjs";
|
|
2
2
|
import { a as listModels, i as estimateTokens, n as defineTool, r as estimateTextTokens, t as defineModel } from "./helper-DJw58Gmz.mjs";
|
|
3
|
-
export { compact, defineModel, defineTool, estimateTextTokens, estimateTokens, get_time_default as getTime, get_weather_default as getWeather, listModels, runAgent, stream };
|
|
3
|
+
export { compact, defineModel, defineTool, estimateTextTokens, estimateTokens, get_time_default as getTime, get_weather_default as getWeather, listModels, nonStream, runAgent, stream };
|
|
@@ -3,18 +3,47 @@ import { extractErrorMessage, isObject, logger, omit } from "@nickyzj2023/utils"
|
|
|
3
3
|
//#region src/tools/mcp.ts
|
|
4
4
|
/** 全局单例MCP加载器 */
|
|
5
5
|
let router = null;
|
|
6
|
+
/**
|
|
7
|
+
* 懒加载SDK并建立到指定URL的连接,setup探测和正式加载共用
|
|
8
|
+
* @param name 客户端名称
|
|
9
|
+
* @param url MCP服务器地址
|
|
10
|
+
* @param options headers与可选的超时信号
|
|
11
|
+
* @returns 已连接的客户端
|
|
12
|
+
*/
|
|
13
|
+
const connectClient = async (name, url, options) => {
|
|
14
|
+
const [{ Client }, { StreamableHTTPClientTransport }] = await Promise.all([import("@modelcontextprotocol/sdk/client"), import("@modelcontextprotocol/sdk/client/streamableHttp.js")]);
|
|
15
|
+
const transport = new StreamableHTTPClientTransport(new URL(url), { requestInit: {
|
|
16
|
+
headers: options?.headers,
|
|
17
|
+
signal: options?.signal
|
|
18
|
+
} });
|
|
19
|
+
const client = new Client({
|
|
20
|
+
name,
|
|
21
|
+
version: "1.0.0"
|
|
22
|
+
});
|
|
23
|
+
await client.connect(transport);
|
|
24
|
+
return client;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* 连上MCP服务器拉一次工具名后立刻断开,不注册到router
|
|
28
|
+
* @param url MCP服务器地址
|
|
29
|
+
* @param options headers等配置
|
|
30
|
+
* @returns 该服务器提供的全部工具名
|
|
31
|
+
*/
|
|
32
|
+
const listMcpToolNames = async (url, options) => {
|
|
33
|
+
const client = await connectClient("ai-setup", url, options);
|
|
34
|
+
try {
|
|
35
|
+
const { tools } = await client.listTools();
|
|
36
|
+
return tools.map((tool) => tool.name);
|
|
37
|
+
} finally {
|
|
38
|
+
await client.close().catch(() => {});
|
|
39
|
+
}
|
|
40
|
+
};
|
|
6
41
|
var MCPRouter = class {
|
|
7
42
|
entries = /* @__PURE__ */ new Map();
|
|
8
43
|
/** 注册一个新的MCP客户端 */
|
|
9
44
|
async addClient(name, url, options) {
|
|
10
45
|
if (this.entries.has(name)) return;
|
|
11
|
-
const
|
|
12
|
-
const transport = new StreamableHTTPClientTransport(new URL(url), { requestInit: { headers: options?.headers } });
|
|
13
|
-
const client = new Client({
|
|
14
|
-
name,
|
|
15
|
-
version: "1.0.0"
|
|
16
|
-
});
|
|
17
|
-
await client.connect(transport);
|
|
46
|
+
const client = await connectClient(name, url, options);
|
|
18
47
|
const { tools } = await client.listTools();
|
|
19
48
|
const normalizedTools = tools.filter((tool) => !options?.ignoredToolNames?.includes(tool.name)).map((tool) => {
|
|
20
49
|
const _properties = { ...tool.inputSchema.properties ?? {} };
|
|
@@ -55,4 +84,4 @@ const loadMCPTools = async (mcpServers = {}) => {
|
|
|
55
84
|
return router.getTools();
|
|
56
85
|
};
|
|
57
86
|
//#endregion
|
|
58
|
-
export {
|
|
87
|
+
export { listMcpToolNames as n, loadMCPTools as r, MCPRouter as t };
|
|
@@ -100,55 +100,128 @@ async function* stream(model, messages, tools = [], options) {
|
|
|
100
100
|
usage
|
|
101
101
|
};
|
|
102
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* 非流式请求模型,一次性拿到完整回复
|
|
105
|
+
* @remarks 与stream()共享同一套请求/解析规则,区别在于不做SSE解析
|
|
106
|
+
* @throws 请求失败(含状态码非2xx)、取消(signal.abort)时抛出异常
|
|
107
|
+
*/
|
|
108
|
+
async function nonStream(model, messages, tools = [], options) {
|
|
109
|
+
const validTools = tools.map((tool) => detachToolArguments(tool)[0]);
|
|
110
|
+
const response = await fetcher(model.baseUrl, { headers: { Authorization: `Bearer ${model.apiKey}` } }).post("/chat/completions", {
|
|
111
|
+
stream: false,
|
|
112
|
+
model: model.model,
|
|
113
|
+
messages,
|
|
114
|
+
tools: validTools,
|
|
115
|
+
...options?.body
|
|
116
|
+
}, options);
|
|
117
|
+
const choice = response.choices?.[0];
|
|
118
|
+
const message = choice?.message;
|
|
119
|
+
return {
|
|
120
|
+
reasoning: message ? extractReasoning(message) : void 0,
|
|
121
|
+
content: typeof message?.content === "string" ? message.content : (message?.content ?? []).filter((part) => part.type === "text").map((part) => part.text).join(""),
|
|
122
|
+
toolCalls: message?.tool_calls ?? [],
|
|
123
|
+
finishReason: choice?.finish_reason ?? null,
|
|
124
|
+
usage: response.usage
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
//#endregion
|
|
128
|
+
//#region src/utils/internalHelper.ts
|
|
129
|
+
const formatter = new Intl.NumberFormat("en-US", {
|
|
130
|
+
notation: "compact",
|
|
131
|
+
maximumFractionDigits: 1
|
|
132
|
+
});
|
|
133
|
+
/** 把数字转换成千分位 */
|
|
134
|
+
const humanizeNumber = (number) => {
|
|
135
|
+
return formatter.format(number);
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* 模型未返回用量时,本地估算一个
|
|
139
|
+
* @param messages 当前上下文(调用模型前,即还未推入assistant回复)
|
|
140
|
+
*/
|
|
141
|
+
const estimateFallbackUsage = (messages, content, reasoning) => {
|
|
142
|
+
const promptTokens = estimateTokens(messages.slice(-1));
|
|
143
|
+
const completionTokens = estimateTextTokens(content + reasoning);
|
|
144
|
+
return {
|
|
145
|
+
prompt_tokens: promptTokens,
|
|
146
|
+
completion_tokens: completionTokens,
|
|
147
|
+
total_tokens: estimateTokens(messages) + promptTokens + completionTokens
|
|
148
|
+
};
|
|
149
|
+
};
|
|
150
|
+
/** 按本轮耗时计算生成速度(tokens/s),直接修改并返回usage */
|
|
151
|
+
const withSpeed = (usage, startTime) => {
|
|
152
|
+
usage.speed = Math.floor(usage.completion_tokens / ((Date.now() - startTime) / 1e3));
|
|
153
|
+
return usage;
|
|
154
|
+
};
|
|
103
155
|
//#endregion
|
|
104
156
|
//#region src/agent.ts
|
|
105
|
-
|
|
157
|
+
/**
|
|
158
|
+
* Agent循环
|
|
159
|
+
* @param options.stream 是否流式输出,默认false(每轮推送一个result事件)
|
|
160
|
+
*/
|
|
161
|
+
async function* runAgent(model, messages, options) {
|
|
162
|
+
const { tools = [], stream: enableStream = false } = options ?? {};
|
|
106
163
|
const toolMap = new Map(tools.map((tool) => [tool.function.name, tool]));
|
|
107
164
|
while (true) {
|
|
108
|
-
let content = "";
|
|
109
165
|
let reasoning = "";
|
|
166
|
+
let content = "";
|
|
110
167
|
const toolCalls = [];
|
|
111
|
-
|
|
112
|
-
let
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
arguments: e.args
|
|
132
|
-
}
|
|
133
|
-
});
|
|
134
|
-
break;
|
|
135
|
-
case "error":
|
|
136
|
-
yield e;
|
|
137
|
-
break;
|
|
138
|
-
case "done":
|
|
139
|
-
if (!e.usage) {
|
|
140
|
-
const promptTokens = estimateTokens(promptMessage);
|
|
141
|
-
const completionTokens = estimateTextTokens(content + reasoning);
|
|
142
|
-
e.usage = {
|
|
143
|
-
prompt_tokens: promptTokens,
|
|
144
|
-
completion_tokens: completionTokens,
|
|
145
|
-
total_tokens: estimateTokens(messages) + promptTokens + completionTokens
|
|
146
|
-
};
|
|
168
|
+
let finishReason = null;
|
|
169
|
+
let usage;
|
|
170
|
+
const startTime = Date.now();
|
|
171
|
+
if (enableStream) for await (const e of stream(model, messages, tools)) switch (e.type) {
|
|
172
|
+
case "reasoning_delta":
|
|
173
|
+
yield e;
|
|
174
|
+
reasoning += e.delta;
|
|
175
|
+
break;
|
|
176
|
+
case "content_delta":
|
|
177
|
+
yield e;
|
|
178
|
+
content += e.delta;
|
|
179
|
+
break;
|
|
180
|
+
case "tool_call":
|
|
181
|
+
yield e;
|
|
182
|
+
toolCalls.push({
|
|
183
|
+
id: e.id,
|
|
184
|
+
type: "function",
|
|
185
|
+
function: {
|
|
186
|
+
name: e.name,
|
|
187
|
+
arguments: e.args
|
|
147
188
|
}
|
|
148
|
-
|
|
149
|
-
|
|
189
|
+
});
|
|
190
|
+
break;
|
|
191
|
+
case "error":
|
|
192
|
+
yield e;
|
|
193
|
+
return;
|
|
194
|
+
case "done":
|
|
195
|
+
finishReason = e.finishReason;
|
|
196
|
+
usage = e.usage;
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
const [error, result] = await to(nonStream(model, messages, tools));
|
|
200
|
+
if (error) {
|
|
201
|
+
yield {
|
|
202
|
+
type: "error",
|
|
203
|
+
message: error.message
|
|
204
|
+
};
|
|
205
|
+
return;
|
|
150
206
|
}
|
|
207
|
+
reasoning = result.reasoning ?? "";
|
|
208
|
+
content = result.content;
|
|
209
|
+
toolCalls.push(...result.toolCalls);
|
|
210
|
+
finishReason = result.finishReason;
|
|
211
|
+
usage = result.usage;
|
|
151
212
|
}
|
|
213
|
+
usage = withSpeed(usage ?? estimateFallbackUsage(messages, content, reasoning), startTime);
|
|
214
|
+
yield enableStream ? {
|
|
215
|
+
type: "done",
|
|
216
|
+
finishReason,
|
|
217
|
+
usage
|
|
218
|
+
} : {
|
|
219
|
+
type: "result",
|
|
220
|
+
content,
|
|
221
|
+
reasoning,
|
|
222
|
+
finishReason,
|
|
223
|
+
usage
|
|
224
|
+
};
|
|
152
225
|
const message = {
|
|
153
226
|
role: "assistant",
|
|
154
227
|
content
|
|
@@ -295,7 +368,7 @@ const defaultReplacerOfToolResultContent = async (content, options) => {
|
|
|
295
368
|
}];
|
|
296
369
|
let simplifiedContent = "";
|
|
297
370
|
if (!model) simplifiedContent = "工具结果已被消费";
|
|
298
|
-
else for await (const e of runAgent(model, messages
|
|
371
|
+
else for await (const e of runAgent(model, messages)) if (e.type === "result") simplifiedContent = e.content;
|
|
299
372
|
else if (e.type === "error") throw new Error(e.message);
|
|
300
373
|
return simplifiedContent;
|
|
301
374
|
};
|
|
@@ -327,7 +400,7 @@ const defaultReplacerOfMediaContent = async (content, options) => {
|
|
|
327
400
|
}];
|
|
328
401
|
let simplifiedContent = "";
|
|
329
402
|
if (!model?.modalities?.includes(modality)) simplifiedContent = "媒体资源已被消费";
|
|
330
|
-
else for await (const e of runAgent(model, messages
|
|
403
|
+
else for await (const e of runAgent(model, messages)) if (e.type === "result") simplifiedContent = e.content;
|
|
331
404
|
else if (e.type === "error") throw new Error(e.message);
|
|
332
405
|
return simplifiedContent;
|
|
333
406
|
};
|
|
@@ -371,9 +444,10 @@ const summarizeMessages = async (compressible, options) => {
|
|
|
371
444
|
});
|
|
372
445
|
let summarized = "";
|
|
373
446
|
let usage;
|
|
374
|
-
for await (const e of runAgent(model, summarizable
|
|
375
|
-
|
|
376
|
-
|
|
447
|
+
for await (const e of runAgent(model, summarizable)) if (e.type === "result") {
|
|
448
|
+
summarized = e.content;
|
|
449
|
+
usage = e.usage;
|
|
450
|
+
} else if (e.type === "error") throw new Error(e.message);
|
|
377
451
|
compressible.splice(1, Infinity, {
|
|
378
452
|
role: "user",
|
|
379
453
|
content: createXMLText("summary", summarized)
|
|
@@ -458,4 +532,4 @@ const compact = Object.assign(async (messages, model, options) => {
|
|
|
458
532
|
discardMessagesUntil
|
|
459
533
|
});
|
|
460
534
|
//#endregion
|
|
461
|
-
export {
|
|
535
|
+
export { humanizeNumber as a, runAgent as i, get_weather_default as n, nonStream as o, get_time_default as r, stream as s, compact as t };
|
package/dist/tools/mcp.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _ as ToolDefinition } from "../types-Bwc1Oqk3.mjs";
|
|
2
2
|
import { Client } from "@modelcontextprotocol/sdk/client";
|
|
3
3
|
//#region src/tools/mcp.d.ts
|
|
4
4
|
type McpServer = {
|
|
@@ -7,6 +7,13 @@ type McpServer = {
|
|
|
7
7
|
headers?: Record<string, any>;
|
|
8
8
|
ignoredToolNames?: string[];
|
|
9
9
|
};
|
|
10
|
+
/**
|
|
11
|
+
* 连上MCP服务器拉一次工具名后立刻断开,不注册到router
|
|
12
|
+
* @param url MCP服务器地址
|
|
13
|
+
* @param options headers等配置
|
|
14
|
+
* @returns 该服务器提供的全部工具名
|
|
15
|
+
*/
|
|
16
|
+
declare const listMcpToolNames: (url: string, options?: Omit<McpServer, "type" | "url">) => Promise<string[]>;
|
|
10
17
|
declare class MCPRouter {
|
|
11
18
|
private entries;
|
|
12
19
|
/** 注册一个新的MCP客户端 */
|
|
@@ -52,4 +59,4 @@ declare class MCPRouter {
|
|
|
52
59
|
*/
|
|
53
60
|
declare const loadMCPTools: (mcpServers?: Record<string, McpServer>) => Promise<ToolDefinition[]>;
|
|
54
61
|
//#endregion
|
|
55
|
-
export { MCPRouter, McpServer, loadMCPTools };
|
|
62
|
+
export { MCPRouter, McpServer, listMcpToolNames, loadMCPTools };
|
package/dist/tools/mcp.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as loadMCPTools, t as MCPRouter } from "../mcp-
|
|
2
|
-
export { MCPRouter, loadMCPTools };
|
|
1
|
+
import { n as listMcpToolNames, r as loadMCPTools, t as MCPRouter } from "../mcp-C22GzADk.mjs";
|
|
2
|
+
export { MCPRouter, listMcpToolNames, loadMCPTools };
|
|
@@ -87,8 +87,18 @@ type ToolCall = {
|
|
|
87
87
|
arguments: string;
|
|
88
88
|
};
|
|
89
89
|
};
|
|
90
|
+
/** 模型可能返回的finish_reason值:停止/工具调用/上下文超限 */
|
|
91
|
+
type FinishReason = "stop" | "tool_calls" | "length" | null;
|
|
92
|
+
type Usage = {
|
|
93
|
+
prompt_tokens: number;
|
|
94
|
+
completion_tokens: number;
|
|
95
|
+
total_tokens: number;
|
|
96
|
+
/** 每秒生成多少个token */
|
|
97
|
+
speed?: number;
|
|
98
|
+
[key: string]: any;
|
|
99
|
+
};
|
|
90
100
|
/** stream()对外输出的事件 */
|
|
91
|
-
type
|
|
101
|
+
type StreamEvent = {
|
|
92
102
|
type: "reasoning_delta";
|
|
93
103
|
delta: string;
|
|
94
104
|
} | {
|
|
@@ -124,21 +134,56 @@ type ChatCompletionsChunk = {
|
|
|
124
134
|
}[];
|
|
125
135
|
usage?: Usage;
|
|
126
136
|
} | "[DONE]";
|
|
127
|
-
/**
|
|
128
|
-
type
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
137
|
+
/** complete()内部要处理的非流式响应 */
|
|
138
|
+
type ChatCompletionsResponse = {
|
|
139
|
+
id: string;
|
|
140
|
+
object: "chat.completion";
|
|
141
|
+
created: number;
|
|
142
|
+
model: string;
|
|
143
|
+
choices: {
|
|
144
|
+
index: number;
|
|
145
|
+
message: Message;
|
|
146
|
+
finish_reason: FinishReason;
|
|
147
|
+
}[];
|
|
148
|
+
usage?: Usage;
|
|
149
|
+
};
|
|
150
|
+
/** complete()对外输出的结果 */
|
|
151
|
+
type NonStreamResult = {
|
|
152
|
+
/** 模型的思考内容(已经把各平台的reasoning_content等不规范的思考字段统一为reasoning) */
|
|
153
|
+
reasoning?: string;
|
|
154
|
+
/** 模型确定的回复内容 */
|
|
155
|
+
content: string;
|
|
156
|
+
/** 模型请求的工具调用(arguments为原始JSON字符串,需自行转换) */
|
|
157
|
+
toolCalls: ToolCall[];
|
|
158
|
+
finishReason: FinishReason;
|
|
159
|
+
usage?: Usage;
|
|
160
|
+
};
|
|
161
|
+
/** runAgent()的可选配置 */
|
|
162
|
+
type RunAgentOptions = {
|
|
163
|
+
/** 本轮可用的工具列表 */
|
|
164
|
+
tools?: ToolDefinition[];
|
|
165
|
+
/**
|
|
166
|
+
* 是否流式输出
|
|
167
|
+
* @default false
|
|
168
|
+
* @remarks 默认每轮只推送一个result事件;true时逐步推送增量事件
|
|
169
|
+
*/
|
|
170
|
+
stream?: boolean;
|
|
171
|
+
};
|
|
172
|
+
/** runAgent()非流式模式下,每轮回复结束后的事件 */
|
|
173
|
+
type NonStreamEvent = {
|
|
174
|
+
type: "result";
|
|
175
|
+
/** 模型本轮确定的回复内容 */
|
|
176
|
+
content: string;
|
|
177
|
+
/** 模型本轮的思考内容 */
|
|
178
|
+
reasoning?: string;
|
|
179
|
+
finishReason: FinishReason;
|
|
180
|
+
usage?: Usage;
|
|
136
181
|
};
|
|
137
|
-
type AgentEvent =
|
|
182
|
+
type AgentEvent = StreamEvent | NonStreamEvent | {
|
|
138
183
|
type: "tool_result";
|
|
139
184
|
id: string;
|
|
140
185
|
name: string;
|
|
141
186
|
result: string;
|
|
142
187
|
};
|
|
143
188
|
//#endregion
|
|
144
|
-
export {
|
|
189
|
+
export { ToolDefinition as _, ContentPart as a, Message as c, NonStreamEvent as d, NonStreamResult as f, ToolCall as g, TextContent as h, ChatCompletionsResponse as i, Modality as l, StreamEvent as m, AudioContent as n, FinishReason as o, RunAgentOptions as p, ChatCompletionsChunk as r, ImageContent as s, AgentEvent as t, Model as u, Usage as v, VideoContent as y };
|