@aigne/core 1.19.0 → 1.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/lib/cjs/agents/agent.d.ts +11 -6
- package/lib/cjs/agents/agent.js +8 -10
- package/lib/cjs/agents/ai-agent.d.ts +18 -6
- package/lib/cjs/agents/ai-agent.js +14 -4
- package/lib/cjs/agents/guide-rail-agent.d.ts +1 -1
- package/lib/cjs/agents/mcp-agent.d.ts +1 -1
- package/lib/cjs/aigne/aigne.d.ts +10 -10
- package/lib/cjs/aigne/context.d.ts +8 -6
- package/lib/cjs/aigne/context.js +62 -42
- package/lib/cjs/aigne/message-queue.d.ts +1 -1
- package/lib/cjs/aigne/message-queue.js +2 -3
- package/lib/cjs/aigne/usage.d.ts +1 -0
- package/lib/cjs/aigne/usage.js +1 -0
- package/lib/cjs/loader/agent-yaml.d.ts +2 -1
- package/lib/cjs/loader/agent-yaml.js +4 -0
- package/lib/cjs/prompt/prompt-builder.d.ts +2 -16
- package/lib/cjs/prompt/prompt-builder.js +12 -25
- package/lib/cjs/utils/stream-utils.d.ts +1 -2
- package/lib/cjs/utils/type-utils.d.ts +1 -0
- package/lib/cjs/utils/type-utils.js +13 -0
- package/lib/dts/agents/agent.d.ts +11 -6
- package/lib/dts/agents/ai-agent.d.ts +18 -6
- package/lib/dts/agents/guide-rail-agent.d.ts +1 -1
- package/lib/dts/agents/mcp-agent.d.ts +1 -1
- package/lib/dts/aigne/aigne.d.ts +10 -10
- package/lib/dts/aigne/context.d.ts +8 -6
- package/lib/dts/aigne/message-queue.d.ts +1 -1
- package/lib/dts/aigne/usage.d.ts +1 -0
- package/lib/dts/loader/agent-yaml.d.ts +2 -1
- package/lib/dts/prompt/prompt-builder.d.ts +2 -16
- package/lib/dts/utils/stream-utils.d.ts +1 -2
- package/lib/dts/utils/type-utils.d.ts +1 -0
- package/lib/esm/agents/agent.d.ts +11 -6
- package/lib/esm/agents/agent.js +8 -10
- package/lib/esm/agents/ai-agent.d.ts +18 -6
- package/lib/esm/agents/ai-agent.js +15 -5
- package/lib/esm/agents/guide-rail-agent.d.ts +1 -1
- package/lib/esm/agents/mcp-agent.d.ts +1 -1
- package/lib/esm/aigne/aigne.d.ts +10 -10
- package/lib/esm/aigne/context.d.ts +8 -6
- package/lib/esm/aigne/context.js +63 -43
- package/lib/esm/aigne/message-queue.d.ts +1 -1
- package/lib/esm/aigne/message-queue.js +2 -3
- package/lib/esm/aigne/usage.d.ts +1 -0
- package/lib/esm/aigne/usage.js +1 -0
- package/lib/esm/loader/agent-yaml.d.ts +2 -1
- package/lib/esm/loader/agent-yaml.js +4 -0
- package/lib/esm/prompt/prompt-builder.d.ts +2 -16
- package/lib/esm/prompt/prompt-builder.js +12 -23
- package/lib/esm/utils/stream-utils.d.ts +1 -2
- package/lib/esm/utils/type-utils.d.ts +1 -0
- package/lib/esm/utils/type-utils.js +12 -0
- package/package.json +2 -2
|
@@ -2,6 +2,7 @@ import { nodejs } from "@aigne/platform-helpers/nodejs/index.js";
|
|
|
2
2
|
import { ZodObject, type ZodType } from "zod";
|
|
3
3
|
import type { AgentEvent, Context, UserContext } from "../aigne/context.js";
|
|
4
4
|
import type { MessagePayload } from "../aigne/message-queue.js";
|
|
5
|
+
import type { ContextUsage } from "../aigne/usage.js";
|
|
5
6
|
import type { Memory, MemoryAgent } from "../memory/memory.js";
|
|
6
7
|
import type { MemoryRecorderInput } from "../memory/recorder.js";
|
|
7
8
|
import type { MemoryRetrieverInput } from "../memory/retriever.js";
|
|
@@ -12,7 +13,11 @@ export * from "./types.js";
|
|
|
12
13
|
/**
|
|
13
14
|
* Basic message type that can contain any key-value pairs
|
|
14
15
|
*/
|
|
15
|
-
export
|
|
16
|
+
export interface Message extends Record<string, unknown> {
|
|
17
|
+
$meta?: {
|
|
18
|
+
usage: ContextUsage;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
16
21
|
/**
|
|
17
22
|
* Topics the agent subscribes to, can be a single topic string or an array of topic strings
|
|
18
23
|
*/
|
|
@@ -328,7 +333,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
|
|
|
328
333
|
* Regular mode waits for the agent to complete processing and return the final result,
|
|
329
334
|
* suitable for scenarios where a complete result is needed at once.
|
|
330
335
|
*
|
|
331
|
-
* @param input Input message to the agent
|
|
336
|
+
* @param input Input message to the agent
|
|
332
337
|
* @param options Invocation options, must set streaming to false or leave unset
|
|
333
338
|
* @returns Final JSON response
|
|
334
339
|
*
|
|
@@ -336,7 +341,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
|
|
|
336
341
|
* Here's an example of invoking an agent with regular mode:
|
|
337
342
|
* {@includeCode ../../test/agents/agent.test.ts#example-invoke}
|
|
338
343
|
*/
|
|
339
|
-
invoke(input: I
|
|
344
|
+
invoke(input: I, options?: Partial<AgentInvokeOptions> & {
|
|
340
345
|
streaming?: false;
|
|
341
346
|
}): Promise<O>;
|
|
342
347
|
/**
|
|
@@ -346,7 +351,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
|
|
|
346
351
|
* suitable for scenarios requiring real-time progress updates, such as
|
|
347
352
|
* chat bot typing effects.
|
|
348
353
|
*
|
|
349
|
-
* @param input Input message to the agent
|
|
354
|
+
* @param input Input message to the agent
|
|
350
355
|
* @param options Invocation options, must set streaming to true for this overload
|
|
351
356
|
* @returns Streaming response object
|
|
352
357
|
*
|
|
@@ -354,7 +359,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
|
|
|
354
359
|
* Here's an example of invoking an agent with streaming response:
|
|
355
360
|
* {@includeCode ../../test/agents/agent.test.ts#example-invoke-streaming}
|
|
356
361
|
*/
|
|
357
|
-
invoke(input: I
|
|
362
|
+
invoke(input: I, options: Partial<AgentInvokeOptions> & {
|
|
358
363
|
streaming: true;
|
|
359
364
|
}): Promise<AgentResponseStream<O>>;
|
|
360
365
|
/**
|
|
@@ -366,7 +371,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
|
|
|
366
371
|
* @param options Invocation options
|
|
367
372
|
* @returns Agent response (streaming or regular)
|
|
368
373
|
*/
|
|
369
|
-
invoke(input: I
|
|
374
|
+
invoke(input: I, options?: Partial<AgentInvokeOptions>): Promise<AgentResponse<O>>;
|
|
370
375
|
protected invokeSkill<I extends Message, O extends Message>(skill: Agent<I, O>, input: I, options: AgentInvokeOptions): Promise<O>;
|
|
371
376
|
/**
|
|
372
377
|
* Process agent output
|
package/lib/esm/agents/agent.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { nodejs } from "@aigne/platform-helpers/nodejs/index.js";
|
|
2
2
|
import { ZodObject, z } from "zod";
|
|
3
|
-
import { createMessage, getMessage } from "../prompt/prompt-builder.js";
|
|
4
3
|
import { logger } from "../utils/logger.js";
|
|
5
4
|
import { agentResponseStreamToObject, asyncGeneratorToReadableStream, isAsyncGenerator, objectToAgentResponseStream, onAgentResponseStreamEnd, } from "../utils/stream-utils.js";
|
|
6
5
|
import { checkArguments, createAccessorArray, isEmpty, orArrayToArray, } from "../utils/type-utils.js";
|
|
@@ -273,7 +272,7 @@ export class Agent {
|
|
|
273
272
|
for (const memory of this.memories) {
|
|
274
273
|
const ms = (await memory.retrieve({
|
|
275
274
|
...input,
|
|
276
|
-
search: typeof input === "string" ? input :
|
|
275
|
+
search: typeof input.search === "string" ? input.search : JSON.stringify(input.search),
|
|
277
276
|
limit: input.limit ?? this.maxRetrieveMemoryCount,
|
|
278
277
|
}, options.context)).memories;
|
|
279
278
|
memories.push(...ms);
|
|
@@ -300,13 +299,12 @@ export class Agent {
|
|
|
300
299
|
opts.context.memories.push(...options.memories);
|
|
301
300
|
options.memories = undefined;
|
|
302
301
|
}
|
|
303
|
-
const message = typeof input === "string" ? createMessage(input) : input;
|
|
304
302
|
logger.debug("Invoke agent %s started with input: %O", this.name, input);
|
|
305
303
|
if (!this.disableEvents)
|
|
306
|
-
opts.context.emit("agentStarted", { agent: this, input
|
|
304
|
+
opts.context.emit("agentStarted", { agent: this, input });
|
|
307
305
|
try {
|
|
308
|
-
await this.hooks.onStart?.({ context: opts.context, input
|
|
309
|
-
const parsedInput = checkArguments(`Agent ${this.name} input`, this.inputSchema,
|
|
306
|
+
await this.hooks.onStart?.({ context: opts.context, input });
|
|
307
|
+
const parsedInput = checkArguments(`Agent ${this.name} input`, this.inputSchema, input);
|
|
310
308
|
await this.preprocess(parsedInput, opts);
|
|
311
309
|
this.checkContextStatus(opts);
|
|
312
310
|
let response = await this.process(parsedInput, opts);
|
|
@@ -319,23 +317,23 @@ export class Agent {
|
|
|
319
317
|
: isAsyncGenerator(response)
|
|
320
318
|
? asyncGeneratorToReadableStream(response)
|
|
321
319
|
: objectToAgentResponseStream(response);
|
|
322
|
-
return this.checkResponseByGuideRails(
|
|
320
|
+
return this.checkResponseByGuideRails(input, onAgentResponseStreamEnd(stream, {
|
|
323
321
|
onResult: async (result) => {
|
|
324
322
|
return await this.processAgentOutput(parsedInput, result, opts);
|
|
325
323
|
},
|
|
326
324
|
onError: async (error) => {
|
|
327
|
-
return await this.processAgentError(
|
|
325
|
+
return await this.processAgentError(input, error, opts);
|
|
328
326
|
},
|
|
329
327
|
}), opts);
|
|
330
328
|
}
|
|
331
|
-
return await this.checkResponseByGuideRails(
|
|
329
|
+
return await this.checkResponseByGuideRails(input, this.processAgentOutput(parsedInput, response instanceof ReadableStream
|
|
332
330
|
? await agentResponseStreamToObject(response)
|
|
333
331
|
: isAsyncGenerator(response)
|
|
334
332
|
? await agentResponseStreamToObject(response)
|
|
335
333
|
: response, opts), opts);
|
|
336
334
|
}
|
|
337
335
|
catch (error) {
|
|
338
|
-
throw await this.processAgentError(
|
|
336
|
+
throw await this.processAgentError(input, error, opts);
|
|
339
337
|
}
|
|
340
338
|
}
|
|
341
339
|
async invokeSkill(skill, input, options) {
|
|
@@ -12,7 +12,7 @@ import type { GuideRailAgentOutput } from "./guide-rail-agent.js";
|
|
|
12
12
|
* @template I The input message type the agent accepts
|
|
13
13
|
* @template O The output message type the agent returns
|
|
14
14
|
*/
|
|
15
|
-
export interface AIAgentOptions<I extends Message = Message
|
|
15
|
+
export interface AIAgentOptions<InputKey extends string = string, I extends Message & InputMessage<InputKey> = Message & InputMessage<InputKey>, O extends Message = Message> extends AgentOptions<Omit<I, InputKey> & Partial<InputMessage<InputKey>>, O> {
|
|
16
16
|
/**
|
|
17
17
|
* The language model to use for this agent
|
|
18
18
|
*
|
|
@@ -26,10 +26,14 @@ export interface AIAgentOptions<I extends Message = Message, O extends Message =
|
|
|
26
26
|
* more complex prompt templates
|
|
27
27
|
*/
|
|
28
28
|
instructions?: string | PromptBuilder;
|
|
29
|
+
/**
|
|
30
|
+
* Pick a message from input to use as the user's message
|
|
31
|
+
*/
|
|
32
|
+
inputKey?: InputKey;
|
|
29
33
|
/**
|
|
30
34
|
* Custom key to use for text output in the response
|
|
31
35
|
*
|
|
32
|
-
* Defaults to
|
|
36
|
+
* Defaults to `message` if not specified
|
|
33
37
|
*/
|
|
34
38
|
outputKey?: string;
|
|
35
39
|
/**
|
|
@@ -106,6 +110,9 @@ export declare const aiAgentToolChoiceSchema: z.ZodUnion<[z.ZodNativeEnum<typeof
|
|
|
106
110
|
export declare const aiAgentOptionsSchema: ZodObject<{
|
|
107
111
|
[key in keyof AIAgentOptions]: ZodType<AIAgentOptions[key]>;
|
|
108
112
|
}>;
|
|
113
|
+
type InputMessage<K> = K extends string ? {
|
|
114
|
+
[key in K]: string;
|
|
115
|
+
} : Message;
|
|
109
116
|
/**
|
|
110
117
|
* AI-powered agent that leverages language models
|
|
111
118
|
*
|
|
@@ -126,7 +133,7 @@ export declare const aiAgentOptionsSchema: ZodObject<{
|
|
|
126
133
|
* Basic AIAgent creation:
|
|
127
134
|
* {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-basic}
|
|
128
135
|
*/
|
|
129
|
-
export declare class AIAgent<I extends Message = Message
|
|
136
|
+
export declare class AIAgent<InputKey extends string = string, I extends Message & InputMessage<InputKey> = Message & InputMessage<InputKey>, O extends Message = Message> extends Agent<I, O> {
|
|
130
137
|
/**
|
|
131
138
|
* Create an AIAgent with the specified options
|
|
132
139
|
*
|
|
@@ -139,13 +146,13 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
|
|
|
139
146
|
* AI agent with custom instructions:
|
|
140
147
|
* {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-instructions}
|
|
141
148
|
*/
|
|
142
|
-
static from<I extends Message
|
|
149
|
+
static from<InputKey extends string, I extends Message & InputMessage<InputKey>, O extends Message>(options: AIAgentOptions<InputKey, I, O>): AIAgent<InputKey, I, O>;
|
|
143
150
|
/**
|
|
144
151
|
* Create an AIAgent instance
|
|
145
152
|
*
|
|
146
153
|
* @param options Configuration options for the AI agent
|
|
147
154
|
*/
|
|
148
|
-
constructor(options: AIAgentOptions<I, O>);
|
|
155
|
+
constructor(options: AIAgentOptions<InputKey, I, O>);
|
|
149
156
|
/**
|
|
150
157
|
* The language model used by this agent
|
|
151
158
|
*
|
|
@@ -163,6 +170,10 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
|
|
|
163
170
|
* {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-prompt-builder}
|
|
164
171
|
*/
|
|
165
172
|
instructions: PromptBuilder;
|
|
173
|
+
/**
|
|
174
|
+
* Pick a message from input to use as the user's message
|
|
175
|
+
*/
|
|
176
|
+
inputKey?: InputKey;
|
|
166
177
|
/**
|
|
167
178
|
* Custom key to use for text output in the response
|
|
168
179
|
*
|
|
@@ -170,7 +181,7 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
|
|
|
170
181
|
* Setting a custom output key:
|
|
171
182
|
* {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-custom-output-key}
|
|
172
183
|
*/
|
|
173
|
-
outputKey
|
|
184
|
+
outputKey: string;
|
|
174
185
|
/**
|
|
175
186
|
* Controls how the agent uses tools during execution
|
|
176
187
|
*
|
|
@@ -224,3 +235,4 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
|
|
|
224
235
|
*/
|
|
225
236
|
_processRouter(input: I, model: ChatModel, modelInput: ChatModelInput, options: AgentInvokeOptions, toolsMap: Map<string, Agent>): AgentProcessAsyncGenerator<O>;
|
|
226
237
|
}
|
|
238
|
+
export {};
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import {
|
|
2
|
+
import { PromptBuilder } from "../prompt/prompt-builder.js";
|
|
3
3
|
import { AgentMessageTemplate, ToolMessageTemplate } from "../prompt/template.js";
|
|
4
4
|
import { checkArguments, isEmpty } from "../utils/type-utils.js";
|
|
5
5
|
import { Agent, agentOptionsSchema, isAgentResponseDelta, } from "./agent.js";
|
|
6
6
|
import { ChatModel, } from "./chat-model.js";
|
|
7
7
|
import { isTransferAgentOutput } from "./types.js";
|
|
8
|
+
const DEFAULT_OUTPUT_KEY = "message";
|
|
8
9
|
/**
|
|
9
10
|
* Tool choice options for AI agents
|
|
10
11
|
*
|
|
@@ -49,6 +50,7 @@ export const aiAgentToolChoiceSchema = z.union([z.nativeEnum(AIAgentToolChoice),
|
|
|
49
50
|
export const aiAgentOptionsSchema = agentOptionsSchema.extend({
|
|
50
51
|
model: z.instanceof(ChatModel).optional(),
|
|
51
52
|
instructions: z.union([z.string(), z.instanceof(PromptBuilder)]).optional(),
|
|
53
|
+
inputKey: z.string().optional(),
|
|
52
54
|
outputKey: z.string().optional(),
|
|
53
55
|
toolChoice: aiAgentToolChoiceSchema.optional(),
|
|
54
56
|
memoryAgentsAsTools: z.boolean().optional(),
|
|
@@ -96,19 +98,23 @@ export class AIAgent extends Agent {
|
|
|
96
98
|
* @param options Configuration options for the AI agent
|
|
97
99
|
*/
|
|
98
100
|
constructor(options) {
|
|
99
|
-
super(options);
|
|
101
|
+
super({ ...options, inputSchema: options.inputSchema });
|
|
100
102
|
checkArguments("AIAgent", aiAgentOptionsSchema, options);
|
|
101
103
|
this.model = options.model;
|
|
102
104
|
this.instructions =
|
|
103
105
|
typeof options.instructions === "string"
|
|
104
106
|
? PromptBuilder.from(options.instructions)
|
|
105
107
|
: (options.instructions ?? new PromptBuilder());
|
|
106
|
-
this.
|
|
108
|
+
this.inputKey = options.inputKey;
|
|
109
|
+
this.outputKey = options.outputKey || DEFAULT_OUTPUT_KEY;
|
|
107
110
|
this.toolChoice = options.toolChoice;
|
|
108
111
|
this.memoryAgentsAsTools = options.memoryAgentsAsTools;
|
|
109
112
|
this.memoryPromptTemplate = options.memoryPromptTemplate;
|
|
110
113
|
if (typeof options.catchToolsError === "boolean")
|
|
111
114
|
this.catchToolsError = options.catchToolsError;
|
|
115
|
+
if (!this.inputKey && !this.instructions) {
|
|
116
|
+
throw new Error("AIAgent requires either inputKey or instructions to be set");
|
|
117
|
+
}
|
|
112
118
|
}
|
|
113
119
|
/**
|
|
114
120
|
* The language model used by this agent
|
|
@@ -127,6 +133,10 @@ export class AIAgent extends Agent {
|
|
|
127
133
|
* {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-prompt-builder}
|
|
128
134
|
*/
|
|
129
135
|
instructions;
|
|
136
|
+
/**
|
|
137
|
+
* Pick a message from input to use as the user's message
|
|
138
|
+
*/
|
|
139
|
+
inputKey;
|
|
130
140
|
/**
|
|
131
141
|
* Custom key to use for text output in the response
|
|
132
142
|
*
|
|
@@ -191,7 +201,7 @@ export class AIAgent extends Agent {
|
|
|
191
201
|
return yield* this._processRouter(input, model, modelInput, options, toolsMap);
|
|
192
202
|
}
|
|
193
203
|
const toolCallMessages = [];
|
|
194
|
-
const outputKey = this.outputKey
|
|
204
|
+
const outputKey = this.outputKey;
|
|
195
205
|
for (;;) {
|
|
196
206
|
const modelOutput = {};
|
|
197
207
|
const stream = await options.context.invoke(model, { ...modelInput, messages: modelInput.messages.concat(toolCallMessages) }, { streaming: true });
|
|
@@ -251,7 +261,7 @@ export class AIAgent extends Agent {
|
|
|
251
261
|
}
|
|
252
262
|
}
|
|
253
263
|
async onGuideRailError(error) {
|
|
254
|
-
const outputKey = this.outputKey ||
|
|
264
|
+
const outputKey = this.outputKey || DEFAULT_OUTPUT_KEY;
|
|
255
265
|
return {
|
|
256
266
|
[outputKey]: error.reason,
|
|
257
267
|
};
|
|
@@ -59,4 +59,4 @@ export interface GuideRailAgentOutput extends Message {
|
|
|
59
59
|
* - Monitor and audit agent behavior
|
|
60
60
|
*/
|
|
61
61
|
export type GuideRailAgent = Agent<GuideRailAgentInput, GuideRailAgentOutput>;
|
|
62
|
-
export declare const guideRailAgentOptions: AgentOptions<
|
|
62
|
+
export declare const guideRailAgentOptions: AgentOptions<any, GuideRailAgentOutput>;
|
|
@@ -192,7 +192,7 @@ export declare abstract class MCPBase<I extends Message, O extends Message> exte
|
|
|
192
192
|
export declare class MCPTool extends MCPBase<Message, CallToolResult> {
|
|
193
193
|
process(input: Message): Promise<CallToolResult>;
|
|
194
194
|
}
|
|
195
|
-
export interface MCPPromptInput extends
|
|
195
|
+
export interface MCPPromptInput extends Record<string, unknown> {
|
|
196
196
|
[key: string]: string;
|
|
197
197
|
}
|
|
198
198
|
export declare class MCPPrompt extends MCPBase<MCPPromptInput, GetPromptResult> {
|
package/lib/esm/aigne/aigne.d.ts
CHANGED
|
@@ -129,12 +129,12 @@ export declare class AIGNE<U extends UserContext = UserContext> {
|
|
|
129
129
|
* This overload is useful when you need to track which agent was ultimately responsible for generating the response.
|
|
130
130
|
*
|
|
131
131
|
* @param agent - Target agent to invoke
|
|
132
|
-
* @param message - Input message to send to the agent
|
|
132
|
+
* @param message - Input message to send to the agent
|
|
133
133
|
* @param options.returnActiveAgent - Must be true to return the final active agent
|
|
134
134
|
* @param options.streaming - Must be false to return a response stream
|
|
135
135
|
* @returns A promise resolving to a tuple containing the agent's response and the final active agent
|
|
136
136
|
*/
|
|
137
|
-
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I
|
|
137
|
+
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions<U> & {
|
|
138
138
|
returnActiveAgent: true;
|
|
139
139
|
streaming?: false;
|
|
140
140
|
}): Promise<[O, Agent]>;
|
|
@@ -143,12 +143,12 @@ export declare class AIGNE<U extends UserContext = UserContext> {
|
|
|
143
143
|
* This overload is useful when you need streaming responses while also tracking which agent provided them.
|
|
144
144
|
*
|
|
145
145
|
* @param agent - Target agent to invoke
|
|
146
|
-
* @param message - Input message to send to the agent
|
|
146
|
+
* @param message - Input message to send to the agent
|
|
147
147
|
* @param options.returnActiveAgent - Must be true to return the final active agent
|
|
148
148
|
* @param options.streaming - Must be true to return a response stream
|
|
149
149
|
* @returns A promise resolving to a tuple containing the agent's response stream and a promise for the final agent
|
|
150
150
|
*/
|
|
151
|
-
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I
|
|
151
|
+
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions<U> & {
|
|
152
152
|
returnActiveAgent: true;
|
|
153
153
|
streaming: true;
|
|
154
154
|
}): Promise<[AgentResponseStream<O>, Promise<Agent>]>;
|
|
@@ -157,7 +157,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
|
|
|
157
157
|
* This is the standard way to invoke an agent when you only need the response.
|
|
158
158
|
*
|
|
159
159
|
* @param agent - Target agent to invoke
|
|
160
|
-
* @param message - Input message to send to the agent
|
|
160
|
+
* @param message - Input message to send to the agent
|
|
161
161
|
* @param options - Optional configuration parameters for the invocation
|
|
162
162
|
* @returns A promise resolving to the agent's complete response
|
|
163
163
|
*
|
|
@@ -165,7 +165,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
|
|
|
165
165
|
* Here's a simple example of how to invoke an agent:
|
|
166
166
|
* {@includeCode ../../test/aigne/aigne.test.ts#example-simple}
|
|
167
167
|
*/
|
|
168
|
-
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I
|
|
168
|
+
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options?: InvokeOptions<U> & {
|
|
169
169
|
returnActiveAgent?: false;
|
|
170
170
|
streaming?: false;
|
|
171
171
|
}): Promise<O>;
|
|
@@ -174,7 +174,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
|
|
|
174
174
|
* This allows processing the response incrementally as it's being generated.
|
|
175
175
|
*
|
|
176
176
|
* @param agent - Target agent to invoke
|
|
177
|
-
* @param message - Input message to send to the agent
|
|
177
|
+
* @param message - Input message to send to the agent
|
|
178
178
|
* @param options - Configuration with streaming enabled to receive incremental response chunks
|
|
179
179
|
* @returns A promise resolving to a stream of the agent's response that can be consumed incrementally
|
|
180
180
|
*
|
|
@@ -182,7 +182,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
|
|
|
182
182
|
* Here's an example of how to invoke an agent with streaming response:
|
|
183
183
|
* {@includeCode ../../test/aigne/aigne.test.ts#example-streaming}
|
|
184
184
|
*/
|
|
185
|
-
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I
|
|
185
|
+
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions<U> & {
|
|
186
186
|
returnActiveAgent?: false;
|
|
187
187
|
streaming: true;
|
|
188
188
|
}): Promise<AgentResponseStream<O>>;
|
|
@@ -196,7 +196,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
|
|
|
196
196
|
* @returns Either a UserAgent (when no message provided) or a promise resolving to the agent's response
|
|
197
197
|
* with optional active agent information based on the provided options
|
|
198
198
|
*/
|
|
199
|
-
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message?: I
|
|
199
|
+
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message?: I, options?: InvokeOptions<U>): UserAgent<I, O> | Promise<AgentResponse<O> | [AgentResponse<O>, Agent]>;
|
|
200
200
|
/**
|
|
201
201
|
* Publishes a message to the message queue for inter-agent communication.
|
|
202
202
|
* This method broadcasts a message to all subscribers of the specified topic(s).
|
|
@@ -210,7 +210,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
|
|
|
210
210
|
* Here's an example of how to publish a message:
|
|
211
211
|
* {@includeCode ../../test/aigne/aigne.test.ts#example-publish-message}
|
|
212
212
|
*/
|
|
213
|
-
publish(topic: string | string[], payload: Omit<MessagePayload, "context"> | Message
|
|
213
|
+
publish(topic: string | string[], payload: Omit<MessagePayload, "context"> | Message, options?: InvokeOptions<U>): void;
|
|
214
214
|
/**
|
|
215
215
|
* Subscribes to receive the next message on a specific topic.
|
|
216
216
|
* This overload returns a Promise that resolves with the next message published to the topic.
|
|
@@ -42,6 +42,7 @@ export type ContextEmitEventMap = {
|
|
|
42
42
|
export interface InvokeOptions<U extends UserContext = UserContext> extends Partial<Omit<AgentInvokeOptions<U>, "context">> {
|
|
43
43
|
returnActiveAgent?: boolean;
|
|
44
44
|
returnProgressChunks?: boolean;
|
|
45
|
+
returnMetadata?: boolean;
|
|
45
46
|
disableTransfer?: boolean;
|
|
46
47
|
sourceAgent?: Agent;
|
|
47
48
|
}
|
|
@@ -77,11 +78,11 @@ export interface Context<U extends UserContext = UserContext> extends TypedEvent
|
|
|
77
78
|
* @param options.streaming return a stream of the output
|
|
78
79
|
* @returns the output of the agent and the final active agent
|
|
79
80
|
*/
|
|
80
|
-
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I
|
|
81
|
+
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions & {
|
|
81
82
|
returnActiveAgent: true;
|
|
82
83
|
streaming?: false;
|
|
83
84
|
}): Promise<[O, Agent]>;
|
|
84
|
-
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I
|
|
85
|
+
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions & {
|
|
85
86
|
returnActiveAgent: true;
|
|
86
87
|
streaming: true;
|
|
87
88
|
}): Promise<[AgentResponseStream<O>, Promise<Agent>]>;
|
|
@@ -91,19 +92,19 @@ export interface Context<U extends UserContext = UserContext> extends TypedEvent
|
|
|
91
92
|
* @param message Message to pass to the agent
|
|
92
93
|
* @returns the output of the agent
|
|
93
94
|
*/
|
|
94
|
-
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I
|
|
95
|
+
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options?: InvokeOptions & {
|
|
95
96
|
streaming?: false;
|
|
96
97
|
}): Promise<O>;
|
|
97
|
-
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I
|
|
98
|
+
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions & {
|
|
98
99
|
streaming: true;
|
|
99
100
|
}): Promise<AgentResponseStream<O>>;
|
|
100
|
-
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message?: I
|
|
101
|
+
invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message?: I, options?: InvokeOptions): UserAgent<I, O> | Promise<AgentResponse<O> | [AgentResponse<O>, Agent]>;
|
|
101
102
|
/**
|
|
102
103
|
* Publish a message to a topic, the aigne will invoke the listeners of the topic
|
|
103
104
|
* @param topic topic name, or an array of topic names
|
|
104
105
|
* @param payload message to publish
|
|
105
106
|
*/
|
|
106
|
-
publish(topic: string | string[], payload: Omit<MessagePayload, "context"> | Message
|
|
107
|
+
publish(topic: string | string[], payload: Omit<MessagePayload, "context"> | Message, options?: InvokeOptions): void;
|
|
107
108
|
subscribe(topic: string | string[], listener?: undefined): Promise<MessagePayload>;
|
|
108
109
|
subscribe(topic: string | string[], listener: MessageQueueListener): Unsubscribe;
|
|
109
110
|
subscribe(topic: string | string[], listener?: MessageQueueListener): Unsubscribe | Promise<MessagePayload>;
|
|
@@ -142,6 +143,7 @@ export declare class AIGNEContext implements Context {
|
|
|
142
143
|
reset?: boolean;
|
|
143
144
|
}): AIGNEContext;
|
|
144
145
|
invoke: Context["invoke"];
|
|
146
|
+
private onInvocationResult;
|
|
145
147
|
publish: Context["publish"];
|
|
146
148
|
subscribe: Context["subscribe"];
|
|
147
149
|
unsubscribe: Context["unsubscribe"];
|
package/lib/esm/aigne/context.js
CHANGED
|
@@ -5,11 +5,10 @@ import { z } from "zod";
|
|
|
5
5
|
import { Agent, isAgentResponseDelta, isEmptyChunk, } from "../agents/agent.js";
|
|
6
6
|
import { isTransferAgentOutput, transferAgentOutputKey, } from "../agents/types.js";
|
|
7
7
|
import { UserAgent } from "../agents/user-agent.js";
|
|
8
|
-
import { createMessage } from "../prompt/prompt-builder.js";
|
|
9
8
|
import { AgentResponseProgressStream } from "../utils/event-stream.js";
|
|
10
9
|
import { promiseWithResolvers } from "../utils/promise.js";
|
|
11
10
|
import { agentResponseStreamToObject, asyncGeneratorToReadableStream, mergeReadableStreams, onAgentResponseStreamEnd, } from "../utils/stream-utils.js";
|
|
12
|
-
import { checkArguments, isEmpty, isNil,
|
|
11
|
+
import { checkArguments, isEmpty, isNil, omit, } from "../utils/type-utils.js";
|
|
13
12
|
import { MessageQueue, toMessagePayload, } from "./message-queue.js";
|
|
14
13
|
import { newEmptyContextUsage } from "./usage.js";
|
|
15
14
|
/**
|
|
@@ -81,10 +80,10 @@ export class AIGNEContext {
|
|
|
81
80
|
});
|
|
82
81
|
}
|
|
83
82
|
const newContext = this.newContext();
|
|
84
|
-
|
|
85
|
-
return Promise.resolve(newContext.internal.invoke(agent, msg, newContext, options)).then(async (response) => {
|
|
83
|
+
return Promise.resolve(newContext.internal.invoke(agent, message, newContext, options)).then(async (response) => {
|
|
86
84
|
if (!options?.streaming) {
|
|
87
|
-
|
|
85
|
+
let { __activeAgent__: activeAgent, ...output } = await agentResponseStreamToObject(response);
|
|
86
|
+
output = await this.onInvocationResult(output, options);
|
|
88
87
|
if (options?.returnActiveAgent) {
|
|
89
88
|
return [output, activeAgent];
|
|
90
89
|
}
|
|
@@ -98,13 +97,14 @@ export class AIGNEContext {
|
|
|
98
97
|
...chunk,
|
|
99
98
|
delta: {
|
|
100
99
|
...chunk.delta,
|
|
101
|
-
json:
|
|
100
|
+
json: omit(chunk.delta.json, "__activeAgent__"),
|
|
102
101
|
},
|
|
103
102
|
};
|
|
104
103
|
}
|
|
105
104
|
},
|
|
106
|
-
onResult
|
|
107
|
-
activeAgentPromise.resolve(
|
|
105
|
+
onResult: async (output) => {
|
|
106
|
+
activeAgentPromise.resolve(output.__activeAgent__);
|
|
107
|
+
return await this.onInvocationResult(output, options);
|
|
108
108
|
},
|
|
109
109
|
});
|
|
110
110
|
const finalStream = !options.returnProgressChunks
|
|
@@ -116,6 +116,18 @@ export class AIGNEContext {
|
|
|
116
116
|
return finalStream;
|
|
117
117
|
});
|
|
118
118
|
});
|
|
119
|
+
async onInvocationResult(output, options) {
|
|
120
|
+
if (!options?.returnMetadata) {
|
|
121
|
+
return output;
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
...output,
|
|
125
|
+
$meta: {
|
|
126
|
+
...output.$meta,
|
|
127
|
+
usage: this.usage,
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
119
131
|
publish = ((topic, payload, options) => {
|
|
120
132
|
if (options?.userContext) {
|
|
121
133
|
Object.assign(this.userContext, options.userContext);
|
|
@@ -201,46 +213,54 @@ class AIGNEContextShared {
|
|
|
201
213
|
return withAbortSignal(this.abortController.signal, new Error("AIGNEContext is timeout"), () => this.invokeAgent(agent, input, context, options));
|
|
202
214
|
}
|
|
203
215
|
async *invokeAgent(agent, input, context, options) {
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
216
|
+
const startedAt = Date.now();
|
|
217
|
+
try {
|
|
218
|
+
let activeAgent = agent;
|
|
219
|
+
for (;;) {
|
|
220
|
+
const result = {};
|
|
221
|
+
if (options?.sourceAgent && activeAgent !== options.sourceAgent) {
|
|
222
|
+
options.sourceAgent.hooks.onHandoff?.({
|
|
223
|
+
context,
|
|
224
|
+
source: options.sourceAgent,
|
|
225
|
+
target: activeAgent,
|
|
226
|
+
input,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
const stream = await activeAgent.invoke(input, { ...options, context, streaming: true });
|
|
230
|
+
for await (const value of stream) {
|
|
231
|
+
if (isAgentResponseDelta(value)) {
|
|
232
|
+
if (value.delta.json) {
|
|
233
|
+
value.delta.json = omitExistsProperties(result, value.delta.json);
|
|
234
|
+
Object.assign(result, value.delta.json);
|
|
235
|
+
}
|
|
236
|
+
delete value.delta.json?.[transferAgentOutputKey];
|
|
221
237
|
}
|
|
222
|
-
|
|
238
|
+
if (isEmptyChunk(value))
|
|
239
|
+
continue;
|
|
240
|
+
yield value;
|
|
223
241
|
}
|
|
224
|
-
if (
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
if (transferToAgent) {
|
|
233
|
-
activeAgent = transferToAgent;
|
|
234
|
-
continue;
|
|
242
|
+
if (!options?.disableTransfer) {
|
|
243
|
+
const transferToAgent = isTransferAgentOutput(result)
|
|
244
|
+
? result[transferAgentOutputKey].agent
|
|
245
|
+
: undefined;
|
|
246
|
+
if (transferToAgent) {
|
|
247
|
+
activeAgent = transferToAgent;
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
235
250
|
}
|
|
251
|
+
break;
|
|
236
252
|
}
|
|
237
|
-
|
|
253
|
+
yield {
|
|
254
|
+
delta: {
|
|
255
|
+
json: { __activeAgent__: activeAgent },
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
finally {
|
|
260
|
+
const endedAt = Date.now();
|
|
261
|
+
const duration = endedAt - startedAt;
|
|
262
|
+
this.usage.duration += duration;
|
|
238
263
|
}
|
|
239
|
-
yield {
|
|
240
|
-
delta: {
|
|
241
|
-
json: { __activeAgent__: activeAgent },
|
|
242
|
-
},
|
|
243
|
-
};
|
|
244
264
|
}
|
|
245
265
|
}
|
|
246
266
|
function omitExistsProperties(result, { ...delta }) {
|
|
@@ -21,7 +21,7 @@ export interface MessagePayload {
|
|
|
21
21
|
/**
|
|
22
22
|
* @hidden
|
|
23
23
|
*/
|
|
24
|
-
export declare function toMessagePayload(payload: Omit<MessagePayload, "context"> |
|
|
24
|
+
export declare function toMessagePayload(payload: Omit<MessagePayload, "context"> | Message, options?: Partial<Pick<MessagePayload, "role" | "source">>): Omit<MessagePayload, "context">;
|
|
25
25
|
/**
|
|
26
26
|
* @hidden
|
|
27
27
|
*/
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Emitter } from "strict-event-emitter";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
-
import { createMessage } from "../prompt/prompt-builder.js";
|
|
4
3
|
import { checkArguments, isNil, orArrayToArray } from "../utils/type-utils.js";
|
|
5
4
|
/**
|
|
6
5
|
* @hidden
|
|
@@ -24,12 +23,12 @@ function isMessagePayload(payload) {
|
|
|
24
23
|
*/
|
|
25
24
|
export function toMessagePayload(payload, options) {
|
|
26
25
|
if (isMessagePayload(payload)) {
|
|
27
|
-
return { ...payload,
|
|
26
|
+
return { ...payload, ...options };
|
|
28
27
|
}
|
|
29
28
|
return {
|
|
30
29
|
role: options?.role || "user",
|
|
31
30
|
source: options?.source,
|
|
32
|
-
message:
|
|
31
|
+
message: payload,
|
|
33
32
|
};
|
|
34
33
|
}
|
|
35
34
|
/**
|
package/lib/esm/aigne/usage.d.ts
CHANGED