@nickyzj2023/ai 1.7.5 → 1.7.7
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 +137 -104
- package/dist/cli.mjs +9 -2
- package/dist/index.d.mts +348 -6
- package/dist/index.mjs +1 -1
- package/dist/tools/mcp.d.mts +49 -9
- package/dist/tools/mcp.mjs +1 -1
- package/package.json +7 -26
- package/dist/agent.d.mts +0 -15
- package/dist/agent.mjs +0 -1
- package/dist/interfaces/setup.mjs +0 -2
- package/dist/interfaces/tui.mjs +0 -6
- package/dist/llm.d.mts +0 -18
- package/dist/llm.mjs +0 -1
- package/dist/tools/get-time.d.mts +0 -5
- package/dist/tools/get-time.mjs +0 -1
- package/dist/tools/get-weather.d.mts +0 -5
- package/dist/tools/get-weather.mjs +0 -1
- package/dist/tools/index.d.mts +0 -3
- package/dist/tools/index.mjs +0 -1
- package/dist/types.d.mts +0 -194
- package/dist/utils/clipboard.mjs +0 -1
- package/dist/utils/compact/helper.mjs +0 -1
- package/dist/utils/compact/index.d.mts +0 -15
- package/dist/utils/compact/index.mjs +0 -1
- package/dist/utils/compact/strategy.d.mts +0 -25
- package/dist/utils/compact/strategy.mjs +0 -1
- package/dist/utils/compact/types.d.mts +0 -78
- package/dist/utils/config.mjs +0 -1
- package/dist/utils/helper.d.mts +0 -30
- package/dist/utils/helper.mjs +0 -1
- package/dist/utils/internalHelper.mjs +0 -1
package/README.md
CHANGED
|
@@ -1,104 +1,137 @@
|
|
|
1
|
-
# ai
|
|
2
|
-
|
|
3
|
-
男生自用Coding Agent,参考了[nanopi教学](https://pi-from-scratch.vercel.app/)
|
|
4
|
-
|
|
5
|
-
不断学习+开发中,当前项目仍属于比nano还简陋的“bare-pi”,but one day...
|
|
6
|
-
|
|
7
|
-

|
|
8
|
-
|
|
9
|
-
## 安装
|
|
10
|
-
|
|
11
|
-
```bash
|
|
12
|
-
# npm
|
|
13
|
-
npm install @nickyzj2023/ai
|
|
14
|
-
|
|
15
|
-
# yarn
|
|
16
|
-
yarn add @nickyzj2023/ai
|
|
17
|
-
|
|
18
|
-
# pnpm
|
|
19
|
-
pnpm add @nickyzj2023/ai
|
|
20
|
-
```
|
|
21
|
-
|
|
22
|
-
## 使用方式
|
|
23
|
-
|
|
24
|
-
### 在项目里使用
|
|
25
|
-
|
|
26
|
-
```typescript
|
|
27
|
-
|
|
28
|
-
//
|
|
29
|
-
import {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
//
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
//
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
//
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
1
|
+
# ai
|
|
2
|
+
|
|
3
|
+
男生自用Coding Agent,参考了[nanopi教学](https://pi-from-scratch.vercel.app/)
|
|
4
|
+
|
|
5
|
+
不断学习+开发中,当前项目仍属于比nano还简陋的“bare-pi”,but one day...
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
## 安装
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
# npm
|
|
13
|
+
npm install @nickyzj2023/ai
|
|
14
|
+
|
|
15
|
+
# yarn
|
|
16
|
+
yarn add @nickyzj2023/ai
|
|
17
|
+
|
|
18
|
+
# pnpm
|
|
19
|
+
pnpm add @nickyzj2023/ai
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## 使用方式
|
|
23
|
+
|
|
24
|
+
### 在项目里使用
|
|
25
|
+
|
|
26
|
+
```typescript
|
|
27
|
+
// Agent循环、内置工具、compact等辅助方法都可以从入口引入
|
|
28
|
+
// 没用到的模块会在构建时摇掉,配置见下一节
|
|
29
|
+
import {
|
|
30
|
+
defineModel,
|
|
31
|
+
defineTool,
|
|
32
|
+
getTime,
|
|
33
|
+
getWeather,
|
|
34
|
+
runAgent,
|
|
35
|
+
type Message,
|
|
36
|
+
} from "@nickyzj2023/ai";
|
|
37
|
+
// 只有MCP要单独引入,因为它会额外引入200kb的MCP SDK
|
|
38
|
+
import { loadMCPTools } from "@nickyzj2023/ai/mcp";
|
|
39
|
+
|
|
40
|
+
const model = defineModel({
|
|
41
|
+
baseUrl: "https://api.deepseek.com/v1",
|
|
42
|
+
apiKey: process.env.APIKEY,
|
|
43
|
+
model: "deepseek-flash",
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const tools = [
|
|
47
|
+
// 内置工具
|
|
48
|
+
getWeather,
|
|
49
|
+
getTime,
|
|
50
|
+
// MCP工具
|
|
51
|
+
...(await loadMCPTools({
|
|
52
|
+
exa: {
|
|
53
|
+
type: "streamable_http",
|
|
54
|
+
url: "https://mcp.exa.ai/mcp",
|
|
55
|
+
headers: {
|
|
56
|
+
"x-api-key": "xxxxx",
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
})),
|
|
60
|
+
// 自定义工具
|
|
61
|
+
defineTool("square", "把一个数字平方", { num: {type: "number", description: "一个数字"} }, ({ num }) => num ** 2),
|
|
62
|
+
];
|
|
63
|
+
|
|
64
|
+
const messages: Message[] = [{ role: "user", content: "查询上海天气" }];
|
|
65
|
+
|
|
66
|
+
// Agent层的用法(推荐)
|
|
67
|
+
// 流式传输,思考/回复内容会逐token输出,工具调用会收集完模型的调用请求后一次性执行完
|
|
68
|
+
for await (const e of runAgent(model, messages, { tools, stream: true })) {
|
|
69
|
+
console.log(e);
|
|
70
|
+
}
|
|
71
|
+
// 默认的非流式,done事件包含了本轮完整的reasoning/content/usage等信息
|
|
72
|
+
for await (const e of runAgent(model, messages, { tools })) {
|
|
73
|
+
if (e.type === "done") console.log(e.content);
|
|
74
|
+
else if (e.type === "error") console.log(e.message);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// LLM层的用法(Agent用的就是它们,stream/nonStream函数只对模型的响应事件做了转发)
|
|
78
|
+
// 流式传输,和runAgent + stream:true没啥区别
|
|
79
|
+
for await (const e of stream(model, messages, tools)) {
|
|
80
|
+
console.log(e);
|
|
81
|
+
}
|
|
82
|
+
// 非流式,直接拿到最终结果
|
|
83
|
+
const result = await nonStream(model, messages, tools);
|
|
84
|
+
console.log(result.content, result.usage);
|
|
85
|
+
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### 让打包器摇掉没用到的模块
|
|
89
|
+
|
|
90
|
+
#### 基于tsdown的后端项目
|
|
91
|
+
|
|
92
|
+
tsdown默认把`dependencies`外置,那样`@nickyzj2023/ai`根本不会进打包流程,也就没有摇树
|
|
93
|
+
|
|
94
|
+
需要显式把它打进产物:
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
// tsdown.config.ts
|
|
98
|
+
import { defineConfig } from "tsdown";
|
|
99
|
+
|
|
100
|
+
export default defineConfig({
|
|
101
|
+
entry: ["src/index.ts"],
|
|
102
|
+
format: ["esm"],
|
|
103
|
+
platform: "node",
|
|
104
|
+
deps: {
|
|
105
|
+
// 始终把本项目打进产物
|
|
106
|
+
// 旧版tsdown里这个字段叫`noExternal`
|
|
107
|
+
alwaysBundle: [/^@nickyzj2023\/ai(\/|$)/],
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
效果:只import`runAgent`时产物约3.9KB,只import`getWeather`时约1.1KB,没用到的函数都不在产物里
|
|
113
|
+
|
|
114
|
+
#### 基于vite的前端项目
|
|
115
|
+
|
|
116
|
+
生产构建走Rollup,`build.rollupOptions.treeshake`默认开启,所以`vite.config.ts`不用为它做任何事,正常import即可
|
|
117
|
+
|
|
118
|
+
### 在终端里使用
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
# 首次使用:交互式配置BASE_URL / APIKEY / MODEL / ...
|
|
122
|
+
ai setup
|
|
123
|
+
|
|
124
|
+
# 启动对话
|
|
125
|
+
ai
|
|
126
|
+
|
|
127
|
+
# 直接开聊,本质是“ai->输入提示词->回车”的语法糖
|
|
128
|
+
ai 你好
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
配置保存在 `~/.@nickyzj2023/ai/config.json`,任意目录下执行`ai`都能读取到
|
|
132
|
+
|
|
133
|
+
终端里的`ai`还会把MCP工具列表缓存到同目录的`mcp-cache.json`:MCP配置没变时开聊直接读缓存,连服务器推迟到真正调用某个MCP工具时;配置变过(`ai setup`里改的)才会重新拉一遍工具并覆盖缓存。这份缓存只属于全局安装的CLI,在项目里`import loadMCPTools`的用法不读写它
|
|
134
|
+
|
|
135
|
+
## License
|
|
136
|
+
|
|
137
|
+
ISC
|
package/dist/cli.mjs
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
|
-
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{compactStr as e,extractErrorMessage as t,fetcher as n,isObject as r,logger as i,omit as a,parseSSE as o,pick as s,to as c}from"@nickyzj2023/utils";import l from"node:readline";import{mkdirSync as u,readFileSync as d,writeFileSync as f}from"node:fs";import{homedir as p}from"node:os";import{dirname as m,join as h}from"node:path";import{MarkdownRenderer as g}from"@wterm/markdown";import{execFile as _}from"node:child_process";const v=e=>({modalities:[`text`],context:131072,...e}),y=(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}},ee=new Intl.Segmenter([],{granularity:`word`}),b=e=>{let t=0,n=0;for(let r of ee.segment(e))r.isWordLike?t++:n++;return Math.ceil(t*1.5+n/4)},x=async(e,t)=>{let{data:r}=await n(e,{headers:t?{Authorization:`Bearer ${t}`}:void 0}).get(`/models`);return(r??[]).map(e=>e.id).filter(e=>typeof e==`string`)},S=e=>e?.length?e.reduce((e,t)=>{let{content:n,tool_calls:r,...i}=t;if(typeof n==`string`)e+=b(n);else for(let t of n)t.type===`text`?e+=b(t.text):e+=4096;return r&&(e+=b(JSON.stringify(r))),e+=b(JSON.stringify(i)),e},0):0,C=({id:e,function:t,...n})=>({...n,type:`tool_call`,id:e,name:t.name,args:t.arguments}),w=({id:e,name:t,args:n,...r})=>({...r,id:e,type:`function`,function:{name:t,arguments:n}}),T=new Intl.NumberFormat(`en-US`,{notation:`compact`,maximumFractionDigits:1}),E=e=>T.format(e),te=(e,t,n)=>{let r=S(e.slice(-1)),i=b(t+n);return{prompt_tokens:r,completion_tokens:i,total_tokens:S(e)+r+i}},D=(e,t)=>(e.speed=Math.floor(e.completion_tokens/((Date.now()-t)/1e3)),e),O=e=>[s(e,[`type`,`function`]),s(e,[`execute`])],k=e=>{let{baseUrl:t,apiKey:n,modalities:r,context:i,mcpServers:a,...o}=e;return[o,{baseUrl:t,apiKey:n,modalities:r,context:i,mcpServers:a}]},A=e=>e.reasoning||e.reasoning_content;async function*j(e,r,i=[],s){let[l,{baseUrl:u,apiKey:d}]=k(e),f=i.map(e=>O(e)[0]),p=n(u,{headers:{Authorization:`Bearer ${d}`},parser:async e=>e}),[m,h]=await c(p.post(`/chat/completions`,{stream:!0,messages:r,tools:f,...l,...s?.body},a(s??{},[`body`])));if(m){if(s?.signal?.aborted)return;yield{type:`error`,message:m.message};return}let g=/* @__PURE__ */ new Map,_,v=null;try{for await(let e of o(h)){if(typeof e==`string`)continue;e.usage&&(_=e.usage);let t=e.choices?.[0];if(!t)continue;let{delta:n}=t,{content:r,tool_calls:i}=n,a=A(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,type:n=`function`,id:r,function:i,...a}=e,o=t??r,s=g.getOrInsert(o,{id:``,type:n,function:{name:``,arguments:``}});r&&(s.id=r),i?.name&&(s.function.name+=i.name),i?.arguments&&(s.function.arguments+=i.arguments),Object.keys(a).length>0&&Object.assign(s,a),g.set(o,s)}t.finish_reason&&(v=t.finish_reason)}}catch(e){if(s?.signal?.aborted)return;yield{type:`error`,message:t(e)};return}for(let[,e]of g)yield C(e);yield{type:`done`,finishReason:v,usage:_}}async function ne(e,t,r=[],i){let[o,{baseUrl:s,apiKey:c}]=k(e),l=r.map(e=>O(e)[0]),u=await n(s,{headers:{Authorization:`Bearer ${c}`}}).post(`/chat/completions`,{stream:!1,messages:t,tools:l,...o,...i?.body},a(i??{},[`body`])),d=u.choices?.[0],f=d?.message;return{reasoning:f?A(f):void 0,content:typeof f?.content==`string`?f.content:(f?.content??[]).filter(e=>e.type===`text`).map(e=>e.text).join(``),toolCalls:f?.tool_calls??[],finishReason:d?.finish_reason??null,usage:u.usage}}async function*re(e,t,n){let{tools:r=[],stream:i=!1}=n??{},a=new Map(r.map(e=>[e.function.name,e]));for(;;){let n=``,o=``,s=[],l=null,u,d=Date.now();if(i)for await(let i of j(e,t,r))switch(i.type){case`reasoning_delta`:yield i,n+=i.delta;break;case`content_delta`:yield i,o+=i.delta;break;case`tool_call`:yield i,s.push(w(i));break;case`error`:yield i;return;case`done`:l=i.finishReason,u=i.usage}else{let[i,a]=await c(ne(e,t,r));if(i){yield{type:`error`,message:i.message};return}for(let e of a.toolCalls)yield C(e),s.push(e);n=a.reasoning??``,o=a.content,l=a.finishReason,u=a.usage}u=D(u??te(t,o,n),d),yield{type:`done`,content:o,reasoning:n,finishReason:l,usage:u};let f={role:`assistant`,content:o};if(s.length>0&&(f.tool_calls=s),t.push(f),s.length===0)return;for(let e of s){let{name:n,arguments:r}=e.function,i=a.get(n),o=``;if(!i)o=`不存在工具“${n}”`;else{let[e,t]=await c(i.execute(JSON.parse(r)));o=e?`工具“${n}”执行出错:${e.message}`:JSON.stringify(t)}let s={type:`tool_result`,id:e.id,name:n,result:o};yield s,t.push({role:`tool`,tool_call_id:e.id,content:s.result})}}}const ie=y(`get_time`,`查询指定时区的当前时间`,{timezone:{type:`string`,description:`完整的IANA时区名称,如Europe/Amsterdam。用户未明确提及时,传入对方语言对应的时区,例如对方使用中文时可传入Asia/Shanghai。`,required:!0}},async({timezone:e})=>n(`https://timeapi.io/api`,{params:{timezone:e}}).get(`/time/current/zone`)),ae=e=>{let t=String(e??``).padStart(4,`0`);return`${t.slice(0,2)}:${t.slice(2)}`},oe=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:ae(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}))}))}},se=y(`get_weather`,`查询指定城市的天气情况`,{city:{type:`string`,description:`城市名,如shanghai、tokyo`,required:!0}},async({city:e})=>{let t=n(`https://wttr.in`,{params:{format:`j1`}}),[r,i]=await c(t.get(`/${e}`));return r?r.message:oe(i)});let M=null;const N=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},ce=async(e,t)=>{let n=await N(`ai-setup`,e,t);try{let{tools:e}=await n.listTools();return e.map(e=>e.name)}finally{await n.close().catch(()=>{})}},le=(e,t)=>{let n={...e.inputSchema.properties??{}};return e.inputSchema.required?.forEach(e=>{r(n[e])&&(n[e]={...n[e],required:!0})}),y(e.name,e.description??``,n,t)},ue=(e,t)=>JSON.stringify(a(e,[`tools`]))===JSON.stringify(a(t,[`tools`]));var P=class{entries=/* @__PURE__ */ new Map;async addServer(e,t,n){let r=this.register(e,t);if(r.tools)return;let i=t.tools??await this.listTools(e);n?.(e,i);let a=t.ignoredToolNames??[];r.tools=i.filter(e=>!a.includes(e.name)).map(t=>le(t,n=>this.callTool(e,t.name,n)))}async addClient(e,t,n){return await this.addServer(e,{type:`streamable_http`,url:t,...n}),this.getClient(e)}async getTools(){return[...this.entries.values()].flatMap(e=>e.tools??[])}register(e,t){let n=this.entries.get(e);if(n&&ue(n.server,t))return n;let r={server:t,tools:null};return this.entries.set(e,r),r}async listTools(e){let{tools:t}=await(await this.getClient(e)).listTools();return t}getClient(e){let t=this.entries.get(e);if(!t)throw Error(`MCP服务器${e}未注册`);return t.client??=N(e,t.server.url,a(t.server,[`type`,`url`,`tools`])).catch(e=>{throw t.client=void 0,e}),t.client}async callTool(e,t,n){return(await this.getClient(e)).callTool({name:t,arguments:n})}};const F=async(e={},n)=>(M||=new P,await Promise.allSettled(Object.entries(e).map(async([e,r])=>{try{await M?.addServer(e,r,n)}catch(n){i(`MCP服务器${e}加载失败:${t(n)}`)}})),M.getTools()),I=()=>h(p(),`.@nickyzj2023`,`ai`,`config.json`),L=()=>h(m(I()),`mcp-cache.json`),R=()=>{try{let e=JSON.parse(d(I(),`utf8`));return typeof e.baseUrl!=`string`||typeof e.apiKey!=`string`||typeof e.model!=`string`?null:e}catch{return null}},z=e=>{let t=I();u(m(t),{recursive:!0}),f(t,`${JSON.stringify(e,null,2)}\n`,`utf8`)},B=e=>a(e,[`tools`]),V=(e,t)=>JSON.stringify(e)===JSON.stringify(t),H=()=>{try{let e=JSON.parse(d(L(),`utf8`));return r(e)?e:{}}catch{return{}}},de=e=>{try{let t=L();u(m(t),{recursive:!0}),f(t,`${JSON.stringify(e,null,2)}\n`,`utf8`)}catch(e){i(`MCP工具缓存写入失败:${t(e)}`)}},U=async(e={})=>{let t=H(),n={};for(let[r,i]of Object.entries(e)){let e=B(i),a=t[r];n[r]=a&&V(a.server,e)?{...e,tools:a.tools}:e}let r=await F(n,(e,r)=>{let i=n[e];i&&(t[e]={server:B(i),tools:r})}),i={};for(let[e,r]of Object.entries(n)){let n=t[e];n&&V(n.server,B(r))&&(i[e]=n)}return de(i),r},W=e=>new Promise(t=>{let n=l.createInterface({input:process.stdin,output:process.stdout});n.question(e,e=>{n.close(),t(e)})}),G=async(e,t)=>(await W(e)).trim()||t,K=async e=>{let n=await G(`名称 [当前为${e?.name??`(新)`}]: `,e?.name);if(!n)return console.log(`名称不能为空,已取消`),null;let i=e?.type??`streamable_http`,a=await G(`类型 streamable_http/sse [当前为${i}]: `,i);if(a!==`streamable_http`&&a!==`sse`)return console.log(`类型无效,已取消`),null;let o=a,s=await G(`URL [当前为${e?.url??`无`}]: `,e?.url);if(!s)return console.log(`URL不能为空,已取消`),null;let l=e?.headers,u=(await W(`headers(JSON对象) [当前为${e?.headers?JSON.stringify(e.headers):`无`}]: `)).trim();if(u)try{let e=JSON.parse(u);r(e)?l=e:console.log(`headers需为JSON对象,已回退到原先的值`)}catch{console.log(`headers解析失败,已回退到原先的值`)}let d=e?.ignoredToolNames,[f,p=[]]=await c(ce(s,l?{headers:l}:void 0));f?console.log(`获取工具列表失败:${t(f)}`):(console.log(`该服务器提供的工具:`),p.forEach((e,t)=>{console.log(`${t+1}. ${e}`)}));let m=(await W(`忽略的工具(名称或序号,用逗号分隔,也支持1-5这样的连续序号) [当前为${e?.ignoredToolNames?.join(`,`)??`无`}]: `)).trim();return m&&(d=fe(m,p)),{name:n,type:o,url:s,...l?{headers:l}:{},...d?.length?{ignoredToolNames:d}:{}}},q=(e,t)=>{let n=Number(e)-1;return Number.isInteger(n)?t[n]:void 0},fe=(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)]},pe=async e=>{let t=!1;for(;;){let n=Object.keys(e);console.log(`
|
|
3
|
+
当前MCP服务器:`),n.length===0?console.log(`(空)`):n.forEach((t,n)=>{let r=e[t];console.log(` ${n+1}. ${t} ${r?`(${r.type} ${r.url})`:`(配置缺失)`}`)});let r=(await W(`输入数字编辑对应服务器,a添加新服务器,d删除服务器,回车或q结束: `)).trim().toLowerCase();if(!r||r===`q`)break;switch(r){case`a`:{let n=await K();n&&(e[n.name]=n,t=!0);break}case`d`:{let r=(await W(`输入要删除的服务器编号: `)).trim(),i=q(r,n);if(!i){console.log(`无效编号,请输入列表中的数字`);break}(await W(`确认删除${i}?(y/n): `)).trim().toLowerCase()===`y`?(delete e[i],t=!0,console.log(`已删除${i}`)):console.log(`已取消删除`);break}default:{let i=q(r,n);if(i){let n=e[i];n||console.log(`该服务器配置缺失,将重新录入`);let r=await K({name:i,...n});r&&(r.name!==i&&console.log(`已重命名 ${i} -> ${r.name}`),delete e[i],e[r.name]=r,t=!0)}else console.log(`无效选择,请输入列表中的数字、a、d或回车`);break}}}if(t){console.log(`正在加载MCP工具并写入缓存……`);let t=await U(e);console.log(`已缓存${t.length}个MCP工具,之后聊天无需等待MCP加载\n`)}},me=async(e,n,r)=>{let[i,a]=await c(e?x(e,n):Promise.resolve([])),o=a??[];i?console.log(`获取模型列表失败:${t(i)}`):o.length===0?console.log(`服务端未返回任何模型,请手动输入模型名`):(console.log(`可用模型(输入序号快速选择,也可直接输入模型名):`),o.forEach((e,t)=>{console.log(` ${t+1}. ${e}`)}));let s=(await W(`MODEL [当前为${r}]: `)).trim();return q(s,o)||s||r},he=async e=>{let t=(await W(`自定义请求体(单行JSON对象,{}表示清空) [当前为${e?JSON.stringify(e):`无`}]: `)).trim();if(!t)return e;try{let n=JSON.parse(t);return r(n)?Object.keys(n).length?n:void 0:(console.log(`自定义请求体需为JSON对象,已沿用原先的值`),e)}catch{return console.log(`自定义请求体解析失败,已沿用原先的值`),e}};async function ge(){let e=R(),n=await W(`BASE_URL [当前为${e?.baseUrl}]: `)||e?.baseUrl,r=await W(`APIKEY [当前为${e?.apiKey}]: `)||e?.apiKey,i=await me(n,r,e?.model),a=await he(e?.body),o={...e?.mcpServers};(await W(`是否配置MCP服务器?(y/n): `)).trim().toLowerCase()===`y`&&await pe(o);try{z({baseUrl:n,apiKey:r,model:i,...a?{body:a}:{},mcpServers:o}),console.log(`配置已保存到${I()},直接运行ai即可开始对话`)}catch(e){console.error(`保存配置失败:${t(e)}`),process.exitCode=1}}const J=(e,t,n)=>new Promise((r,i)=>{_(e,t,{encoding:`buffer`,timeout:5e3,maxBuffer:n},(e,t)=>{e?i(e):r(t)})}),Y=(e,t=`image/png`)=>({url:`data:${t};base64,${e.toString(`base64`)}`,bytes:e.length}),X=async()=>{let e=(await J(`powershell.exe`,[`-NoProfile`,`-Command`,`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()); }`],67108864)).toString(`utf8`).trim();return e?Y(Buffer.from(e,`base64`)):null},_e=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 t=await J(e.command,e.args,0xa00000);if(t.length===0)continue;return e.base64?Y(Buffer.from(t.toString(`ascii`).trim(),`base64`)):Y(t)}catch{}return null},ve=async()=>{try{return process.platform===`win32`?await X():await _e()}catch{return null}};var ye=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=l.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;this.pendingImages=[],!t&&n.length===0?this.prompting():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 e=await ve();e?e.bytes>5242880?this.printNotice(`[图片过大(${E(e.bytes)}B),已忽略]`):(this.pendingImages.push({type:`image_url`,image_url:{url:e.url}}),this.printNotice(`[已粘贴图片:共${this.pendingImages.length}张]`)):this.printNotice(`[剪贴板中没有图片]`)}preparePrint(e){if(this.prevPrintType===e)return!1;if(e===`content_delta`&&this.md===null&&(this.md=new g),this.prevPrintType===`content_delta`){let e=this.md?.flush();e&&process.stdout.write(e)}return process.stdout.write(`
|
|
4
|
+
`),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`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(`
|
|
5
|
+
`,``)}`),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(t,n,r){let{ellipsis:i=!0}=r??{},a=i?e(n,{maxLength:100,truncateMiddle:!0}):n;this.preparePrint(`tool_result`),process.stdout.write(this.colorize(`[工具结果:${t}] ${a}\n`,`90`))}printFinish(e,t){this.preparePrint(`done`),process.stdout.write(this.colorize(`[本轮结束:${e}] ${t?`输入${E(t.prompt_tokens)},输出${E(t.completion_tokens)},总共${E(t.total_tokens)}`:``}${t?.speed?`,速度${t.speed}/秒`:``}${e===`stop`?`
|
|
6
|
+
|
|
7
|
+
`:`
|
|
8
|
+
`}`,`90`))}printNotice(e){process.stdout.write(`${this.colorize(e,`93`)}\n`),this.isPrompting&&this.rl?.prompt(!0)}};const be=(e,t)=>{if(t.length===0)return e;let n=[];return e&&n.push({type:`text`,text:e}),n.push(...t),n},Z=async e=>{let t=R();t||(console.error("请先运行 `ai setup` 配置一个模型"),process.exit(1));let{body:n,...r}=t,i=v({...r,...n}),a=!1,o=U(t.mcpServers).then(e=>(a=!0,e)),s=[{role:`system`,content:`你是${i.model},当前时间${(/* @__PURE__ */ new Date()).toLocaleString()}`}],c=null,l=new ye(async({text:e,images:t})=>{s.push({role:`user`,content:be(e,t)}),a||l.printNotice(`MCP工具还未加载完成,请稍候……`),c??=[se,ie,...await o];for await(let e of re(i,s,{tools:c,stream:!0}))l.render(e)});l.start(e)},xe=()=>{console.log(`用法: ai [命令/提示词]
|
|
2
9
|
|
|
3
10
|
命令:
|
|
4
11
|
--help 显示帮助
|
|
5
12
|
setup 交互式配置模型APIKEY / BASE_URL / MODEL(保存到 ~/.@nickyzj2023/ai/config.json)
|
|
6
13
|
|
|
7
14
|
带上提示词时,启动对话的同时先把这段提示词发出去(如\`ai 明天适合洗车吗\`)
|
|
8
|
-
不带参数则直接进入对话`)},
|
|
15
|
+
不带参数则直接进入对话`)},Q=process.argv.slice(2),$=Q[0];switch($){case void 0:Z();break;case`setup`:await ge();break;case`--help`:case`-h`:xe();break;default:$.startsWith(`-`)&&(console.error(`未知命令:${$}(可以运行ai --help查看用法)`),process.exit(1)),Z(Q.join(` `).trim()||void 0)}export{};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,348 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
type Model = {
|
|
2
|
+
baseUrl: string;
|
|
3
|
+
/** 如果不传,会尝试使用GET {baseUrl}/models获取到的第一个模型 */
|
|
4
|
+
model?: string;
|
|
5
|
+
/** 使用本地llama.cpp等服务时可以不填 */
|
|
6
|
+
apiKey?: string;
|
|
7
|
+
/**
|
|
8
|
+
* 模型支持的消息输入类型
|
|
9
|
+
* @default ["text"]
|
|
10
|
+
* @remarks 会在每轮对话前校验消息类型,存在不支持的输入时报错
|
|
11
|
+
*/
|
|
12
|
+
modalities?: Modality[];
|
|
13
|
+
/**
|
|
14
|
+
* 模型的最大上下文
|
|
15
|
+
* @default 131072
|
|
16
|
+
* @remarks 调用compact函数时会根据模型上下文长度触发不同的压缩策略
|
|
17
|
+
*/
|
|
18
|
+
context?: number;
|
|
19
|
+
/**
|
|
20
|
+
* 自定义请求体,会在每轮请求时带上
|
|
21
|
+
* @example chat_template_kwargs: { enable_thinking: false }
|
|
22
|
+
*/
|
|
23
|
+
[key: string]: unknown;
|
|
24
|
+
};
|
|
25
|
+
/** 文/图/音/视频,暂未实现文件输入 */
|
|
26
|
+
type Modality = "text" | "image" | "audio" | "video";
|
|
27
|
+
type Message = {
|
|
28
|
+
role: "system" | "user" | "assistant" | "tool";
|
|
29
|
+
reasoning?: string | null;
|
|
30
|
+
content: string | ContentPart[];
|
|
31
|
+
tool_calls?: ToolCall[];
|
|
32
|
+
tool_call_id?: string;
|
|
33
|
+
[key: string]: unknown;
|
|
34
|
+
};
|
|
35
|
+
type ContentPart = TextContent | ImageContent | AudioContent | VideoContent;
|
|
36
|
+
type TextContent = {
|
|
37
|
+
type: "text";
|
|
38
|
+
text: string;
|
|
39
|
+
};
|
|
40
|
+
type ImageContent = {
|
|
41
|
+
type: "image_url";
|
|
42
|
+
image_url: {
|
|
43
|
+
url: string;
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
type AudioContent = {
|
|
47
|
+
type: "input_audio";
|
|
48
|
+
input_audio: {
|
|
49
|
+
/** 使用公网可访问的音频链接 */
|
|
50
|
+
url?: string;
|
|
51
|
+
/** 使用base64 */
|
|
52
|
+
data?: string;
|
|
53
|
+
format: string;
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
type VideoContent = {
|
|
57
|
+
type: "video_url";
|
|
58
|
+
video_url: {
|
|
59
|
+
url: string;
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
type ToolDefinition = {
|
|
63
|
+
type: "function";
|
|
64
|
+
function: {
|
|
65
|
+
name: string;
|
|
66
|
+
description: string;
|
|
67
|
+
parameters: {
|
|
68
|
+
type: "object";
|
|
69
|
+
properties: Record<string, {
|
|
70
|
+
type: string;
|
|
71
|
+
description?: string;
|
|
72
|
+
/** defineTool()提供的语法糖,等价于在parameters.required.push(当前property key) */
|
|
73
|
+
required?: boolean;
|
|
74
|
+
}>;
|
|
75
|
+
required?: string[];
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
/** 工具的实际执行函数 */
|
|
79
|
+
execute: (...args: any) => any;
|
|
80
|
+
};
|
|
81
|
+
type ToolCall = {
|
|
82
|
+
id: string;
|
|
83
|
+
type: "function";
|
|
84
|
+
function: {
|
|
85
|
+
name: string;
|
|
86
|
+
arguments: string;
|
|
87
|
+
};
|
|
88
|
+
/** Gemini等模型会在工具调用中要求保存thoughtsignature等自定义字段 */
|
|
89
|
+
[key: string]: any;
|
|
90
|
+
};
|
|
91
|
+
/** 模型可能返回的finish_reason值:停止/工具调用/上下文超限 */
|
|
92
|
+
type FinishReason = "stop" | "tool_calls" | "length" | null;
|
|
93
|
+
type Usage = {
|
|
94
|
+
prompt_tokens: number;
|
|
95
|
+
completion_tokens: number;
|
|
96
|
+
total_tokens: number;
|
|
97
|
+
/** 每秒生成多少个token */
|
|
98
|
+
speed?: number;
|
|
99
|
+
[key: string]: any;
|
|
100
|
+
};
|
|
101
|
+
/** stream()对外输出的事件 */
|
|
102
|
+
type StreamEvent = {
|
|
103
|
+
type: "reasoning_delta";
|
|
104
|
+
delta: string;
|
|
105
|
+
} | {
|
|
106
|
+
type: "content_delta";
|
|
107
|
+
delta: string;
|
|
108
|
+
} | {
|
|
109
|
+
type: "tool_call";
|
|
110
|
+
id: string;
|
|
111
|
+
name: string;
|
|
112
|
+
args: any;
|
|
113
|
+
/** Gemini等模型会在工具调用中要求保存thoughtsignature等自定义字段 */
|
|
114
|
+
[key: string]: any;
|
|
115
|
+
} | {
|
|
116
|
+
type: "done";
|
|
117
|
+
finishReason: FinishReason;
|
|
118
|
+
usage?: Usage;
|
|
119
|
+
} | {
|
|
120
|
+
type: "error";
|
|
121
|
+
message: string;
|
|
122
|
+
};
|
|
123
|
+
/** stream()内部要处理的事件流 */
|
|
124
|
+
type ChatCompletionsChunk = {
|
|
125
|
+
id: string;
|
|
126
|
+
object: "chat.completion.chunk";
|
|
127
|
+
created: number;
|
|
128
|
+
model: string;
|
|
129
|
+
choices: {
|
|
130
|
+
index: number;
|
|
131
|
+
delta: Pick<Message, "reasoning" | "content"> & {
|
|
132
|
+
tool_calls?: ({
|
|
133
|
+
index: number;
|
|
134
|
+
} & Partial<ToolCall>)[];
|
|
135
|
+
};
|
|
136
|
+
finish_reason: FinishReason;
|
|
137
|
+
}[];
|
|
138
|
+
usage?: Usage;
|
|
139
|
+
} | "[DONE]";
|
|
140
|
+
/** complete()内部要处理的非流式响应 */
|
|
141
|
+
type ChatCompletionsResponse = {
|
|
142
|
+
id: string;
|
|
143
|
+
object: "chat.completion";
|
|
144
|
+
created: number;
|
|
145
|
+
model: string;
|
|
146
|
+
choices: {
|
|
147
|
+
index: number;
|
|
148
|
+
message: Message;
|
|
149
|
+
finish_reason: FinishReason;
|
|
150
|
+
}[];
|
|
151
|
+
usage?: Usage;
|
|
152
|
+
};
|
|
153
|
+
/** complete()对外输出的结果 */
|
|
154
|
+
type NonStreamResult = {
|
|
155
|
+
/** 模型的思考内容(已经把各平台的reasoning_content等不规范的思考字段统一为reasoning) */
|
|
156
|
+
reasoning?: string;
|
|
157
|
+
/** 模型确定的回复内容 */
|
|
158
|
+
content: string;
|
|
159
|
+
/** 模型请求的工具调用(arguments为原始JSON字符串,需自行转换) */
|
|
160
|
+
toolCalls: ToolCall[];
|
|
161
|
+
finishReason: FinishReason;
|
|
162
|
+
usage?: Usage;
|
|
163
|
+
};
|
|
164
|
+
/** runAgent()的可选配置 */
|
|
165
|
+
type RunAgentOptions = {
|
|
166
|
+
/** 本轮可用的工具列表 */
|
|
167
|
+
tools?: ToolDefinition[];
|
|
168
|
+
/**
|
|
169
|
+
* 是否流式输出
|
|
170
|
+
* @default false
|
|
171
|
+
*/
|
|
172
|
+
stream?: boolean;
|
|
173
|
+
};
|
|
174
|
+
/** runAgent()每轮回复结束后的事件,流式/非流式统一为done */
|
|
175
|
+
type DoneEvent = {
|
|
176
|
+
type: "done";
|
|
177
|
+
/** 模型本轮确定的回复内容(流式模式下等于本轮所有content_delta的拼接) */
|
|
178
|
+
content: string;
|
|
179
|
+
/** 模型本轮的思考内容(流式模式下等于本轮所有reasoning_delta的拼接) */
|
|
180
|
+
reasoning?: string;
|
|
181
|
+
finishReason: FinishReason;
|
|
182
|
+
usage?: Usage;
|
|
183
|
+
};
|
|
184
|
+
type AgentEvent = Exclude<StreamEvent, {
|
|
185
|
+
type: "done";
|
|
186
|
+
}> | DoneEvent | {
|
|
187
|
+
type: "tool_result";
|
|
188
|
+
id: string;
|
|
189
|
+
name: string;
|
|
190
|
+
result: string;
|
|
191
|
+
};
|
|
192
|
+
type ToolCallEvent = Extract<AgentEvent, {
|
|
193
|
+
type: "tool_call";
|
|
194
|
+
}>;
|
|
195
|
+
type ToolResultEvent = Extract<AgentEvent, {
|
|
196
|
+
type: "tool_result";
|
|
197
|
+
}>;
|
|
198
|
+
/**
|
|
199
|
+
* Agent循环
|
|
200
|
+
* @param options.stream 是否流式输出,默认false(每轮推送一个result事件)
|
|
201
|
+
*/
|
|
202
|
+
export declare function runAgent(model: Model, messages: Message[], options?: RunAgentOptions): AsyncGenerator<AgentEvent>;
|
|
203
|
+
/**
|
|
204
|
+
* 流式请求模型,转发
|
|
205
|
+
*/
|
|
206
|
+
export declare function stream(model: Model, messages: Message[], tools?: ToolDefinition[], options?: Omit<RequestInit, "body"> & {
|
|
207
|
+
body?: Record<string, unknown>;
|
|
208
|
+
}): AsyncGenerator<StreamEvent>;
|
|
209
|
+
/**
|
|
210
|
+
* 非流式请求模型,一次性拿到完整回复
|
|
211
|
+
* @remarks 与stream()共享同一套请求/解析规则,区别在于不做SSE解析
|
|
212
|
+
* @throws 请求失败(含状态码非2xx)、取消(signal.abort)时抛出异常
|
|
213
|
+
*/
|
|
214
|
+
export declare function nonStream(model: Model, messages: Message[], tools?: ToolDefinition[], options?: Omit<RequestInit, "body"> & {
|
|
215
|
+
body?: Record<string, unknown>;
|
|
216
|
+
}): Promise<NonStreamResult>;
|
|
217
|
+
declare namespace Compact {
|
|
218
|
+
type Options = {
|
|
219
|
+
/** 提供token消耗情况时,能更准确地判断上下文是否达到阈值 */
|
|
220
|
+
usage?: Usage;
|
|
221
|
+
/**
|
|
222
|
+
* 各种压缩方式统一保留的最近消息条数
|
|
223
|
+
* @default 10
|
|
224
|
+
* @remarks 压缩工具调用结果、压缩媒体消息、总结消息、硬删除兜底都会保留最近keepCount条消息不处理
|
|
225
|
+
*/
|
|
226
|
+
keepCount?: number;
|
|
227
|
+
/**
|
|
228
|
+
* 压缩工具/媒体消息时做个标记,防止下次重复压缩
|
|
229
|
+
* @default "[已压缩]"
|
|
230
|
+
*/
|
|
231
|
+
compactedMessageMark?: string;
|
|
232
|
+
/**
|
|
233
|
+
* 上下文>总上下文*ratio时压缩工具调用结果
|
|
234
|
+
* @default 0.6
|
|
235
|
+
*/
|
|
236
|
+
ratioToCompactToolResults?: number;
|
|
237
|
+
/**
|
|
238
|
+
* 如何压缩工具调用结果
|
|
239
|
+
* @default 让其他模型返回简化后的工具结果
|
|
240
|
+
*/
|
|
241
|
+
replacerOfToolResultContent?: Compact.ReplacerOfToolResultContent;
|
|
242
|
+
/**
|
|
243
|
+
* 上下文>总上下文*ratio时压缩图片/音频/视频消息
|
|
244
|
+
* @default 0.7
|
|
245
|
+
*/
|
|
246
|
+
ratioToCompactMedia?: number;
|
|
247
|
+
/**
|
|
248
|
+
* 如何压缩媒体消息
|
|
249
|
+
* @default 让其他模型用自然语言简短描述一遍
|
|
250
|
+
*/
|
|
251
|
+
replacerOfMediaContent?: Compact.ReplacerOfMediaContent;
|
|
252
|
+
/**
|
|
253
|
+
* 上下文>总上下文*ratio时总结消息
|
|
254
|
+
* @default 0.8
|
|
255
|
+
* @remarks 如果总结成功,会把keepCount以前的消息压成一条用户消息
|
|
256
|
+
*/
|
|
257
|
+
ratioToSummarize?: number;
|
|
258
|
+
/**
|
|
259
|
+
* 总结消息时的配置项
|
|
260
|
+
* @default { systemPrompt: "你现在的任务是总结历史消息" }
|
|
261
|
+
*/
|
|
262
|
+
summarizeOptions?: Partial<Compact.SummarizeOptions>;
|
|
263
|
+
};
|
|
264
|
+
type ReplacerOfToolResultContent = (content: Message["content"], options?: {
|
|
265
|
+
model?: Model;
|
|
266
|
+
[key: string]: any;
|
|
267
|
+
}) => Promise<string> | string;
|
|
268
|
+
type ReplacerOfMediaContent = (content: Message["content"], options?: {
|
|
269
|
+
model?: Model;
|
|
270
|
+
modality?: Modality;
|
|
271
|
+
[key: string]: any;
|
|
272
|
+
}) => Promise<string> | string;
|
|
273
|
+
type SummarizeOptions = {
|
|
274
|
+
/** 指导大模型如何总结消息 */
|
|
275
|
+
systemPrompt: string;
|
|
276
|
+
model: Model;
|
|
277
|
+
/** 触发总结前的钩子 */
|
|
278
|
+
beforeSummarize?: (summarizable: Message[]) => void | Promise<void>;
|
|
279
|
+
};
|
|
280
|
+
type Result = {
|
|
281
|
+
/** 是否压缩了工具调用结果 */
|
|
282
|
+
hasCompactedToolResults: boolean;
|
|
283
|
+
/** 是否压缩了图片/音频/视频消息 */
|
|
284
|
+
hasCompactedMedia: boolean;
|
|
285
|
+
/** 是否总结了消息 */
|
|
286
|
+
hasSummarized: boolean;
|
|
287
|
+
/** 是否丢弃了一些旧消息(最终兜底策略) */
|
|
288
|
+
hasDiscardMessages: boolean;
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* @returns 实际处理了几条消息
|
|
293
|
+
*/
|
|
294
|
+
declare const compactToolResults: (compressible: Message[], options: {
|
|
295
|
+
replacer?: Compact.ReplacerOfToolResultContent;
|
|
296
|
+
mark: string;
|
|
297
|
+
model?: Model;
|
|
298
|
+
}) => Promise<number>;
|
|
299
|
+
/**
|
|
300
|
+
* @returns 实际处理了几条消息
|
|
301
|
+
*/
|
|
302
|
+
declare const compactMediaMessages: (compressible: Message[], options: {
|
|
303
|
+
replacer?: Compact.ReplacerOfMediaContent;
|
|
304
|
+
model?: Model;
|
|
305
|
+
}) => Promise<number>;
|
|
306
|
+
declare const summarizeMessages: (compressible: Message[], options: Compact.SummarizeOptions) => Promise<number>;
|
|
307
|
+
/**
|
|
308
|
+
* 最终的兜底压缩策略,从头删除旧消息,直到第二个回调函数返回true(达成目标)
|
|
309
|
+
*/
|
|
310
|
+
declare const discardMessagesUntil: (compressible: Message[], until: (compressible: Message[]) => boolean) => number;
|
|
311
|
+
/**
|
|
312
|
+
* 自动优化上下文,类似AI Coding Agent的/compact命令
|
|
313
|
+
*/
|
|
314
|
+
export declare const compact: ((messages: Message[], model: Model, options?: Compact.Options) => Promise<Compact.Result>) & {
|
|
315
|
+
compactToolResults: typeof compactToolResults;
|
|
316
|
+
compactMediaMessages: typeof compactMediaMessages;
|
|
317
|
+
summarizeMessages: typeof summarizeMessages;
|
|
318
|
+
discardMessagesUntil: typeof discardMessagesUntil;
|
|
319
|
+
};
|
|
320
|
+
export declare const getTime: ToolDefinition;
|
|
321
|
+
export declare const getWeather: ToolDefinition;
|
|
322
|
+
/**
|
|
323
|
+
* 辅助定义一个POST /chat/completions支持的model参数
|
|
324
|
+
* @remarks 只有baseUrl字段是必须的
|
|
325
|
+
*/
|
|
326
|
+
export declare const defineModel: (config: Model) => Model;
|
|
327
|
+
/**
|
|
328
|
+
* 辅助定义一个POST /chat/completions支持的tool对象
|
|
329
|
+
* @param execute 实际执行工具的函数
|
|
330
|
+
*/
|
|
331
|
+
export declare const defineTool: (name: ToolDefinition["function"]["name"], description: ToolDefinition["function"]["description"], properties: ToolDefinition["function"]["parameters"]["properties"], execute: ToolDefinition["execute"]) => ToolDefinition;
|
|
332
|
+
export declare const estimateTextTokens: (text: string) => number;
|
|
333
|
+
/**
|
|
334
|
+
* 列出GET /models返回的模型id
|
|
335
|
+
* @param baseUrl 接口前缀,如http://127.0.0.1:11434/v1
|
|
336
|
+
* @param apiKey 本地llama.cpp等不校验鉴权的服务可以不传,不传就不带Authorization头
|
|
337
|
+
* @returns 模型的id列表
|
|
338
|
+
* @remarks 请求失败(服务没起、鉴权不过等)会抛异常,由调用方自行兜底
|
|
339
|
+
*/
|
|
340
|
+
export declare const listModels: (baseUrl: string, apiKey?: string) => Promise<string[]>;
|
|
341
|
+
/**
|
|
342
|
+
* 根据上下文里的中/英文/多模态消息,估算出可能消耗的token
|
|
343
|
+
* - 单词 ≈ 1.5token
|
|
344
|
+
* - 标点/空白等非词字符每4个 ≈ 1token
|
|
345
|
+
* - 图片/音频/视频/文件 ≈ 4096token(不好估算,取个较大的值)
|
|
346
|
+
*/
|
|
347
|
+
export declare const estimateTokens: (messages?: Message[]) => number;
|
|
348
|
+
export type { AgentEvent, AudioContent, ChatCompletionsChunk, ChatCompletionsResponse, ContentPart, DoneEvent, FinishReason, ImageContent, Message, Modality, Model, NonStreamResult, RunAgentOptions, StreamEvent, TextContent, ToolCall, ToolCallEvent, ToolDefinition, ToolResultEvent, Usage, VideoContent };
|