@nickyzj2023/ai 1.7.0 → 1.7.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.
@@ -1,87 +0,0 @@
1
- import { n as defineTool } from "./helper-DJw58Gmz.mjs";
2
- import { extractErrorMessage, isObject, logger, omit } from "@nickyzj2023/utils";
3
- //#region src/tools/mcp.ts
4
- /** 全局单例MCP加载器 */
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
- };
41
- var MCPRouter = class {
42
- entries = /* @__PURE__ */ new Map();
43
- /** 注册一个新的MCP客户端 */
44
- async addClient(name, url, options) {
45
- if (this.entries.has(name)) return;
46
- const client = await connectClient(name, url, options);
47
- const { tools } = await client.listTools();
48
- const normalizedTools = tools.filter((tool) => !options?.ignoredToolNames?.includes(tool.name)).map((tool) => {
49
- const _properties = { ...tool.inputSchema.properties ?? {} };
50
- tool.inputSchema.required?.forEach((key) => {
51
- if (isObject(_properties[key])) _properties[key] = {
52
- ..._properties[key],
53
- required: true
54
- };
55
- });
56
- return defineTool(tool.name, tool.description ?? "", _properties, (args) => client.callTool({
57
- name: tool.name,
58
- arguments: args
59
- }));
60
- });
61
- this.entries.set(name, {
62
- client,
63
- tools: normalizedTools
64
- });
65
- return client;
66
- }
67
- /** 返回OpenAI API兼容的tools数组 */
68
- async getTools() {
69
- return [...this.entries.values()].flatMap((e) => e.tools);
70
- }
71
- };
72
- /**
73
- * 把传入的MCPServer列表转换成OpenAI API兼容的tools数组
74
- */
75
- const loadMCPTools = async (mcpServers = {}) => {
76
- router ||= new MCPRouter();
77
- await Promise.allSettled(Object.entries(mcpServers).map(async ([name, server]) => {
78
- try {
79
- await router?.addClient(name, server.url, omit(server, ["type", "url"]));
80
- } catch (e) {
81
- logger(`MCP服务器${name}加载失败:${extractErrorMessage(e)}`);
82
- }
83
- }));
84
- return router.getTools();
85
- };
86
- //#endregion
87
- export { listMcpToolNames as n, loadMCPTools as r, MCPRouter as t };
@@ -1,535 +0,0 @@
1
- import { i as estimateTokens, n as defineTool, r as estimateTextTokens } from "./helper-DJw58Gmz.mjs";
2
- import { createXMLText, extractErrorMessage, fetcher, logger, parseSSE, pick, to } from "@nickyzj2023/utils";
3
- //#region src/llm.ts
4
- /**
5
- * 分离ToolDefinition中的valid/invalid字段,前者可以传给模型,后者用于本地运算
6
- * @returns [validObj, invalidObj]
7
- */
8
- const detachToolArguments = (toolDefinition) => {
9
- return [pick(toolDefinition, ["type", "function"]), pick(toolDefinition, ["execute"])];
10
- };
11
- /**
12
- * 从消息中提取模型的思考内容。
13
- * 不同供应商,即使都用OpenAI API Compatible接口,输出的思考内容字段也可能不同,例如:
14
- * - OpenRouter里的思考字段为reasoning
15
- * - 火山引擎的叫reasoning_content
16
- * @returns 统一返回reasoning作为思考内容字段
17
- */
18
- const extractReasoning = (msgLike) => {
19
- return msgLike.reasoning || msgLike.reasoning_content;
20
- };
21
- /**
22
- * 流式请求模型,转发
23
- */
24
- async function* stream(model, messages, tools = [], options) {
25
- const validTools = tools.map((tool) => detachToolArguments(tool)[0]);
26
- const api = fetcher(model.baseUrl, {
27
- headers: { Authorization: `Bearer ${model.apiKey}` },
28
- parser: async (res) => res
29
- });
30
- const [error, response] = await to(api.post("/chat/completions", {
31
- stream: true,
32
- model: model.model,
33
- messages,
34
- tools: validTools,
35
- ...options?.body
36
- }, options));
37
- if (error) {
38
- if (options?.signal?.aborted) return;
39
- yield {
40
- type: "error",
41
- message: error.message
42
- };
43
- return;
44
- }
45
- const toolCallBuffers = /* @__PURE__ */ new Map();
46
- let usage;
47
- let finishReason = null;
48
- try {
49
- for await (const chunk of parseSSE(response)) {
50
- if (typeof chunk === "string") continue;
51
- if (chunk.usage) usage = chunk.usage;
52
- const choice = chunk.choices?.[0];
53
- if (!choice) continue;
54
- const { delta } = choice;
55
- const { content: contentDelta, tool_calls: toolCalls } = delta;
56
- const reasoning = extractReasoning(delta);
57
- if (reasoning) yield {
58
- type: "reasoning_delta",
59
- delta: reasoning
60
- };
61
- if (contentDelta) yield {
62
- type: "content_delta",
63
- delta: contentDelta.toString()
64
- };
65
- if (toolCalls) for (const call of toolCalls) {
66
- const { index = 0, type = "function", id, function: fn, ...extra } = call;
67
- const existing = toolCallBuffers.getOrInsert(index, {
68
- id: "",
69
- type,
70
- function: {
71
- name: "",
72
- arguments: ""
73
- }
74
- });
75
- if (id) existing.id = id;
76
- if (fn?.name) existing.function.name += fn.name;
77
- if (fn?.arguments) existing.function.arguments += fn.arguments;
78
- if (extra) Object.assign(existing, extra);
79
- toolCallBuffers.set(index, existing);
80
- }
81
- if (choice.finish_reason) finishReason = choice.finish_reason;
82
- }
83
- } catch (e) {
84
- if (options?.signal?.aborted) return;
85
- yield {
86
- type: "error",
87
- message: extractErrorMessage(e)
88
- };
89
- return;
90
- }
91
- for (const [, call] of toolCallBuffers) yield {
92
- type: "tool_call",
93
- id: call.id,
94
- name: call.function.name,
95
- args: call.function.arguments
96
- };
97
- yield {
98
- type: "done",
99
- finishReason,
100
- usage
101
- };
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
- };
155
- //#endregion
156
- //#region src/agent.ts
157
- /**
158
- * Agent循环
159
- * @param options.stream 是否流式输出,默认false(每轮推送一个result事件)
160
- */
161
- async function* runAgent(model, messages, options) {
162
- const { tools = [], stream: enableStream = false } = options ?? {};
163
- const toolMap = new Map(tools.map((tool) => [tool.function.name, tool]));
164
- while (true) {
165
- let reasoning = "";
166
- let content = "";
167
- const toolCalls = [];
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
188
- }
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;
206
- }
207
- reasoning = result.reasoning ?? "";
208
- content = result.content;
209
- toolCalls.push(...result.toolCalls);
210
- finishReason = result.finishReason;
211
- usage = result.usage;
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
- };
225
- const message = {
226
- role: "assistant",
227
- content
228
- };
229
- if (toolCalls.length > 0) message.tool_calls = toolCalls;
230
- messages.push(message);
231
- if (toolCalls.length === 0) return;
232
- for (const call of toolCalls) {
233
- const { name, arguments: args } = call.function;
234
- const tool = toolMap.get(name);
235
- let result = "";
236
- if (!tool) result = `不存在工具“${name}”`;
237
- else {
238
- const [error, response] = await to(tool.execute(JSON.parse(args)));
239
- result = error ? `工具“${name}”执行出错:${error.message}` : JSON.stringify(response);
240
- }
241
- messages.push({
242
- role: "tool",
243
- tool_call_id: call.id,
244
- content: result
245
- });
246
- yield {
247
- type: "tool_result",
248
- id: call.id,
249
- name,
250
- result
251
- };
252
- }
253
- }
254
- }
255
- //#endregion
256
- //#region src/tools/get-time.ts
257
- var get_time_default = defineTool("get_time", "查询指定时区的当前时间", { timezone: {
258
- type: "string",
259
- description: "完整的IANA时区名称,如Europe/Amsterdam。用户未明确提及时,传入对方语言对应的时区,例如对方使用中文时可传入Asia/Shanghai。",
260
- required: true
261
- } }, async ({ timezone }) => {
262
- return fetcher("https://timeapi.io/api", { params: { timezone } }).get("/time/current/zone");
263
- });
264
- //#endregion
265
- //#region src/tools/get-weather.ts
266
- /**
267
- * 把wttr.in的时间转成好读的"HH:mm"
268
- * @param rawTime - wttr.in hourly里的time字段,3小时粒度不带冒号,比如"0"、"300"、"1200"
269
- * @returns 补零后的时间字符串,比如"00:00"、"03:00"、"12:00"
270
- * @example toHHmm("930") // "09:30"
271
- */
272
- const toHHmm = (rawTime) => {
273
- const padded = String(rawTime ?? "").padStart(4, "0");
274
- return `${padded.slice(0, 2)}:${padded.slice(2)}`;
275
- };
276
- /**
277
- * 精简wttr.in返回的天气数据
278
- * @param rawData - wttr.in API返回的原始JSON
279
- * @returns 精简后的天气数据
280
- */
281
- const pickValuableFields = (rawData) => {
282
- if (!rawData) return null;
283
- const area = rawData.nearest_area?.[0] || {};
284
- return {
285
- location: {
286
- city: area.areaName?.[0]?.value || "",
287
- region: area.region?.[0]?.value || "",
288
- country: area.country?.[0]?.value || "",
289
- latitude: area.latitude,
290
- longitude: area.longitude
291
- },
292
- forecast: (rawData.weather || []).map((day) => ({
293
- date: day.date,
294
- maxTempC: day.maxtempC,
295
- minTempC: day.mintempC,
296
- astro: {
297
- sunrise: day.astronomy?.[0]?.sunrise || "",
298
- sunset: day.astronomy?.[0]?.sunset || "",
299
- moonPhase: day.astronomy?.[0]?.moon_phase || ""
300
- },
301
- hourly: (day.hourly || []).map((h) => ({
302
- time: toHHmm(h.time),
303
- tempC: h.tempC,
304
- feelsLikeC: h.FeelsLikeC,
305
- weatherDesc: h.weatherDesc?.[0]?.value || "",
306
- chanceOfRain: h.chanceofrain,
307
- precipMM: h.precipMM,
308
- humidity: h.humidity,
309
- windSpeedKmph: h.windspeedKmph,
310
- windDir: h.winddir16Point
311
- }))
312
- }))
313
- };
314
- };
315
- var get_weather_default = defineTool("get_weather", "查询指定城市的天气情况", { city: {
316
- type: "string",
317
- description: "城市名,如shanghai、tokyo",
318
- required: true
319
- } }, async ({ city }) => {
320
- const api = fetcher("https://wttr.in", { params: { format: "j1" } });
321
- const [error, response] = await to(api.get(`/${city}`));
322
- if (error) return error.message;
323
- return pickValuableFields(response);
324
- });
325
- //#endregion
326
- //#region src/utils/compact/helper.ts
327
- /**
328
- * 校验assistant(tool_calls)消息
329
- */
330
- const isToolCalls = (message) => {
331
- return message?.role === "assistant" && Array.isArray(message.tool_calls);
332
- };
333
- /**
334
- * 校验多模态消息
335
- */
336
- const isMediaMessage = (message) => {
337
- if (message && Array.isArray(message.content)) for (const part of message.content) {
338
- if (part.type === "image_url") return "image";
339
- if (part.type === "input_audio") return "audio";
340
- if (part.type === "video_url") return "video";
341
- }
342
- };
343
- /**
344
- * 查找assistant(tool_calls) + tool配对组范围
345
- * @param messages 消息数组
346
- * @param toolIndex 组内任意tool消息下标
347
- * @returns 下标数组[组头assistant(tool_calls), 组内最后一个tool),找不到组头时返回null
348
- */
349
- const findToolGroupRange = (messages, toolIndex) => {
350
- let groupStart = toolIndex;
351
- while (groupStart > 0 && messages[groupStart - 1]?.role === "tool") groupStart--;
352
- if (!isToolCalls(messages[groupStart - 1])) return null;
353
- let groupEnd = groupStart;
354
- while (groupEnd < messages.length && messages[groupEnd]?.role === "tool") groupEnd++;
355
- return [groupStart - 1, groupEnd];
356
- };
357
- //#endregion
358
- //#region src/utils/compact/strategy.ts
359
- /** 默认的压缩工具结果策略:让大模型精简消息内容 */
360
- const defaultReplacerOfToolResultContent = async (content, options) => {
361
- const { model } = options ?? {};
362
- const messages = [{
363
- role: "user",
364
- content
365
- }, {
366
- role: "user",
367
- content: "请用一句话简述上面这条消息(直击要点,不要添加任何前言后语)"
368
- }];
369
- let simplifiedContent = "";
370
- if (!model) simplifiedContent = "工具结果已被消费";
371
- else for await (const e of runAgent(model, messages)) if (e.type === "result") simplifiedContent = e.content;
372
- else if (e.type === "error") throw new Error(e.message);
373
- return simplifiedContent;
374
- };
375
- /**
376
- * @returns 实际处理了几条消息
377
- */
378
- const compactToolResults = async (compressible, options) => {
379
- const { replacer, mark, model } = options ?? {};
380
- if (!replacer && !model) return 0;
381
- const _replacer = replacer || defaultReplacerOfToolResultContent;
382
- let count = 0;
383
- for (const message of compressible) if (message?.role === "tool" && typeof message.content === "string") {
384
- if (message.content.startsWith(mark)) continue;
385
- message.content = mark + await _replacer(message.content, { model });
386
- count++;
387
- }
388
- if (count > 0) logger(`压缩了${count}条工具调用结果`);
389
- return count;
390
- };
391
- /** 默认的压缩多模态消息策略:让大模型精简消息内容 */
392
- const defaultReplacerOfMediaContent = async (content, options) => {
393
- const { model, modality = "image" } = options ?? {};
394
- const messages = [{
395
- role: "user",
396
- content
397
- }, {
398
- role: "user",
399
- content: "请用一句话简述上面这条消息(直击要点,不要添加任何前言后语)"
400
- }];
401
- let simplifiedContent = "";
402
- if (!model?.modalities?.includes(modality)) simplifiedContent = "媒体资源已被消费";
403
- else for await (const e of runAgent(model, messages)) if (e.type === "result") simplifiedContent = e.content;
404
- else if (e.type === "error") throw new Error(e.message);
405
- return simplifiedContent;
406
- };
407
- /**
408
- * @returns 实际处理了几条消息
409
- */
410
- const compactMediaMessages = async (compressible, options) => {
411
- const { replacer, model } = options ?? {};
412
- if (!replacer && !model) return 0;
413
- const _replacer = replacer || defaultReplacerOfMediaContent;
414
- let count = 0;
415
- for (const message of compressible) {
416
- const mediaModality = isMediaMessage(message);
417
- if (mediaModality) {
418
- const compacted = await _replacer(message.content, {
419
- model,
420
- modality: mediaModality
421
- });
422
- message.content = createXMLText("media", compacted);
423
- count++;
424
- }
425
- }
426
- if (count > 0) logger(`压缩了${count}条多模态消息`);
427
- return count;
428
- };
429
- const summarizeMessages = async (compressible, options) => {
430
- const { model, systemPrompt, beforeSummarize } = options ?? {};
431
- const summarizable = compressible.slice(1);
432
- if (summarizable.length === 0) {
433
- logger("消息太少,无需总结");
434
- return 0;
435
- }
436
- await beforeSummarize?.(summarizable);
437
- const count = summarizable.length;
438
- summarizable.push({
439
- role: "system",
440
- content: systemPrompt
441
- }, {
442
- role: "user",
443
- content: "开始总结上下文"
444
- });
445
- let summarized = "";
446
- let usage;
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);
451
- compressible.splice(1, Infinity, {
452
- role: "user",
453
- content: createXMLText("summary", summarized)
454
- });
455
- logger(`总结了${count}条消息,消耗:`, usage);
456
- return count;
457
- };
458
- /**
459
- * 最终的兜底压缩策略,从头删除旧消息,直到第二个回调函数返回true(达成目标)
460
- */
461
- const discardMessagesUntil = (compressible, until) => {
462
- let count = 0;
463
- while (compressible.length > 0 && !until(compressible)) {
464
- let endIndex = Math.max(1, Math.floor(compressible.length / 10));
465
- if (compressible[endIndex]?.role === "tool") {
466
- const range = findToolGroupRange(compressible, endIndex);
467
- if (range) endIndex = range[1];
468
- else while (compressible[endIndex]?.role === "tool") endIndex++;
469
- }
470
- count += compressible.splice(0, endIndex).length;
471
- }
472
- logger(`丢弃了${count}条旧消息`);
473
- return count;
474
- };
475
- /**
476
- * 自动优化上下文,类似AI Coding Agent的/compact命令
477
- */
478
- const compact = Object.assign(async (messages, model, options) => {
479
- const { usage, keepCount = 10, compactedMessageMark = "[已简化]", ratioToCompactToolResults = .6, replacerOfToolResultContent, ratioToCompactMedia = .7, replacerOfMediaContent, ratioToSummarize = .8, summarizeOptions } = options ?? {};
480
- const context = model?.context ?? 131072;
481
- const tokens = usage?.total_tokens ?? estimateTokens(messages);
482
- const result = {
483
- hasCompactedToolResults: false,
484
- hasCompactedMedia: false,
485
- hasSummarized: false,
486
- hasDiscardMessages: false
487
- };
488
- const startIndex = 1;
489
- let endIndex = Math.max(startIndex, messages.length - keepCount);
490
- if (messages[endIndex]?.role === "tool") {
491
- const range = findToolGroupRange(messages, endIndex);
492
- if (range) endIndex = range[1];
493
- else while (messages[endIndex]?.role === "tool") endIndex++;
494
- }
495
- endIndex = Math.max(startIndex, endIndex);
496
- const reservedStart = messages.slice(0, startIndex);
497
- const compressible = messages.slice(startIndex, endIndex);
498
- const reservedEnd = messages.slice(endIndex);
499
- if (tokens > context * ratioToCompactToolResults) result.hasCompactedToolResults = await compactToolResults(compressible, {
500
- replacer: replacerOfToolResultContent,
501
- mark: compactedMessageMark,
502
- model
503
- }) > 0;
504
- if (tokens > context * ratioToCompactMedia) result.hasCompactedMedia = await compactMediaMessages(compressible, {
505
- replacer: replacerOfMediaContent,
506
- model
507
- }) > 0;
508
- if (tokens > context * ratioToSummarize) {
509
- const { systemPrompt = "你现在的任务是总结历史消息", beforeSummarize } = summarizeOptions ?? {};
510
- const [error, count] = await to(summarizeMessages(compressible, {
511
- model,
512
- systemPrompt,
513
- beforeSummarize
514
- }));
515
- if (!error) result.hasSummarized = count > 0;
516
- else result.hasDiscardMessages = discardMessagesUntil(compressible, (compressible) => {
517
- if (compressible.length === 0) return true;
518
- const tempMessages = [
519
- ...reservedStart,
520
- ...compressible,
521
- ...reservedEnd
522
- ];
523
- return estimateTokens(tempMessages) < context * ratioToSummarize;
524
- }) > 0;
525
- messages.splice(0, Infinity, ...reservedStart, ...compressible, ...reservedEnd);
526
- }
527
- return result;
528
- }, {
529
- compactToolResults,
530
- compactMediaMessages,
531
- summarizeMessages,
532
- discardMessagesUntil
533
- });
534
- //#endregion
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 };