@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.
package/dist/index.d.mts CHANGED
@@ -1,168 +1,6 @@
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
- //#region src/agent.d.ts
3
- /**
4
- * Agent循环
5
- * @param options.stream 是否流式输出,默认false(每轮推送一个result事件)
6
- */
7
- declare function runAgent(model: Model, messages: Message[], options?: RunAgentOptions): AsyncGenerator<AgentEvent>;
8
- //#endregion
9
- //#region src/llm.d.ts
10
- /**
11
- * 流式请求模型,转发
12
- */
13
- declare function stream(model: Model, messages: Message[], tools?: ToolDefinition[], options?: Omit<RequestInit, "body"> & {
14
- body?: Record<string, unknown>;
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>;
24
- //#endregion
25
- //#region src/tools/get-time.d.ts
26
- declare const _default: ToolDefinition;
27
- //#endregion
28
- //#region src/tools/get-weather.d.ts
29
- declare const _default$1: ToolDefinition;
30
- //#endregion
31
- //#region src/utils/compact/types.d.ts
32
- declare namespace Compact {
33
- type Options = {
34
- /** 提供token消耗情况时,能更准确地判断上下文是否达到阈值 */
35
- usage?: Usage;
36
- /**
37
- * 各种压缩方式统一保留的最近消息条数
38
- * @default 10
39
- * @remarks 压缩工具调用结果、压缩媒体消息、总结消息、硬删除兜底都会保留最近keepCount条消息不处理
40
- */
41
- keepCount?: number;
42
- /**
43
- * 压缩工具/媒体消息时做个标记,防止下次重复压缩
44
- * @default "[已压缩]"
45
- */
46
- compactedMessageMark?: string;
47
- /**
48
- * 上下文>总上下文*ratio时压缩工具调用结果
49
- * @default 0.6
50
- */
51
- ratioToCompactToolResults?: number;
52
- /**
53
- * 如何压缩工具调用结果
54
- * @default 让其他模型返回简化后的工具结果
55
- */
56
- replacerOfToolResultContent?: Compact.ReplacerOfToolResultContent;
57
- /**
58
- * 上下文>总上下文*ratio时压缩图片/音频/视频消息
59
- * @default 0.7
60
- */
61
- ratioToCompactMedia?: number;
62
- /**
63
- * 如何压缩媒体消息
64
- * @default 让其他模型用自然语言简短描述一遍
65
- */
66
- replacerOfMediaContent?: Compact.ReplacerOfMediaContent;
67
- /**
68
- * 上下文>总上下文*ratio时总结消息
69
- * @default 0.8
70
- * @remarks 如果总结成功,会把keepCount以前的消息压成一条用户消息
71
- */
72
- ratioToSummarize?: number;
73
- /**
74
- * 总结消息时的配置项
75
- * @default { systemPrompt: "你现在的任务是总结历史消息" }
76
- */
77
- summarizeOptions?: Partial<Compact.SummarizeOptions>;
78
- };
79
- type ReplacerOfToolResultContent = (content: Message["content"], options?: {
80
- model?: Model;
81
- [key: string]: any;
82
- }) => Promise<string> | string;
83
- type ReplacerOfMediaContent = (content: Message["content"], options?: {
84
- model?: Model;
85
- modality?: Modality;
86
- [key: string]: any;
87
- }) => Promise<string> | string;
88
- type SummarizeOptions = {
89
- /** 指导大模型如何总结消息 */
90
- systemPrompt: string;
91
- model: Model;
92
- /** 触发总结前的钩子 */
93
- beforeSummarize?: (summarizable: Message[]) => void | Promise<void>;
94
- };
95
- type Result = {
96
- /** 是否压缩了工具调用结果 */
97
- hasCompactedToolResults: boolean;
98
- /** 是否压缩了图片/音频/视频消息 */
99
- hasCompactedMedia: boolean;
100
- /** 是否总结了消息 */
101
- hasSummarized: boolean;
102
- /** 是否丢弃了一些旧消息(最终兜底策略) */
103
- hasDiscardMessages: boolean;
104
- };
105
- }
106
- //#endregion
107
- //#region src/utils/compact/strategy.d.ts
108
- /**
109
- * @returns 实际处理了几条消息
110
- */
111
- declare const compactToolResults: (compressible: Message[], options: {
112
- replacer?: Compact.ReplacerOfToolResultContent;
113
- mark: string;
114
- model?: Model;
115
- }) => Promise<number>;
116
- /**
117
- * @returns 实际处理了几条消息
118
- */
119
- declare const compactMediaMessages: (compressible: Message[], options: {
120
- replacer?: Compact.ReplacerOfMediaContent;
121
- model?: Model;
122
- }) => Promise<number>;
123
- declare const summarizeMessages: (compressible: Message[], options: Compact.SummarizeOptions) => Promise<number>;
124
- /**
125
- * 最终的兜底压缩策略,从头删除旧消息,直到第二个回调函数返回true(达成目标)
126
- */
127
- declare const discardMessagesUntil: (compressible: Message[], until: (compressible: Message[]) => boolean) => number;
128
- //#endregion
129
- //#region src/utils/compact/index.d.ts
130
- /**
131
- * 自动优化上下文,类似AI Coding Agent的/compact命令
132
- */
133
- declare const compact: ((messages: Message[], model: Model, options?: Compact.Options) => Promise<Compact.Result>) & {
134
- compactToolResults: typeof compactToolResults;
135
- compactMediaMessages: typeof compactMediaMessages;
136
- summarizeMessages: typeof summarizeMessages;
137
- discardMessagesUntil: typeof discardMessagesUntil;
138
- };
139
- //#endregion
140
- //#region src/utils/helper.d.ts
141
- /**
142
- * 辅助定义一个POST /chat/completions支持的model参数
143
- * @remarks 只有baseUrl字段是必须的
144
- */
145
- declare const defineModel: (config: Model) => Model;
146
- /**
147
- * 辅助定义一个POST /chat/completions支持的tool对象
148
- * @param execute 实际执行工具的函数
149
- */
150
- declare const defineTool: (name: ToolDefinition["function"]["name"], description: ToolDefinition["function"]["description"], properties: ToolDefinition["function"]["parameters"]["properties"], execute: ToolDefinition["execute"]) => ToolDefinition;
151
- declare const estimateTextTokens: (text: string) => number;
152
- /**
153
- * 列出GET /models返回的模型id
154
- * @param baseUrl 接口前缀,如http://127.0.0.1:11434/v1
155
- * @param apiKey 本地llama.cpp等不校验鉴权的服务可以不传,不传就不带Authorization头
156
- * @returns 模型的id列表
157
- * @remarks 请求失败(服务没起、鉴权不过等)会抛异常,由调用方自行兜底
158
- */
159
- declare const listModels: (baseUrl: string, apiKey?: string) => Promise<string[]>;
160
- /**
161
- * 根据上下文里的中/英文/多模态消息,估算出可能消耗的token
162
- * - 单词 ≈ 1.5token
163
- * - 标点/空白等非词字符每4个 ≈ 1token
164
- * - 图片/音频/视频/文件 ≈ 4096token(不好估算,取个较大的值)
165
- */
166
- declare const estimateTokens: (messages?: Message[]) => number;
167
- //#endregion
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 };
1
+ import { AgentEvent, AudioContent, ChatCompletionsChunk, ChatCompletionsResponse, ContentPart, FinishReason, ImageContent, Message, Modality, Model, NonStreamEvent, NonStreamResult, RunAgentOptions, StreamEvent, TextContent, ToolCall, ToolDefinition, Usage, VideoContent } from "./types.mjs";
2
+ import { runAgent } from "./agent.mjs";
3
+ import { nonStream, stream } from "./llm.mjs";
4
+ import { compact } from "./utils/compact/index.mjs";
5
+ import { defineModel, defineTool, estimateTextTokens, estimateTokens, listModels } from "./utils/helper.mjs";
6
+ 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, listModels, nonStream, runAgent, stream };
package/dist/index.mjs CHANGED
@@ -1,3 +1 @@
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
- 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, nonStream, runAgent, stream };
1
+ import{nonStream as e,stream as t}from"./llm.mjs";import{defineModel as n,defineTool as r,estimateTextTokens as i,estimateTokens as a,listModels as o}from"./utils/helper.mjs";import{runAgent as s}from"./agent.mjs";import{compact as c}from"./utils/compact/index.mjs";export{c as compact,n as defineModel,r as defineTool,i as estimateTextTokens,a as estimateTokens,o as listModels,e as nonStream,s as runAgent,t as stream};
@@ -0,0 +1,2 @@
1
+ import{listModels as e}from"../utils/helper.mjs";import{listMcpToolNames as t}from"../tools/mcp.mjs";import{getConfigPath as n,loadConfig as r,saveConfig as i}from"../utils/config.mjs";import{extractErrorMessage as a,isObject as o,to as s}from"@nickyzj2023/utils";import c from"node:readline";const l=e=>new Promise(t=>{let n=c.createInterface({input:process.stdin,output:process.stdout});n.question(e,e=>{n.close(),t(e)})}),u=async(e,t)=>(await l(e)).trim()||t,d=async e=>{let n=await u(`名称 [当前为${e?.name??`(新)`}]: `,e?.name);if(!n)return console.log(`名称不能为空,已取消`),null;let r=e?.type??`streamable_http`,i=await u(`类型 streamable_http/sse [当前为${r}]: `,r);if(i!==`streamable_http`&&i!==`sse`)return console.log(`类型无效,已取消`),null;let c=i,d=await u(`URL [当前为${e?.url??`无`}]: `,e?.url);if(!d)return console.log(`URL不能为空,已取消`),null;let f=e?.headers,m=(await l(`headers(JSON对象) [当前为${e?.headers?JSON.stringify(e.headers):`无`}]: `)).trim();if(m)try{let e=JSON.parse(m);o(e)?f=e:console.log(`headers需为JSON对象,已回退到原先的值`)}catch{console.log(`headers解析失败,已回退到原先的值`)}let h=e?.ignoredToolNames,[g,_=[]]=await s(t(d,f?{headers:f}:void 0));g?console.log(`获取工具列表失败:${a(g)}`):(console.log(`该服务器提供的工具:`),_.forEach((e,t)=>{console.log(`${t+1}. ${e}`)}));let v=(await l(`忽略的工具(名称或序号,用逗号分隔,也支持1-5这样的连续序号) [当前为${e?.ignoredToolNames?.join(`,`)??`无`}]: `)).trim();return v&&(h=p(v,_)),{name:n,type:c,url:d,...f?{headers:f}:{},...h?.length?{ignoredToolNames:h}:{}}},f=(e,t)=>{let n=Number(e)-1;return Number.isInteger(n)?t[n]:void 0},p=(e,t)=>{let n=e.split(`,`).map(e=>e.trim()).filter(Boolean).flatMap(e=>{let n=/^(\d+)\s*-\s*(\d+)$/.exec(e);if(!n)return/^\d+$/.test(e)?[t[Number(e)-1]]:[e];let r=Number(n[1]),i=Number(n[2]);return r>i?[]:Array.from({length:i-r+1},(e,n)=>t[r+n-1])}).filter(e=>!!e);return[...new Set(n)]},m=async e=>{for(;;){let t=Object.keys(e);console.log(`
2
+ 当前MCP服务器:`),t.length===0?console.log(`(空)`):t.forEach((t,n)=>{let r=e[t];console.log(` ${n+1}. ${t} ${r?`(${r.type} ${r.url})`:`(配置缺失)`}`)});let n=(await l(`输入数字编辑对应服务器,a添加新服务器,d删除服务器,回车或q结束: `)).trim().toLowerCase();if(!n||n===`q`)break;switch(n){case`a`:{let t=await d();t&&(e[t.name]=t);break}case`d`:{let n=(await l(`输入要删除的服务器编号: `)).trim(),r=f(n,t);if(!r){console.log(`无效编号,请输入列表中的数字`);break}(await l(`确认删除${r}?(y/n): `)).trim().toLowerCase()===`y`?(delete e[r],console.log(`已删除${r}`)):console.log(`已取消删除`);break}default:{let r=f(n,t);if(r){let t=e[r];t||console.log(`该服务器配置缺失,将重新录入`);let n=await d({name:r,...t});n&&(n.name!==r&&console.log(`已重命名 ${r} -> ${n.name}`),delete e[r],e[n.name]=n)}else console.log(`无效选择,请输入列表中的数字、a、d或回车`);break}}}},h=async(t,n,r)=>{let[i,o]=await s(t?e(t,n):Promise.resolve([])),c=o??[];i?console.log(`获取模型列表失败:${a(i)}`):c.length===0?console.log(`服务端未返回任何模型,请手动输入模型名`):(console.log(`可用模型(输入序号快速选择,也可直接输入模型名):`),c.forEach((e,t)=>{console.log(` ${t+1}. ${e}`)}));let u=(await l(`MODEL [当前为${r}]: `)).trim();return f(u,c)||u||r};async function g(){let e=r(),t=await l(`BASE_URL [当前为${e?.baseUrl}]: `)||e?.baseUrl,o=await l(`APIKEY [当前为${e?.apiKey}]: `)||e?.apiKey,s=await h(t,o,e?.model),c={...e?.mcpServers};(await l(`是否配置MCP服务器?(y/n): `)).trim().toLowerCase()===`y`&&await m(c);try{i({baseUrl:t,apiKey:o,model:s,mcpServers:c}),console.log(`配置已保存到${n()},直接运行ai即可开始对话`)}catch(e){console.error(`保存配置失败:${a(e)}`),process.exitCode=1}}export{g as runSetup};
@@ -0,0 +1,6 @@
1
+ import{humanizeNumber as e}from"../utils/internalHelper.mjs";import{readClipboardImage as t}from"../utils/clipboard.mjs";import{compactStr as n}from"@nickyzj2023/utils";import r from"node:readline";import{MarkdownRenderer as i}from"@wterm/markdown";var a=class{rl=null;onPrompt=null;pendingImages=[];clipboardTask=Promise.resolve();md=null;isBusy=!1;isPrompting=!1;prevPrintType=void 0;constructor(e){this.onPrompt=e}start(e){this.rl=r.createInterface({input:process.stdin,output:process.stdout}),process.stdin.on(`keypress`,this.onKeypress),this.rl.on(`close`,()=>{process.stdin.off(`keypress`,this.onKeypress),this.rl?.close(),this.rl=null}),e?(process.stdout.write(`> ${e}\n`),this.submit({text:e,images:[]})):this.prompting()}onKeypress=(e,t)=>{this.isBusy||t?.ctrl&&t?.name===`v`&&(this.clipboardTask=this.clipboardTask.then(()=>this.attachImage()))};prompting(){this.isBusy||(this.isPrompting=!0,this.rl?.question(`> `,async e=>{this.isPrompting=!1,await this.clipboardTask;let t=e.trim(),n=this.pendingImages;if(this.pendingImages=[],!t&&n.length===0){this.prompting();return}await this.submit({text:t,images:n})}))}async submit(e){this.isBusy=!0,await this.onPrompt?.(e),this.isBusy=!1,this.prompting()}async attachImage(){let n=await t();if(!n){this.printNotice(`[剪贴板中没有图片]`);return}if(n.bytes>5242880){this.printNotice(`[图片过大(${e(n.bytes)}B),已忽略]`);return}this.pendingImages.push({type:`image_url`,image_url:{url:n.url}}),this.printNotice(`[已粘贴图片:共${this.pendingImages.length}张]`)}preparePrint(e){if(this.prevPrintType===e)return!1;if(e===`content_delta`&&this.md===null&&(this.md=new i),this.prevPrintType===`content_delta`){let e=this.md?.flush();e&&process.stdout.write(e)}return process.stdout.write(`
2
+ `),this.prevPrintType=e,!0}colorize(e,t){return process.stdout.isTTY?`\x1b[${t}m${e}\x1b[0m`:e}render(e){switch(e.type){case`reasoning_delta`:this.printReasoning(e.delta);break;case`content_delta`:this.printContent(e.delta);break;case`tool_call`:this.printToolCall(e.name,e.args);break;case`result`:this.printContent(e.content);break;case`tool_result`:this.printToolResult(e.name,e.result);break;case`error`:this.printContent(e.message);break;case`done`:this.printFinish(e.finishReason,e.usage)}}printReasoning(e){this.preparePrint(`reasoning_delta`)&&(e=`[思考内容] ${e.replaceAll(`
3
+ `,``)}`),process.stdout.write(this.colorize(e,`90`))}printContent(e){this.preparePrint(`content_delta`);let t=this.md?.push(e);t&&process.stdout.write(t)}printToolCall(e,t){this.preparePrint(`tool_call`),process.stdout.write(`[工具调用:${e}] ${t}\n`)}printToolResult(e,t,r){let{ellipsis:i=!0}=r??{},a=i?n(t,{maxLength:100,truncateMiddle:!0}):t;this.preparePrint(`tool_result`),process.stdout.write(this.colorize(`[工具结果:${e}] ${a}\n`,`90`))}printFinish(t,n){this.preparePrint(`done`),process.stdout.write(this.colorize(`[本轮结束:${t}] ${n?`输入${e(n.prompt_tokens)},输出${e(n.completion_tokens)},总共${e(n.total_tokens)}`:``}${n?.speed?`,速度${n.speed}/秒`:``}${t===`stop`?`
4
+
5
+ `:`
6
+ `}`,`90`))}printNotice(e){process.stdout.write(`${this.colorize(e,`93`)}\n`),this.isPrompting&&this.rl?.prompt(!0)}};export{a as TUI};
package/dist/llm.d.mts ADDED
@@ -0,0 +1,18 @@
1
+ import { Message, Model, NonStreamResult, StreamEvent, ToolDefinition } from "./types.mjs";
2
+ //#region src/llm.d.ts
3
+ /**
4
+ * 流式请求模型,转发
5
+ */
6
+ declare function stream(model: Model, messages: Message[], tools?: ToolDefinition[], options?: Omit<RequestInit, "body"> & {
7
+ body?: Record<string, unknown>;
8
+ }): AsyncGenerator<StreamEvent>;
9
+ /**
10
+ * 非流式请求模型,一次性拿到完整回复
11
+ * @remarks 与stream()共享同一套请求/解析规则,区别在于不做SSE解析
12
+ * @throws 请求失败(含状态码非2xx)、取消(signal.abort)时抛出异常
13
+ */
14
+ declare function nonStream(model: Model, messages: Message[], tools?: ToolDefinition[], options?: Omit<RequestInit, "body"> & {
15
+ body?: Record<string, unknown>;
16
+ }): Promise<NonStreamResult>;
17
+ //#endregion
18
+ export { nonStream, stream };
package/dist/llm.mjs ADDED
@@ -0,0 +1 @@
1
+ import{extractErrorMessage as e,fetcher as t,parseSSE as n,pick as r,to as i}from"@nickyzj2023/utils";const a=e=>[r(e,[`type`,`function`]),r(e,[`execute`])],o=e=>e.reasoning||e.reasoning_content;async function*s(r,s,c=[],l){let u=c.map(e=>a(e)[0]),d=t(r.baseUrl,{headers:{Authorization:`Bearer ${r.apiKey}`},parser:async e=>e}),[f,p]=await i(d.post(`/chat/completions`,{stream:!0,model:r.model,messages:s,tools:u,...l?.body},l));if(f){if(l?.signal?.aborted)return;yield{type:`error`,message:f.message};return}let m=/* @__PURE__ */ new Map,h,g=null;try{for await(let e of n(p)){if(typeof e==`string`)continue;e.usage&&(h=e.usage);let t=e.choices?.[0];if(!t)continue;let{delta:n}=t,{content:r,tool_calls:i}=n,a=o(n);if(a&&(yield{type:`reasoning_delta`,delta:a}),r&&(yield{type:`content_delta`,delta:r.toString()}),i)for(let e of i){let{index:t=0,type:n=`function`,id:r,function:i,...a}=e,o=m.getOrInsert(t,{id:``,type:n,function:{name:``,arguments:``}});r&&(o.id=r),i?.name&&(o.function.name+=i.name),i?.arguments&&(o.function.arguments+=i.arguments),a&&Object.assign(o,a),m.set(t,o)}t.finish_reason&&(g=t.finish_reason)}}catch(t){if(l?.signal?.aborted)return;yield{type:`error`,message:e(t)};return}for(let[,e]of m)yield{type:`tool_call`,id:e.id,name:e.function.name,args:e.function.arguments};yield{type:`done`,finishReason:g,usage:h}}async function c(e,n,r=[],i){let s=r.map(e=>a(e)[0]),c=await t(e.baseUrl,{headers:{Authorization:`Bearer ${e.apiKey}`}}).post(`/chat/completions`,{stream:!1,model:e.model,messages:n,tools:s,...i?.body},i),l=c.choices?.[0],u=l?.message;return{reasoning:u?o(u):void 0,content:typeof u?.content==`string`?u.content:(u?.content??[]).filter(e=>e.type===`text`).map(e=>e.text).join(``),toolCalls:u?.tool_calls??[],finishReason:l?.finish_reason??null,usage:c.usage}}export{c as nonStream,s as stream};
@@ -0,0 +1,5 @@
1
+ import { ToolDefinition } from "../types.mjs";
2
+ //#region src/tools/get-time.d.ts
3
+ declare const getTime: ToolDefinition;
4
+ //#endregion
5
+ export { getTime as default, getTime };
@@ -0,0 +1 @@
1
+ import{defineTool as e}from"../utils/helper.mjs";import{fetcher as t}from"@nickyzj2023/utils";const n=e(`get_time`,`查询指定时区的当前时间`,{timezone:{type:`string`,description:`完整的IANA时区名称,如Europe/Amsterdam。用户未明确提及时,传入对方语言对应的时区,例如对方使用中文时可传入Asia/Shanghai。`,required:!0}},async({timezone:e})=>t(`https://timeapi.io/api`,{params:{timezone:e}}).get(`/time/current/zone`));export{n as default,n as getTime};
@@ -0,0 +1,5 @@
1
+ import { ToolDefinition } from "../types.mjs";
2
+ //#region src/tools/get-weather.d.ts
3
+ declare const getWeather: ToolDefinition;
4
+ //#endregion
5
+ export { getWeather as default, getWeather };
@@ -0,0 +1 @@
1
+ import{defineTool as e}from"../utils/helper.mjs";import{fetcher as t,to as n}from"@nickyzj2023/utils";const r=e=>{let t=String(e??``).padStart(4,`0`);return`${t.slice(0,2)}:${t.slice(2)}`},i=e=>{if(!e)return null;let t=e.nearest_area?.[0]||{};return{location:{city:t.areaName?.[0]?.value||``,region:t.region?.[0]?.value||``,country:t.country?.[0]?.value||``,latitude:t.latitude,longitude:t.longitude},forecast:(e.weather||[]).map(e=>({date:e.date,maxTempC:e.maxtempC,minTempC:e.mintempC,astro:{sunrise:e.astronomy?.[0]?.sunrise||``,sunset:e.astronomy?.[0]?.sunset||``,moonPhase:e.astronomy?.[0]?.moon_phase||``},hourly:(e.hourly||[]).map(e=>({time:r(e.time),tempC:e.tempC,feelsLikeC:e.FeelsLikeC,weatherDesc:e.weatherDesc?.[0]?.value||``,chanceOfRain:e.chanceofrain,precipMM:e.precipMM,humidity:e.humidity,windSpeedKmph:e.windspeedKmph,windDir:e.winddir16Point}))}))}},a=e(`get_weather`,`查询指定城市的天气情况`,{city:{type:`string`,description:`城市名,如shanghai、tokyo`,required:!0}},async({city:e})=>{let r=t(`https://wttr.in`,{params:{format:`j1`}}),[a,o]=await n(r.get(`/${e}`));return a?a.message:i(o)});export{a as default,a as getWeather};
@@ -0,0 +1,3 @@
1
+ import getTime from "./get-time.mjs";
2
+ import getWeather from "./get-weather.mjs";
3
+ export { getTime, getWeather };
@@ -0,0 +1 @@
1
+ import e from"./get-time.mjs";import t from"./get-weather.mjs";export{e as getTime,t as getWeather};
@@ -1,4 +1,4 @@
1
- import { _ as ToolDefinition } from "../types-Bwc1Oqk3.mjs";
1
+ import { ToolDefinition } from "../types.mjs";
2
2
  import { Client } from "@modelcontextprotocol/sdk/client";
3
3
  //#region src/tools/mcp.d.ts
4
4
  type McpServer = {
@@ -1,2 +1 @@
1
- import { n as listMcpToolNames, r as loadMCPTools, t as MCPRouter } from "../mcp-C22GzADk.mjs";
2
- export { MCPRouter, listMcpToolNames, loadMCPTools };
1
+ import{defineTool as e}from"../utils/helper.mjs";import{extractErrorMessage as t,isObject as n,logger as r,omit as i}from"@nickyzj2023/utils";let a=null;const o=async(e,t,n)=>{let[{Client:r},{StreamableHTTPClientTransport:i}]=await Promise.all([import(`@modelcontextprotocol/sdk/client`),import(`@modelcontextprotocol/sdk/client/streamableHttp.js`)]),a=new i(new URL(t),{requestInit:{headers:n?.headers,signal:n?.signal}}),o=new r({name:e,version:`1.0.0`});return await o.connect(a),o},s=async(e,t)=>{let n=await o(`ai-setup`,e,t);try{let{tools:e}=await n.listTools();return e.map(e=>e.name)}finally{await n.close().catch(()=>{})}};var c=class{entries=/* @__PURE__ */ new Map;async addClient(t,r,i){if(this.entries.has(t))return;let a=await o(t,r,i),{tools:s}=await a.listTools(),c=s.filter(e=>!i?.ignoredToolNames?.includes(e.name)).map(t=>{let r={...t.inputSchema.properties??{}};return t.inputSchema.required?.forEach(e=>{n(r[e])&&(r[e]={...r[e],required:!0})}),e(t.name,t.description??``,r,e=>a.callTool({name:t.name,arguments:e}))});return this.entries.set(t,{client:a,tools:c}),a}async getTools(){return[...this.entries.values()].flatMap(e=>e.tools)}};const l=async(e={})=>(a||=new c,await Promise.allSettled(Object.entries(e).map(async([e,n])=>{try{await a?.addClient(e,n.url,i(n,[`type`,`url`]))}catch(n){r(`MCP服务器${e}加载失败:${t(n)}`)}})),a.getTools());export{c as MCPRouter,s as listMcpToolNames,l as loadMCPTools};
@@ -186,4 +186,4 @@ type AgentEvent = StreamEvent | NonStreamEvent | {
186
186
  result: string;
187
187
  };
188
188
  //#endregion
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 };
189
+ export { AgentEvent, AudioContent, ChatCompletionsChunk, ChatCompletionsResponse, ContentPart, FinishReason, ImageContent, Message, Modality, Model, NonStreamEvent, NonStreamResult, RunAgentOptions, StreamEvent, TextContent, ToolCall, ToolDefinition, Usage, VideoContent };
@@ -0,0 +1 @@
1
+ import{execFile as e}from"node:child_process";const t=5242880,n=(t,n,r)=>new Promise((i,a)=>{e(t,n,{encoding:`buffer`,timeout:5e3,maxBuffer:r},(e,t)=>{e?a(e):i(t)})}),r=(e,t=`image/png`)=>({url:`data:${t};base64,${e.toString(`base64`)}`,bytes:e.length}),i=async()=>{let e=[`Add-Type -AssemblyName System.Windows.Forms`,`Add-Type -AssemblyName System.Drawing`,`$img = [System.Windows.Forms.Clipboard]::GetImage()`,`if ($img) {`,`$ms = New-Object System.IO.MemoryStream`,`$img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)`,`[Convert]::ToBase64String($ms.ToArray())`,`}`].join(`; `),t=(await n(`powershell.exe`,[`-NoProfile`,`-Command`,e],67108864)).toString(`utf8`).trim();return t?r(Buffer.from(t,`base64`)):null},a=async()=>{for(let e of[{command:`wl-paste`,args:[`--no-newline`,`--type`,`image/png`]},{command:`xclip`,args:[`-selection`,`clipboard`,`-t`,`image/png`,`-o`]}])try{let i=await n(e.command,e.args,t*2);if(i.length===0)continue;return e.base64?r(Buffer.from(i.toString(`ascii`).trim(),`base64`)):r(i)}catch{}return null},o=async()=>{try{switch(process.platform){case`win32`:return await i();default:return await a()}}catch{return null}};export{t as MAX_CLIPBOARD_IMAGE_BYTES,o as readClipboardImage};
@@ -0,0 +1 @@
1
+ const e=e=>e?.role===`assistant`&&Array.isArray(e.tool_calls),t=e=>{if(e&&Array.isArray(e.content))for(let t of e.content){if(t.type===`image_url`)return`image`;if(t.type===`input_audio`)return`audio`;if(t.type===`video_url`)return`video`}},n=(t,n)=>{let r=n;for(;r>0&&t[r-1]?.role===`tool`;)r--;if(!e(t[r-1]))return null;let i=r;for(;i<t.length&&t[i]?.role===`tool`;)i++;return[r-1,i]};export{n as findToolGroupRange,t as isMediaMessage,e as isToolCalls};
@@ -0,0 +1,15 @@
1
+ import { Message, Model } from "../../types.mjs";
2
+ import { Compact } from "./types.mjs";
3
+ import { compactMediaMessages, compactToolResults, discardMessagesUntil, summarizeMessages } from "./strategy.mjs";
4
+ //#region src/utils/compact/index.d.ts
5
+ /**
6
+ * 自动优化上下文,类似AI Coding Agent的/compact命令
7
+ */
8
+ declare const compact: ((messages: Message[], model: Model, options?: Compact.Options) => Promise<Compact.Result>) & {
9
+ compactToolResults: typeof compactToolResults;
10
+ compactMediaMessages: typeof compactMediaMessages;
11
+ summarizeMessages: typeof summarizeMessages;
12
+ discardMessagesUntil: typeof discardMessagesUntil;
13
+ };
14
+ //#endregion
15
+ export { compact };
@@ -0,0 +1 @@
1
+ import{estimateTokens as e}from"../helper.mjs";import{findToolGroupRange as t}from"./helper.mjs";import{compactMediaMessages as n,compactToolResults as r,discardMessagesUntil as i,summarizeMessages as a}from"./strategy.mjs";import{to as o}from"@nickyzj2023/utils";const s=Object.assign(async(s,c,l)=>{let{usage:u,keepCount:d=10,compactedMessageMark:f=`[已简化]`,ratioToCompactToolResults:p=.6,replacerOfToolResultContent:m,ratioToCompactMedia:h=.7,replacerOfMediaContent:g,ratioToSummarize:_=.8,summarizeOptions:v}=l??{},y=c?.context??131072,b=u?.total_tokens??e(s),x={hasCompactedToolResults:!1,hasCompactedMedia:!1,hasSummarized:!1,hasDiscardMessages:!1},S=Math.max(1,s.length-d);if(s[S]?.role===`tool`){let e=t(s,S);if(e)S=e[1];else for(;s[S]?.role===`tool`;)S++}S=Math.max(1,S);let C=s.slice(0,1),w=s.slice(1,S),T=s.slice(S);if(b>y*p&&(x.hasCompactedToolResults=await r(w,{replacer:m,mark:f,model:c})>0),b>y*h&&(x.hasCompactedMedia=await n(w,{replacer:g,model:c})>0),b>y*_){let{systemPrompt:t=`你现在的任务是总结历史消息`,beforeSummarize:n}=v??{},[r,l]=await o(a(w,{model:c,systemPrompt:t,beforeSummarize:n}));r?x.hasDiscardMessages=i(w,t=>{if(t.length===0)return!0;let n=[...C,...t,...T];return e(n)<y*_})>0:x.hasSummarized=l>0,s.splice(0,1/0,...C,...w,...T)}return x},{compactToolResults:r,compactMediaMessages:n,summarizeMessages:a,discardMessagesUntil:i});export{s as compact};
@@ -0,0 +1,25 @@
1
+ import { Message, Model } from "../../types.mjs";
2
+ import { Compact } from "./types.mjs";
3
+ //#region src/utils/compact/strategy.d.ts
4
+ /**
5
+ * @returns 实际处理了几条消息
6
+ */
7
+ declare const compactToolResults: (compressible: Message[], options: {
8
+ replacer?: Compact.ReplacerOfToolResultContent;
9
+ mark: string;
10
+ model?: Model;
11
+ }) => Promise<number>;
12
+ /**
13
+ * @returns 实际处理了几条消息
14
+ */
15
+ declare const compactMediaMessages: (compressible: Message[], options: {
16
+ replacer?: Compact.ReplacerOfMediaContent;
17
+ model?: Model;
18
+ }) => Promise<number>;
19
+ declare const summarizeMessages: (compressible: Message[], options: Compact.SummarizeOptions) => Promise<number>;
20
+ /**
21
+ * 最终的兜底压缩策略,从头删除旧消息,直到第二个回调函数返回true(达成目标)
22
+ */
23
+ declare const discardMessagesUntil: (compressible: Message[], until: (compressible: Message[]) => boolean) => number;
24
+ //#endregion
25
+ export { compactMediaMessages, compactToolResults, discardMessagesUntil, summarizeMessages };
@@ -0,0 +1 @@
1
+ import{runAgent as e}from"../../agent.mjs";import{findToolGroupRange as t,isMediaMessage as n}from"./helper.mjs";import{createXMLText as r,logger as i}from"@nickyzj2023/utils";const a=async(t,n)=>{let{model:r}=n??{},i=[{role:`user`,content:t},{role:`user`,content:`请用一句话简述上面这条消息(直击要点,不要添加任何前言后语)`}],a=``;if(!r)a=`工具结果已被消费`;else for await(let t of e(r,i))if(t.type===`result`)a=t.content;else if(t.type===`error`)throw Error(t.message);return a},o=async(e,t)=>{let{replacer:n,mark:r,model:o}=t??{};if(!n&&!o)return 0;let s=n||a,c=0;for(let t of e)if(t?.role===`tool`&&typeof t.content==`string`){if(t.content.startsWith(r))continue;t.content=r+await s(t.content,{model:o}),c++}return c>0&&i(`压缩了${c}条工具调用结果`),c},s=async(t,n)=>{let{model:r,modality:i=`image`}=n??{},a=[{role:`user`,content:t},{role:`user`,content:`请用一句话简述上面这条消息(直击要点,不要添加任何前言后语)`}],o=``;if(!r?.modalities?.includes(i))o=`媒体资源已被消费`;else for await(let t of e(r,a))if(t.type===`result`)o=t.content;else if(t.type===`error`)throw Error(t.message);return o},c=async(e,t)=>{let{replacer:a,model:o}=t??{};if(!a&&!o)return 0;let c=a||s,l=0;for(let t of e){let e=n(t);if(e){let n=await c(t.content,{model:o,modality:e});t.content=r(`media`,n),l++}}return l>0&&i(`压缩了${l}条多模态消息`),l},l=async(t,n)=>{let{model:a,systemPrompt:o,beforeSummarize:s}=n??{},c=t.slice(1);if(c.length===0)return i(`消息太少,无需总结`),0;await s?.(c);let l=c.length;c.push({role:`system`,content:o},{role:`user`,content:`开始总结上下文`});let u=``,d;for await(let t of e(a,c))if(t.type===`result`)u=t.content,d=t.usage;else if(t.type===`error`)throw Error(t.message);return t.splice(1,1/0,{role:`user`,content:r(`summary`,u)}),i(`总结了${l}条消息,消耗:`,d),l},u=(e,n)=>{let r=0;for(;e.length>0&&!n(e);){let n=Math.max(1,Math.floor(e.length/10));if(e[n]?.role===`tool`){let r=t(e,n);if(r)n=r[1];else for(;e[n]?.role===`tool`;)n++}r+=e.splice(0,n).length}return i(`丢弃了${r}条旧消息`),r};export{c as compactMediaMessages,o as compactToolResults,u as discardMessagesUntil,l as summarizeMessages};
@@ -0,0 +1,78 @@
1
+ import { Message, Modality, Model, Usage } from "../../types.mjs";
2
+ //#region src/utils/compact/types.d.ts
3
+ declare namespace Compact {
4
+ type Options = {
5
+ /** 提供token消耗情况时,能更准确地判断上下文是否达到阈值 */
6
+ usage?: Usage;
7
+ /**
8
+ * 各种压缩方式统一保留的最近消息条数
9
+ * @default 10
10
+ * @remarks 压缩工具调用结果、压缩媒体消息、总结消息、硬删除兜底都会保留最近keepCount条消息不处理
11
+ */
12
+ keepCount?: number;
13
+ /**
14
+ * 压缩工具/媒体消息时做个标记,防止下次重复压缩
15
+ * @default "[已压缩]"
16
+ */
17
+ compactedMessageMark?: string;
18
+ /**
19
+ * 上下文>总上下文*ratio时压缩工具调用结果
20
+ * @default 0.6
21
+ */
22
+ ratioToCompactToolResults?: number;
23
+ /**
24
+ * 如何压缩工具调用结果
25
+ * @default 让其他模型返回简化后的工具结果
26
+ */
27
+ replacerOfToolResultContent?: Compact.ReplacerOfToolResultContent;
28
+ /**
29
+ * 上下文>总上下文*ratio时压缩图片/音频/视频消息
30
+ * @default 0.7
31
+ */
32
+ ratioToCompactMedia?: number;
33
+ /**
34
+ * 如何压缩媒体消息
35
+ * @default 让其他模型用自然语言简短描述一遍
36
+ */
37
+ replacerOfMediaContent?: Compact.ReplacerOfMediaContent;
38
+ /**
39
+ * 上下文>总上下文*ratio时总结消息
40
+ * @default 0.8
41
+ * @remarks 如果总结成功,会把keepCount以前的消息压成一条用户消息
42
+ */
43
+ ratioToSummarize?: number;
44
+ /**
45
+ * 总结消息时的配置项
46
+ * @default { systemPrompt: "你现在的任务是总结历史消息" }
47
+ */
48
+ summarizeOptions?: Partial<Compact.SummarizeOptions>;
49
+ };
50
+ type ReplacerOfToolResultContent = (content: Message["content"], options?: {
51
+ model?: Model;
52
+ [key: string]: any;
53
+ }) => Promise<string> | string;
54
+ type ReplacerOfMediaContent = (content: Message["content"], options?: {
55
+ model?: Model;
56
+ modality?: Modality;
57
+ [key: string]: any;
58
+ }) => Promise<string> | string;
59
+ type SummarizeOptions = {
60
+ /** 指导大模型如何总结消息 */
61
+ systemPrompt: string;
62
+ model: Model;
63
+ /** 触发总结前的钩子 */
64
+ beforeSummarize?: (summarizable: Message[]) => void | Promise<void>;
65
+ };
66
+ type Result = {
67
+ /** 是否压缩了工具调用结果 */
68
+ hasCompactedToolResults: boolean;
69
+ /** 是否压缩了图片/音频/视频消息 */
70
+ hasCompactedMedia: boolean;
71
+ /** 是否总结了消息 */
72
+ hasSummarized: boolean;
73
+ /** 是否丢弃了一些旧消息(最终兜底策略) */
74
+ hasDiscardMessages: boolean;
75
+ };
76
+ }
77
+ //#endregion
78
+ export { Compact };
@@ -0,0 +1 @@
1
+ import{mkdirSync as e,readFileSync as t,writeFileSync as n}from"node:fs";import{homedir as r}from"node:os";import{dirname as i,join as a}from"node:path";const o=()=>a(r(),`.@nickyzj2023`,`ai`,`config.json`),s=()=>{try{let e=JSON.parse(t(o(),`utf8`));return typeof e.baseUrl!=`string`||typeof e.apiKey!=`string`||typeof e.model!=`string`?null:e}catch{return null}},c=t=>{let r=o();e(i(r),{recursive:!0}),n(r,`${JSON.stringify(t,null,2)}\n`,`utf8`)};export{o as getConfigPath,s as loadConfig,c as saveConfig};
@@ -0,0 +1,30 @@
1
+ import { Message, Model, ToolDefinition } from "../types.mjs";
2
+ //#region src/utils/helper.d.ts
3
+ /**
4
+ * 辅助定义一个POST /chat/completions支持的model参数
5
+ * @remarks 只有baseUrl字段是必须的
6
+ */
7
+ declare const defineModel: (config: Model) => Model;
8
+ /**
9
+ * 辅助定义一个POST /chat/completions支持的tool对象
10
+ * @param execute 实际执行工具的函数
11
+ */
12
+ declare const defineTool: (name: ToolDefinition["function"]["name"], description: ToolDefinition["function"]["description"], properties: ToolDefinition["function"]["parameters"]["properties"], execute: ToolDefinition["execute"]) => ToolDefinition;
13
+ declare const estimateTextTokens: (text: string) => number;
14
+ /**
15
+ * 列出GET /models返回的模型id
16
+ * @param baseUrl 接口前缀,如http://127.0.0.1:11434/v1
17
+ * @param apiKey 本地llama.cpp等不校验鉴权的服务可以不传,不传就不带Authorization头
18
+ * @returns 模型的id列表
19
+ * @remarks 请求失败(服务没起、鉴权不过等)会抛异常,由调用方自行兜底
20
+ */
21
+ declare const listModels: (baseUrl: string, apiKey?: string) => Promise<string[]>;
22
+ /**
23
+ * 根据上下文里的中/英文/多模态消息,估算出可能消耗的token
24
+ * - 单词 ≈ 1.5token
25
+ * - 标点/空白等非词字符每4个 ≈ 1token
26
+ * - 图片/音频/视频/文件 ≈ 4096token(不好估算,取个较大的值)
27
+ */
28
+ declare const estimateTokens: (messages?: Message[]) => number;
29
+ //#endregion
30
+ export { defineModel, defineTool, estimateTextTokens, estimateTokens, listModels };
@@ -0,0 +1 @@
1
+ import{fetcher as e}from"@nickyzj2023/utils";const t=e=>({modalities:[`text`],context:131072,...e}),n=(e,t,n,r)=>{let i=[];return{type:`function`,function:{name:e,description:t,parameters:{type:`object`,properties:Object.entries(n).reduce((e,[t,n])=>(`required`in n&&(i.push(t),delete n.required),e[t]=n,e),{}),required:i}},execute:r}},r=new Intl.Segmenter([],{granularity:`word`}),i=e=>{let t=0,n=0;for(let i of r.segment(e))i.isWordLike?t++:n++;return Math.ceil(t*1.5+n/4)},a=async(t,n)=>{let{data:r}=await e(t,{headers:n?{Authorization:`Bearer ${n}`}:void 0}).get(`/models`);return(r??[]).map(e=>e.id).filter(e=>typeof e==`string`)},o=e=>e?.length?e.reduce((e,t)=>{let{content:n,tool_calls:r,...a}=t;if(typeof n==`string`)e+=i(n);else for(let t of n)t.type===`text`?e+=i(t.text):e+=4096;return r&&(e+=i(JSON.stringify(r))),e+=i(JSON.stringify(a)),e},0):0;export{t as defineModel,n as defineTool,i as estimateTextTokens,o as estimateTokens,a as listModels};
@@ -0,0 +1 @@
1
+ import{estimateTextTokens as e,estimateTokens as t}from"./helper.mjs";const n=new Intl.NumberFormat(`en-US`,{notation:`compact`,maximumFractionDigits:1}),r=e=>n.format(e),i=(n,r,i)=>{let a=t(n.slice(-1)),o=e(r+i);return{prompt_tokens:a,completion_tokens:o,total_tokens:t(n)+a+o}},a=(e,t)=>(e.speed=Math.floor(e.completion_tokens/((Date.now()-t)/1e3)),e);export{i as estimateFallbackUsage,r as humanizeNumber,a as withSpeed};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nickyzj2023/ai",
3
- "version": "1.7.0",
3
+ "version": "1.7.1",
4
4
  "description": "我的“pi”,参考了pi-from-scratch",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -10,10 +10,27 @@
10
10
  "types": "./dist/index.d.mts",
11
11
  "import": "./dist/index.mjs"
12
12
  },
13
+ "./agent": {
14
+ "types": "./dist/agent.d.mts",
15
+ "import": "./dist/agent.mjs"
16
+ },
17
+ "./llm": {
18
+ "types": "./dist/llm.d.mts",
19
+ "import": "./dist/llm.mjs"
20
+ },
21
+ "./compact": {
22
+ "types": "./dist/utils/compact/index.d.mts",
23
+ "import": "./dist/utils/compact/index.mjs"
24
+ },
25
+ "./tools": {
26
+ "types": "./dist/tools/index.d.mts",
27
+ "import": "./dist/tools/index.mjs"
28
+ },
13
29
  "./mcp": {
14
30
  "types": "./dist/tools/mcp.d.mts",
15
31
  "import": "./dist/tools/mcp.mjs"
16
- }
32
+ },
33
+ "./package.json": "./package.json"
17
34
  },
18
35
  "files": [
19
36
  "dist"
@@ -40,8 +57,12 @@
40
57
  "@nickyzj2023/utils": "^1.0.95",
41
58
  "@wterm/markdown": "^0.5.4"
42
59
  },
60
+ "sideEffects": [
61
+ "./dist/cli.mjs",
62
+ "./dist/interfaces/**"
63
+ ],
43
64
  "scripts": {
44
- "build": "tsdown",
65
+ "build": "tsdown && node scripts/check-dist.mjs",
45
66
  "check": "biome check --diagnostic-level=error --write src/",
46
67
  "typecheck": "tsc --noEmit"
47
68
  }
@@ -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 };