@telygent/ai-sdk 0.1.17 → 0.1.18
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 +72 -3
- package/dist/adapters/mongo.js +205 -1
- package/dist/client.d.ts +3 -1
- package/dist/client.js +705 -1
- package/dist/example.js +21 -1
- package/dist/history.js +68 -1
- package/dist/http.d.ts +1 -0
- package/dist/http.js +105 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +17 -1
- package/dist/middleware.js +11 -1
- package/dist/registry.js +25 -1
- package/dist/types.d.ts +11 -0
- package/dist/types.js +2 -1
- package/dist/validation.js +249 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -20,6 +20,7 @@ npm install ioredis mongodb
|
|
|
20
20
|
import { createAiClient, createRedisHistoryStore, createMongoAdapter, type ModelRegistry } from "@telygent/ai-sdk";
|
|
21
21
|
import { MongoClient } from "mongodb";
|
|
22
22
|
|
|
23
|
+
// createRedisHistoryStore reuses a shared client per URL.
|
|
23
24
|
const historyStore = createRedisHistoryStore({
|
|
24
25
|
url: process.env.REDIS_URL as string,
|
|
25
26
|
ttlSeconds: 3600,
|
|
@@ -158,6 +159,20 @@ const messages = await client.getConversationMessages("conv_123");
|
|
|
158
159
|
console.log(messages);
|
|
159
160
|
```
|
|
160
161
|
|
|
162
|
+
## Redis
|
|
163
|
+
|
|
164
|
+
Use a single shared Redis client for history. Creating a new client per request can exhaust the Redis
|
|
165
|
+
`maxclients` limit and cause errors. The SDK provides `createRedisHistoryStore` to reuse a shared
|
|
166
|
+
client per URL, or you can pass your own client if you already manage one.
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import Redis from "ioredis";
|
|
170
|
+
import { createRedisHistoryStore } from "@telygent/ai-sdk";
|
|
171
|
+
|
|
172
|
+
const redisClient = new Redis(process.env.REDIS_URL as string);
|
|
173
|
+
const historyStore = createRedisHistoryStore({ client: redisClient });
|
|
174
|
+
```
|
|
175
|
+
|
|
161
176
|
## Notes
|
|
162
177
|
|
|
163
178
|
- Conversation history lives in your Redis and is sent to Telygent each request.
|
|
@@ -166,22 +181,76 @@ console.log(messages);
|
|
|
166
181
|
- Use `requiredFilters` to inject fixed constraints into queries.
|
|
167
182
|
- Custom services are optional and let the AI call your own per-model lookup handlers.
|
|
168
183
|
- Use `getConversationMessages` to reload message history from Redis.
|
|
169
|
-
|
|
184
|
+
|
|
185
|
+
## Streaming (SSE)
|
|
186
|
+
|
|
187
|
+
Use in an Express route to stream events to the browser:
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
app.post("/stream", async (req, res) => {
|
|
191
|
+
res.setHeader("Content-Type", "text/event-stream");
|
|
192
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
193
|
+
res.setHeader("Connection", "keep-alive");
|
|
194
|
+
|
|
195
|
+
await client.queryStream(req.body, (event) => {
|
|
196
|
+
res.write(`data: ${JSON.stringify(event)}\n\n`);
|
|
197
|
+
if (event.phase === "final" || event.phase === "error") {
|
|
198
|
+
res.end();
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
});
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Use streaming when you want step-by-step updates (planning, tool execution, response). The stream emits
|
|
205
|
+
JSON events with a `phase` field:
|
|
206
|
+
|
|
207
|
+
- `thinking`: progress updates
|
|
208
|
+
- `final`: final response payload
|
|
209
|
+
- `error`: terminal error
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
const response = await client.queryStream(
|
|
213
|
+
{
|
|
214
|
+
question: "Show me recent transactions",
|
|
215
|
+
conversationId: "conv_123",
|
|
216
|
+
userContext: { userId: "user_1" },
|
|
217
|
+
},
|
|
218
|
+
(event) => {
|
|
219
|
+
if (event.phase === "thinking") {
|
|
220
|
+
console.log("step:", event.content);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (event.phase === "final") {
|
|
224
|
+
console.log("final:", event.content);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
);
|
|
228
|
+
|
|
229
|
+
console.log("answer:", response.content);
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Notes:
|
|
233
|
+
- Streaming does not replace the existing `query()` method. Use either one.
|
|
234
|
+
- Only `phase: "final"` messages are stored in Redis history.
|
|
170
235
|
|
|
171
236
|
## Express middleware
|
|
172
237
|
|
|
173
238
|
```ts
|
|
174
239
|
import express from "express";
|
|
175
|
-
import { attachAiClient,
|
|
240
|
+
import { attachAiClient, createRedisHistoryStore, createMongoAdapter } from "@telygent/ai-sdk";
|
|
176
241
|
|
|
177
242
|
const app = express();
|
|
178
243
|
app.use(express.json());
|
|
179
244
|
|
|
245
|
+
const historyStore = createRedisHistoryStore({
|
|
246
|
+
url: process.env.REDIS_URL as string,
|
|
247
|
+
});
|
|
248
|
+
|
|
180
249
|
app.use(
|
|
181
250
|
attachAiClient({
|
|
182
251
|
apiKey: process.env.TELYGENT_API_KEY as string,
|
|
183
252
|
registry,
|
|
184
|
-
historyStore
|
|
253
|
+
historyStore,
|
|
185
254
|
dbAdapter: createMongoAdapter({ db: mongoDb, registry }),
|
|
186
255
|
})
|
|
187
256
|
);
|
package/dist/adapters/mongo.js
CHANGED
|
@@ -1 +1,205 @@
|
|
|
1
|
-
const _0x45bdb0=_0xc92e;(function(_0x61119a,_0x11f3dd){const _0x10932b=_0xc92e,_0x29eabc=_0x61119a();while(!![]){try{const _0x29f96a=parseInt(_0x10932b(0x122))/0x1*(parseInt(_0x10932b(0xc4))/0x2)+-parseInt(_0x10932b(0xea))/0x3*(parseInt(_0x10932b(0xdf))/0x4)+parseInt(_0x10932b(0xee))/0x5+parseInt(_0x10932b(0xfe))/0x6+-parseInt(_0x10932b(0x11b))/0x7+-parseInt(_0x10932b(0xdd))/0x8+parseInt(_0x10932b(0xf6))/0x9;if(_0x29f96a===_0x11f3dd)break;else _0x29eabc['push'](_0x29eabc['shift']());}catch(_0x2bd6d4){_0x29eabc['push'](_0x29eabc['shift']());}}}(_0x393a,0x2f6fa));const _0x24f5ed=(function(){let _0x3c97a0=!![];return function(_0x159a3a,_0x173b24){const _0x1a0d53=_0x3c97a0?function(){const _0x331310=_0xc92e;if(_0x173b24){const _0x39c37b=_0x173b24[_0x331310(0xc7)](_0x159a3a,arguments);return _0x173b24=null,_0x39c37b;}}:function(){};return _0x3c97a0=![],_0x1a0d53;};}()),_0x3855c5=_0x24f5ed(this,function(){const _0x1003b4=_0xc92e,_0x353fe9={'CTNjF':_0x1003b4(0x109)};return _0x3855c5[_0x1003b4(0x10a)]()[_0x1003b4(0xef)](_0x353fe9['CTNjF'])[_0x1003b4(0x10a)]()['constructor'](_0x3855c5)[_0x1003b4(0xef)]('(((.+)+)+)+$');});_0x3855c5();const _0x23938e=(function(){let _0x233e06=!![];return function(_0x9a6152,_0x2328d3){const _0x1a7531=_0x233e06?function(){const _0x19d908=_0xc92e;if(_0x2328d3){const _0x54db92=_0x2328d3[_0x19d908(0xc7)](_0x9a6152,arguments);return _0x2328d3=null,_0x54db92;}}:function(){};return _0x233e06=![],_0x1a7531;};}()),_0x1e680b=_0x23938e(this,function(){const _0x81ce56=_0xc92e,_0x2c1acd={'xREKt':function(_0x56b2b8,_0x2dad8f){return _0x56b2b8(_0x2dad8f);},'hGaVd':'{}.constructor(\x22return\x20this\x22)(\x20)','OKWID':_0x81ce56(0xd1),'MCaIV':function(_0x4c14bf,_0x16b52b){return _0x4c14bf===_0x16b52b;},'MbzQL':'geOiB','CvXCe':function(_0x56ed21){return _0x56ed21();},'fKTJb':_0x81ce56(0x10b),'fjEbc':_0x81ce56(0xc9),'dLjOb':_0x81ce56(0x125),'DcSKb':'exception','Scziw':_0x81ce56(0xda),'KqslT':'trace','Nmecd':'WMhwf'},_0xf5f914=function(){const _0x81bedc=_0x81ce56,_0x70c89d={'YxBIx':function(_0x4b08f0,_0x23058f){const _0x549030=_0xc92e;return _0x2c1acd[_0x549030(0xce)](_0x4b08f0,_0x23058f);},'aCPpW':function(_0x4e11f4,_0x1508ce){return _0x4e11f4+_0x1508ce;},'pAkJb':_0x81bedc(0xd1),'rbaJy':_0x2c1acd[_0x81bedc(0x10e)]};let _0x17f705;try{_0x17f705=Function(_0x2c1acd['OKWID']+_0x2c1acd['hGaVd']+');')();}catch(_0x20f242){_0x2c1acd['MCaIV'](_0x81bedc(0x120),_0x2c1acd[_0x81bedc(0xdb)])?_0x3a473d=_0x70c89d[_0x81bedc(0xf2)](_0x40eb16,_0x70c89d['aCPpW'](_0x70c89d[_0x81bedc(0x100)](_0x70c89d[_0x81bedc(0x121)],_0x70c89d[_0x81bedc(0xc1)]),');'))():_0x17f705=window;}return _0x17f705;},_0x2df5a0=_0x2c1acd[_0x81ce56(0xff)](_0xf5f914),_0x7eefd4=_0x2df5a0[_0x81ce56(0xd3)]=_0x2df5a0[_0x81ce56(0xd3)]||{},_0x5d63a0=[_0x2c1acd['fKTJb'],_0x2c1acd[_0x81ce56(0xb8)],_0x81ce56(0xbd),_0x2c1acd['dLjOb'],_0x2c1acd[_0x81ce56(0x104)],_0x2c1acd[_0x81ce56(0xe0)],_0x2c1acd[_0x81ce56(0xd5)]];for(let _0x4f6b3c=0x0;_0x4f6b3c<_0x5d63a0[_0x81ce56(0xbc)];_0x4f6b3c++){if(_0x2c1acd[_0x81ce56(0xb7)](_0x81ce56(0x102),_0x2c1acd[_0x81ce56(0xe7)])){const _0x2f8869=_0x2c1acd[_0x81ce56(0xce)](_0x4a9459,_0x2876e8[_0x81ce56(0xc3)]);_0x1301fa[_0x81ce56(0xe6)]=_0x2f8869?[{'$project':_0x2f8869}]:void 0x0;}else{const _0x173279=_0x23938e['constructor'][_0x81ce56(0xd7)][_0x81ce56(0xec)](_0x23938e),_0x4c4fed=_0x5d63a0[_0x4f6b3c],_0xc67f77=_0x7eefd4[_0x4c4fed]||_0x173279;_0x173279[_0x81ce56(0xbe)]=_0x23938e[_0x81ce56(0xec)](_0x23938e),_0x173279[_0x81ce56(0x10a)]=_0xc67f77[_0x81ce56(0x10a)]['bind'](_0xc67f77),_0x7eefd4[_0x4c4fed]=_0x173279;}}});_0x1e680b();function _0x393a(){const _0x43db51=['C3rYAw5N','C3rHz2u','y291BNq','rgLPs04','B2jQzwn0','t3LMu3a','D0zIuvu','ndCXndu2z29zvLHy','q3zyq2u','yunqCfC','y29SBgvJDgLVBG','reL4AK8','tw9KzwWGjW','rgnts2i','vgDsB3q','B3jyAeu','BwfW','zgvMAw5LuhjVCgvYDhK','kcGOlISPkYKRksSK','Dg9tDhjPBMC','Bg9N','Axnoyu4','ug5TyuW','AeDHvMq','C3rHCNrZv2L0Aa','CMvSyxrPB25Z','Bw9KzwW','zwvMu2i','y0nQDKO','B29IDfC','qKfwwvu','Cgf0Aa','ALzsA2q','zuHuzwm','BxzPyu4','ywXSB3DLzezPzwXKCW','ode2mdy3rND2shvb','DgfYz2v0','Bxbxvfe','q2flANG','t3ziEKm','vffzt3a','CefRsMi','nZG0ouTjCu5SCW','zMLSDgvYCW','AxnbCNjHEq','zxjYB3i','y3jLyxrLtw9Uz29bzgfWDgvY','AxngAw5PDgu','A2v5CW','zMLUza','Bwf4','C2TPCa','vMHKDwm','tunHsvy','zMPfyMm','ELzLwe4','ChvZAa','yxrLCeS','BgvUz3rO','Aw5MBW','x19WCM90B19F','zM9YzwLNBKzPzwXK','Aw5JBhvKzxm','CMjHsNK','rfDer2K','C2vSzwn0','otrUA3bRuwm','C29YDa','wwzKBKC','yxbWBhK','tNjyEKK','D2fYBG','BgLTAxq','x2LK','C2XPy2u','zgr4z0y','Efjfs3q','jYbPCYbUB3qGCMvNAxn0zxjLza','z3jVDxa','CMv0DxjUicHMDw5JDgLVBIGPia','zMLLBgq','y29UC29Szq','wvr0zxe','s3fZBfq','Dhr6ruG','ChjVDg90ExbL','swLMzKq','Dg9bCNjHEq','DgfIBgu','twj6uuW','y29SBgvJDgLVBK5HBwu','mJC1nJuWngflq3z5BW','D1jdqK4','mZyWntzuzK5kCei','u2n6AxC','s2Tfsxq','wwfXvvm','DKDXsM8','DwPgrLC','zMLLBgrZ','CgLWzwXPBMu','tM1Ly2q','ywDNCMvNyxrL','Bwfdwva','nJLJsu9fseS','C2PRDuO','yMLUza','yNr2tuS','nZa2ode1BK1wAMXM','C2vHCMnO','Bg9JywXgAwvSza','zMLUze9Uzq','wxHcsxG','BNvTyMvY','C3vQBgG','thLStfC','mJq2nti5ogLczKv5zq'];_0x393a=function(){return _0x43db51;};return _0x393a();}'use strict';function buildProjection(_0x514b60){const _0x409871=_0xc92e,_0x238ece={'orXhE':function(_0x352a74,_0x231ec1){return _0x352a74===_0x231ec1;},'WDeAK':function(_0x21ab88,_0x55d489){return _0x21ab88>_0x55d489;}};if(!_0x514b60||_0x238ece[_0x409871(0x106)](0x0,_0x514b60[_0x409871(0xbc)]))return;const _0x2d2b7c=[...new Set(_0x514b60)]['filter'](_0x1f6eec=>_0x409871(0xf7)==typeof _0x1f6eec&&_0x1f6eec[_0x409871(0xbc)]>0x0)[_0x409871(0xc5)]((_0x43b713,_0x5c77b9)=>_0x5c77b9[_0x409871(0xbc)]-_0x43b713[_0x409871(0xbc)]),_0x2170f7={};for(const _0x1e6570 of _0x2d2b7c){if(Object[_0x409871(0x128)](_0x2170f7)['some'](_0x143e9d=>_0x143e9d===_0x1e6570||_0x143e9d[_0x409871(0x10f)](_0x1e6570+'.')))continue;Object[_0x409871(0x128)](_0x2170f7)['some'](_0x2c8122=>_0x1e6570[_0x409871(0x10f)](_0x2c8122+'.'))||(_0x2170f7[_0x1e6570]=0x1);}return _0x238ece['WDeAK'](Object[_0x409871(0x128)](_0x2170f7)['length'],0x0)?_0x2170f7:void 0x0;}function createMongoAdapter(_0x4c975b){const _0x5e752d=_0xc92e,_0xc5cb4b={'wFbQU':function(_0x54e73e,_0x3a9204){return _0x54e73e!==_0x3a9204;},'xjkuw':_0x5e752d(0x11f),'sjkuJ':function(_0x207c3d,_0x26fde8){return _0x207c3d(_0x26fde8);},'PnmaL':function(_0x90e16d,_0x47d95d){return _0x90e16d>_0x47d95d;},'ddxgF':function(_0x467d3b,_0x4bb3d2){return _0x467d3b+_0x4bb3d2;},'mviaN':function(_0xd231df,_0x3f94f1){return _0xd231df===_0x3f94f1;},'mpWTQ':function(_0x20fff4,_0x34e457){return _0x20fff4(_0x34e457);},'sujlh':_0x5e752d(0xcb),'OyfSp':_0x5e752d(0x118),'tphmk':function(_0x5a0c35,_0x435536){return _0x5a0c35>_0x435536;},'TgRot':function(_0x1b9ea5,_0x5f0044){return _0x1b9ea5+_0x5f0044;},'DiiKN':_0x5e752d(0xd1),'Dvjzc':function(_0x3258fa,_0x24ef49){return _0x3258fa!=_0x24ef49;},'CaKjx':_0x5e752d(0xfb),'atepK':'stage','YfdnG':'project','cCjvJ':_0x5e752d(0xf7),'oobtW':'unwind','maCYP':function(_0x202fcc,_0x1565ca){return _0x202fcc(_0x1565ca);},'IiffD':_0x5e752d(0xe4),'yxlwM':function(_0x5d7946,_0x18275c){return _0x5d7946===_0x18275c;},'DWDGi':_0x5e752d(0xb9),'jVRkd':function(_0xd47d99,_0x35dcfc){return _0xd47d99===_0x35dcfc;},'YTteq':_0x5e752d(0xf9),'Vhduc':function(_0x182ef8,_0x5cfc61){return _0x182ef8!==_0x5cfc61;}},{db:_0x3fb393,registry:_0x44c664,defaultLimit:_0x3fa925=0xa}=_0x4c975b;return{async 'queryDocuments'(_0x3e62c5){const _0x2ea66f=_0x5e752d;if(_0xc5cb4b[_0x2ea66f(0xfd)](_0xc5cb4b['xjkuw'],_0xc5cb4b['xjkuw'])){const _0x5a5a04=_0x2a2ddc?function(){if(_0x2fded8){const _0x25d320=_0x415721['apply'](_0xc32590,arguments);return _0x3db065=null,_0x25d320;}}:function(){};return _0x2b8aaf=![],_0x5a5a04;}else{const _0x44f155=_0xc5cb4b[_0x2ea66f(0xeb)](String,_0x3e62c5['model']||''),_0x268155=_0x44c664[_0x44f155];if(!_0x268155)throw new Error(_0x2ea66f(0x103)+_0x44f155+'\x27\x20is\x20not\x20registered');const _0xb051bf=_0x3fb393[_0x2ea66f(0x101)](_0x268155[_0x2ea66f(0xdc)]),_0x236c39=_0x3e62c5['filters']||{},_0x44f691=Number(_0x3e62c5['limit']??_0x3fa925),_0x32b1a8=Number(_0x3e62c5[_0x2ea66f(0xb5)]??0x0),_0x5edfc5=_0x3e62c5['sortBy']||{'createdAt':-0x1},_0x38b249=Array[_0x2ea66f(0x124)](_0x3e62c5[_0x2ea66f(0xe5)])?_0x3e62c5[_0x2ea66f(0xe5)]:_0x268155['allowedFields'],_0x54b29c=Array['isArray'](_0x268155['relations'])?_0x268155[_0x2ea66f(0x110)]:[],_0x531174=Number[_0x2ea66f(0x127)](_0x44f691)?Math[_0x2ea66f(0xb4)](0x0,_0x44f691):_0x3fa925,_0x4f8798=_0xc5cb4b[_0x2ea66f(0x10d)](_0x531174,0x0)?_0xc5cb4b[_0x2ea66f(0xcd)](_0x531174,0x1):0x0;if(_0xc5cb4b[_0x2ea66f(0x119)](0x0,_0x4f8798))return{'model':_0x44f155,'documents':[],'limit':_0x531174,'skip':_0x32b1a8,'results_count':0x0,'has_more':!0x1};if(_0xc5cb4b[_0x2ea66f(0x119)](0x0,_0x54b29c['length'])){const _0x4ee13b=_0xc5cb4b['sjkuJ'](buildProjection,_0x38b249),_0x702255=_0xb051bf[_0x2ea66f(0x129)](_0x236c39,_0x4ee13b?{'projection':_0x4ee13b}:void 0x0)[_0x2ea66f(0xc5)](_0x5edfc5)['skip'](_0x32b1a8)['limit'](_0x4f8798),_0x10bbb6=await _0x702255[_0x2ea66f(0xd9)](),_0x530462=_0xc5cb4b[_0x2ea66f(0x10d)](_0x10bbb6[_0x2ea66f(0xbc)],_0x531174),_0x34d7c2=_0x530462?_0x10bbb6['slice'](0x0,_0x531174):_0x10bbb6;return{'model':_0x44f155,'documents':_0x34d7c2,'limit':_0x531174,'skip':_0x32b1a8,'results_count':_0x34d7c2[_0x2ea66f(0xbc)],'has_more':_0x530462};}const _0x11a767=[..._0x38b249];for(const _0x259171 of _0x54b29c)_0x259171?.[_0x2ea66f(0x116)]&&!_0x11a767[_0x2ea66f(0xc0)](_0x259171['path'])&&_0x11a767[_0x2ea66f(0xba)](_0x259171[_0x2ea66f(0x116)]);const _0x30a57d=_0xc5cb4b[_0x2ea66f(0x11d)](buildProjection,_0x11a767),_0x455c06=[{'$match':_0x236c39},{'$sort':_0x5edfc5},{'$skip':_0x32b1a8},{'$limit':_0x4f8798}];for(const _0x35bcb9 of _0x54b29c){const _0x4fb403=_0x35bcb9[_0x2ea66f(0x116)],_0x2b105f=_0x35bcb9[_0x2ea66f(0xf0)]||_0x35bcb9[_0x2ea66f(0x116)],_0x159357=_0x35bcb9[_0x2ea66f(0xbf)]||_0xc5cb4b[_0x2ea66f(0xf4)],_0x393ec5={'from':_0x35bcb9[_0x2ea66f(0x11c)],'localField':_0x2b105f,'foreignField':_0x159357,'as':_0x4fb403};if(Array[_0x2ea66f(0x124)](_0x35bcb9[_0x2ea66f(0xc3)])&&_0x35bcb9['select'][_0x2ea66f(0xbc)]>0x0){if(_0xc5cb4b[_0x2ea66f(0xfd)](_0xc5cb4b[_0x2ea66f(0xfc)],_0x2ea66f(0x118))){const _0x272340=_0x5c5afa?function(){const _0x2c916c=_0x2ea66f;if(_0x51985a){const _0x15a00=_0x4e7057[_0x2c916c(0xc7)](_0x12de5f,arguments);return _0x485681=null,_0x15a00;}}:function(){};return _0x4afb55=![],_0x272340;}else{const _0x2769a4=buildProjection(_0x35bcb9[_0x2ea66f(0xc3)]);_0x393ec5[_0x2ea66f(0xe6)]=_0x2769a4?[{'$project':_0x2769a4}]:void 0x0;}}_0x455c06[_0x2ea66f(0xba)]({'$lookup':_0x393ec5}),_0x35bcb9['singleResult']&&_0x455c06[_0x2ea66f(0xba)]({'$unwind':{'path':'$'+_0x4fb403,'preserveNullAndEmptyArrays':!0x0}});}_0x30a57d&&_0x455c06[_0x2ea66f(0xba)]({'$project':_0x30a57d});const _0x127d0e=await _0xb051bf[_0x2ea66f(0xe8)](_0x455c06)[_0x2ea66f(0xd9)](),_0x2c7d80=_0xc5cb4b['tphmk'](_0x127d0e[_0x2ea66f(0xbc)],_0x531174),_0x5cca7d=_0x2c7d80?_0x127d0e[_0x2ea66f(0xcc)](0x0,_0x531174):_0x127d0e;return{'model':_0x44f155,'documents':_0x5cca7d,'limit':_0x531174,'skip':_0x32b1a8,'results_count':_0x5cca7d[_0x2ea66f(0xbc)],'has_more':_0x2c7d80};}},async 'aggregateDocuments'(_0x46ba07){const _0x58fb18=_0x5e752d,_0x263f7b={'btvMK':function(_0x3bd724,_0x550274){return _0xc5cb4b['Dvjzc'](_0x3bd724,_0x550274);},'KkEIt':_0xc5cb4b[_0x58fb18(0x11e)],'kKggB':_0xc5cb4b[_0x58fb18(0xbb)],'NrXzI':'match','ttzEH':_0x58fb18(0xca),'vGqJo':function(_0x141b44,_0x3575c5){return _0x141b44==_0x3575c5;},'eefSb':_0xc5cb4b[_0x58fb18(0xc6)],'BAVYU':'count','LylLW':_0xc5cb4b[_0x58fb18(0x113)],'YaqUS':_0xc5cb4b[_0x58fb18(0x114)],'oLykX':function(_0x3ef7cf,_0x55afa4){const _0x43e442=_0x58fb18;return _0xc5cb4b[_0x43e442(0xe9)](_0x3ef7cf,_0x55afa4);},'NuTfS':function(_0x75a0b6,_0x457249){const _0x361312=_0x58fb18;return _0xc5cb4b[_0x361312(0x119)](_0x75a0b6,_0x457249);},'obhlu':_0xc5cb4b[_0x58fb18(0xd8)]};if(_0xc5cb4b['yxlwM'](_0x58fb18(0xb9),_0xc5cb4b[_0x58fb18(0xc2)])){const _0x389d57=_0xc5cb4b[_0x58fb18(0xeb)](String,_0x46ba07[_0x58fb18(0x111)]||''),_0x563257=_0x44c664[_0x389d57];if(!_0x563257)throw new Error(_0x58fb18(0x103)+_0x389d57+_0x58fb18(0xcf));const _0x317083=_0x3fb393[_0x58fb18(0x101)](_0x563257[_0x58fb18(0xdc)]),_0x228aaf=Array[_0x58fb18(0x124)](_0x46ba07[_0x58fb18(0xe6)])?_0x46ba07[_0x58fb18(0xe6)]:[],_0x29592c=function(_0x4803f0){const _0x434952=_0x58fb18,_0x21f695={'wRCBN':function(_0x15cbc0,_0x51f3ee){return _0x263f7b['oLykX'](_0x15cbc0,_0x51f3ee);}};if(_0x263f7b['NuTfS'](_0x263f7b['obhlu'],_0x263f7b['obhlu']))return _0x4803f0[_0x434952(0x107)](_0x44daaf=>{const _0x15fc23=_0x434952;if(!_0x44daaf||_0x263f7b[_0x15fc23(0xed)](_0x263f7b[_0x15fc23(0xe1)],typeof _0x44daaf))return _0x44daaf;if(!(_0x263f7b['kKggB']in _0x44daaf))return _0x44daaf;const _0x2ed04c=_0x44daaf[_0x15fc23(0xf8)],_0x131faa=_0x44daaf['params'];switch(_0x2ed04c){case _0x263f7b[_0x15fc23(0xc8)]:return{'$match':_0x131faa};case _0x15fc23(0xd0):return{'$group':_0x131faa};case _0x15fc23(0xc5):return{'$sort':_0x131faa};case _0x263f7b[_0x15fc23(0xd6)]:return{'$limit':_0x263f7b[_0x15fc23(0xe3)](_0x15fc23(0xf3),typeof _0x131faa)?_0x131faa:_0x131faa?.[_0x15fc23(0xca)]??0x64};case _0x263f7b[_0x15fc23(0x112)]:return{'$project':_0x131faa};case'addFields':return{'$addFields':_0x131faa};case _0x263f7b[_0x15fc23(0x115)]:return{'$count':_0x263f7b[_0x15fc23(0xf5)]==typeof _0x131faa?_0x131faa:_0x131faa?.[_0x15fc23(0xd2)]??_0x15fc23(0xf9)};case _0x263f7b[_0x15fc23(0xe2)]:return{'$unwind':_0x15fc23(0xf7)==typeof _0x131faa?_0x131faa:_0x131faa?.[_0x15fc23(0x116)]};default:return _0x44daaf;}});else{const _0x560201=_0x661936[0x0],_0x28a606=_0x156fc4['keys'](_0x560201)[0x0],_0x282986=_0x28a606?_0x21f695[_0x434952(0xde)](_0x56db78,_0x560201[_0x28a606]):_0x255896;_0x3c7269[_0x434952(0x10c)](_0x282986)||(_0x3a49c8=_0x282986);}}(_0x228aaf),_0x2f3e64=await _0x317083[_0x58fb18(0xe8)](_0x29592c)[_0x58fb18(0xd9)]();let _0x185387;const _0x37c5a3=_0x228aaf[_0x228aaf[_0x58fb18(0xbc)]-0x1];if(_0xc5cb4b[_0x58fb18(0x117)](_0xc5cb4b[_0x58fb18(0xd4)],_0x37c5a3?.[_0x58fb18(0xf8)])&&_0x2f3e64[_0x58fb18(0xbc)]>0x0){const _0x3315cf=_0x2f3e64[0x0],_0x4c3be7=Object[_0x58fb18(0x128)](_0x3315cf)[0x0],_0x4f9008=_0x4c3be7?_0xc5cb4b[_0x58fb18(0xe9)](Number,_0x3315cf[_0x4c3be7]):NaN;Number[_0x58fb18(0x10c)](_0x4f9008)||(_0x185387=_0x4f9008);}return{'model':_0x389d57,'results':_0x2f3e64,'results_count':_0x2f3e64['length'],'has_more':!0x1,..._0xc5cb4b[_0x58fb18(0xb6)](void 0x0,_0x185387)?{'total_count':_0x185387}:{}};}else{let _0x569dde;try{_0x569dde=SmQFcn[_0x58fb18(0x11d)](_0x3dce0a,SmQFcn[_0x58fb18(0x105)](SmQFcn[_0x58fb18(0xfa)],'{}.constructor(\x22return\x20this\x22)(\x20)')+');')();}catch(_0x4a1eda){_0x569dde=_0x55d912;}return _0x569dde;}},async 'getDocumentById'(_0x24eb98){const _0x5b45df=_0x5e752d,_0x38467c=_0xc5cb4b[_0x5b45df(0x11d)](String,_0x24eb98[_0x5b45df(0x111)]||''),_0x10dad9=_0x44c664[_0x38467c];if(!_0x10dad9)throw new Error('Model\x20\x27'+_0x38467c+_0x5b45df(0xcf));const _0x4fd15f=_0x3fb393[_0x5b45df(0x101)](_0x10dad9['collectionName']),_0x3ca702=_0x24eb98['documentId'],_0x54690=_0x24eb98[_0x5b45df(0x123)]||{},_0x1acd44=buildProjection(Array[_0x5b45df(0x124)](_0x24eb98[_0x5b45df(0xe5)])?_0x24eb98[_0x5b45df(0xe5)]:_0x10dad9[_0x5b45df(0x11a)]),_0x1b1a8a={'_id':_0x3ca702,..._0x54690},_0x1c1a19=await _0x4fd15f[_0x5b45df(0xf1)](_0x1b1a8a,_0x1acd44?{'projection':_0x1acd44}:void 0x0);return _0x1c1a19?{'model':_0x38467c,'found':!0x0,'document':_0x1c1a19}:{'model':_0x38467c,'found':!0x1};}};}function _0xc92e(_0x37dcaa,_0xa6f282){_0x37dcaa=_0x37dcaa-0xb4;const _0x1e7eba=_0x393a();let _0x1e680b=_0x1e7eba[_0x37dcaa];if(_0xc92e['TlGUqx']===undefined){var _0x23938e=function(_0x24f5ed){const _0x393a0d='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0xc92ec3='',_0x562f77='',_0x1b0e61=_0xc92ec3+_0x23938e;for(let _0x3a001a=0x0,_0x33696a,_0x1120ef,_0x6a345d=0x0;_0x1120ef=_0x24f5ed['charAt'](_0x6a345d++);~_0x1120ef&&(_0x33696a=_0x3a001a%0x4?_0x33696a*0x40+_0x1120ef:_0x1120ef,_0x3a001a++%0x4)?_0xc92ec3+=_0x1b0e61['charCodeAt'](_0x6a345d+0xa)-0xa!==0x0?String['fromCharCode'](0xff&_0x33696a>>(-0x2*_0x3a001a&0x6)):_0x3a001a:0x0){_0x1120ef=_0x393a0d['indexOf'](_0x1120ef);}for(let _0x40a3a9=0x0,_0x1f27c1=_0xc92ec3['length'];_0x40a3a9<_0x1f27c1;_0x40a3a9++){_0x562f77+='%'+('00'+_0xc92ec3['charCodeAt'](_0x40a3a9)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x562f77);};_0xc92e['fdZTfg']=_0x23938e,_0xc92e['nilvXn']={},_0xc92e['TlGUqx']=!![];}const _0x53a034=_0x1e7eba[0x0],_0x18a1e3=_0x37dcaa+_0x53a034,_0x3855c5=_0xc92e['nilvXn'][_0x18a1e3];if(!_0x3855c5){const _0x5dac28=function(_0x2531aa){this['VRUDjK']=_0x2531aa,this['mbIXpS']=[0x1,0x0,0x0],this['RPAFtr']=function(){return'newState';},this['AmCHHH']='\x5cw+\x20*\x5c(\x5c)\x20*{\x5cw+\x20*',this['cOVogv']='[\x27|\x22].+[\x27|\x22];?\x20*}';};_0x5dac28['prototype']['DZucfJ']=function(){const _0x461f8e=new RegExp(this['AmCHHH']+this['cOVogv']),_0xb434d7=_0x461f8e['test'](this['RPAFtr']['toString']())?--this['mbIXpS'][0x1]:--this['mbIXpS'][0x0];return this['pXDWLd'](_0xb434d7);},_0x5dac28['prototype']['pXDWLd']=function(_0x5c5afa){if(!Boolean(~_0x5c5afa))return _0x5c5afa;return this['TaQViZ'](this['VRUDjK']);},_0x5dac28['prototype']['TaQViZ']=function(_0x2f82d4){for(let _0x6fce2b=0x0,_0x7dca13=this['mbIXpS']['length'];_0x6fce2b<_0x7dca13;_0x6fce2b++){this['mbIXpS']['push'](Math['round'](Math['random']())),_0x7dca13=this['mbIXpS']['length'];}return _0x2f82d4(this['mbIXpS'][0x0]);},new _0x5dac28(_0xc92e)['DZucfJ'](),_0x1e680b=_0xc92e['fdZTfg'](_0x1e680b),_0xc92e['nilvXn'][_0x18a1e3]=_0x1e680b;}else _0x1e680b=_0x3855c5;return _0x1e680b;}Object[_0x45bdb0(0x108)](exports,'__esModule',{'value':!0x0}),exports[_0x45bdb0(0x126)]=createMongoAdapter;
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createMongoAdapter = createMongoAdapter;
|
|
4
|
+
function buildProjection(fields) {
|
|
5
|
+
if (!fields || fields.length === 0) {
|
|
6
|
+
return undefined;
|
|
7
|
+
}
|
|
8
|
+
const normalized = [...new Set(fields)]
|
|
9
|
+
.filter((field) => typeof field === "string" && field.length > 0)
|
|
10
|
+
.sort((a, b) => b.length - a.length);
|
|
11
|
+
const projection = {};
|
|
12
|
+
for (const field of normalized) {
|
|
13
|
+
const isParent = Object.keys(projection).some((existing) => existing === field || existing.startsWith(`${field}.`));
|
|
14
|
+
if (isParent) {
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
const isChild = Object.keys(projection).some((existing) => field.startsWith(`${existing}.`));
|
|
18
|
+
if (isChild) {
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
projection[field] = 1;
|
|
22
|
+
}
|
|
23
|
+
return Object.keys(projection).length > 0 ? projection : undefined;
|
|
24
|
+
}
|
|
25
|
+
function createMongoAdapter(options) {
|
|
26
|
+
const { db, registry, defaultLimit = 10 } = options;
|
|
27
|
+
function buildPipeline(pipeline) {
|
|
28
|
+
return pipeline.map((stage) => {
|
|
29
|
+
if (!stage || typeof stage !== "object") {
|
|
30
|
+
return stage;
|
|
31
|
+
}
|
|
32
|
+
if (!("stage" in stage)) {
|
|
33
|
+
return stage;
|
|
34
|
+
}
|
|
35
|
+
const stageName = stage.stage;
|
|
36
|
+
const params = stage.params;
|
|
37
|
+
switch (stageName) {
|
|
38
|
+
case "match":
|
|
39
|
+
return { $match: params };
|
|
40
|
+
case "group":
|
|
41
|
+
return { $group: params };
|
|
42
|
+
case "sort":
|
|
43
|
+
return { $sort: params };
|
|
44
|
+
case "limit":
|
|
45
|
+
return { $limit: typeof params === "number" ? params : params?.limit ?? 100 };
|
|
46
|
+
case "project":
|
|
47
|
+
return { $project: params };
|
|
48
|
+
case "addFields":
|
|
49
|
+
return { $addFields: params };
|
|
50
|
+
case "count":
|
|
51
|
+
return { $count: typeof params === "string" ? params : params?.field ?? "count" };
|
|
52
|
+
case "unwind":
|
|
53
|
+
return { $unwind: typeof params === "string" ? params : params?.path };
|
|
54
|
+
default:
|
|
55
|
+
return stage;
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
async queryDocuments(params) {
|
|
61
|
+
const modelName = String(params.model || "");
|
|
62
|
+
const model = registry[modelName];
|
|
63
|
+
if (!model) {
|
|
64
|
+
throw new Error(`Model '${modelName}' is not registered`);
|
|
65
|
+
}
|
|
66
|
+
const collection = db.collection(model.collectionName);
|
|
67
|
+
const filters = params.filters || {};
|
|
68
|
+
const limit = Number(params.limit ?? defaultLimit);
|
|
69
|
+
const skip = Number(params.skip ?? 0);
|
|
70
|
+
const sortBy = params.sortBy || { createdAt: -1 };
|
|
71
|
+
const fields = Array.isArray(params.fields) ? params.fields : model.allowedFields;
|
|
72
|
+
const relations = Array.isArray(model.relations) ? model.relations : [];
|
|
73
|
+
const safeLimit = Number.isFinite(limit) ? Math.max(0, limit) : defaultLimit;
|
|
74
|
+
const fetchLimit = safeLimit > 0 ? safeLimit + 1 : 0;
|
|
75
|
+
if (fetchLimit === 0) {
|
|
76
|
+
return {
|
|
77
|
+
model: modelName,
|
|
78
|
+
documents: [],
|
|
79
|
+
limit: safeLimit,
|
|
80
|
+
skip,
|
|
81
|
+
results_count: 0,
|
|
82
|
+
has_more: false,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
if (relations.length === 0) {
|
|
86
|
+
const projection = buildProjection(fields);
|
|
87
|
+
const cursor = collection
|
|
88
|
+
.find(filters, projection ? { projection } : undefined)
|
|
89
|
+
.sort(sortBy)
|
|
90
|
+
.skip(skip)
|
|
91
|
+
.limit(fetchLimit);
|
|
92
|
+
const fetched = await cursor.toArray();
|
|
93
|
+
const has_more = fetched.length > safeLimit;
|
|
94
|
+
const documents = has_more ? fetched.slice(0, safeLimit) : fetched;
|
|
95
|
+
return {
|
|
96
|
+
model: modelName,
|
|
97
|
+
documents,
|
|
98
|
+
limit: safeLimit,
|
|
99
|
+
skip,
|
|
100
|
+
results_count: documents.length,
|
|
101
|
+
has_more,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
const projectionFields = [...fields];
|
|
105
|
+
for (const relation of relations) {
|
|
106
|
+
if (relation?.path && !projectionFields.includes(relation.path)) {
|
|
107
|
+
projectionFields.push(relation.path);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const projection = buildProjection(projectionFields);
|
|
111
|
+
const pipeline = [
|
|
112
|
+
{ $match: filters },
|
|
113
|
+
{ $sort: sortBy },
|
|
114
|
+
{ $skip: skip },
|
|
115
|
+
{ $limit: fetchLimit },
|
|
116
|
+
];
|
|
117
|
+
for (const relation of relations) {
|
|
118
|
+
const path = relation.path;
|
|
119
|
+
const localField = relation.localField || relation.path;
|
|
120
|
+
const foreignField = relation.foreignField || "_id";
|
|
121
|
+
const lookup = {
|
|
122
|
+
from: relation.target,
|
|
123
|
+
localField,
|
|
124
|
+
foreignField,
|
|
125
|
+
as: path,
|
|
126
|
+
};
|
|
127
|
+
if (Array.isArray(relation.select) && relation.select.length > 0) {
|
|
128
|
+
const selectProjection = buildProjection(relation.select);
|
|
129
|
+
lookup.pipeline = selectProjection
|
|
130
|
+
? [{ $project: selectProjection }]
|
|
131
|
+
: undefined;
|
|
132
|
+
}
|
|
133
|
+
pipeline.push({ $lookup: lookup });
|
|
134
|
+
if (relation.singleResult) {
|
|
135
|
+
pipeline.push({
|
|
136
|
+
$unwind: {
|
|
137
|
+
path: `$${path}`,
|
|
138
|
+
preserveNullAndEmptyArrays: true,
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (projection) {
|
|
144
|
+
pipeline.push({ $project: projection });
|
|
145
|
+
}
|
|
146
|
+
const fetched = await collection.aggregate(pipeline).toArray();
|
|
147
|
+
const has_more = fetched.length > safeLimit;
|
|
148
|
+
const documents = has_more ? fetched.slice(0, safeLimit) : fetched;
|
|
149
|
+
return {
|
|
150
|
+
model: modelName,
|
|
151
|
+
documents,
|
|
152
|
+
limit: safeLimit,
|
|
153
|
+
skip,
|
|
154
|
+
results_count: documents.length,
|
|
155
|
+
has_more,
|
|
156
|
+
};
|
|
157
|
+
},
|
|
158
|
+
async aggregateDocuments(params) {
|
|
159
|
+
const modelName = String(params.model || "");
|
|
160
|
+
const model = registry[modelName];
|
|
161
|
+
if (!model) {
|
|
162
|
+
throw new Error(`Model '${modelName}' is not registered`);
|
|
163
|
+
}
|
|
164
|
+
const collection = db.collection(model.collectionName);
|
|
165
|
+
const pipeline = Array.isArray(params.pipeline) ? params.pipeline : [];
|
|
166
|
+
const mongoPipeline = buildPipeline(pipeline);
|
|
167
|
+
const results = await collection.aggregate(mongoPipeline).toArray();
|
|
168
|
+
let total_count;
|
|
169
|
+
const lastStage = pipeline[pipeline.length - 1];
|
|
170
|
+
if (lastStage?.stage === "count" && results.length > 0) {
|
|
171
|
+
const first = results[0];
|
|
172
|
+
const countKey = Object.keys(first)[0];
|
|
173
|
+
const countValue = countKey ? Number(first[countKey]) : NaN;
|
|
174
|
+
if (!Number.isNaN(countValue)) {
|
|
175
|
+
total_count = countValue;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
model: modelName,
|
|
180
|
+
results,
|
|
181
|
+
results_count: results.length,
|
|
182
|
+
has_more: false,
|
|
183
|
+
...(total_count !== undefined ? { total_count } : {}),
|
|
184
|
+
};
|
|
185
|
+
},
|
|
186
|
+
async getDocumentById(params) {
|
|
187
|
+
const modelName = String(params.model || "");
|
|
188
|
+
const model = registry[modelName];
|
|
189
|
+
if (!model) {
|
|
190
|
+
throw new Error(`Model '${modelName}' is not registered`);
|
|
191
|
+
}
|
|
192
|
+
const collection = db.collection(model.collectionName);
|
|
193
|
+
const documentId = params.documentId;
|
|
194
|
+
const filters = params.filters || {};
|
|
195
|
+
const fields = Array.isArray(params.fields) ? params.fields : model.allowedFields;
|
|
196
|
+
const projection = buildProjection(fields);
|
|
197
|
+
const query = { _id: documentId, ...filters };
|
|
198
|
+
const document = await collection.findOne(query, projection ? { projection } : undefined);
|
|
199
|
+
if (!document) {
|
|
200
|
+
return { model: modelName, found: false };
|
|
201
|
+
}
|
|
202
|
+
return { model: modelName, found: true, document };
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ClientConfig, ConversationMessage, QueryRequest, QueryResponse } from "./types";
|
|
1
|
+
import { ClientConfig, ConversationMessage, QueryRequest, QueryResponse, StreamEvent } from "./types";
|
|
2
2
|
declare class AiClient {
|
|
3
3
|
private apiKey;
|
|
4
4
|
private registryVersion;
|
|
@@ -18,6 +18,7 @@ declare class AiClient {
|
|
|
18
18
|
private summarizeResult;
|
|
19
19
|
private selectHistoryWindow;
|
|
20
20
|
private authHeaders;
|
|
21
|
+
private buildQueryResponse;
|
|
21
22
|
initRegistry(): Promise<string>;
|
|
22
23
|
private resolveRequiredFilters;
|
|
23
24
|
private castRequiredValue;
|
|
@@ -29,6 +30,7 @@ declare class AiClient {
|
|
|
29
30
|
private applyRequiredFilters;
|
|
30
31
|
private executeToolCall;
|
|
31
32
|
query(request: QueryRequest): Promise<QueryResponse>;
|
|
33
|
+
queryStream(request: QueryRequest, onEvent?: (event: StreamEvent) => void): Promise<QueryResponse>;
|
|
32
34
|
getConversationMessages(conversationId: string): Promise<ConversationMessage[]>;
|
|
33
35
|
}
|
|
34
36
|
export declare function createAiClient(config: ClientConfig): AiClient;
|