@nickyzj2023/ai 1.7.4 → 1.7.6
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 +106 -104
- package/dist/agent.mjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/interfaces/setup.mjs +2 -2
- package/dist/llm.mjs +1 -1
- package/dist/tools/mcp.d.mts +27 -3
- package/dist/tools/mcp.mjs +1 -1
- package/dist/types.d.mts +4 -0
- package/dist/utils/compact/strategy.mjs +1 -1
- package/dist/utils/config.mjs +1 -1
- package/dist/utils/internalHelper.mjs +1 -1
- package/dist/utils/mcp-cache.mjs +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,104 +1,106 @@
|
|
|
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
|
-
import { defineModel, runAgent } from "@nickyzj2023/ai";
|
|
28
|
-
// 内置工具已从主入口拆出,按需引入
|
|
29
|
-
import { getTime, getWeather } from "@nickyzj2023/ai/tools";
|
|
30
|
-
// MCP体积较大(200kb),有需要时单独引入
|
|
31
|
-
import { loadMCPTools } from "@nickyzj2023/ai/mcp";
|
|
32
|
-
|
|
33
|
-
// 也可以按需引入,只加载真正用到的模块(不会带上CLI/TUI或compact等无关代码)
|
|
34
|
-
// import { runAgent } from "@nickyzj2023/ai/agent";
|
|
35
|
-
// import { stream, nonStream } from "@nickyzj2023/ai/llm";
|
|
36
|
-
// import { compact } from "@nickyzj2023/ai/compact";
|
|
37
|
-
// import { getWeather } from "@nickyzj2023/ai/tools/get-weather";
|
|
38
|
-
|
|
39
|
-
const model = defineModel({
|
|
40
|
-
baseUrl: "https://api.deepseek.com/v1",
|
|
41
|
-
apiKey: process.env.APIKEY,
|
|
42
|
-
model: "deepseek-flash",
|
|
43
|
-
});
|
|
44
|
-
|
|
45
|
-
const tools = [
|
|
46
|
-
// 内置工具
|
|
47
|
-
getWeather,
|
|
48
|
-
getTime,
|
|
49
|
-
// MCP工具
|
|
50
|
-
..(await loadMCPTools({
|
|
51
|
-
exa: {
|
|
52
|
-
type: "streamable_http",
|
|
53
|
-
url: "https://mcp.exa.ai/mcp",
|
|
54
|
-
headers: {
|
|
55
|
-
"x-api-key": "xxxxx",
|
|
56
|
-
},
|
|
57
|
-
}
|
|
58
|
-
})),
|
|
59
|
-
// 自定义工具
|
|
60
|
-
defineTool("square", "把一个数字平方", { num: {type: "number", description: "一个数字"} }, ({ num }) => num ** 2),
|
|
61
|
-
];
|
|
62
|
-
|
|
63
|
-
const messages = [{ role: "user", content: "查询上海天气" }];
|
|
64
|
-
|
|
65
|
-
// Agent层的用法(推荐)
|
|
66
|
-
// 流式传输,思考/回复内容会逐token输出,工具调用会收集完模型的调用请求后一次性执行完
|
|
67
|
-
for await (const e of runAgent(model, messages, { tools, stream: true })) {
|
|
68
|
-
console.log(e);
|
|
69
|
-
}
|
|
70
|
-
// 默认的非流式,done事件包含了本轮完整的reasoning/content/usage等信息
|
|
71
|
-
for await (const e of runAgent(model, messages, { tools })) {
|
|
72
|
-
if (e.type === "done") console.log(e.content);
|
|
73
|
-
else if (e.type === "error") console.log(e.message);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// LLM层的用法(Agent用的就是它们,stream/nonStream函数只对模型的响应事件做了转发)
|
|
77
|
-
// 流式传输,和runAgent + stream:true没啥区别
|
|
78
|
-
for await (const e of stream(model, messages, tools)) {
|
|
79
|
-
console.log(e);
|
|
80
|
-
}
|
|
81
|
-
// 非流式,直接拿到最终结果
|
|
82
|
-
const result = await nonStream(model, messages, tools);
|
|
83
|
-
console.log(result.content, result.usage);
|
|
84
|
-
|
|
85
|
-
```
|
|
86
|
-
|
|
87
|
-
### 在终端里使用
|
|
88
|
-
|
|
89
|
-
```bash
|
|
90
|
-
# 首次使用:交互式配置BASE_URL / APIKEY / MODEL / ...
|
|
91
|
-
ai setup
|
|
92
|
-
|
|
93
|
-
# 启动对话
|
|
94
|
-
ai
|
|
95
|
-
|
|
96
|
-
# 直接开聊,本质是“ai->输入提示词->回车”的语法糖
|
|
97
|
-
ai 你好
|
|
98
|
-
```
|
|
99
|
-
|
|
100
|
-
配置保存在 `~/.@nickyzj2023/ai/config.json`,任意目录下执行`ai`都能读取到
|
|
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
|
+
import { defineModel, runAgent } from "@nickyzj2023/ai";
|
|
28
|
+
// 内置工具已从主入口拆出,按需引入
|
|
29
|
+
import { getTime, getWeather } from "@nickyzj2023/ai/tools";
|
|
30
|
+
// MCP体积较大(200kb),有需要时单独引入
|
|
31
|
+
import { loadMCPTools } from "@nickyzj2023/ai/mcp";
|
|
32
|
+
|
|
33
|
+
// 也可以按需引入,只加载真正用到的模块(不会带上CLI/TUI或compact等无关代码)
|
|
34
|
+
// import { runAgent } from "@nickyzj2023/ai/agent";
|
|
35
|
+
// import { stream, nonStream } from "@nickyzj2023/ai/llm";
|
|
36
|
+
// import { compact } from "@nickyzj2023/ai/compact";
|
|
37
|
+
// import { getWeather } from "@nickyzj2023/ai/tools/get-weather";
|
|
38
|
+
|
|
39
|
+
const model = defineModel({
|
|
40
|
+
baseUrl: "https://api.deepseek.com/v1",
|
|
41
|
+
apiKey: process.env.APIKEY,
|
|
42
|
+
model: "deepseek-flash",
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const tools = [
|
|
46
|
+
// 内置工具
|
|
47
|
+
getWeather,
|
|
48
|
+
getTime,
|
|
49
|
+
// MCP工具
|
|
50
|
+
..(await loadMCPTools({
|
|
51
|
+
exa: {
|
|
52
|
+
type: "streamable_http",
|
|
53
|
+
url: "https://mcp.exa.ai/mcp",
|
|
54
|
+
headers: {
|
|
55
|
+
"x-api-key": "xxxxx",
|
|
56
|
+
},
|
|
57
|
+
}
|
|
58
|
+
})),
|
|
59
|
+
// 自定义工具
|
|
60
|
+
defineTool("square", "把一个数字平方", { num: {type: "number", description: "一个数字"} }, ({ num }) => num ** 2),
|
|
61
|
+
];
|
|
62
|
+
|
|
63
|
+
const messages = [{ role: "user", content: "查询上海天气" }];
|
|
64
|
+
|
|
65
|
+
// Agent层的用法(推荐)
|
|
66
|
+
// 流式传输,思考/回复内容会逐token输出,工具调用会收集完模型的调用请求后一次性执行完
|
|
67
|
+
for await (const e of runAgent(model, messages, { tools, stream: true })) {
|
|
68
|
+
console.log(e);
|
|
69
|
+
}
|
|
70
|
+
// 默认的非流式,done事件包含了本轮完整的reasoning/content/usage等信息
|
|
71
|
+
for await (const e of runAgent(model, messages, { tools })) {
|
|
72
|
+
if (e.type === "done") console.log(e.content);
|
|
73
|
+
else if (e.type === "error") console.log(e.message);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// LLM层的用法(Agent用的就是它们,stream/nonStream函数只对模型的响应事件做了转发)
|
|
77
|
+
// 流式传输,和runAgent + stream:true没啥区别
|
|
78
|
+
for await (const e of stream(model, messages, tools)) {
|
|
79
|
+
console.log(e);
|
|
80
|
+
}
|
|
81
|
+
// 非流式,直接拿到最终结果
|
|
82
|
+
const result = await nonStream(model, messages, tools);
|
|
83
|
+
console.log(result.content, result.usage);
|
|
84
|
+
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### 在终端里使用
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
# 首次使用:交互式配置BASE_URL / APIKEY / MODEL / ...
|
|
91
|
+
ai setup
|
|
92
|
+
|
|
93
|
+
# 启动对话
|
|
94
|
+
ai
|
|
95
|
+
|
|
96
|
+
# 直接开聊,本质是“ai->输入提示词->回车”的语法糖
|
|
97
|
+
ai 你好
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
配置保存在 `~/.@nickyzj2023/ai/config.json`,任意目录下执行`ai`都能读取到
|
|
101
|
+
|
|
102
|
+
终端里的`ai`还会把MCP工具列表缓存到同目录的`mcp-cache.json`:MCP配置没变时开聊直接读缓存,连服务器推迟到真正调用某个MCP工具时;配置变过(`ai setup`里改的)才会重新拉一遍工具并覆盖缓存。这份缓存只属于全局安装的CLI,在项目里`import loadMCPTools`的用法不读写它
|
|
103
|
+
|
|
104
|
+
## License
|
|
105
|
+
|
|
106
|
+
ISC
|
package/dist/agent.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{estimateFallbackUsage as e,toToolCall as t,toToolCallEvent as n,withSpeed as r}from"./utils/internalHelper.mjs";import{nonStream as i,stream as a}from"./llm.mjs";import{to as o}from"@nickyzj2023/utils";async function*s(s,c,l){let{tools:u=[],stream:d=!1}=l??{},f=new Map(u.map(e=>[e.function.name,e]));for(;;){let l=``,p=``,m=[],h=null,g,_=Date.now();if(d)for await(let e of a(s,c,u))switch(e.type){case`reasoning_delta`:yield e,l+=e.delta;break;case`content_delta`:yield e,p+=e.delta;break;case`tool_call`:yield e,m.push(t(e));break;case`error`:yield e;return;case`done`:h=e.finishReason,g=e.usage}else{let[e,t]=await o(i(s,c,u));if(e){yield{type:`error`,message:e.message};return}for(let e of t.toolCalls)yield n(e),m.push(e);l=t.reasoning??``,p=t.content,h=t.finishReason,g=t.usage}g=r(g??e(c,p,l),_),yield{type:`done`,content:p,reasoning:l,finishReason:h,usage:g};let v={role:`assistant`,content:p};if(m.length>0&&(v.tool_calls=m),c.push(v),m.length===0)return;for(let e of m){let{name:t,arguments:n}=e.function,r=f.get(t),i=``;if(!r)i=`不存在工具“${t}”`;else{let[e,a]=await o(r.execute(JSON.parse(n)));i=e?`工具“${t}”执行出错:${e.message}`:JSON.stringify(a)}let a={type:`tool_result`,id:e.id,name:t,result:i};yield a,c.push({role:`tool`,tool_call_id:e.id,content:a.result})}}}export{s as runAgent};
|
package/dist/cli.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{defineModel as e}from"./utils/helper.mjs";import{runAgent as t}from"./agent.mjs";import n from"./tools/get-time.mjs";import r from"./tools/get-weather.mjs";import{
|
|
1
|
+
import{defineModel as e}from"./utils/helper.mjs";import{runAgent as t}from"./agent.mjs";import n from"./tools/get-time.mjs";import r from"./tools/get-weather.mjs";import{loadConfig as i}from"./utils/config.mjs";import{loadCachedMCPTools as a}from"./utils/mcp-cache.mjs";import{runSetup as o}from"./interfaces/setup.mjs";import{TUI as s}from"./interfaces/tui.mjs";const c=(e,t)=>{if(t.length===0)return e;let n=[];return e&&n.push({type:`text`,text:e}),n.push(...t),n},l=async o=>{let l=i();l||(console.error("请先运行 `ai setup` 配置一个模型"),process.exit(1));let{body:u,...d}=l,f=e({...d,...u}),p=!1,m=a(l.mcpServers).then(e=>(p=!0,e)),h=[{role:`system`,content:`你是${f.model},当前时间${(/* @__PURE__ */ new Date()).toLocaleString()}`}],g=null,_=new s(async({text:e,images:i})=>{h.push({role:`user`,content:c(e,i)}),p||_.printNotice(`MCP工具还未加载完成,请稍候……`),g??=[r,n,...await m];for await(let e of t(f,h,{tools:g,stream:!0}))_.render(e)});_.start(o)},u=()=>{console.log(`用法: ai [命令/提示词]
|
|
2
2
|
|
|
3
3
|
命令:
|
|
4
4
|
--help 显示帮助
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{defineModel as e,defineTool as t,estimateTextTokens as n,estimateTokens as r,listModels as i}from"./utils/helper.mjs";import{nonStream as a,stream as o}from"./llm.mjs";import{runAgent as s}from"./agent.mjs";import{compact as c}from"./utils/compact/index.mjs";export{c as compact,e as defineModel,t as defineTool,n as estimateTextTokens,r as estimateTokens,i as listModels,a as nonStream,s as runAgent,o as stream};
|
|
@@ -1,2 +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
|
|
2
|
-
当前MCP服务器:`),
|
|
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{loadCachedMCPTools as a}from"../utils/mcp-cache.mjs";import{extractErrorMessage as o,isObject as s,to as c}from"@nickyzj2023/utils";import l from"node:readline";const u=e=>new Promise(t=>{let n=l.createInterface({input:process.stdin,output:process.stdout});n.question(e,e=>{n.close(),t(e)})}),d=async(e,t)=>(await u(e)).trim()||t,f=async e=>{let n=await d(`名称 [当前为${e?.name??`(新)`}]: `,e?.name);if(!n)return console.log(`名称不能为空,已取消`),null;let r=e?.type??`streamable_http`,i=await d(`类型 streamable_http/sse [当前为${r}]: `,r);if(i!==`streamable_http`&&i!==`sse`)return console.log(`类型无效,已取消`),null;let a=i,l=await d(`URL [当前为${e?.url??`无`}]: `,e?.url);if(!l)return console.log(`URL不能为空,已取消`),null;let f=e?.headers,p=(await u(`headers(JSON对象) [当前为${e?.headers?JSON.stringify(e.headers):`无`}]: `)).trim();if(p)try{let e=JSON.parse(p);s(e)?f=e:console.log(`headers需为JSON对象,已回退到原先的值`)}catch{console.log(`headers解析失败,已回退到原先的值`)}let h=e?.ignoredToolNames,[g,_=[]]=await c(t(l,f?{headers:f}:void 0));g?console.log(`获取工具列表失败:${o(g)}`):(console.log(`该服务器提供的工具:`),_.forEach((e,t)=>{console.log(`${t+1}. ${e}`)}));let v=(await u(`忽略的工具(名称或序号,用逗号分隔,也支持1-5这样的连续序号) [当前为${e?.ignoredToolNames?.join(`,`)??`无`}]: `)).trim();return v&&(h=m(v,_)),{name:n,type:a,url:l,...f?{headers:f}:{},...h?.length?{ignoredToolNames:h}:{}}},p=(e,t)=>{let n=Number(e)-1;return Number.isInteger(n)?t[n]:void 0},m=(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)]},h=async e=>{let t=!1;for(;;){let n=Object.keys(e);console.log(`
|
|
2
|
+
当前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 u(`输入数字编辑对应服务器,a添加新服务器,d删除服务器,回车或q结束: `)).trim().toLowerCase();if(!r||r===`q`)break;switch(r){case`a`:{let n=await f();n&&(e[n.name]=n,t=!0);break}case`d`:{let r=(await u(`输入要删除的服务器编号: `)).trim(),i=p(r,n);if(!i){console.log(`无效编号,请输入列表中的数字`);break}(await u(`确认删除${i}?(y/n): `)).trim().toLowerCase()===`y`?(delete e[i],t=!0,console.log(`已删除${i}`)):console.log(`已取消删除`);break}default:{let i=p(r,n);if(i){let n=e[i];n||console.log(`该服务器配置缺失,将重新录入`);let r=await f({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 a(e);console.log(`已缓存${t.length}个MCP工具,之后聊天无需等待MCP加载\n`)}},g=async(t,n,r)=>{let[i,a]=await c(t?e(t,n):Promise.resolve([])),s=a??[];i?console.log(`获取模型列表失败:${o(i)}`):s.length===0?console.log(`服务端未返回任何模型,请手动输入模型名`):(console.log(`可用模型(输入序号快速选择,也可直接输入模型名):`),s.forEach((e,t)=>{console.log(` ${t+1}. ${e}`)}));let l=(await u(`MODEL [当前为${r}]: `)).trim();return p(l,s)||l||r},_=async e=>{let t=(await u(`自定义请求体(单行JSON对象,{}表示清空) [当前为${e?JSON.stringify(e):`无`}]: `)).trim();if(!t)return e;try{let n=JSON.parse(t);return s(n)?Object.keys(n).length?n:void 0:(console.log(`自定义请求体需为JSON对象,已沿用原先的值`),e)}catch{return console.log(`自定义请求体解析失败,已沿用原先的值`),e}};async function v(){let e=r(),t=await u(`BASE_URL [当前为${e?.baseUrl}]: `)||e?.baseUrl,a=await u(`APIKEY [当前为${e?.apiKey}]: `)||e?.apiKey,s=await g(t,a,e?.model),c=await _(e?.body),l={...e?.mcpServers};(await u(`是否配置MCP服务器?(y/n): `)).trim().toLowerCase()===`y`&&await h(l);try{i({baseUrl:t,apiKey:a,model:s,...c?{body:c}:{},mcpServers:l}),console.log(`配置已保存到${n()},直接运行ai即可开始对话`)}catch(e){console.error(`保存配置失败:${o(e)}`),process.exitCode=1}}export{v as runSetup};
|
package/dist/llm.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{extractErrorMessage as
|
|
1
|
+
import{toToolCallEvent as e}from"./utils/internalHelper.mjs";import{extractErrorMessage as t,fetcher as n,omit as r,parseSSE as i,pick as a,to as o}from"@nickyzj2023/utils";const s=e=>[a(e,[`type`,`function`]),a(e,[`execute`])],c=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}]},l=e=>e.reasoning||e.reasoning_content;async function*u(a,u,d=[],f){let[p,{baseUrl:m,apiKey:h}]=c(a),g=d.map(e=>s(e)[0]),_=n(m,{headers:{Authorization:`Bearer ${h}`},parser:async e=>e}),[v,y]=await o(_.post(`/chat/completions`,{stream:!0,messages:u,tools:g,...p,...f?.body},r(f??{},[`body`])));if(v){if(f?.signal?.aborted)return;yield{type:`error`,message:v.message};return}let b=/* @__PURE__ */ new Map,x,S=null;try{for await(let e of i(y)){if(typeof e==`string`)continue;e.usage&&(x=e.usage);let t=e.choices?.[0];if(!t)continue;let{delta:n}=t,{content:r,tool_calls:i}=n,a=l(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=b.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),b.set(o,s)}t.finish_reason&&(S=t.finish_reason)}}catch(e){if(f?.signal?.aborted)return;yield{type:`error`,message:t(e)};return}for(let[,t]of b)yield e(t);yield{type:`done`,finishReason:S,usage:x}}async function d(e,t,i=[],a){let[o,{baseUrl:u,apiKey:d}]=c(e),f=i.map(e=>s(e)[0]),p=await n(u,{headers:{Authorization:`Bearer ${d}`}}).post(`/chat/completions`,{stream:!1,messages:t,tools:f,...o,...a?.body},r(a??{},[`body`])),m=p.choices?.[0],h=m?.message;return{reasoning:h?l(h):void 0,content:typeof h?.content==`string`?h.content:(h?.content??[]).filter(e=>e.type===`text`).map(e=>e.text).join(``),toolCalls:h?.tool_calls??[],finishReason:m?.finish_reason??null,usage:p.usage}}export{d as nonStream,u as stream};
|
package/dist/tools/mcp.d.mts
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import { ToolDefinition } from "../types.mjs";
|
|
2
2
|
import { Client } from "@modelcontextprotocol/sdk/client";
|
|
3
|
+
import { Tool } from "@modelcontextprotocol/sdk/types.js";
|
|
3
4
|
//#region src/tools/mcp.d.ts
|
|
5
|
+
/** listTools()返回的工具schema */
|
|
6
|
+
type McpTool = Tool;
|
|
4
7
|
type McpServer = {
|
|
5
8
|
type: "streamable_http" | "sse";
|
|
6
9
|
url: string;
|
|
7
10
|
headers?: Record<string, any>;
|
|
8
11
|
ignoredToolNames?: string[];
|
|
12
|
+
/**
|
|
13
|
+
* 可选的listTools()结果,带了就直接当工具列表用,不再连服务器拉一遍
|
|
14
|
+
* @remarks 留给上层做工具缓存的“口子”(如CLI层的mcp-cache.json),普通用法不用管
|
|
15
|
+
*/
|
|
16
|
+
tools?: McpTool[];
|
|
9
17
|
};
|
|
10
18
|
/**
|
|
11
19
|
* 连上MCP服务器拉一次工具名后立刻断开,不注册到router
|
|
@@ -16,6 +24,12 @@ type McpServer = {
|
|
|
16
24
|
declare const listMcpToolNames: (url: string, options?: Omit<McpServer, "type" | "url">) => Promise<string[]>;
|
|
17
25
|
declare class MCPRouter {
|
|
18
26
|
private entries;
|
|
27
|
+
/**
|
|
28
|
+
* 登记一个MCP服务器并备好它的工具
|
|
29
|
+
* @param onToolsListed 真的去服务器拉工具列表时的回调,上层凭它写缓存
|
|
30
|
+
* @remarks server.tools有值(缓存命中)就直接复用,一次网络请求都不发
|
|
31
|
+
*/
|
|
32
|
+
addServer(name: string, server: McpServer, onToolsListed?: (name: string, tools: McpTool[]) => void): Promise<void>;
|
|
19
33
|
/** 注册一个新的MCP客户端 */
|
|
20
34
|
addClient(name: string, url: string, options?: Omit<McpServer, "type" | "url">): Promise<Client<{
|
|
21
35
|
method: string;
|
|
@@ -50,13 +64,23 @@ declare class MCPRouter {
|
|
|
50
64
|
taskId: string;
|
|
51
65
|
} | undefined;
|
|
52
66
|
} | undefined;
|
|
53
|
-
}
|
|
67
|
+
}>>;
|
|
54
68
|
/** 返回OpenAI API兼容的tools数组 */
|
|
55
69
|
getTools(): Promise<ToolDefinition[]>;
|
|
70
|
+
/** 登记配置:配置没变就复用,变了就换成全新的空壳 */
|
|
71
|
+
private register;
|
|
72
|
+
/** 连服务器拉一次工具列表(只有没带tools的服务器才走这里) */
|
|
73
|
+
private listTools;
|
|
74
|
+
/** 懒连接:同一个服务器只会连一次,连失败就清掉,下次还能重试 */
|
|
75
|
+
private getClient;
|
|
76
|
+
/** 调用MCP工具:连接在第一次调用时才建立 */
|
|
77
|
+
private callTool;
|
|
56
78
|
}
|
|
57
79
|
/**
|
|
58
80
|
* 把传入的MCPServer列表转换成OpenAI API兼容的tools数组
|
|
81
|
+
* @param onToolsListed 每个服务器成功拿到工具列表时的回调(命中缓存时不会触发)
|
|
82
|
+
* @remarks 服务器配置里带了tools就直接复用,不连服务器
|
|
59
83
|
*/
|
|
60
|
-
declare const loadMCPTools: (mcpServers?: Record<string, McpServer
|
|
84
|
+
declare const loadMCPTools: (mcpServers?: Record<string, McpServer>, onToolsListed?: (name: string, tools: McpTool[]) => void) => Promise<ToolDefinition[]>;
|
|
61
85
|
//#endregion
|
|
62
|
-
export { MCPRouter, McpServer, listMcpToolNames, loadMCPTools };
|
|
86
|
+
export { MCPRouter, McpServer, McpTool, listMcpToolNames, loadMCPTools };
|
package/dist/tools/mcp.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
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
|
|
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(()=>{})}},c=(t,r)=>{let i={...t.inputSchema.properties??{}};return t.inputSchema.required?.forEach(e=>{n(i[e])&&(i[e]={...i[e],required:!0})}),e(t.name,t.description??``,i,r)},l=(e,t)=>JSON.stringify(i(e,[`tools`]))===JSON.stringify(i(t,[`tools`]));var u=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=>c(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&&l(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??=o(e,t.server.url,i(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 d=async(e={},n)=>(a||=new u,await Promise.allSettled(Object.entries(e).map(async([e,i])=>{try{await a?.addServer(e,i,n)}catch(n){r(`MCP服务器${e}加载失败:${t(n)}`)}})),a.getTools());export{u as MCPRouter,s as listMcpToolNames,d as loadMCPTools};
|
package/dist/types.d.mts
CHANGED
|
@@ -86,6 +86,8 @@ type ToolCall = {
|
|
|
86
86
|
name: string;
|
|
87
87
|
arguments: string;
|
|
88
88
|
};
|
|
89
|
+
/** Gemini等模型会在工具调用中要求保存thoughtsignature等自定义字段 */
|
|
90
|
+
[key: string]: any;
|
|
89
91
|
};
|
|
90
92
|
/** 模型可能返回的finish_reason值:停止/工具调用/上下文超限 */
|
|
91
93
|
type FinishReason = "stop" | "tool_calls" | "length" | null;
|
|
@@ -109,6 +111,8 @@ type StreamEvent = {
|
|
|
109
111
|
id: string;
|
|
110
112
|
name: string;
|
|
111
113
|
args: any;
|
|
114
|
+
/** Gemini等模型会在工具调用中要求保存thoughtsignature等自定义字段 */
|
|
115
|
+
[key: string]: any;
|
|
112
116
|
} | {
|
|
113
117
|
type: "done";
|
|
114
118
|
finishReason: FinishReason;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{estimateFallbackUsage as e,withSpeed as t}from"../internalHelper.mjs";import{nonStream as n}from"../../llm.mjs";import{findToolGroupRange as r,isMediaMessage as i}from"./helper.mjs";import{createXMLText as a,logger as o}from"@nickyzj2023/utils";const s=async(r,i)=>{let a=Date.now(),o=await n(r,i);return{content:o.content,usage:t(o.usage??e(i,o.content,o.reasoning??``),a)}},c=async(e,t)=>{let{model:n}=t??{};return n?(await s(n,[{role:`user`,content:e},{role:`user`,content:`请用一句话简述上面这条消息(直击要点,不要添加任何前言后语)`}])).content:`工具结果已被消费`},l=async(e,t)=>{let{replacer:n,mark:r,model:i}=t??{};if(!n&&!i)return 0;let a=n||c,s=0;for(let t of e)if(t?.role===`tool`&&typeof t.content==`string`){if(t.content.startsWith(r))continue;t.content=r+await a(t.content,{model:i}),s++}return s>0&&o(`压缩了${s}条工具调用结果`),s},u=async(e,t)=>{let{model:n,modality:r=`image`}=t??{};return n?.modalities?.includes(r)?(await s(n,[{role:`user`,content:e},{role:`user`,content:`请用一句话简述上面这条消息(直击要点,不要添加任何前言后语)`}])).content:`媒体资源已被消费`},d=async(e,t)=>{let{replacer:n,model:r}=t??{};if(!n&&!r)return 0;let s=n||u,c=0;for(let t of e){let e=i(t);if(e){let n=await s(t.content,{model:r,modality:e});t.content=a(`media`,n),c++}}return c>0&&o(`压缩了${c}条多模态消息`),c},f=async(e,t)=>{let{model:n,systemPrompt:r,beforeSummarize:i}=t??{},c=e.slice(1);if(c.length===0)return o(`消息太少,无需总结`),0;await i?.(c);let l=c.length;c.push({role:`system`,content:r},{role:`user`,content:`开始总结上下文`});let u=await s(n,c);return e.splice(1,1/0,{role:`user`,content:a(`summary`,u.content)}),o(`总结了${l}条消息,消耗:`,u.usage),l},p=(e,t)=>{let n=0;for(;e.length>0&&!t(e);){let t=Math.max(1,Math.floor(e.length/10));if(e[t]?.role===`tool`){let n=r(e,t);if(n)t=n[1];else for(;e[t]?.role===`tool`;)t++}n+=e.splice(0,t).length}return o(`丢弃了${n}条旧消息`),n};export{d as compactMediaMessages,l as compactToolResults,p as discardMessagesUntil,f as summarizeMessages};
|
package/dist/utils/config.mjs
CHANGED
|
@@ -1 +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}},
|
|
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=()=>a(i(o()),`mcp-cache.json`),c=()=>{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}},l=t=>{let r=o();e(i(r),{recursive:!0}),n(r,`${JSON.stringify(t,null,2)}\n`,`utf8`)};export{o as getConfigPath,s as getMcpToolsCachePath,c as loadConfig,l as saveConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{estimateTextTokens as e,estimateTokens as t}from"./helper.mjs";const n=new Intl.NumberFormat(`en-US`,{notation:`compact`,maximumFractionDigits:1}),
|
|
1
|
+
import{estimateTextTokens as e,estimateTokens as t}from"./helper.mjs";const n=({id:e,function:t,...n})=>({...n,type:`tool_call`,id:e,name:t.name,args:t.arguments}),r=({id:e,name:t,args:n,...r})=>({...r,id:e,type:`function`,function:{name:t,arguments:n}}),i=new Intl.NumberFormat(`en-US`,{notation:`compact`,maximumFractionDigits:1}),a=e=>i.format(e),o=(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}},s=(e,t)=>(e.speed=Math.floor(e.completion_tokens/((Date.now()-t)/1e3)),e);export{o as estimateFallbackUsage,a as humanizeNumber,r as toToolCall,n as toToolCallEvent,s as withSpeed};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{loadMCPTools as e}from"../tools/mcp.mjs";import{getMcpToolsCachePath as t}from"./config.mjs";import{extractErrorMessage as n,isObject as r,logger as i,omit as a}from"@nickyzj2023/utils";import{mkdirSync as o,readFileSync as s,writeFileSync as c}from"node:fs";import{dirname as l}from"node:path";const u=e=>a(e,[`tools`]),d=(e,t)=>JSON.stringify(e)===JSON.stringify(t),f=()=>{try{let e=JSON.parse(s(t(),`utf8`));return r(e)?e:{}}catch{return{}}},p=e=>{try{let n=t();o(l(n),{recursive:!0}),c(n,`${JSON.stringify(e,null,2)}\n`,`utf8`)}catch(e){i(`MCP工具缓存写入失败:${n(e)}`)}},m=async(t={})=>{let n=f(),r={};for(let[e,i]of Object.entries(t)){let t=u(i),a=n[e];r[e]=a&&d(a.server,t)?{...t,tools:a.tools}:t}let i=await e(r,(e,t)=>{let i=r[e];i&&(n[e]={server:u(i),tools:t})}),a={};for(let[e,t]of Object.entries(r)){let r=n[e];r&&d(r.server,u(t))&&(a[e]=r)}return p(a),i};export{m as loadCachedMCPTools};
|