@aigne/agent-library 1.17.9 → 1.20.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.
Files changed (36) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +2 -2
  3. package/README.zh.md +2 -2
  4. package/lib/cjs/agentic-memory/index.d.ts +38 -0
  5. package/lib/cjs/agentic-memory/index.js +73 -0
  6. package/lib/cjs/agentic-memory/prompt.d.ts +1 -0
  7. package/lib/cjs/agentic-memory/prompt.js +44 -0
  8. package/lib/cjs/data-mapper/tools.js +2 -2
  9. package/lib/cjs/default-memory/default-memory-storage/index.d.ts +2 -0
  10. package/lib/cjs/default-memory/default-memory-storage/index.js +4 -2
  11. package/lib/cjs/default-memory/index.d.ts +20 -12
  12. package/lib/cjs/default-memory/index.js +53 -35
  13. package/lib/cjs/default-memory/storage.d.ts +1 -0
  14. package/lib/cjs/orchestrator/index.js +1 -1
  15. package/lib/cjs/orchestrator/orchestrator-prompts.d.ts +3 -3
  16. package/lib/cjs/orchestrator/orchestrator-prompts.js +16 -16
  17. package/lib/dts/agentic-memory/index.d.ts +38 -0
  18. package/lib/dts/agentic-memory/prompt.d.ts +1 -0
  19. package/lib/dts/default-memory/default-memory-storage/index.d.ts +2 -0
  20. package/lib/dts/default-memory/index.d.ts +20 -12
  21. package/lib/dts/default-memory/storage.d.ts +1 -0
  22. package/lib/dts/orchestrator/orchestrator-prompts.d.ts +3 -3
  23. package/lib/esm/agentic-memory/index.d.ts +38 -0
  24. package/lib/esm/agentic-memory/index.js +67 -0
  25. package/lib/esm/agentic-memory/prompt.d.ts +1 -0
  26. package/lib/esm/agentic-memory/prompt.js +41 -0
  27. package/lib/esm/data-mapper/tools.js +2 -2
  28. package/lib/esm/default-memory/default-memory-storage/index.d.ts +2 -0
  29. package/lib/esm/default-memory/default-memory-storage/index.js +5 -3
  30. package/lib/esm/default-memory/index.d.ts +20 -12
  31. package/lib/esm/default-memory/index.js +53 -37
  32. package/lib/esm/default-memory/storage.d.ts +1 -0
  33. package/lib/esm/orchestrator/index.js +3 -3
  34. package/lib/esm/orchestrator/orchestrator-prompts.d.ts +3 -3
  35. package/lib/esm/orchestrator/orchestrator-prompts.js +16 -16
  36. package/package.json +8 -8
package/CHANGELOG.md CHANGED
@@ -13,6 +13,58 @@
13
13
  * @aigne/core bumped to 1.22.0
14
14
  * @aigne/openai bumped to 0.3.4
15
15
 
16
+ ## [1.20.0](https://github.com/AIGNE-io/aigne-framework/compare/agent-library-v1.19.0...agent-library-v1.20.0) (2025-07-08)
17
+
18
+
19
+ ### Features
20
+
21
+ * **core:** add jinja syntax support for prompt builder ([#230](https://github.com/AIGNE-io/aigne-framework/issues/230)) ([74436a7](https://github.com/AIGNE-io/aigne-framework/commit/74436a7faac0c59a32b0153481386162649f4357))
22
+
23
+
24
+ ### Bug Fixes
25
+
26
+ * wrong type AgenticMemoryRetrieverOptions ([0893e02](https://github.com/AIGNE-io/aigne-framework/commit/0893e0271ea6870a420f8c6fd59022ab6566b9c2))
27
+
28
+
29
+ ### Dependencies
30
+
31
+ * The following workspace dependencies were updated
32
+ * dependencies
33
+ * @aigne/core bumped to 1.32.0
34
+ * @aigne/openai bumped to 0.8.0
35
+
36
+ ## [1.19.0](https://github.com/AIGNE-io/aigne-framework/compare/agent-library-v1.18.0...agent-library-v1.19.0) (2025-07-04)
37
+
38
+
39
+ ### Features
40
+
41
+ * **memory:** add support for AgenticMemory & some improvements for DefaultMemory ([#224](https://github.com/AIGNE-io/aigne-framework/issues/224)) ([f4a08af](https://github.com/AIGNE-io/aigne-framework/commit/f4a08aff935205c62615c060763c835a9579607d))
42
+
43
+
44
+ ### Dependencies
45
+
46
+ * The following workspace dependencies were updated
47
+ * dependencies
48
+ * @aigne/core bumped to 1.31.0
49
+ * @aigne/openai bumped to 0.7.1
50
+ * @aigne/sqlite bumped to 0.3.0
51
+
52
+ ## [1.18.0](https://github.com/AIGNE-io/aigne-framework/compare/agent-library-v1.17.9...agent-library-v1.18.0) (2025-07-03)
53
+
54
+
55
+ ### Features
56
+
57
+ * upgrade dependencies and adapt code to breaking changes ([#216](https://github.com/AIGNE-io/aigne-framework/issues/216)) ([f215ced](https://github.com/AIGNE-io/aigne-framework/commit/f215cedc1a57e321164064c33316e496eae8d25f))
58
+
59
+
60
+ ### Dependencies
61
+
62
+ * The following workspace dependencies were updated
63
+ * dependencies
64
+ * @aigne/core bumped to 1.30.0
65
+ * @aigne/openai bumped to 0.7.0
66
+ * @aigne/sqlite bumped to 0.2.0
67
+
16
68
  ## [1.17.9](https://github.com/AIGNE-io/aigne-framework/compare/agent-library-v1.17.8...agent-library-v1.17.9) (2025-07-02)
17
69
 
18
70
 
package/README.md CHANGED
@@ -45,9 +45,9 @@ pnpm add @aigne/agent-library @aigne/core
45
45
  ## Basic Usage
46
46
 
47
47
  ```typescript
48
+ import { OrchestratorAgent } from "@aigne/agent-library/orchestrator";
48
49
  import { AIGNE } from "@aigne/core";
49
50
  import { OpenAIChatModel } from "@aigne/core/models/openai-chat-model.js";
50
- import { OrchestratorAgent } from "@aigne/agent-library/orchestrator";
51
51
 
52
52
  // Create AI model instance
53
53
  const model = new OpenAIChatModel({
@@ -85,9 +85,9 @@ The library currently provides one specialized agent implementation:
85
85
  ### Creating an Orchestration Workflow
86
86
 
87
87
  ```typescript
88
+ import { OrchestratorAgent } from "@aigne/agent-library/orchestrator";
88
89
  import { AIAgent, AIGNE } from "@aigne/core";
89
90
  import { OpenAIChatModel } from "@aigne/core/models/openai-chat-model.js";
90
- import { OrchestratorAgent } from "@aigne/agent-library/orchestrator";
91
91
 
92
92
  const model = new OpenAIChatModel({
93
93
  apiKey: process.env.OPENAI_API_KEY,
package/README.zh.md CHANGED
@@ -45,9 +45,9 @@ pnpm add @aigne/agent-library @aigne/core
45
45
  ## 基本用法
46
46
 
47
47
  ```typescript
48
+ import { OrchestratorAgent } from "@aigne/agent-library/orchestrator";
48
49
  import { AIGNE } from "@aigne/core";
49
50
  import { OpenAIChatModel } from "@aigne/core/models/openai-chat-model.js";
50
- import { OrchestratorAgent } from "@aigne/agent-library/orchestrator";
51
51
 
52
52
  // 创建 AI 模型实例
53
53
  const model = new OpenAIChatModel({
@@ -85,9 +85,9 @@ console.log(result);
85
85
  ### 创建编排工作流
86
86
 
87
87
  ```typescript
88
+ import { OrchestratorAgent } from "@aigne/agent-library/orchestrator";
88
89
  import { AIAgent, AIGNE } from "@aigne/core";
89
90
  import { OpenAIChatModel } from "@aigne/core/models/openai-chat-model.js";
90
- import { OrchestratorAgent } from "@aigne/agent-library/orchestrator";
91
91
 
92
92
  const model = new OpenAIChatModel({
93
93
  apiKey: process.env.OPENAI_API_KEY,
@@ -0,0 +1,38 @@
1
+ import { type AgentInvokeOptions, type AgentOptions, AIAgent, MemoryAgent, type MemoryAgentOptions, MemoryRecorder, type MemoryRecorderInput, type MemoryRecorderOutput, type Message, type PromptBuilder } from "@aigne/core";
2
+ import { type DefaultMemoryStorageOptions } from "../default-memory/default-memory-storage/index.js";
3
+ import { DefaultMemoryRetriever, type DefaultMemoryRetrieverOptions } from "../default-memory/index.js";
4
+ import { MemoryStorage } from "../default-memory/storage.js";
5
+ export interface AgenticMemoryOptions extends Partial<MemoryAgentOptions>, Omit<AgenticMemoryRecorderOptions, "storage" | keyof AgentOptions>, Omit<AgenticMemoryRetrieverOptions, "storage" | keyof AgentOptions> {
6
+ storage?: MemoryStorage | DefaultMemoryStorageOptions;
7
+ }
8
+ export declare class AgenticMemory extends MemoryAgent {
9
+ constructor(options?: AgenticMemoryOptions);
10
+ storage: MemoryStorage;
11
+ }
12
+ export interface AgenticMemoryRetrieverOptions extends DefaultMemoryRetrieverOptions {
13
+ }
14
+ export declare class AgenticMemoryRetriever extends DefaultMemoryRetriever {
15
+ }
16
+ export interface AgenticMemoryRecorderOptions extends AgentOptions<MemoryRecorderInput, MemoryRecorderOutput> {
17
+ storage: MemoryStorage;
18
+ instructions?: string | PromptBuilder;
19
+ agent?: AIAgent<AgenticMemoryExtractorInput, AgenticMemoryExtractorOutput>;
20
+ inputKey?: string | string[];
21
+ outputKey?: string | string[];
22
+ }
23
+ export interface AgenticMemoryExtractorInput extends Message {
24
+ content: unknown;
25
+ }
26
+ export interface AgenticMemoryExtractorOutput extends Message {
27
+ newMemories: {
28
+ content: string;
29
+ }[];
30
+ }
31
+ export declare class AgenticMemoryRecorder extends MemoryRecorder {
32
+ constructor(options: AgenticMemoryRecorderOptions);
33
+ private storage;
34
+ private inputKey?;
35
+ private outputKey?;
36
+ private agent;
37
+ process(input: MemoryRecorderInput, options: AgentInvokeOptions): Promise<MemoryRecorderOutput>;
38
+ }
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AgenticMemoryRecorder = exports.AgenticMemoryRetriever = exports.AgenticMemory = void 0;
4
+ const core_1 = require("@aigne/core");
5
+ const type_utils_js_1 = require("@aigne/core/utils/type-utils.js");
6
+ const zod_1 = require("zod");
7
+ const index_js_1 = require("../default-memory/default-memory-storage/index.js");
8
+ const index_js_2 = require("../default-memory/index.js");
9
+ const storage_js_1 = require("../default-memory/storage.js");
10
+ const prompt_js_1 = require("./prompt.js");
11
+ class AgenticMemory extends core_1.MemoryAgent {
12
+ constructor(options = {}) {
13
+ const storage = options.storage instanceof storage_js_1.MemoryStorage
14
+ ? options.storage
15
+ : new index_js_1.DefaultMemoryStorage(options.storage);
16
+ super({
17
+ ...options,
18
+ recorder: options.recorder ?? new AgenticMemoryRecorder({ ...options, storage }),
19
+ retriever: options.retriever ?? new AgenticMemoryRetriever({ ...options, storage }),
20
+ autoUpdate: options.autoUpdate ?? true,
21
+ });
22
+ this.storage = storage;
23
+ }
24
+ storage;
25
+ }
26
+ exports.AgenticMemory = AgenticMemory;
27
+ class AgenticMemoryRetriever extends index_js_2.DefaultMemoryRetriever {
28
+ }
29
+ exports.AgenticMemoryRetriever = AgenticMemoryRetriever;
30
+ class AgenticMemoryRecorder extends core_1.MemoryRecorder {
31
+ constructor(options) {
32
+ super(options);
33
+ this.storage = options.storage;
34
+ this.inputKey = (0, type_utils_js_1.flat)(options.inputKey);
35
+ this.outputKey = (0, type_utils_js_1.flat)(options.outputKey);
36
+ this.agent =
37
+ options.agent ??
38
+ core_1.AIAgent.from({
39
+ name: "agentic_memory_extractor",
40
+ description: "Records memories in files by AI agent",
41
+ instructions: options.instructions || prompt_js_1.DEFAULT_FS_MEMORY_RECORDER_INSTRUCTIONS,
42
+ outputSchema: zod_1.z.object({
43
+ newMemories: zod_1.z
44
+ .array(zod_1.z.object({
45
+ content: zod_1.z.string().describe("Content of the memory"),
46
+ }))
47
+ .describe("Newly created memories"),
48
+ }),
49
+ });
50
+ }
51
+ storage;
52
+ inputKey;
53
+ outputKey;
54
+ agent;
55
+ async process(input, options) {
56
+ const agenticMemories = await options.context.invoke(this.agent, {
57
+ content: input.content.map((item) => ({
58
+ input: item.input && this.inputKey?.length ? (0, type_utils_js_1.pick)(item.input, this.inputKey) : item.input,
59
+ output: item.output && this.outputKey?.length ? (0, type_utils_js_1.pick)(item.output, this.outputKey) : item.output,
60
+ source: item.source,
61
+ })),
62
+ });
63
+ const newMemories = [];
64
+ for (const item of agenticMemories.newMemories) {
65
+ const { result } = await this.storage.create({ content: item.content }, options);
66
+ newMemories.push(result);
67
+ }
68
+ return {
69
+ memories: newMemories,
70
+ };
71
+ }
72
+ }
73
+ exports.AgenticMemoryRecorder = AgenticMemoryRecorder;
@@ -0,0 +1 @@
1
+ export declare const DEFAULT_FS_MEMORY_RECORDER_INSTRUCTIONS = "You manage memory based on conversation analysis and the existing memories.\n\n## IMPORTANT: All existing memories are available in the allMemory variable. DO NOT call any tools.\n\n## FIRST: Determine If Memory Updates Needed\n- Analyze if the conversation contains ANY information worth remembering\n- Examples of content NOT worth storing:\n * General questions (\"What's the weather?\", \"How do I do X?\")\n * Greetings and small talk (\"Hello\", \"How are you?\", \"Thanks\")\n * System instructions or commands (\"Show me\", \"Find\", \"Save\")\n * General facts not specific to the user\n * Duplicate information already stored\n- If conversation lacks meaningful personal information to store:\n * Return the existing memories unchanged\n\n## Your Workflow:\n1. Read the existing memories from the allMemory variable\n2. Extract key topics from the conversation\n3. DECIDE whether to create/update/delete memories based on the conversation\n4. Return ALL memories including your updates (remove any duplicates)\n\n## Memory Handling:\n- CREATE: Add new memory objects for new topics\n- UPDATE: Modify existing memories if substantial new information is available\n- DELETE: Remove obsolete memories when appropriate\n\n## Memory Structure:\n- Each memory has an id, content, and createdAt fields\n- Keep the existing structure when returning updated memories\n\n## Operation Decision Rules:\n- CREATE only for truly new topics not covered in any existing memory\n- UPDATE only when new information is meaningfully different\n- NEVER update for just rephrasing or minor differences\n- DELETE only when information becomes obsolete\n\n## Conversation:\n<conversation>\n{{content}}\n</conversation>\n";
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_FS_MEMORY_RECORDER_INSTRUCTIONS = void 0;
4
+ exports.DEFAULT_FS_MEMORY_RECORDER_INSTRUCTIONS = `You manage memory based on conversation analysis and the existing memories.
5
+
6
+ ## IMPORTANT: All existing memories are available in the allMemory variable. DO NOT call any tools.
7
+
8
+ ## FIRST: Determine If Memory Updates Needed
9
+ - Analyze if the conversation contains ANY information worth remembering
10
+ - Examples of content NOT worth storing:
11
+ * General questions ("What's the weather?", "How do I do X?")
12
+ * Greetings and small talk ("Hello", "How are you?", "Thanks")
13
+ * System instructions or commands ("Show me", "Find", "Save")
14
+ * General facts not specific to the user
15
+ * Duplicate information already stored
16
+ - If conversation lacks meaningful personal information to store:
17
+ * Return the existing memories unchanged
18
+
19
+ ## Your Workflow:
20
+ 1. Read the existing memories from the allMemory variable
21
+ 2. Extract key topics from the conversation
22
+ 3. DECIDE whether to create/update/delete memories based on the conversation
23
+ 4. Return ALL memories including your updates (remove any duplicates)
24
+
25
+ ## Memory Handling:
26
+ - CREATE: Add new memory objects for new topics
27
+ - UPDATE: Modify existing memories if substantial new information is available
28
+ - DELETE: Remove obsolete memories when appropriate
29
+
30
+ ## Memory Structure:
31
+ - Each memory has an id, content, and createdAt fields
32
+ - Keep the existing structure when returning updated memories
33
+
34
+ ## Operation Decision Rules:
35
+ - CREATE only for truly new topics not covered in any existing memory
36
+ - UPDATE only when new information is meaningfully different
37
+ - NEVER update for just rephrasing or minor differences
38
+ - DELETE only when information becomes obsolete
39
+
40
+ ## Conversation:
41
+ <conversation>
42
+ {{content}}
43
+ </conversation>
44
+ `;
@@ -139,7 +139,7 @@ function addNullableToOptional(schema) {
139
139
  if (schema.type === "object" && schema.properties) {
140
140
  const required = new Set(Array.isArray(schema.required) ? schema.required : []);
141
141
  newSchema.properties = Object.entries(schema.properties).reduce((acc, [key, value]) => ({
142
- // biome-ignore lint/performance/noAccumulatingSpread: <explanation>
142
+ // biome-ignore lint/performance/noAccumulatingSpread: false positive
143
143
  ...acc,
144
144
  [key]: !required.has(key) ? makeNullable(value) : addNullableToOptional(value),
145
145
  }), {});
@@ -164,7 +164,7 @@ function makeNullable(schema) {
164
164
  // Recursively process nested properties
165
165
  if (schema.properties) {
166
166
  newSchema.properties = Object.entries(schema.properties).reduce((acc, [key, value]) => ({
167
- // biome-ignore lint/performance/noAccumulatingSpread: <explanation>
167
+ // biome-ignore lint/performance/noAccumulatingSpread: false positive
168
168
  ...acc,
169
169
  [key]: makeNullable(value),
170
170
  }), {});
@@ -2,6 +2,7 @@ import type { AgentInvokeOptions, Context, Memory } from "@aigne/core";
2
2
  import type { PromiseOrValue } from "@aigne/core/utils/type-utils.js";
3
3
  import type { SqliteRemoteDatabase } from "drizzle-orm/sqlite-proxy";
4
4
  import { MemoryStorage } from "../storage.js";
5
+ import { Memories } from "./models/memory.js";
5
6
  export interface DefaultMemoryStorageOptions {
6
7
  url?: string;
7
8
  getSessionId?: (context: Context) => PromiseOrValue<string>;
@@ -17,6 +18,7 @@ export declare class DefaultMemoryStorage extends MemoryStorage {
17
18
  search(query: {
18
19
  search?: string;
19
20
  limit?: number;
21
+ orderBy?: [keyof typeof Memories.$inferSelect, "asc" | "desc"];
20
22
  }, { context }: AgentInvokeOptions): Promise<{
21
23
  result: Memory[];
22
24
  }>;
@@ -51,11 +51,13 @@ class DefaultMemoryStorage extends storage_js_1.MemoryStorage {
51
51
  .select()
52
52
  .from(memory_js_1.Memories)
53
53
  .where(sessionId ? (0, drizzle_orm_1.eq)(memory_js_1.Memories.sessionId, sessionId) : (0, drizzle_orm_1.isNull)(memory_js_1.Memories.sessionId))
54
- .orderBy((0, drizzle_orm_1.desc)(memory_js_1.Memories.id))
54
+ .orderBy(query.orderBy
55
+ ? (query.orderBy[1] === "asc" ? drizzle_orm_1.asc : drizzle_orm_1.desc)(drizzle_orm_1.sql.identifier(query.orderBy[0]))
56
+ : (0, drizzle_orm_1.desc)(memory_js_1.Memories.id))
55
57
  .limit(limit)
56
58
  .execute();
57
59
  return {
58
- result: memories.reverse().map(this.convertMemory),
60
+ result: memories.map(this.convertMemory),
59
61
  };
60
62
  }
61
63
  async create(memory, { context }) {
@@ -1,11 +1,8 @@
1
- import { type AgentInvokeOptions, type AgentOptions, MemoryAgent, type MemoryAgentOptions, type MemoryRecorderInput, type MemoryRecorderOutput, MemoryRetriever, type MemoryRetrieverInput, type MemoryRetrieverOutput } from "@aigne/core";
1
+ import { type AgentInvokeOptions, type AgentOptions, MemoryAgent, type MemoryAgentOptions, MemoryRecorder, type MemoryRecorderInput, type MemoryRecorderOutput, MemoryRetriever, type MemoryRetrieverInput, type MemoryRetrieverOutput } from "@aigne/core";
2
2
  import { type DefaultMemoryStorageOptions } from "./default-memory-storage/index.js";
3
3
  import { MemoryStorage } from "./storage.js";
4
- export interface DefaultMemoryOptions extends Partial<MemoryAgentOptions> {
4
+ export interface DefaultMemoryOptions extends Partial<MemoryAgentOptions>, Omit<DefaultMemoryRecorderOptions, "storage" | keyof AgentOptions>, Omit<DefaultMemoryRetrieverOptions, "storage" | keyof AgentOptions> {
5
5
  storage?: MemoryStorage | DefaultMemoryStorageOptions;
6
- recorderOptions?: Omit<DefaultMemoryRecorderOptions, "storage">;
7
- retrieverOptions?: Omit<DefaultMemoryRetrieverOptions, "storage">;
8
- messageKey?: string | string[];
9
6
  }
10
7
  export declare class DefaultMemory extends MemoryAgent {
11
8
  constructor(options?: DefaultMemoryOptions);
@@ -13,17 +10,21 @@ export declare class DefaultMemory extends MemoryAgent {
13
10
  }
14
11
  export interface DefaultMemoryRetrieverOptions extends AgentOptions<MemoryRetrieverInput, MemoryRetrieverOutput> {
15
12
  storage: MemoryStorage;
16
- defaultRetrieveMemoryCount?: number;
17
- retrieveFromMessageKey?: string | string[];
13
+ retrieveMemoryCount?: number;
14
+ retrieveRecentMemoryCount?: number;
15
+ inputKey?: string | string[];
16
+ outputKey?: string | string[];
18
17
  getSearchPattern?: DefaultMemoryRetriever["getSearchPattern"];
19
18
  formatMessage?: DefaultMemoryRetriever["formatMessage"];
20
19
  formatMemory?: DefaultMemoryRetriever["formatMemory"];
21
20
  }
22
- declare class DefaultMemoryRetriever extends MemoryRetriever {
21
+ export declare class DefaultMemoryRetriever extends MemoryRetriever {
23
22
  constructor(options: DefaultMemoryRetrieverOptions);
24
23
  private storage;
25
- private defaultRetrieveMemoryCount?;
26
- private retrieveFromMessageKey?;
24
+ private retrieveMemoryCount?;
25
+ private retrieveRecentMemoryCount?;
26
+ private inputKey?;
27
+ private outputKey?;
27
28
  private getSearchPattern;
28
29
  private formatMessage;
29
30
  private formatMemory;
@@ -31,6 +32,13 @@ declare class DefaultMemoryRetriever extends MemoryRetriever {
31
32
  }
32
33
  export interface DefaultMemoryRecorderOptions extends AgentOptions<MemoryRecorderInput, MemoryRecorderOutput> {
33
34
  storage: MemoryStorage;
34
- rememberFromMessageKey?: string | string[];
35
+ inputKey?: string | string[];
36
+ outputKey?: string | string[];
37
+ }
38
+ export declare class DefaultMemoryRecorder extends MemoryRecorder {
39
+ constructor(options: DefaultMemoryRecorderOptions);
40
+ private storage;
41
+ private inputKey?;
42
+ private outputKey?;
43
+ process(input: MemoryRecorderInput, options: AgentInvokeOptions): Promise<MemoryRecorderOutput>;
35
44
  }
36
- export {};
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DefaultMemory = void 0;
3
+ exports.DefaultMemoryRecorder = exports.DefaultMemoryRetriever = exports.DefaultMemory = void 0;
4
4
  const core_1 = require("@aigne/core");
5
5
  const type_utils_js_1 = require("@aigne/core/utils/type-utils.js");
6
6
  const index_js_1 = require("./default-memory-storage/index.js");
@@ -13,16 +13,12 @@ class DefaultMemory extends core_1.MemoryAgent {
13
13
  : new index_js_1.DefaultMemoryStorage(options.storage);
14
14
  super({
15
15
  ...options,
16
- recorder: options.recorder ??
17
- new DefaultMemoryRecorder({
18
- ...options.recorderOptions,
19
- rememberFromMessageKey: options.recorderOptions?.rememberFromMessageKey ?? options.messageKey,
20
- storage,
21
- }),
16
+ recorder: options.recorder ?? new DefaultMemoryRecorder({ ...options, storage }),
22
17
  retriever: options.retriever ??
23
18
  new DefaultMemoryRetriever({
24
- ...options.retrieverOptions,
25
- retrieveFromMessageKey: options.retrieverOptions?.retrieveFromMessageKey ?? options.messageKey,
19
+ ...options,
20
+ retrieveRecentMemoryCount: options.retrieveRecentMemoryCount ??
21
+ Math.ceil(options.retrieveMemoryCount ?? DEFAULT_RETRIEVE_MEMORY_COUNT) / 2,
26
22
  storage,
27
23
  }),
28
24
  autoUpdate: options.autoUpdate ?? true,
@@ -36,8 +32,10 @@ class DefaultMemoryRetriever extends core_1.MemoryRetriever {
36
32
  constructor(options) {
37
33
  super(options);
38
34
  this.storage = options.storage;
39
- this.defaultRetrieveMemoryCount = options.defaultRetrieveMemoryCount;
40
- this.retrieveFromMessageKey = options.retrieveFromMessageKey;
35
+ this.retrieveMemoryCount = options.retrieveMemoryCount;
36
+ this.retrieveRecentMemoryCount = options.retrieveRecentMemoryCount;
37
+ this.inputKey = (0, type_utils_js_1.flat)(options.inputKey);
38
+ this.outputKey = (0, type_utils_js_1.flat)(options.outputKey);
41
39
  if (options.getSearchPattern)
42
40
  this.getSearchPattern = options.getSearchPattern;
43
41
  if (options.formatMessage)
@@ -46,61 +44,80 @@ class DefaultMemoryRetriever extends core_1.MemoryRetriever {
46
44
  this.formatMemory = options.formatMemory;
47
45
  }
48
46
  storage;
49
- defaultRetrieveMemoryCount;
50
- retrieveFromMessageKey;
47
+ retrieveMemoryCount;
48
+ retrieveRecentMemoryCount;
49
+ inputKey;
50
+ outputKey;
51
51
  getSearchPattern = (search) => {
52
52
  if (!search || typeof search === "string")
53
53
  return search;
54
- const obj = search && this.retrieveFromMessageKey ? (0, type_utils_js_1.pick)(search, this.retrieveFromMessageKey) : search;
54
+ const obj = search && this.inputKey ? (0, type_utils_js_1.pick)(search, this.inputKey) : search;
55
55
  return Object.values(obj)
56
56
  .map((v) => (typeof v === "string" ? v : undefined))
57
57
  .join("\n");
58
58
  };
59
- formatMessage = (content) => {
60
- if (!this.retrieveFromMessageKey || !(0, type_utils_js_1.isRecord)(content))
59
+ formatMessage = (content, key) => {
60
+ if (!(0, type_utils_js_1.isRecord)(content))
61
61
  return content;
62
- const obj = (0, type_utils_js_1.pick)(content, this.retrieveFromMessageKey);
62
+ const obj = !key?.length ? content : (0, type_utils_js_1.pick)(content, key);
63
63
  return Object.values(obj)
64
64
  .map((v) => (typeof v === "string" ? v : undefined))
65
65
  .join("\n");
66
66
  };
67
67
  formatMemory = (content) => {
68
- if (!(0, type_utils_js_1.isRecord)(content))
69
- return content;
70
- if ("input" in content || "output" in content) {
68
+ if ((0, type_utils_js_1.isRecord)(content) && "input" in content && "output" in content) {
71
69
  return {
72
- user: this.formatMessage(content.input),
73
- agent: this.formatMessage(content.output),
70
+ input: this.formatMessage(content.input, this.inputKey),
71
+ output: this.formatMessage(content.output, this.outputKey),
72
+ source: content.source,
74
73
  };
75
74
  }
75
+ return content;
76
76
  };
77
77
  async process(input, options) {
78
- const { result } = await this.storage.search({
79
- ...input,
80
- search: this.getSearchPattern(input.search),
81
- limit: input.limit ?? this.defaultRetrieveMemoryCount ?? DEFAULT_RETRIEVE_MEMORY_COUNT,
82
- }, options);
83
- return { memories: result.map((i) => ({ ...i, content: this.formatMemory(i.content) })) };
78
+ const limit = input.limit ?? this.retrieveMemoryCount ?? DEFAULT_RETRIEVE_MEMORY_COUNT;
79
+ const search = this.getSearchPattern(input.search);
80
+ const recentLimit = this.retrieveRecentMemoryCount;
81
+ const [recent, related] = await Promise.all([
82
+ // Query latest messages
83
+ !recentLimit
84
+ ? []
85
+ : this.storage
86
+ .search({ limit: recentLimit, orderBy: ["createdAt", "desc"] }, options)
87
+ .then(({ result }) => result.reverse()),
88
+ // Query related messages
89
+ !input.search
90
+ ? []
91
+ : this.storage.search({ ...input, search, limit }, options).then(({ result }) => result),
92
+ ]);
93
+ const recentSet = new Set(recent.map((i) => i.id));
94
+ const memories = related
95
+ // Filter out recent memories from related results
96
+ .filter((i) => !recentSet.has(i.id))
97
+ .concat(recent)
98
+ .slice(-limit);
99
+ return { memories: memories.map((i) => ({ ...i, content: this.formatMemory(i.content) })) };
84
100
  }
85
101
  }
102
+ exports.DefaultMemoryRetriever = DefaultMemoryRetriever;
86
103
  class DefaultMemoryRecorder extends core_1.MemoryRecorder {
87
104
  constructor(options) {
88
105
  super(options);
89
106
  this.storage = options.storage;
90
- this.rememberFromMessageKey = options.rememberFromMessageKey;
107
+ this.inputKey = (0, type_utils_js_1.flat)(options.inputKey);
108
+ this.outputKey = (0, type_utils_js_1.flat)(options.outputKey);
91
109
  }
92
110
  storage;
93
- rememberFromMessageKey;
111
+ inputKey;
112
+ outputKey;
94
113
  async process(input, options) {
95
114
  const newMemories = [];
96
115
  for (const item of input.content) {
97
116
  const { result } = await this.storage.create({
98
117
  content: {
99
- input: item.input && this.rememberFromMessageKey
100
- ? (0, type_utils_js_1.pick)(item.input, this.rememberFromMessageKey)
101
- : item.input,
102
- output: item.output && this.rememberFromMessageKey
103
- ? (0, type_utils_js_1.pick)(item.output, this.rememberFromMessageKey)
118
+ input: item.input && this.inputKey?.length ? (0, type_utils_js_1.pick)(item.input, this.inputKey) : item.input,
119
+ output: item.output && this.outputKey?.length
120
+ ? (0, type_utils_js_1.pick)(item.output, this.outputKey)
104
121
  : item.output,
105
122
  source: item.source,
106
123
  },
@@ -112,3 +129,4 @@ class DefaultMemoryRecorder extends core_1.MemoryRecorder {
112
129
  };
113
130
  }
114
131
  }
132
+ exports.DefaultMemoryRecorder = DefaultMemoryRecorder;
@@ -6,6 +6,7 @@ export declare abstract class MemoryStorage {
6
6
  abstract search(query: {
7
7
  search?: string;
8
8
  limit?: number;
9
+ orderBy?: [string, "asc" | "desc"];
9
10
  }, options: AgentInvokeOptions): Promise<{
10
11
  result: Memory[];
11
12
  }>;
@@ -167,7 +167,7 @@ class OrchestratorAgent extends core_1.Agent {
167
167
  const agent = this.skills.find((skill) => skill.name === task.agent);
168
168
  if (!agent)
169
169
  throw new Error(`Agent ${task.agent} not found`);
170
- const prompt = core_1.PromptTemplate.from(orchestrator_prompts_js_1.TASK_PROMPT_TEMPLATE).format({
170
+ const prompt = await core_1.PromptTemplate.from(orchestrator_prompts_js_1.TASK_PROMPT_TEMPLATE).format({
171
171
  objective: planResult.objective,
172
172
  step,
173
173
  task,
@@ -102,7 +102,7 @@ export interface FullPlanInput extends Message {
102
102
  /**
103
103
  * @hidden
104
104
  */
105
- export declare const FULL_PLAN_PROMPT_TEMPLATE = "You are tasked with orchestrating a plan to complete an objective.\nYou can analyze results from the previous steps already executed to decide if the objective is complete.\nYour plan must be structured in sequential steps, with each step containing independent parallel subtasks.\n\n<objective>\n{{objective}}\n</objective>\n\n<steps_completed>\n{{#steps}}\n- Step: {{step.description}}\n Result: {{result}}\n{{/steps}}\n</steps_completed>\n\n<previous_plan_status>\n{{plan.status}}\n</previous_plan_status>\n\n<previous_plan_result>\n{{plan.result}}\n</previous_plan_result>\n\nYou have access to the following Agents(which are collections of tools/functions):\n\n<agents>\n{{#agents}}\n- Agent: {{name}}\n Description: {{description}}\n Functions:\n {{#tools}}\n - Tool: {{name}}\n Description: {{description}}\n {{/tools}}\n{{/agents}}\n</agents>\n\n- If the previous plan results achieve the objective, return isComplete=true.\n- Otherwise, generate remaining steps needed.\n- Generate a plan with all remaining steps needed.\n- Steps are sequential, but each Step can have parallel subtasks.\n- For each Step, specify a description of the step and independent subtasks that can run in parallel.\n- For each subtask specify:\n 1. Clear description of the task that an LLM can execute\n 2. Name of 1 Agent to use for the task";
105
+ export declare const FULL_PLAN_PROMPT_TEMPLATE = "You are tasked with orchestrating a plan to complete an objective.\nYou can analyze results from the previous steps already executed to decide if the objective is complete.\nYour plan must be structured in sequential steps, with each step containing independent parallel subtasks.\n\n<objective>\n{{objective}}\n</objective>\n\n<steps_completed>\n{% for step in steps %}\n- Step: {{step.description}}\n Result: {{result}}\n{% endfor %}\n</steps_completed>\n\n<previous_plan_status>\n{{plan.status}}\n</previous_plan_status>\n\n<previous_plan_result>\n{{plan.result}}\n</previous_plan_result>\n\nYou have access to the following Agents(which are collections of tools/functions):\n\n<agents>\n{% for agent in agents %}\n- Agent: {{agent.name}}\n Description: {{agent.description}}\n Functions:\n {% for tool in tools %}\n - Tool: {{tool.name}}\n Description: {{tool.description}}\n {% endfor %}\n{% endfor %}\n</agents>\n\n- If the previous plan results achieve the objective, return isComplete=true.\n- Otherwise, generate remaining steps needed.\n- Generate a plan with all remaining steps needed.\n- Steps are sequential, but each Step can have parallel subtasks.\n- For each Step, specify a description of the step and independent subtasks that can run in parallel.\n- For each subtask specify:\n 1. Clear description of the task that an LLM can execute\n 2. Name of 1 Agent to use for the task";
106
106
  /**
107
107
  * @hidden
108
108
  */
@@ -115,7 +115,7 @@ export interface TaskPromptInput extends Message {
115
115
  /**
116
116
  * @hidden
117
117
  */
118
- export declare const TASK_PROMPT_TEMPLATE = "You are part of a larger workflow to achieve the step then the objective:\n\n<objective>\n{{objective}}\n</objective>\n\n<step>\n{{step.description}}\n</step>\n\nYour job is to accomplish only the following task:\n\n<task>\n{{task.description}}\n</task>\n\nResults so far that may provide helpful context:\n\n<steps_completed>\n{{#steps}}\n- Step: {{step.description}}\n Result: {{result}}\n{{/steps}}\n</steps_completed>\n";
118
+ export declare const TASK_PROMPT_TEMPLATE = "You are part of a larger workflow to achieve the step then the objective:\n\n<objective>\n{{objective}}\n</objective>\n\n<step>\n{{step.description}}\n</step>\n\nYour job is to accomplish only the following task:\n\n<task>\n{{task.description}}\n</task>\n\nResults so far that may provide helpful context:\n\n<steps_completed>\n{% for step in steps %}\n- Step: {{step.description}}\n Result: {{step.result}}\n{% endfor %}\n</steps_completed>\n";
119
119
  /**
120
120
  * @hidden
121
121
  */
@@ -127,4 +127,4 @@ export interface SynthesizeStepPromptInput extends Message {
127
127
  /**
128
128
  * @hidden
129
129
  */
130
- export declare const SYNTHESIZE_STEP_PROMPT_TEMPLATE = "Synthesize the results of these parallel tasks into a cohesive result\n\n<objective>\n{{objective}}\n</objective>\n\n<step>\n{{step.description}}\n</step>\n\n<tasks>\n{{#tasks}}\n- Task: {{task.description}}\n Result: {{result}}\n{{/tasks}}\n</tasks>\n";
130
+ export declare const SYNTHESIZE_STEP_PROMPT_TEMPLATE = "Synthesize the results of these parallel tasks into a cohesive result\n\n<objective>\n{{objective}}\n</objective>\n\n<step>\n{{step.description}}\n</step>\n\n<tasks>\n{% for task in tasks %}\n- Task: {{task.description}}\n Result: {{task.result}}\n{% endfor %}\n</tasks>\n";
@@ -47,10 +47,10 @@ Your plan must be structured in sequential steps, with each step containing inde
47
47
  </objective>
48
48
 
49
49
  <steps_completed>
50
- {{#steps}}
50
+ {% for step in steps %}
51
51
  - Step: {{step.description}}
52
52
  Result: {{result}}
53
- {{/steps}}
53
+ {% endfor %}
54
54
  </steps_completed>
55
55
 
56
56
  <previous_plan_status>
@@ -64,15 +64,15 @@ Your plan must be structured in sequential steps, with each step containing inde
64
64
  You have access to the following Agents(which are collections of tools/functions):
65
65
 
66
66
  <agents>
67
- {{#agents}}
68
- - Agent: {{name}}
69
- Description: {{description}}
67
+ {% for agent in agents %}
68
+ - Agent: {{agent.name}}
69
+ Description: {{agent.description}}
70
70
  Functions:
71
- {{#tools}}
72
- - Tool: {{name}}
73
- Description: {{description}}
74
- {{/tools}}
75
- {{/agents}}
71
+ {% for tool in tools %}
72
+ - Tool: {{tool.name}}
73
+ Description: {{tool.description}}
74
+ {% endfor %}
75
+ {% endfor %}
76
76
  </agents>
77
77
 
78
78
  - If the previous plan results achieve the objective, return isComplete=true.
@@ -106,10 +106,10 @@ Your job is to accomplish only the following task:
106
106
  Results so far that may provide helpful context:
107
107
 
108
108
  <steps_completed>
109
- {{#steps}}
109
+ {% for step in steps %}
110
110
  - Step: {{step.description}}
111
- Result: {{result}}
112
- {{/steps}}
111
+ Result: {{step.result}}
112
+ {% endfor %}
113
113
  </steps_completed>
114
114
  `;
115
115
  /**
@@ -127,9 +127,9 @@ Synthesize the results of these parallel tasks into a cohesive result
127
127
  </step>
128
128
 
129
129
  <tasks>
130
- {{#tasks}}
130
+ {% for task in tasks %}
131
131
  - Task: {{task.description}}
132
- Result: {{result}}
133
- {{/tasks}}
132
+ Result: {{task.result}}
133
+ {% endfor %}
134
134
  </tasks>
135
135
  `;