@nickyzj2023/ai 1.6.4 → 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,77 +0,0 @@
1
- import { fetcher } from "@nickyzj2023/utils";
2
- //#region src/utils/helper.ts
3
- /**
4
- * 辅助定义一个POST /chat/completions支持的model参数
5
- * @remarks 只有baseUrl字段是必须的
6
- */
7
- const defineModel = (config) => ({
8
- modalities: ["text"],
9
- context: 131072,
10
- ...config
11
- });
12
- /**
13
- * 辅助定义一个POST /chat/completions支持的tool对象
14
- * @param execute 实际执行工具的函数
15
- */
16
- const defineTool = (name, description, properties, execute) => {
17
- const _required = [];
18
- return {
19
- type: "function",
20
- function: {
21
- name,
22
- description,
23
- parameters: {
24
- type: "object",
25
- properties: Object.entries(properties).reduce((result, [key, property]) => {
26
- if ("required" in property) {
27
- _required.push(key);
28
- delete property.required;
29
- }
30
- result[key] = property;
31
- return result;
32
- }, {}),
33
- required: _required
34
- }
35
- },
36
- execute
37
- };
38
- };
39
- const segmenter = new Intl.Segmenter([], { granularity: "word" });
40
- const estimateTextTokens = (text) => {
41
- let words = 0;
42
- let others = 0;
43
- for (const seg of segmenter.segment(text)) if (seg.isWordLike) words++;
44
- else others++;
45
- return Math.ceil(words * 1.5 + others / 4);
46
- };
47
- /**
48
- * 列出GET /models返回的模型id
49
- * @param baseUrl 接口前缀,如http://127.0.0.1:11434/v1
50
- * @param apiKey 本地llama.cpp等不校验鉴权的服务可以不传,不传就不带Authorization头
51
- * @returns 模型的id列表
52
- * @remarks 请求失败(服务没起、鉴权不过等)会抛异常,由调用方自行兜底
53
- */
54
- const listModels = async (baseUrl, apiKey) => {
55
- const { data } = await fetcher(baseUrl, { headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : void 0 }).get("/models");
56
- return (data ?? []).map((model) => model.id).filter((id) => typeof id === "string");
57
- };
58
- /**
59
- * 根据上下文里的中/英文/多模态消息,估算出可能消耗的token
60
- * - 单词 ≈ 1.5token
61
- * - 标点/空白等非词字符每4个 ≈ 1token
62
- * - 图片/音频/视频/文件 ≈ 4096token(不好估算,取个较大的值)
63
- */
64
- const estimateTokens = (messages) => {
65
- if (!messages?.length) return 0;
66
- return messages.reduce((acc, message) => {
67
- const { content, tool_calls, ...metadata } = message;
68
- if (typeof content === "string") acc += estimateTextTokens(content);
69
- else for (const part of content) if (part.type === "text") acc += estimateTextTokens(part.text);
70
- else acc += 4096;
71
- if (tool_calls) acc += estimateTextTokens(JSON.stringify(tool_calls));
72
- acc += estimateTextTokens(JSON.stringify(metadata));
73
- return acc;
74
- }, 0);
75
- };
76
- //#endregion
77
- export { listModels as a, estimateTokens as i, defineTool as n, estimateTextTokens as r, defineModel as t };
@@ -1,58 +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
- var MCPRouter = class {
7
- entries = /* @__PURE__ */ new Map();
8
- /** 注册一个新的MCP客户端 */
9
- async addClient(name, url, options) {
10
- if (this.entries.has(name)) return;
11
- const [{ Client }, { StreamableHTTPClientTransport }] = await Promise.all([import("@modelcontextprotocol/sdk/client"), import("@modelcontextprotocol/sdk/client/streamableHttp.js")]);
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);
18
- const { tools } = await client.listTools();
19
- const normalizedTools = tools.filter((tool) => !options?.ignoredToolNames?.includes(tool.name)).map((tool) => {
20
- const _properties = { ...tool.inputSchema.properties ?? {} };
21
- tool.inputSchema.required?.forEach((key) => {
22
- if (isObject(_properties[key])) _properties[key] = {
23
- ..._properties[key],
24
- required: true
25
- };
26
- });
27
- return defineTool(tool.name, tool.description ?? "", _properties, (args) => client.callTool({
28
- name: tool.name,
29
- arguments: args
30
- }));
31
- });
32
- this.entries.set(name, {
33
- client,
34
- tools: normalizedTools
35
- });
36
- return client;
37
- }
38
- /** 返回OpenAI API兼容的tools数组 */
39
- async getTools() {
40
- return [...this.entries.values()].flatMap((e) => e.tools);
41
- }
42
- };
43
- /**
44
- * 把传入的MCPServer列表转换成OpenAI API兼容的tools数组
45
- */
46
- const loadMCPTools = async (mcpServers = {}) => {
47
- router ||= new MCPRouter();
48
- await Promise.allSettled(Object.entries(mcpServers).map(async ([name, server]) => {
49
- try {
50
- await router?.addClient(name, server.url, omit(server, ["type", "url"]));
51
- } catch (e) {
52
- logger(`MCP服务器${name}加载失败:${extractErrorMessage(e)}`);
53
- }
54
- }));
55
- return router.getTools();
56
- };
57
- //#endregion
58
- export { loadMCPTools as n, MCPRouter as t };
@@ -1,461 +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
- //#endregion
104
- //#region src/agent.ts
105
- async function* runAgent(model, messages, tools) {
106
- const toolMap = new Map(tools.map((tool) => [tool.function.name, tool]));
107
- while (true) {
108
- let content = "";
109
- let reasoning = "";
110
- const toolCalls = [];
111
- const promptMessage = messages.slice(-1);
112
- let startTime = 0;
113
- for await (const e of stream(model, messages, tools)) {
114
- startTime ||= Date.now();
115
- switch (e.type) {
116
- case "reasoning_delta":
117
- yield e;
118
- reasoning += e.delta;
119
- break;
120
- case "content_delta":
121
- yield e;
122
- content += e.delta;
123
- break;
124
- case "tool_call":
125
- yield e;
126
- toolCalls.push({
127
- id: e.id,
128
- type: "function",
129
- function: {
130
- name: e.name,
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
- };
147
- }
148
- e.usage.speed = Math.floor(e.usage.completion_tokens / ((Date.now() - startTime) / 1e3));
149
- yield e;
150
- }
151
- }
152
- const message = {
153
- role: "assistant",
154
- content
155
- };
156
- if (toolCalls.length > 0) message.tool_calls = toolCalls;
157
- messages.push(message);
158
- if (toolCalls.length === 0) return;
159
- for (const call of toolCalls) {
160
- const { name, arguments: args } = call.function;
161
- const tool = toolMap.get(name);
162
- let result = "";
163
- if (!tool) result = `不存在工具“${name}”`;
164
- else {
165
- const [error, response] = await to(tool.execute(JSON.parse(args)));
166
- result = error ? `工具“${name}”执行出错:${error.message}` : JSON.stringify(response);
167
- }
168
- messages.push({
169
- role: "tool",
170
- tool_call_id: call.id,
171
- content: result
172
- });
173
- yield {
174
- type: "tool_result",
175
- id: call.id,
176
- name,
177
- result
178
- };
179
- }
180
- }
181
- }
182
- //#endregion
183
- //#region src/tools/get-time.ts
184
- var get_time_default = defineTool("get_time", "查询指定时区的当前时间", { timezone: {
185
- type: "string",
186
- description: "完整的IANA时区名称,如Europe/Amsterdam。用户未明确提及时,传入对方语言对应的时区,例如对方使用中文时可传入Asia/Shanghai。",
187
- required: true
188
- } }, async ({ timezone }) => {
189
- return fetcher("https://timeapi.io/api", { params: { timezone } }).get("/time/current/zone");
190
- });
191
- //#endregion
192
- //#region src/tools/get-weather.ts
193
- /**
194
- * 把wttr.in的时间转成好读的"HH:mm"
195
- * @param rawTime - wttr.in hourly里的time字段,3小时粒度不带冒号,比如"0"、"300"、"1200"
196
- * @returns 补零后的时间字符串,比如"00:00"、"03:00"、"12:00"
197
- * @example toHHmm("930") // "09:30"
198
- */
199
- const toHHmm = (rawTime) => {
200
- const padded = String(rawTime ?? "").padStart(4, "0");
201
- return `${padded.slice(0, 2)}:${padded.slice(2)}`;
202
- };
203
- /**
204
- * 精简wttr.in返回的天气数据
205
- * @param rawData - wttr.in API返回的原始JSON
206
- * @returns 精简后的天气数据
207
- */
208
- const pickValuableFields = (rawData) => {
209
- if (!rawData) return null;
210
- const area = rawData.nearest_area?.[0] || {};
211
- return {
212
- location: {
213
- city: area.areaName?.[0]?.value || "",
214
- region: area.region?.[0]?.value || "",
215
- country: area.country?.[0]?.value || "",
216
- latitude: area.latitude,
217
- longitude: area.longitude
218
- },
219
- forecast: (rawData.weather || []).map((day) => ({
220
- date: day.date,
221
- maxTempC: day.maxtempC,
222
- minTempC: day.mintempC,
223
- astro: {
224
- sunrise: day.astronomy?.[0]?.sunrise || "",
225
- sunset: day.astronomy?.[0]?.sunset || "",
226
- moonPhase: day.astronomy?.[0]?.moon_phase || ""
227
- },
228
- hourly: (day.hourly || []).map((h) => ({
229
- time: toHHmm(h.time),
230
- tempC: h.tempC,
231
- feelsLikeC: h.FeelsLikeC,
232
- weatherDesc: h.weatherDesc?.[0]?.value || "",
233
- chanceOfRain: h.chanceofrain,
234
- precipMM: h.precipMM,
235
- humidity: h.humidity,
236
- windSpeedKmph: h.windspeedKmph,
237
- windDir: h.winddir16Point
238
- }))
239
- }))
240
- };
241
- };
242
- var get_weather_default = defineTool("get_weather", "查询指定城市的天气情况", { city: {
243
- type: "string",
244
- description: "城市名,如shanghai、tokyo",
245
- required: true
246
- } }, async ({ city }) => {
247
- const api = fetcher("https://wttr.in", { params: { format: "j1" } });
248
- const [error, response] = await to(api.get(`/${city}`));
249
- if (error) return error.message;
250
- return pickValuableFields(response);
251
- });
252
- //#endregion
253
- //#region src/utils/compact/helper.ts
254
- /**
255
- * 校验assistant(tool_calls)消息
256
- */
257
- const isToolCalls = (message) => {
258
- return message?.role === "assistant" && Array.isArray(message.tool_calls);
259
- };
260
- /**
261
- * 校验多模态消息
262
- */
263
- const isMediaMessage = (message) => {
264
- if (message && Array.isArray(message.content)) for (const part of message.content) {
265
- if (part.type === "image_url") return "image";
266
- if (part.type === "input_audio") return "audio";
267
- if (part.type === "video_url") return "video";
268
- }
269
- };
270
- /**
271
- * 查找assistant(tool_calls) + tool配对组范围
272
- * @param messages 消息数组
273
- * @param toolIndex 组内任意tool消息下标
274
- * @returns 下标数组[组头assistant(tool_calls), 组内最后一个tool),找不到组头时返回null
275
- */
276
- const findToolGroupRange = (messages, toolIndex) => {
277
- let groupStart = toolIndex;
278
- while (groupStart > 0 && messages[groupStart - 1]?.role === "tool") groupStart--;
279
- if (!isToolCalls(messages[groupStart - 1])) return null;
280
- let groupEnd = groupStart;
281
- while (groupEnd < messages.length && messages[groupEnd]?.role === "tool") groupEnd++;
282
- return [groupStart - 1, groupEnd];
283
- };
284
- //#endregion
285
- //#region src/utils/compact/strategy.ts
286
- /** 默认的压缩工具结果策略:让大模型精简消息内容 */
287
- const defaultReplacerOfToolResultContent = async (content, options) => {
288
- const { model } = options ?? {};
289
- const messages = [{
290
- role: "user",
291
- content
292
- }, {
293
- role: "user",
294
- content: "请用一句话简述上面这条消息(直击要点,不要添加任何前言后语)"
295
- }];
296
- let simplifiedContent = "";
297
- if (!model) simplifiedContent = "工具结果已被消费";
298
- else for await (const e of runAgent(model, messages, [])) if (e.type === "content_delta") simplifiedContent += e.delta;
299
- else if (e.type === "error") throw new Error(e.message);
300
- return simplifiedContent;
301
- };
302
- /**
303
- * @returns 实际处理了几条消息
304
- */
305
- const compactToolResults = async (compressible, options) => {
306
- const { replacer, mark, model } = options ?? {};
307
- if (!replacer && !model) return 0;
308
- const _replacer = replacer || defaultReplacerOfToolResultContent;
309
- let count = 0;
310
- for (const message of compressible) if (message?.role === "tool" && typeof message.content === "string") {
311
- if (message.content.startsWith(mark)) continue;
312
- message.content = mark + await _replacer(message.content, { model });
313
- count++;
314
- }
315
- if (count > 0) logger(`压缩了${count}条工具调用结果`);
316
- return count;
317
- };
318
- /** 默认的压缩多模态消息策略:让大模型精简消息内容 */
319
- const defaultReplacerOfMediaContent = async (content, options) => {
320
- const { model, modality = "image" } = options ?? {};
321
- const messages = [{
322
- role: "user",
323
- content
324
- }, {
325
- role: "user",
326
- content: "请用一句话简述上面这条消息(直击要点,不要添加任何前言后语)"
327
- }];
328
- let simplifiedContent = "";
329
- if (!model?.modalities?.includes(modality)) simplifiedContent = "媒体资源已被消费";
330
- else for await (const e of runAgent(model, messages, [])) if (e.type === "content_delta") simplifiedContent += e.delta;
331
- else if (e.type === "error") throw new Error(e.message);
332
- return simplifiedContent;
333
- };
334
- /**
335
- * @returns 实际处理了几条消息
336
- */
337
- const compactMediaMessages = async (compressible, options) => {
338
- const { replacer, model } = options ?? {};
339
- if (!replacer && !model) return 0;
340
- const _replacer = replacer || defaultReplacerOfMediaContent;
341
- let count = 0;
342
- for (const message of compressible) {
343
- const mediaModality = isMediaMessage(message);
344
- if (mediaModality) {
345
- const compacted = await _replacer(message.content, {
346
- model,
347
- modality: mediaModality
348
- });
349
- message.content = createXMLText("media", compacted);
350
- count++;
351
- }
352
- }
353
- if (count > 0) logger(`压缩了${count}条多模态消息`);
354
- return count;
355
- };
356
- const summarizeMessages = async (compressible, options) => {
357
- const { model, systemPrompt, beforeSummarize } = options ?? {};
358
- const summarizable = compressible.slice(1);
359
- if (summarizable.length === 0) {
360
- logger("消息太少,无需总结");
361
- return 0;
362
- }
363
- await beforeSummarize?.(summarizable);
364
- const count = summarizable.length;
365
- summarizable.push({
366
- role: "system",
367
- content: systemPrompt
368
- }, {
369
- role: "user",
370
- content: "开始总结上下文"
371
- });
372
- let summarized = "";
373
- let usage;
374
- for await (const e of runAgent(model, summarizable, [])) if (e.type === "content_delta") summarized += e.delta;
375
- else if (e.type === "done") usage = e.usage;
376
- else if (e.type === "error") throw new Error(e.message);
377
- compressible.splice(1, Infinity, {
378
- role: "user",
379
- content: createXMLText("summary", summarized)
380
- });
381
- logger(`总结了${count}条消息,消耗:`, usage);
382
- return count;
383
- };
384
- /**
385
- * 最终的兜底压缩策略,从头删除旧消息,直到第二个回调函数返回true(达成目标)
386
- */
387
- const discardMessagesUntil = (compressible, until) => {
388
- let count = 0;
389
- while (compressible.length > 0 && !until(compressible)) {
390
- let endIndex = Math.max(1, Math.floor(compressible.length / 10));
391
- if (compressible[endIndex]?.role === "tool") {
392
- const range = findToolGroupRange(compressible, endIndex);
393
- if (range) endIndex = range[1];
394
- else while (compressible[endIndex]?.role === "tool") endIndex++;
395
- }
396
- count += compressible.splice(0, endIndex).length;
397
- }
398
- logger(`丢弃了${count}条旧消息`);
399
- return count;
400
- };
401
- /**
402
- * 自动优化上下文,类似AI Coding Agent的/compact命令
403
- */
404
- const compact = Object.assign(async (messages, model, options) => {
405
- const { usage, keepCount = 10, compactedMessageMark = "[已简化]", ratioToCompactToolResults = .6, replacerOfToolResultContent, ratioToCompactMedia = .7, replacerOfMediaContent, ratioToSummarize = .8, summarizeOptions } = options ?? {};
406
- const context = model?.context ?? 131072;
407
- const tokens = usage?.total_tokens ?? estimateTokens(messages);
408
- const result = {
409
- hasCompactedToolResults: false,
410
- hasCompactedMedia: false,
411
- hasSummarized: false,
412
- hasDiscardMessages: false
413
- };
414
- const startIndex = 1;
415
- let endIndex = Math.max(startIndex, messages.length - keepCount);
416
- if (messages[endIndex]?.role === "tool") {
417
- const range = findToolGroupRange(messages, endIndex);
418
- if (range) endIndex = range[1];
419
- else while (messages[endIndex]?.role === "tool") endIndex++;
420
- }
421
- endIndex = Math.max(startIndex, endIndex);
422
- const reservedStart = messages.slice(0, startIndex);
423
- const compressible = messages.slice(startIndex, endIndex);
424
- const reservedEnd = messages.slice(endIndex);
425
- if (tokens > context * ratioToCompactToolResults) result.hasCompactedToolResults = await compactToolResults(compressible, {
426
- replacer: replacerOfToolResultContent,
427
- mark: compactedMessageMark,
428
- model
429
- }) > 0;
430
- if (tokens > context * ratioToCompactMedia) result.hasCompactedMedia = await compactMediaMessages(compressible, {
431
- replacer: replacerOfMediaContent,
432
- model
433
- }) > 0;
434
- if (tokens > context * ratioToSummarize) {
435
- const { systemPrompt = "你现在的任务是总结历史消息", beforeSummarize } = summarizeOptions ?? {};
436
- const [error, count] = await to(summarizeMessages(compressible, {
437
- model,
438
- systemPrompt,
439
- beforeSummarize
440
- }));
441
- if (!error) result.hasSummarized = count > 0;
442
- else result.hasDiscardMessages = discardMessagesUntil(compressible, (compressible) => {
443
- if (compressible.length === 0) return true;
444
- const tempMessages = [
445
- ...reservedStart,
446
- ...compressible,
447
- ...reservedEnd
448
- ];
449
- return estimateTokens(tempMessages) < context * ratioToSummarize;
450
- }) > 0;
451
- messages.splice(0, Infinity, ...reservedStart, ...compressible, ...reservedEnd);
452
- }
453
- return result;
454
- }, {
455
- compactToolResults,
456
- compactMediaMessages,
457
- summarizeMessages,
458
- discardMessagesUntil
459
- });
460
- //#endregion
461
- export { stream as a, runAgent as i, get_weather_default as n, get_time_default as r, compact as t };