@aigne/core 1.16.0 → 1.18.0
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/CHANGELOG.md +37 -16
- package/lib/cjs/agents/agent.d.ts +69 -37
- package/lib/cjs/agents/agent.js +93 -65
- package/lib/cjs/agents/ai-agent.d.ts +4 -7
- package/lib/cjs/agents/ai-agent.js +10 -19
- package/lib/cjs/agents/chat-model.d.ts +7 -8
- package/lib/cjs/agents/chat-model.js +9 -9
- package/lib/cjs/agents/mcp-agent.d.ts +4 -5
- package/lib/cjs/agents/mcp-agent.js +7 -13
- package/lib/cjs/agents/team-agent.d.ts +7 -8
- package/lib/cjs/agents/team-agent.js +10 -10
- package/lib/cjs/agents/user-agent.d.ts +4 -5
- package/lib/cjs/agents/user-agent.js +11 -12
- package/lib/cjs/aigne/aigne.d.ts +10 -9
- package/lib/cjs/aigne/aigne.js +5 -4
- package/lib/cjs/aigne/context.d.ts +18 -9
- package/lib/cjs/aigne/context.js +23 -12
- package/lib/cjs/aigne/message-queue.d.ts +6 -2
- package/lib/cjs/aigne/message-queue.js +2 -2
- package/lib/cjs/index.d.ts +3 -1
- package/lib/cjs/index.js +3 -1
- package/lib/cjs/loader/agent-js.d.ts +1 -1
- package/lib/cjs/loader/agent-yaml.d.ts +3 -2
- package/lib/cjs/loader/agent-yaml.js +3 -2
- package/lib/cjs/loader/index.d.ts +5 -1
- package/lib/cjs/loader/index.js +25 -16
- package/lib/cjs/memory/memory.d.ts +3 -2
- package/lib/cjs/memory/memory.js +1 -1
- package/lib/cjs/memory/retriever.d.ts +2 -2
- package/lib/cjs/prompt/prompt-builder.d.ts +9 -7
- package/lib/cjs/prompt/prompt-builder.js +14 -10
- package/lib/cjs/prompt/template.js +1 -3
- package/lib/cjs/utils/logger.js +3 -3
- package/lib/cjs/utils/nodejs.d.ts +8 -0
- package/lib/cjs/utils/nodejs.js +24 -0
- package/lib/cjs/utils/type-utils.d.ts +2 -2
- package/lib/dts/agents/agent.d.ts +69 -37
- package/lib/dts/agents/ai-agent.d.ts +4 -7
- package/lib/dts/agents/chat-model.d.ts +7 -8
- package/lib/dts/agents/mcp-agent.d.ts +4 -5
- package/lib/dts/agents/team-agent.d.ts +7 -8
- package/lib/dts/agents/user-agent.d.ts +4 -5
- package/lib/dts/aigne/aigne.d.ts +10 -9
- package/lib/dts/aigne/context.d.ts +18 -9
- package/lib/dts/aigne/message-queue.d.ts +6 -2
- package/lib/dts/index.d.ts +3 -1
- package/lib/dts/loader/agent-js.d.ts +1 -1
- package/lib/dts/loader/agent-yaml.d.ts +3 -2
- package/lib/dts/loader/index.d.ts +5 -1
- package/lib/dts/memory/memory.d.ts +3 -2
- package/lib/dts/memory/retriever.d.ts +2 -2
- package/lib/dts/prompt/prompt-builder.d.ts +9 -7
- package/lib/dts/utils/nodejs.d.ts +8 -0
- package/lib/dts/utils/type-utils.d.ts +2 -2
- package/lib/esm/agents/agent.d.ts +69 -37
- package/lib/esm/agents/agent.js +94 -66
- package/lib/esm/agents/ai-agent.d.ts +4 -7
- package/lib/esm/agents/ai-agent.js +10 -19
- package/lib/esm/agents/chat-model.d.ts +7 -8
- package/lib/esm/agents/chat-model.js +9 -9
- package/lib/esm/agents/mcp-agent.d.ts +4 -5
- package/lib/esm/agents/mcp-agent.js +7 -13
- package/lib/esm/agents/team-agent.d.ts +7 -8
- package/lib/esm/agents/team-agent.js +10 -10
- package/lib/esm/agents/user-agent.d.ts +4 -5
- package/lib/esm/agents/user-agent.js +10 -11
- package/lib/esm/aigne/aigne.d.ts +10 -9
- package/lib/esm/aigne/aigne.js +5 -4
- package/lib/esm/aigne/context.d.ts +18 -9
- package/lib/esm/aigne/context.js +24 -10
- package/lib/esm/aigne/message-queue.d.ts +6 -2
- package/lib/esm/aigne/message-queue.js +2 -2
- package/lib/esm/index.d.ts +3 -1
- package/lib/esm/index.js +3 -1
- package/lib/esm/loader/agent-js.d.ts +1 -1
- package/lib/esm/loader/agent-yaml.d.ts +3 -2
- package/lib/esm/loader/agent-yaml.js +3 -2
- package/lib/esm/loader/index.d.ts +5 -1
- package/lib/esm/loader/index.js +25 -16
- package/lib/esm/memory/memory.d.ts +3 -2
- package/lib/esm/memory/memory.js +2 -2
- package/lib/esm/memory/retriever.d.ts +2 -2
- package/lib/esm/prompt/prompt-builder.d.ts +9 -7
- package/lib/esm/prompt/prompt-builder.js +15 -11
- package/lib/esm/prompt/template.js +1 -3
- package/lib/esm/utils/logger.js +3 -3
- package/lib/esm/utils/nodejs.d.ts +8 -0
- package/lib/esm/utils/nodejs.js +21 -0
- package/lib/esm/utils/type-utils.d.ts +2 -2
- package/package.json +4 -3
- package/lib/cjs/memory/default-memory.d.ts +0 -16
- package/lib/cjs/memory/default-memory.js +0 -70
- package/lib/cjs/utils/fs.d.ts +0 -2
- package/lib/cjs/utils/fs.js +0 -25
- package/lib/dts/memory/default-memory.d.ts +0 -16
- package/lib/dts/utils/fs.d.ts +0 -2
- package/lib/esm/memory/default-memory.d.ts +0 -16
- package/lib/esm/memory/default-memory.js +0 -63
- package/lib/esm/utils/fs.d.ts +0 -2
- package/lib/esm/utils/fs.js +0 -21
package/lib/cjs/agents/agent.js
CHANGED
|
@@ -40,10 +40,10 @@ exports.FunctionAgent = exports.Agent = exports.agentOptionsSchema = void 0;
|
|
|
40
40
|
exports.isEmptyChunk = isEmptyChunk;
|
|
41
41
|
exports.textDelta = textDelta;
|
|
42
42
|
exports.jsonDelta = jsonDelta;
|
|
43
|
-
const node_util_1 = require("node:util");
|
|
44
43
|
const zod_1 = require("zod");
|
|
45
44
|
const prompt_builder_js_1 = require("../prompt/prompt-builder.js");
|
|
46
45
|
const logger_js_1 = require("../utils/logger.js");
|
|
46
|
+
const nodejs_js_1 = require("../utils/nodejs.js");
|
|
47
47
|
const stream_utils_js_1 = require("../utils/stream-utils.js");
|
|
48
48
|
const type_utils_js_1 = require("../utils/type-utils.js");
|
|
49
49
|
const types_js_1 = require("./types.js");
|
|
@@ -61,6 +61,7 @@ exports.agentOptionsSchema = zod_1.z.object({
|
|
|
61
61
|
skills: zod_1.z.array(zod_1.z.union([zod_1.z.custom(), zod_1.z.custom()])).optional(),
|
|
62
62
|
disableEvents: zod_1.z.boolean().optional(),
|
|
63
63
|
memory: zod_1.z.union([zod_1.z.custom(), zod_1.z.array(zod_1.z.custom())]).optional(),
|
|
64
|
+
maxRetrieveMemoryCount: zod_1.z.number().optional(),
|
|
64
65
|
hooks: zod_1.z
|
|
65
66
|
.object({
|
|
66
67
|
onStart: zod_1.z.custom().optional(),
|
|
@@ -117,6 +118,7 @@ class Agent {
|
|
|
117
118
|
else if (options.memory) {
|
|
118
119
|
this.memories.push(options.memory);
|
|
119
120
|
}
|
|
121
|
+
this.maxRetrieveMemoryCount = options.maxRetrieveMemoryCount;
|
|
120
122
|
this.hooks = options.hooks ?? {};
|
|
121
123
|
this.guideRails = options.guideRails;
|
|
122
124
|
}
|
|
@@ -124,6 +126,10 @@ class Agent {
|
|
|
124
126
|
* List of memories this agent can use
|
|
125
127
|
*/
|
|
126
128
|
memories = [];
|
|
129
|
+
/**
|
|
130
|
+
* Maximum number of memory items to retrieve
|
|
131
|
+
*/
|
|
132
|
+
maxRetrieveMemoryCount;
|
|
127
133
|
/**
|
|
128
134
|
* Lifecycle hooks for agent processing.
|
|
129
135
|
*
|
|
@@ -292,68 +298,92 @@ class Agent {
|
|
|
292
298
|
/**
|
|
293
299
|
* Check context status to ensure it hasn't timed out
|
|
294
300
|
*
|
|
295
|
-
* @param
|
|
301
|
+
* @param options Invocation options containing context
|
|
296
302
|
* @throws Error if the context has timed out
|
|
297
303
|
*/
|
|
298
|
-
checkContextStatus(
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
throw new Error(`AIGNE for agent ${this.name} has timed out`);
|
|
303
|
-
}
|
|
304
|
+
checkContextStatus(options) {
|
|
305
|
+
const { status } = options.context;
|
|
306
|
+
if (status === "timeout") {
|
|
307
|
+
throw new Error(`AIGNE for agent ${this.name} has timed out`);
|
|
304
308
|
}
|
|
305
309
|
}
|
|
306
310
|
async newDefaultContext() {
|
|
307
311
|
return Promise.resolve().then(() => __importStar(require("../aigne/context.js"))).then((m) => new m.AIGNEContext());
|
|
308
312
|
}
|
|
309
|
-
async
|
|
310
|
-
const
|
|
313
|
+
async retrieveMemories(input, options) {
|
|
314
|
+
const memories = [];
|
|
315
|
+
for (const memory of this.memories) {
|
|
316
|
+
const ms = (await memory.retrieve({
|
|
317
|
+
...input,
|
|
318
|
+
search: typeof input === "string" ? input : input && (0, prompt_builder_js_1.getMessage)(input),
|
|
319
|
+
limit: input.limit ?? this.maxRetrieveMemoryCount,
|
|
320
|
+
}, options.context)).memories;
|
|
321
|
+
memories.push(...ms);
|
|
322
|
+
}
|
|
323
|
+
return memories;
|
|
324
|
+
}
|
|
325
|
+
async recordMemories(input, options) {
|
|
326
|
+
for (const memory of this.memories) {
|
|
327
|
+
if (memory.autoUpdate) {
|
|
328
|
+
await memory.record(input, options.context);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
async invoke(input, options = {}) {
|
|
333
|
+
const opts = {
|
|
334
|
+
...options,
|
|
335
|
+
context: options.context ?? (await this.newDefaultContext()),
|
|
336
|
+
};
|
|
337
|
+
if (options.userContext) {
|
|
338
|
+
Object.assign(opts.context.userContext, options.userContext);
|
|
339
|
+
}
|
|
311
340
|
const message = typeof input === "string" ? (0, prompt_builder_js_1.createMessage)(input) : input;
|
|
312
341
|
logger_js_1.logger.debug("Invoke agent %s started with input: %O", this.name, input);
|
|
313
342
|
if (!this.disableEvents)
|
|
314
|
-
|
|
343
|
+
opts.context.emit("agentStarted", { agent: this, input: message });
|
|
315
344
|
try {
|
|
316
|
-
await this.hooks.onStart?.({ input: message });
|
|
345
|
+
await this.hooks.onStart?.({ context: opts.context, input: message });
|
|
317
346
|
const parsedInput = (0, type_utils_js_1.checkArguments)(`Agent ${this.name} input`, this.inputSchema, message);
|
|
318
|
-
await this.preprocess(parsedInput,
|
|
319
|
-
this.checkContextStatus(
|
|
320
|
-
let response = await this.process(parsedInput,
|
|
347
|
+
await this.preprocess(parsedInput, opts);
|
|
348
|
+
this.checkContextStatus(opts);
|
|
349
|
+
let response = await this.process(parsedInput, opts);
|
|
321
350
|
if (response instanceof Agent) {
|
|
322
351
|
response = (0, types_js_1.transferToAgentOutput)(response);
|
|
323
352
|
}
|
|
324
|
-
if (
|
|
353
|
+
if (opts.streaming) {
|
|
325
354
|
const stream = response instanceof ReadableStream
|
|
326
355
|
? response
|
|
327
356
|
: (0, stream_utils_js_1.isAsyncGenerator)(response)
|
|
328
357
|
? (0, stream_utils_js_1.asyncGeneratorToReadableStream)(response)
|
|
329
358
|
: (0, stream_utils_js_1.objectToAgentResponseStream)(response);
|
|
330
359
|
return this.checkResponseByGuideRails(message, (0, stream_utils_js_1.onAgentResponseStreamEnd)(stream, async (result) => {
|
|
331
|
-
return await this.processAgentOutput(parsedInput, result,
|
|
360
|
+
return await this.processAgentOutput(parsedInput, result, opts);
|
|
332
361
|
}, {
|
|
333
362
|
errorCallback: async (error) => {
|
|
334
|
-
return await this.processAgentError(message, error,
|
|
363
|
+
return await this.processAgentError(message, error, opts);
|
|
335
364
|
},
|
|
336
|
-
}),
|
|
365
|
+
}), opts);
|
|
337
366
|
}
|
|
338
367
|
return await this.checkResponseByGuideRails(message, this.processAgentOutput(parsedInput, response instanceof ReadableStream
|
|
339
368
|
? await (0, stream_utils_js_1.agentResponseStreamToObject)(response)
|
|
340
369
|
: (0, stream_utils_js_1.isAsyncGenerator)(response)
|
|
341
370
|
? await (0, stream_utils_js_1.agentResponseStreamToObject)(response)
|
|
342
|
-
: response,
|
|
371
|
+
: response, opts), opts);
|
|
343
372
|
}
|
|
344
373
|
catch (error) {
|
|
345
|
-
throw await this.processAgentError(message, error,
|
|
374
|
+
throw await this.processAgentError(message, error, opts);
|
|
346
375
|
}
|
|
347
376
|
}
|
|
348
|
-
async invokeSkill(skill, input,
|
|
349
|
-
|
|
377
|
+
async invokeSkill(skill, input, options) {
|
|
378
|
+
const { context } = options;
|
|
379
|
+
await this.hooks.onSkillStart?.({ context, skill, input });
|
|
350
380
|
try {
|
|
351
381
|
const output = await context.invoke(skill, input);
|
|
352
|
-
await this.hooks.onSkillEnd?.({ skill, input, output });
|
|
382
|
+
await this.hooks.onSkillEnd?.({ context, skill, input, output });
|
|
353
383
|
return output;
|
|
354
384
|
}
|
|
355
385
|
catch (error) {
|
|
356
|
-
await this.hooks.onSkillEnd?.({ skill, input, error });
|
|
386
|
+
await this.hooks.onSkillEnd?.({ context, skill, input, error });
|
|
357
387
|
throw error;
|
|
358
388
|
}
|
|
359
389
|
}
|
|
@@ -364,17 +394,18 @@ class Agent {
|
|
|
364
394
|
*
|
|
365
395
|
* @param input Original input message
|
|
366
396
|
* @param output Raw output produced by the agent
|
|
367
|
-
* @param
|
|
397
|
+
* @param options Invocation options
|
|
368
398
|
* @returns Final processed output
|
|
369
399
|
*/
|
|
370
|
-
async processAgentOutput(input, output,
|
|
400
|
+
async processAgentOutput(input, output, options) {
|
|
401
|
+
const { context } = options;
|
|
371
402
|
const parsedOutput = (0, type_utils_js_1.checkArguments)(`Agent ${this.name} output`, this.outputSchema, output);
|
|
372
403
|
const finalOutput = this.includeInputInOutput ? { ...input, ...parsedOutput } : parsedOutput;
|
|
373
|
-
await this.postprocess(input, finalOutput,
|
|
404
|
+
await this.postprocess(input, finalOutput, options);
|
|
374
405
|
logger_js_1.logger.debug("Invoke agent %s succeed with output: %O", this.name, finalOutput);
|
|
375
406
|
if (!this.disableEvents)
|
|
376
407
|
context.emit("agentSucceed", { agent: this, output: finalOutput });
|
|
377
|
-
await this.hooks.onEnd?.({ input, output: finalOutput });
|
|
408
|
+
await this.hooks.onEnd?.({ context, input, output: finalOutput });
|
|
378
409
|
return finalOutput;
|
|
379
410
|
}
|
|
380
411
|
/**
|
|
@@ -383,13 +414,14 @@ class Agent {
|
|
|
383
414
|
* Logs error information, triggers failure events, and re-throws the error
|
|
384
415
|
*
|
|
385
416
|
* @param error Caught error
|
|
386
|
-
* @param
|
|
417
|
+
* @param options Invocation options
|
|
387
418
|
*/
|
|
388
|
-
async processAgentError(input, error,
|
|
419
|
+
async processAgentError(input, error, options) {
|
|
389
420
|
logger_js_1.logger.error("Invoke agent %s failed with error: %O", this.name, error);
|
|
390
421
|
if (!this.disableEvents)
|
|
391
|
-
context.emit("agentFailed", { agent: this, error });
|
|
392
|
-
|
|
422
|
+
options.context.emit("agentFailed", { agent: this, error });
|
|
423
|
+
const { context } = options;
|
|
424
|
+
await this.hooks.onEnd?.({ context, input, error });
|
|
393
425
|
return error;
|
|
394
426
|
}
|
|
395
427
|
/**
|
|
@@ -398,11 +430,11 @@ class Agent {
|
|
|
398
430
|
* If the context has a maximum invocation limit set, checks if the limit
|
|
399
431
|
* has been exceeded and increments the invocation counter
|
|
400
432
|
*
|
|
401
|
-
* @param context
|
|
433
|
+
* @param options Invocation options containing context and limits
|
|
402
434
|
* @throws Error if maximum invocation limit is exceeded
|
|
403
435
|
*/
|
|
404
|
-
checkAgentInvokesUsage(
|
|
405
|
-
const { limits, usage } = context;
|
|
436
|
+
checkAgentInvokesUsage(options) {
|
|
437
|
+
const { limits, usage } = options.context;
|
|
406
438
|
if (limits?.maxAgentInvokes && usage.agentCalls >= limits.maxAgentInvokes) {
|
|
407
439
|
throw new Error(`Exceeded max agent invokes ${usage.agentCalls}/${limits.maxAgentInvokes}`);
|
|
408
440
|
}
|
|
@@ -416,19 +448,19 @@ class Agent {
|
|
|
416
448
|
* - Verifying invocation limits
|
|
417
449
|
*
|
|
418
450
|
* @param _ Input message (unused)
|
|
419
|
-
* @param
|
|
451
|
+
* @param options Options for agent invocation
|
|
420
452
|
*/
|
|
421
|
-
preprocess(_,
|
|
422
|
-
this.checkContextStatus(
|
|
423
|
-
this.checkAgentInvokesUsage(
|
|
453
|
+
async preprocess(_, options) {
|
|
454
|
+
this.checkContextStatus(options);
|
|
455
|
+
this.checkAgentInvokesUsage(options);
|
|
424
456
|
}
|
|
425
|
-
async checkResponseByGuideRails(input, output,
|
|
457
|
+
async checkResponseByGuideRails(input, output, options) {
|
|
426
458
|
if (!this.guideRails?.length)
|
|
427
459
|
return output;
|
|
428
460
|
const result = await output;
|
|
429
461
|
if (result instanceof ReadableStream) {
|
|
430
462
|
return (0, stream_utils_js_1.onAgentResponseStreamEnd)(result, async (result) => {
|
|
431
|
-
const error = await this.runGuideRails(input, result,
|
|
463
|
+
const error = await this.runGuideRails(input, result, options);
|
|
432
464
|
if (error) {
|
|
433
465
|
return {
|
|
434
466
|
...(await this.onGuideRailError(error)),
|
|
@@ -437,13 +469,13 @@ class Agent {
|
|
|
437
469
|
}
|
|
438
470
|
});
|
|
439
471
|
}
|
|
440
|
-
const error = await this.runGuideRails(input, result,
|
|
472
|
+
const error = await this.runGuideRails(input, result, options);
|
|
441
473
|
if (!error)
|
|
442
474
|
return output;
|
|
443
475
|
return { ...(await this.onGuideRailError(error)), $status: "GuideRailError" };
|
|
444
476
|
}
|
|
445
|
-
async runGuideRails(input, output,
|
|
446
|
-
const result = await Promise.all((this.guideRails ?? []).map((i) => context.invoke(i, { input, output })));
|
|
477
|
+
async runGuideRails(input, output, options) {
|
|
478
|
+
const result = await Promise.all((this.guideRails ?? []).map((i) => options.context.invoke(i, { input, output })));
|
|
447
479
|
return result.find((i) => !!i.abort);
|
|
448
480
|
}
|
|
449
481
|
/**
|
|
@@ -473,26 +505,22 @@ class Agent {
|
|
|
473
505
|
*
|
|
474
506
|
* @param input Input message
|
|
475
507
|
* @param output Output message
|
|
476
|
-
* @param
|
|
508
|
+
* @param options Options for agent invocation
|
|
477
509
|
*/
|
|
478
|
-
postprocess(input, output,
|
|
479
|
-
this.checkContextStatus(
|
|
480
|
-
this.publishToTopics(output,
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
],
|
|
488
|
-
}, context);
|
|
489
|
-
}
|
|
490
|
-
}
|
|
510
|
+
async postprocess(input, output, options) {
|
|
511
|
+
this.checkContextStatus(options);
|
|
512
|
+
this.publishToTopics(output, options);
|
|
513
|
+
await this.recordMemories({
|
|
514
|
+
content: [
|
|
515
|
+
{ role: "user", content: input },
|
|
516
|
+
{ role: "agent", content: (0, types_js_1.replaceTransferAgentToName)(output), source: this.name },
|
|
517
|
+
],
|
|
518
|
+
}, options);
|
|
491
519
|
}
|
|
492
|
-
async publishToTopics(output,
|
|
520
|
+
async publishToTopics(output, options) {
|
|
493
521
|
const publishTopics = typeof this.publishTopic === "function" ? await this.publishTopic(output) : this.publishTopic;
|
|
494
522
|
if (publishTopics?.length) {
|
|
495
|
-
context.publish(publishTopics, {
|
|
523
|
+
options.context.publish(publishTopics, {
|
|
496
524
|
role: this.constructor.name === "UserAgent" ? "user" : "agent",
|
|
497
525
|
source: this.name,
|
|
498
526
|
message: output,
|
|
@@ -529,7 +557,7 @@ class Agent {
|
|
|
529
557
|
*
|
|
530
558
|
* @returns Agent name
|
|
531
559
|
*/
|
|
532
|
-
[
|
|
560
|
+
[nodejs_js_1.nodejs.customInspect]() {
|
|
533
561
|
return this.name;
|
|
534
562
|
}
|
|
535
563
|
/**
|
|
@@ -645,11 +673,11 @@ class FunctionAgent extends Agent {
|
|
|
645
673
|
* Process input implementation, calls the configured processing function
|
|
646
674
|
*
|
|
647
675
|
* @param input Input message
|
|
648
|
-
* @param
|
|
676
|
+
* @param options Invocation options
|
|
649
677
|
* @returns Processing result
|
|
650
678
|
*/
|
|
651
|
-
process(input,
|
|
652
|
-
return this._process(input,
|
|
679
|
+
process(input, options) {
|
|
680
|
+
return this._process(input, options);
|
|
653
681
|
}
|
|
654
682
|
}
|
|
655
683
|
exports.FunctionAgent = FunctionAgent;
|
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { type ZodObject, type ZodType, z } from "zod";
|
|
2
|
-
import type { Context } from "../aigne/context.js";
|
|
3
|
-
import { type DefaultMemoryOptions } from "../memory/default-memory.js";
|
|
4
2
|
import { PromptBuilder } from "../prompt/prompt-builder.js";
|
|
5
|
-
import { Agent, type AgentOptions, type AgentProcessAsyncGenerator, type Message } from "./agent.js";
|
|
3
|
+
import { Agent, type AgentInvokeOptions, type AgentOptions, type AgentProcessAsyncGenerator, type Message } from "./agent.js";
|
|
6
4
|
import { ChatModel, type ChatModelInput } from "./chat-model.js";
|
|
7
5
|
import type { GuideRailAgentOutput } from "./guide-rail-agent.js";
|
|
8
6
|
/**
|
|
@@ -14,7 +12,7 @@ import type { GuideRailAgentOutput } from "./guide-rail-agent.js";
|
|
|
14
12
|
* @template I The input message type the agent accepts
|
|
15
13
|
* @template O The output message type the agent returns
|
|
16
14
|
*/
|
|
17
|
-
export interface AIAgentOptions<I extends Message = Message, O extends Message = Message> extends
|
|
15
|
+
export interface AIAgentOptions<I extends Message = Message, O extends Message = Message> extends AgentOptions<I, O> {
|
|
18
16
|
/**
|
|
19
17
|
* The language model to use for this agent
|
|
20
18
|
*
|
|
@@ -66,7 +64,6 @@ export interface AIAgentOptions<I extends Message = Message, O extends Message =
|
|
|
66
64
|
* The template receives a {{memories}} variable containing serialized memory content.
|
|
67
65
|
*/
|
|
68
66
|
memoryPromptTemplate?: string;
|
|
69
|
-
memory?: AgentOptions<I, O>["memory"] | DefaultMemoryOptions | true;
|
|
70
67
|
}
|
|
71
68
|
/**
|
|
72
69
|
* Tool choice options for AI agents
|
|
@@ -215,7 +212,7 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
|
|
|
215
212
|
*
|
|
216
213
|
* @protected
|
|
217
214
|
*/
|
|
218
|
-
process(input: I,
|
|
215
|
+
process(input: I, options: AgentInvokeOptions): AgentProcessAsyncGenerator<O>;
|
|
219
216
|
protected onGuideRailError(error: GuideRailAgentOutput): Promise<O | GuideRailAgentOutput>;
|
|
220
217
|
/**
|
|
221
218
|
* Process router mode requests
|
|
@@ -225,5 +222,5 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
|
|
|
225
222
|
*
|
|
226
223
|
* @protected
|
|
227
224
|
*/
|
|
228
|
-
_processRouter(input: I, model: ChatModel, modelInput: ChatModelInput,
|
|
225
|
+
_processRouter(input: I, model: ChatModel, modelInput: ChatModelInput, options: AgentInvokeOptions, toolsMap: Map<string, Agent>): AgentProcessAsyncGenerator<O>;
|
|
229
226
|
}
|
|
@@ -2,8 +2,6 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.AIAgent = exports.aiAgentOptionsSchema = exports.aiAgentToolChoiceSchema = exports.AIAgentToolChoice = void 0;
|
|
4
4
|
const zod_1 = require("zod");
|
|
5
|
-
const default_memory_js_1 = require("../memory/default-memory.js");
|
|
6
|
-
const memory_js_1 = require("../memory/memory.js");
|
|
7
5
|
const prompt_builder_js_1 = require("../prompt/prompt-builder.js");
|
|
8
6
|
const template_js_1 = require("../prompt/template.js");
|
|
9
7
|
const type_utils_js_1 = require("../utils/type-utils.js");
|
|
@@ -101,14 +99,7 @@ class AIAgent extends agent_js_1.Agent {
|
|
|
101
99
|
* @param options Configuration options for the AI agent
|
|
102
100
|
*/
|
|
103
101
|
constructor(options) {
|
|
104
|
-
super(
|
|
105
|
-
...options,
|
|
106
|
-
memory: !options.memory
|
|
107
|
-
? undefined
|
|
108
|
-
: Array.isArray(options.memory) || options.memory instanceof memory_js_1.MemoryAgent
|
|
109
|
-
? options.memory
|
|
110
|
-
: new default_memory_js_1.DefaultMemory(options.memory === true ? {} : options.memory),
|
|
111
|
-
});
|
|
102
|
+
super(options);
|
|
112
103
|
(0, type_utils_js_1.checkArguments)("AIAgent", exports.aiAgentOptionsSchema, options);
|
|
113
104
|
this.model = options.model;
|
|
114
105
|
this.instructions =
|
|
@@ -188,26 +179,26 @@ class AIAgent extends agent_js_1.Agent {
|
|
|
188
179
|
*
|
|
189
180
|
* @protected
|
|
190
181
|
*/
|
|
191
|
-
async *process(input,
|
|
192
|
-
const model = this.model ?? context.model;
|
|
182
|
+
async *process(input, options) {
|
|
183
|
+
const model = this.model ?? options.context.model;
|
|
193
184
|
if (!model)
|
|
194
185
|
throw new Error("model is required to run AIAgent");
|
|
195
186
|
const { toolAgents, ...modelInput } = await this.instructions.build({
|
|
187
|
+
...options,
|
|
196
188
|
agent: this,
|
|
197
189
|
input,
|
|
198
190
|
model,
|
|
199
|
-
context,
|
|
200
191
|
});
|
|
201
192
|
const toolsMap = new Map(toolAgents?.map((i) => [i.name, i]));
|
|
202
193
|
if (this.toolChoice === "router") {
|
|
203
|
-
yield* this._processRouter(input, model, modelInput,
|
|
194
|
+
yield* this._processRouter(input, model, modelInput, options, toolsMap);
|
|
204
195
|
return;
|
|
205
196
|
}
|
|
206
197
|
const toolCallMessages = [];
|
|
207
198
|
const outputKey = this.outputKey || prompt_builder_js_1.MESSAGE_KEY;
|
|
208
199
|
for (;;) {
|
|
209
200
|
const modelOutput = {};
|
|
210
|
-
const stream = await context.invoke(model, { ...modelInput, messages: modelInput.messages.concat(toolCallMessages) }, { streaming: true });
|
|
201
|
+
const stream = await options.context.invoke(model, { ...modelInput, messages: modelInput.messages.concat(toolCallMessages) }, { streaming: true });
|
|
211
202
|
for await (const value of stream) {
|
|
212
203
|
if (value.delta.text?.text) {
|
|
213
204
|
yield { delta: { text: { [outputKey]: value.delta.text.text } } };
|
|
@@ -225,7 +216,7 @@ class AIAgent extends agent_js_1.Agent {
|
|
|
225
216
|
if (!tool)
|
|
226
217
|
throw new Error(`Tool not found: ${call.function.name}`);
|
|
227
218
|
// NOTE: should pass both arguments (model generated) and input (user provided) to the tool
|
|
228
|
-
const output = await this.invokeSkill(tool, { ...input, ...call.function.arguments },
|
|
219
|
+
const output = await this.invokeSkill(tool, { ...input, ...call.function.arguments }, options).catch((error) => {
|
|
229
220
|
if (!this.catchToolsError) {
|
|
230
221
|
return Promise.reject(error);
|
|
231
222
|
}
|
|
@@ -275,15 +266,15 @@ class AIAgent extends agent_js_1.Agent {
|
|
|
275
266
|
*
|
|
276
267
|
* @protected
|
|
277
268
|
*/
|
|
278
|
-
async *_processRouter(input, model, modelInput,
|
|
279
|
-
const { toolCalls: [call] = [], } = await context.invoke(model, modelInput);
|
|
269
|
+
async *_processRouter(input, model, modelInput, options, toolsMap) {
|
|
270
|
+
const { toolCalls: [call] = [], } = await options.context.invoke(model, modelInput);
|
|
280
271
|
if (!call) {
|
|
281
272
|
throw new Error("Router toolChoice requires exactly one tool to be executed");
|
|
282
273
|
}
|
|
283
274
|
const tool = toolsMap.get(call.function.name);
|
|
284
275
|
if (!tool)
|
|
285
276
|
throw new Error(`Tool not found: ${call.function.name}`);
|
|
286
|
-
const stream = await context.invoke(tool, { ...call.function.arguments, ...input }, { streaming: true, sourceAgent: this });
|
|
277
|
+
const stream = await options.context.invoke(tool, { ...call.function.arguments, ...input }, { streaming: true, sourceAgent: this });
|
|
287
278
|
yield* stream;
|
|
288
279
|
}
|
|
289
280
|
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import type { Context } from "../aigne/context.js";
|
|
2
1
|
import type { PromiseOrValue } from "../utils/type-utils.js";
|
|
3
|
-
import { Agent, type AgentProcessResult, type Message } from "./agent.js";
|
|
2
|
+
import { Agent, type AgentInvokeOptions, type AgentProcessResult, type Message } from "./agent.js";
|
|
4
3
|
/**
|
|
5
4
|
* ChatModel is an abstract base class for interacting with Large Language Models (LLMs).
|
|
6
5
|
*
|
|
@@ -61,10 +60,10 @@ export declare abstract class ChatModel extends Agent<ChatModelInput, ChatModelO
|
|
|
61
60
|
* Primarily checks if token usage exceeds limits, throwing an exception if limits are exceeded
|
|
62
61
|
*
|
|
63
62
|
* @param input Input message
|
|
64
|
-
* @param
|
|
63
|
+
* @param options Options for invoking the agent
|
|
65
64
|
* @throws Error if token usage exceeds maximum limit
|
|
66
65
|
*/
|
|
67
|
-
protected preprocess(input: ChatModelInput,
|
|
66
|
+
protected preprocess(input: ChatModelInput, options: AgentInvokeOptions): Promise<void>;
|
|
68
67
|
/**
|
|
69
68
|
* Performs postprocessing operations after handling output
|
|
70
69
|
*
|
|
@@ -72,9 +71,9 @@ export declare abstract class ChatModel extends Agent<ChatModelInput, ChatModelO
|
|
|
72
71
|
*
|
|
73
72
|
* @param input Input message
|
|
74
73
|
* @param output Output message
|
|
75
|
-
* @param
|
|
74
|
+
* @param options Options for invoking the agent
|
|
76
75
|
*/
|
|
77
|
-
protected postprocess(input: ChatModelInput, output: ChatModelOutput,
|
|
76
|
+
protected postprocess(input: ChatModelInput, output: ChatModelOutput, options: AgentInvokeOptions): Promise<void>;
|
|
78
77
|
/**
|
|
79
78
|
* Processes input messages and generates model responses
|
|
80
79
|
*
|
|
@@ -92,10 +91,10 @@ export declare abstract class ChatModel extends Agent<ChatModelInput, ChatModelO
|
|
|
92
91
|
* - Tool call processing if applicable
|
|
93
92
|
*
|
|
94
93
|
* @param input - The standardized input containing messages and model options
|
|
95
|
-
* @param
|
|
94
|
+
* @param options - The options for invoking the agent, including context and limits
|
|
96
95
|
* @returns A promise or direct value containing the model's response
|
|
97
96
|
*/
|
|
98
|
-
abstract process(input: ChatModelInput,
|
|
97
|
+
abstract process(input: ChatModelInput, options: AgentInvokeOptions): PromiseOrValue<AgentProcessResult<ChatModelOutput>>;
|
|
99
98
|
}
|
|
100
99
|
/**
|
|
101
100
|
* Input message format for ChatModel
|
|
@@ -78,12 +78,12 @@ class ChatModel extends agent_js_1.Agent {
|
|
|
78
78
|
* Primarily checks if token usage exceeds limits, throwing an exception if limits are exceeded
|
|
79
79
|
*
|
|
80
80
|
* @param input Input message
|
|
81
|
-
* @param
|
|
81
|
+
* @param options Options for invoking the agent
|
|
82
82
|
* @throws Error if token usage exceeds maximum limit
|
|
83
83
|
*/
|
|
84
|
-
async preprocess(input,
|
|
85
|
-
super.preprocess(input,
|
|
86
|
-
const { limits, usage } = context;
|
|
84
|
+
async preprocess(input, options) {
|
|
85
|
+
super.preprocess(input, options);
|
|
86
|
+
const { limits, usage } = options.context;
|
|
87
87
|
const usedTokens = usage.outputTokens + usage.inputTokens;
|
|
88
88
|
if (limits?.maxTokens && usedTokens >= limits.maxTokens) {
|
|
89
89
|
throw new Error(`Exceeded max tokens ${usedTokens}/${limits.maxTokens}`);
|
|
@@ -112,9 +112,9 @@ class ChatModel extends agent_js_1.Agent {
|
|
|
112
112
|
*
|
|
113
113
|
* @param input Input message
|
|
114
114
|
* @param output Output message
|
|
115
|
-
* @param
|
|
115
|
+
* @param options Options for invoking the agent
|
|
116
116
|
*/
|
|
117
|
-
postprocess(input, output,
|
|
117
|
+
async postprocess(input, output, options) {
|
|
118
118
|
// Restore original tool names in the output
|
|
119
119
|
if (output.toolCalls?.length) {
|
|
120
120
|
const toolsMap = input._toolsMap;
|
|
@@ -128,11 +128,11 @@ class ChatModel extends agent_js_1.Agent {
|
|
|
128
128
|
}
|
|
129
129
|
}
|
|
130
130
|
}
|
|
131
|
-
super.postprocess(input, output,
|
|
131
|
+
super.postprocess(input, output, options);
|
|
132
132
|
const { usage } = output;
|
|
133
133
|
if (usage) {
|
|
134
|
-
context.usage.outputTokens += usage.outputTokens;
|
|
135
|
-
context.usage.inputTokens += usage.inputTokens;
|
|
134
|
+
options.context.usage.outputTokens += usage.outputTokens;
|
|
135
|
+
options.context.usage.inputTokens += usage.inputTokens;
|
|
136
136
|
}
|
|
137
137
|
}
|
|
138
138
|
}
|
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
import { Client, type ClientOptions } from "@modelcontextprotocol/sdk/client/index.js";
|
|
2
2
|
import { type SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
3
|
-
import {
|
|
3
|
+
import type { StdioServerParameters } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
4
4
|
import { type StreamableHTTPClientTransportOptions } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
5
5
|
import type { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.js";
|
|
6
6
|
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
7
7
|
import type { CallToolResult, GetPromptResult, Implementation, ReadResourceResult, Request } from "@modelcontextprotocol/sdk/types.js";
|
|
8
8
|
import { type ZodType, z } from "zod";
|
|
9
|
-
import type { Context } from "../aigne/context.js";
|
|
10
9
|
import { type PromiseOrValue } from "../utils/type-utils.js";
|
|
11
|
-
import { Agent, type AgentOptions, type Message } from "./agent.js";
|
|
10
|
+
import { Agent, type AgentInvokeOptions, type AgentOptions, type Message } from "./agent.js";
|
|
12
11
|
export interface MCPAgentOptions extends AgentOptions {
|
|
13
12
|
client: Client;
|
|
14
13
|
prompts?: MCPPrompt[];
|
|
@@ -150,10 +149,10 @@ export declare class MCPAgent extends Agent {
|
|
|
150
149
|
* throws an error if called.
|
|
151
150
|
*
|
|
152
151
|
* @param _input Input message (unused)
|
|
153
|
-
* @param
|
|
152
|
+
* @param _options AgentInvokeOptions (unused)
|
|
154
153
|
* @throws Error This method always throws an error since MCPAgent is not directly invokable
|
|
155
154
|
*/
|
|
156
|
-
process(_input: Message,
|
|
155
|
+
process(_input: Message, _options: AgentInvokeOptions): Promise<Message>;
|
|
157
156
|
/**
|
|
158
157
|
* Shut down the agent and close the MCP connection.
|
|
159
158
|
*
|
|
@@ -4,15 +4,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.MCPResource = exports.MCPPrompt = exports.MCPTool = exports.MCPBase = exports.MCPAgent = void 0;
|
|
7
|
+
const stdio_client_transport_js_1 = require("@aigne/platform-helpers/mcp/stdio-client-transport.js");
|
|
7
8
|
const index_js_1 = require("@modelcontextprotocol/sdk/client/index.js");
|
|
8
9
|
const sse_js_1 = require("@modelcontextprotocol/sdk/client/sse.js");
|
|
9
|
-
const stdio_js_1 = require("@modelcontextprotocol/sdk/client/stdio.js");
|
|
10
10
|
const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
|
|
11
11
|
const uriTemplate_js_1 = require("@modelcontextprotocol/sdk/shared/uriTemplate.js");
|
|
12
12
|
const p_retry_1 = __importDefault(require("p-retry"));
|
|
13
13
|
const zod_1 = require("zod");
|
|
14
14
|
const logger_js_1 = require("../utils/logger.js");
|
|
15
15
|
const mcp_utils_js_1 = require("../utils/mcp-utils.js");
|
|
16
|
+
const nodejs_js_1 = require("../utils/nodejs.js");
|
|
16
17
|
const type_utils_js_1 = require("../utils/type-utils.js");
|
|
17
18
|
const agent_js_1 = require("./agent.js");
|
|
18
19
|
const MCP_AGENT_CLIENT_NAME = "AIGNE/MCPAgent";
|
|
@@ -22,7 +23,7 @@ const DEFAULT_TIMEOUT = () => zod_1.z.coerce
|
|
|
22
23
|
.number()
|
|
23
24
|
.int()
|
|
24
25
|
.min(0)
|
|
25
|
-
.safeParse(
|
|
26
|
+
.safeParse(nodejs_js_1.nodejs.env.MCP_TIMEOUT || nodejs_js_1.nodejs.env.TIMEOUT).data || 60e3;
|
|
26
27
|
function isSSEServerParameters(options) {
|
|
27
28
|
return "url" in options && typeof options.url === "string";
|
|
28
29
|
}
|
|
@@ -66,14 +67,7 @@ class MCPAgent extends agent_js_1.Agent {
|
|
|
66
67
|
return MCPAgent.fromTransport(transport, options);
|
|
67
68
|
}
|
|
68
69
|
if (isStdioServerParameters(options)) {
|
|
69
|
-
const transport = () =>
|
|
70
|
-
...options,
|
|
71
|
-
env: {
|
|
72
|
-
...(0, stdio_js_1.getDefaultEnvironment)(),
|
|
73
|
-
...options.env,
|
|
74
|
-
},
|
|
75
|
-
stderr: "pipe",
|
|
76
|
-
});
|
|
70
|
+
const transport = async () => (0, stdio_client_transport_js_1.createStdioClientTransport)(options);
|
|
77
71
|
return MCPAgent.fromTransport(transport, options);
|
|
78
72
|
}
|
|
79
73
|
return new MCPAgent(options);
|
|
@@ -83,7 +77,7 @@ class MCPAgent extends agent_js_1.Agent {
|
|
|
83
77
|
name: MCP_AGENT_CLIENT_NAME,
|
|
84
78
|
version: MCP_AGENT_CLIENT_VERSION,
|
|
85
79
|
}, undefined, isSSEServerParameters(options) ? { transportCreator, ...options } : undefined);
|
|
86
|
-
const transport = transportCreator();
|
|
80
|
+
const transport = await transportCreator();
|
|
87
81
|
logger_js_1.logger.debug(`Connecting to MCP server: ${getMCPServerString(options)}`);
|
|
88
82
|
await client.connect(transport);
|
|
89
83
|
const mcpServer = getMCPServerName(client);
|
|
@@ -183,10 +177,10 @@ class MCPAgent extends agent_js_1.Agent {
|
|
|
183
177
|
* throws an error if called.
|
|
184
178
|
*
|
|
185
179
|
* @param _input Input message (unused)
|
|
186
|
-
* @param
|
|
180
|
+
* @param _options AgentInvokeOptions (unused)
|
|
187
181
|
* @throws Error This method always throws an error since MCPAgent is not directly invokable
|
|
188
182
|
*/
|
|
189
|
-
async process(_input,
|
|
183
|
+
async process(_input, _options) {
|
|
190
184
|
throw new Error("Method not implemented.");
|
|
191
185
|
}
|
|
192
186
|
/**
|