@aigne/agent-library 1.17.8 → 1.19.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 CHANGED
@@ -13,6 +13,48 @@
13
13
  * @aigne/core bumped to 1.22.0
14
14
  * @aigne/openai bumped to 0.3.4
15
15
 
16
+ ## [1.19.0](https://github.com/AIGNE-io/aigne-framework/compare/agent-library-v1.18.0...agent-library-v1.19.0) (2025-07-04)
17
+
18
+
19
+ ### Features
20
+
21
+ * **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))
22
+
23
+
24
+ ### Dependencies
25
+
26
+ * The following workspace dependencies were updated
27
+ * dependencies
28
+ * @aigne/core bumped to 1.31.0
29
+ * @aigne/openai bumped to 0.7.1
30
+ * @aigne/sqlite bumped to 0.3.0
31
+
32
+ ## [1.18.0](https://github.com/AIGNE-io/aigne-framework/compare/agent-library-v1.17.9...agent-library-v1.18.0) (2025-07-03)
33
+
34
+
35
+ ### Features
36
+
37
+ * 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))
38
+
39
+
40
+ ### Dependencies
41
+
42
+ * The following workspace dependencies were updated
43
+ * dependencies
44
+ * @aigne/core bumped to 1.30.0
45
+ * @aigne/openai bumped to 0.7.0
46
+ * @aigne/sqlite bumped to 0.2.0
47
+
48
+ ## [1.17.9](https://github.com/AIGNE-io/aigne-framework/compare/agent-library-v1.17.8...agent-library-v1.17.9) (2025-07-02)
49
+
50
+
51
+ ### Dependencies
52
+
53
+ * The following workspace dependencies were updated
54
+ * dependencies
55
+ * @aigne/core bumped to 1.29.1
56
+ * @aigne/openai bumped to 0.6.4
57
+
16
58
  ## [1.17.8](https://github.com/AIGNE-io/aigne-framework/compare/agent-library-v1.17.7...agent-library-v1.17.8) (2025-07-02)
17
59
 
18
60
 
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,28 @@
1
+ import { type AgentOptions, AIAgent, MemoryAgent, type MemoryAgentOptions, 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 { type DefaultMemoryRecorderOptions } 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 DefaultMemoryRecorderOptions {
13
+ }
14
+ export interface AgenticMemoryRecorderOptions extends AgentOptions<MemoryRecorderInput, MemoryRecorderOutput> {
15
+ storage: MemoryStorage;
16
+ instructions?: string | PromptBuilder;
17
+ agent?: AIAgent<AgenticMemoryExtractorInput, AgenticMemoryExtractorOutput>;
18
+ inputKey?: string | string[];
19
+ outputKey?: string | string[];
20
+ }
21
+ export interface AgenticMemoryExtractorInput extends Message {
22
+ content: unknown;
23
+ }
24
+ export interface AgenticMemoryExtractorOutput extends Message {
25
+ newMemories: {
26
+ content: string;
27
+ }[];
28
+ }
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ 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
+ class AgenticMemoryRecorder extends core_1.MemoryRecorder {
30
+ constructor(options) {
31
+ super(options);
32
+ this.storage = options.storage;
33
+ this.inputKey = (0, type_utils_js_1.flat)(options.inputKey);
34
+ this.outputKey = (0, type_utils_js_1.flat)(options.outputKey);
35
+ this.agent =
36
+ options.agent ??
37
+ core_1.AIAgent.from({
38
+ name: "agentic_memory_extractor",
39
+ description: "Records memories in files by AI agent",
40
+ instructions: options.instructions || prompt_js_1.DEFAULT_FS_MEMORY_RECORDER_INSTRUCTIONS,
41
+ outputSchema: zod_1.z.object({
42
+ newMemories: zod_1.z
43
+ .array(zod_1.z.object({
44
+ content: zod_1.z.string().describe("Content of the memory"),
45
+ }))
46
+ .describe("Newly created memories"),
47
+ }),
48
+ });
49
+ }
50
+ storage;
51
+ inputKey;
52
+ outputKey;
53
+ agent;
54
+ async process(input, options) {
55
+ const agenticMemories = await options.context.invoke(this.agent, {
56
+ content: input.content.map((item) => ({
57
+ input: item.input && this.inputKey?.length ? (0, type_utils_js_1.pick)(item.input, this.inputKey) : item.input,
58
+ output: item.output && this.outputKey?.length ? (0, type_utils_js_1.pick)(item.output, this.outputKey) : item.output,
59
+ source: item.source,
60
+ })),
61
+ });
62
+ const newMemories = [];
63
+ for (const item of agenticMemories.newMemories) {
64
+ const { result } = await this.storage.create({ content: item.content }, options);
65
+ newMemories.push(result);
66
+ }
67
+ return {
68
+ memories: newMemories,
69
+ };
70
+ }
71
+ }
@@ -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
  }>;
@@ -0,0 +1,28 @@
1
+ import { type AgentOptions, AIAgent, MemoryAgent, type MemoryAgentOptions, 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 { type DefaultMemoryRecorderOptions } 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 DefaultMemoryRecorderOptions {
13
+ }
14
+ export interface AgenticMemoryRecorderOptions extends AgentOptions<MemoryRecorderInput, MemoryRecorderOutput> {
15
+ storage: MemoryStorage;
16
+ instructions?: string | PromptBuilder;
17
+ agent?: AIAgent<AgenticMemoryExtractorInput, AgenticMemoryExtractorOutput>;
18
+ inputKey?: string | string[];
19
+ outputKey?: string | string[];
20
+ }
21
+ export interface AgenticMemoryExtractorInput extends Message {
22
+ content: unknown;
23
+ }
24
+ export interface AgenticMemoryExtractorOutput extends Message {
25
+ newMemories: {
26
+ content: string;
27
+ }[];
28
+ }
@@ -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";
@@ -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
  }>;
@@ -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 {};
@@ -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
  }>;
@@ -0,0 +1,28 @@
1
+ import { type AgentOptions, AIAgent, MemoryAgent, type MemoryAgentOptions, 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 { type DefaultMemoryRecorderOptions } 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 DefaultMemoryRecorderOptions {
13
+ }
14
+ export interface AgenticMemoryRecorderOptions extends AgentOptions<MemoryRecorderInput, MemoryRecorderOutput> {
15
+ storage: MemoryStorage;
16
+ instructions?: string | PromptBuilder;
17
+ agent?: AIAgent<AgenticMemoryExtractorInput, AgenticMemoryExtractorOutput>;
18
+ inputKey?: string | string[];
19
+ outputKey?: string | string[];
20
+ }
21
+ export interface AgenticMemoryExtractorInput extends Message {
22
+ content: unknown;
23
+ }
24
+ export interface AgenticMemoryExtractorOutput extends Message {
25
+ newMemories: {
26
+ content: string;
27
+ }[];
28
+ }
@@ -0,0 +1,67 @@
1
+ import { AIAgent, MemoryAgent, MemoryRecorder, } from "@aigne/core";
2
+ import { flat, pick } from "@aigne/core/utils/type-utils.js";
3
+ import { z } from "zod";
4
+ import { DefaultMemoryStorage, } from "../default-memory/default-memory-storage/index.js";
5
+ import { DefaultMemoryRetriever, } from "../default-memory/index.js";
6
+ import { MemoryStorage } from "../default-memory/storage.js";
7
+ import { DEFAULT_FS_MEMORY_RECORDER_INSTRUCTIONS } from "./prompt.js";
8
+ export class AgenticMemory extends MemoryAgent {
9
+ constructor(options = {}) {
10
+ const storage = options.storage instanceof MemoryStorage
11
+ ? options.storage
12
+ : new DefaultMemoryStorage(options.storage);
13
+ super({
14
+ ...options,
15
+ recorder: options.recorder ?? new AgenticMemoryRecorder({ ...options, storage }),
16
+ retriever: options.retriever ?? new AgenticMemoryRetriever({ ...options, storage }),
17
+ autoUpdate: options.autoUpdate ?? true,
18
+ });
19
+ this.storage = storage;
20
+ }
21
+ storage;
22
+ }
23
+ class AgenticMemoryRetriever extends DefaultMemoryRetriever {
24
+ }
25
+ class AgenticMemoryRecorder extends MemoryRecorder {
26
+ constructor(options) {
27
+ super(options);
28
+ this.storage = options.storage;
29
+ this.inputKey = flat(options.inputKey);
30
+ this.outputKey = flat(options.outputKey);
31
+ this.agent =
32
+ options.agent ??
33
+ AIAgent.from({
34
+ name: "agentic_memory_extractor",
35
+ description: "Records memories in files by AI agent",
36
+ instructions: options.instructions || DEFAULT_FS_MEMORY_RECORDER_INSTRUCTIONS,
37
+ outputSchema: z.object({
38
+ newMemories: z
39
+ .array(z.object({
40
+ content: z.string().describe("Content of the memory"),
41
+ }))
42
+ .describe("Newly created memories"),
43
+ }),
44
+ });
45
+ }
46
+ storage;
47
+ inputKey;
48
+ outputKey;
49
+ agent;
50
+ async process(input, options) {
51
+ const agenticMemories = await options.context.invoke(this.agent, {
52
+ content: input.content.map((item) => ({
53
+ input: item.input && this.inputKey?.length ? pick(item.input, this.inputKey) : item.input,
54
+ output: item.output && this.outputKey?.length ? pick(item.output, this.outputKey) : item.output,
55
+ source: item.source,
56
+ })),
57
+ });
58
+ const newMemories = [];
59
+ for (const item of agenticMemories.newMemories) {
60
+ const { result } = await this.storage.create({ content: item.content }, options);
61
+ newMemories.push(result);
62
+ }
63
+ return {
64
+ memories: newMemories,
65
+ };
66
+ }
67
+ }
@@ -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,41 @@
1
+ export const DEFAULT_FS_MEMORY_RECORDER_INSTRUCTIONS = `You manage memory based on conversation analysis and the existing memories.
2
+
3
+ ## IMPORTANT: All existing memories are available in the allMemory variable. DO NOT call any tools.
4
+
5
+ ## FIRST: Determine If Memory Updates Needed
6
+ - Analyze if the conversation contains ANY information worth remembering
7
+ - Examples of content NOT worth storing:
8
+ * General questions ("What's the weather?", "How do I do X?")
9
+ * Greetings and small talk ("Hello", "How are you?", "Thanks")
10
+ * System instructions or commands ("Show me", "Find", "Save")
11
+ * General facts not specific to the user
12
+ * Duplicate information already stored
13
+ - If conversation lacks meaningful personal information to store:
14
+ * Return the existing memories unchanged
15
+
16
+ ## Your Workflow:
17
+ 1. Read the existing memories from the allMemory variable
18
+ 2. Extract key topics from the conversation
19
+ 3. DECIDE whether to create/update/delete memories based on the conversation
20
+ 4. Return ALL memories including your updates (remove any duplicates)
21
+
22
+ ## Memory Handling:
23
+ - CREATE: Add new memory objects for new topics
24
+ - UPDATE: Modify existing memories if substantial new information is available
25
+ - DELETE: Remove obsolete memories when appropriate
26
+
27
+ ## Memory Structure:
28
+ - Each memory has an id, content, and createdAt fields
29
+ - Keep the existing structure when returning updated memories
30
+
31
+ ## Operation Decision Rules:
32
+ - CREATE only for truly new topics not covered in any existing memory
33
+ - UPDATE only when new information is meaningfully different
34
+ - NEVER update for just rephrasing or minor differences
35
+ - DELETE only when information becomes obsolete
36
+
37
+ ## Conversation:
38
+ <conversation>
39
+ {{content}}
40
+ </conversation>
41
+ `;
@@ -129,7 +129,7 @@ export function addNullableToOptional(schema) {
129
129
  if (schema.type === "object" && schema.properties) {
130
130
  const required = new Set(Array.isArray(schema.required) ? schema.required : []);
131
131
  newSchema.properties = Object.entries(schema.properties).reduce((acc, [key, value]) => ({
132
- // biome-ignore lint/performance/noAccumulatingSpread: <explanation>
132
+ // biome-ignore lint/performance/noAccumulatingSpread: false positive
133
133
  ...acc,
134
134
  [key]: !required.has(key) ? makeNullable(value) : addNullableToOptional(value),
135
135
  }), {});
@@ -154,7 +154,7 @@ function makeNullable(schema) {
154
154
  // Recursively process nested properties
155
155
  if (schema.properties) {
156
156
  newSchema.properties = Object.entries(schema.properties).reduce((acc, [key, value]) => ({
157
- // biome-ignore lint/performance/noAccumulatingSpread: <explanation>
157
+ // biome-ignore lint/performance/noAccumulatingSpread: false positive
158
158
  ...acc,
159
159
  [key]: makeNullable(value),
160
160
  }), {});
@@ -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
  }>;
@@ -1,5 +1,5 @@
1
1
  import { initDatabase } from "@aigne/sqlite";
2
- import { desc, eq, isNull, sql } from "drizzle-orm";
2
+ import { asc, desc, eq, isNull, sql } from "drizzle-orm";
3
3
  import { v7 } from "uuid";
4
4
  import { stringify } from "yaml";
5
5
  import { MemoryStorage } from "../storage.js";
@@ -48,11 +48,13 @@ export class DefaultMemoryStorage extends MemoryStorage {
48
48
  .select()
49
49
  .from(Memories)
50
50
  .where(sessionId ? eq(Memories.sessionId, sessionId) : isNull(Memories.sessionId))
51
- .orderBy(desc(Memories.id))
51
+ .orderBy(query.orderBy
52
+ ? (query.orderBy[1] === "asc" ? asc : desc)(sql.identifier(query.orderBy[0]))
53
+ : desc(Memories.id))
52
54
  .limit(limit)
53
55
  .execute();
54
56
  return {
55
- result: memories.reverse().map(this.convertMemory),
57
+ result: memories.map(this.convertMemory),
56
58
  };
57
59
  }
58
60
  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,5 +1,5 @@
1
1
  import { MemoryAgent, MemoryRecorder, MemoryRetriever, } from "@aigne/core";
2
- import { isRecord, pick } from "@aigne/core/utils/type-utils.js";
2
+ import { flat, isRecord, pick } from "@aigne/core/utils/type-utils.js";
3
3
  import { DefaultMemoryStorage, } from "./default-memory-storage/index.js";
4
4
  import { MemoryStorage } from "./storage.js";
5
5
  const DEFAULT_RETRIEVE_MEMORY_COUNT = 10;
@@ -10,16 +10,12 @@ export class DefaultMemory extends MemoryAgent {
10
10
  : new DefaultMemoryStorage(options.storage);
11
11
  super({
12
12
  ...options,
13
- recorder: options.recorder ??
14
- new DefaultMemoryRecorder({
15
- ...options.recorderOptions,
16
- rememberFromMessageKey: options.recorderOptions?.rememberFromMessageKey ?? options.messageKey,
17
- storage,
18
- }),
13
+ recorder: options.recorder ?? new DefaultMemoryRecorder({ ...options, storage }),
19
14
  retriever: options.retriever ??
20
15
  new DefaultMemoryRetriever({
21
- ...options.retrieverOptions,
22
- retrieveFromMessageKey: options.retrieverOptions?.retrieveFromMessageKey ?? options.messageKey,
16
+ ...options,
17
+ retrieveRecentMemoryCount: options.retrieveRecentMemoryCount ??
18
+ Math.ceil(options.retrieveMemoryCount ?? DEFAULT_RETRIEVE_MEMORY_COUNT) / 2,
23
19
  storage,
24
20
  }),
25
21
  autoUpdate: options.autoUpdate ?? true,
@@ -28,12 +24,14 @@ export class DefaultMemory extends MemoryAgent {
28
24
  }
29
25
  storage;
30
26
  }
31
- class DefaultMemoryRetriever extends MemoryRetriever {
27
+ export class DefaultMemoryRetriever extends MemoryRetriever {
32
28
  constructor(options) {
33
29
  super(options);
34
30
  this.storage = options.storage;
35
- this.defaultRetrieveMemoryCount = options.defaultRetrieveMemoryCount;
36
- this.retrieveFromMessageKey = options.retrieveFromMessageKey;
31
+ this.retrieveMemoryCount = options.retrieveMemoryCount;
32
+ this.retrieveRecentMemoryCount = options.retrieveRecentMemoryCount;
33
+ this.inputKey = flat(options.inputKey);
34
+ this.outputKey = flat(options.outputKey);
37
35
  if (options.getSearchPattern)
38
36
  this.getSearchPattern = options.getSearchPattern;
39
37
  if (options.formatMessage)
@@ -42,61 +40,79 @@ class DefaultMemoryRetriever extends MemoryRetriever {
42
40
  this.formatMemory = options.formatMemory;
43
41
  }
44
42
  storage;
45
- defaultRetrieveMemoryCount;
46
- retrieveFromMessageKey;
43
+ retrieveMemoryCount;
44
+ retrieveRecentMemoryCount;
45
+ inputKey;
46
+ outputKey;
47
47
  getSearchPattern = (search) => {
48
48
  if (!search || typeof search === "string")
49
49
  return search;
50
- const obj = search && this.retrieveFromMessageKey ? pick(search, this.retrieveFromMessageKey) : search;
50
+ const obj = search && this.inputKey ? pick(search, this.inputKey) : search;
51
51
  return Object.values(obj)
52
52
  .map((v) => (typeof v === "string" ? v : undefined))
53
53
  .join("\n");
54
54
  };
55
- formatMessage = (content) => {
56
- if (!this.retrieveFromMessageKey || !isRecord(content))
55
+ formatMessage = (content, key) => {
56
+ if (!isRecord(content))
57
57
  return content;
58
- const obj = pick(content, this.retrieveFromMessageKey);
58
+ const obj = !key?.length ? content : pick(content, key);
59
59
  return Object.values(obj)
60
60
  .map((v) => (typeof v === "string" ? v : undefined))
61
61
  .join("\n");
62
62
  };
63
63
  formatMemory = (content) => {
64
- if (!isRecord(content))
65
- return content;
66
- if ("input" in content || "output" in content) {
64
+ if (isRecord(content) && "input" in content && "output" in content) {
67
65
  return {
68
- user: this.formatMessage(content.input),
69
- agent: this.formatMessage(content.output),
66
+ input: this.formatMessage(content.input, this.inputKey),
67
+ output: this.formatMessage(content.output, this.outputKey),
68
+ source: content.source,
70
69
  };
71
70
  }
71
+ return content;
72
72
  };
73
73
  async process(input, options) {
74
- const { result } = await this.storage.search({
75
- ...input,
76
- search: this.getSearchPattern(input.search),
77
- limit: input.limit ?? this.defaultRetrieveMemoryCount ?? DEFAULT_RETRIEVE_MEMORY_COUNT,
78
- }, options);
79
- return { memories: result.map((i) => ({ ...i, content: this.formatMemory(i.content) })) };
74
+ const limit = input.limit ?? this.retrieveMemoryCount ?? DEFAULT_RETRIEVE_MEMORY_COUNT;
75
+ const search = this.getSearchPattern(input.search);
76
+ const recentLimit = this.retrieveRecentMemoryCount;
77
+ const [recent, related] = await Promise.all([
78
+ // Query latest messages
79
+ !recentLimit
80
+ ? []
81
+ : this.storage
82
+ .search({ limit: recentLimit, orderBy: ["createdAt", "desc"] }, options)
83
+ .then(({ result }) => result.reverse()),
84
+ // Query related messages
85
+ !input.search
86
+ ? []
87
+ : this.storage.search({ ...input, search, limit }, options).then(({ result }) => result),
88
+ ]);
89
+ const recentSet = new Set(recent.map((i) => i.id));
90
+ const memories = related
91
+ // Filter out recent memories from related results
92
+ .filter((i) => !recentSet.has(i.id))
93
+ .concat(recent)
94
+ .slice(-limit);
95
+ return { memories: memories.map((i) => ({ ...i, content: this.formatMemory(i.content) })) };
80
96
  }
81
97
  }
82
- class DefaultMemoryRecorder extends MemoryRecorder {
98
+ export class DefaultMemoryRecorder extends MemoryRecorder {
83
99
  constructor(options) {
84
100
  super(options);
85
101
  this.storage = options.storage;
86
- this.rememberFromMessageKey = options.rememberFromMessageKey;
102
+ this.inputKey = flat(options.inputKey);
103
+ this.outputKey = flat(options.outputKey);
87
104
  }
88
105
  storage;
89
- rememberFromMessageKey;
106
+ inputKey;
107
+ outputKey;
90
108
  async process(input, options) {
91
109
  const newMemories = [];
92
110
  for (const item of input.content) {
93
111
  const { result } = await this.storage.create({
94
112
  content: {
95
- input: item.input && this.rememberFromMessageKey
96
- ? pick(item.input, this.rememberFromMessageKey)
97
- : item.input,
98
- output: item.output && this.rememberFromMessageKey
99
- ? pick(item.output, this.rememberFromMessageKey)
113
+ input: item.input && this.inputKey?.length ? pick(item.input, this.inputKey) : item.input,
114
+ output: item.output && this.outputKey?.length
115
+ ? pick(item.output, this.outputKey)
100
116
  : item.output,
101
117
  source: item.source,
102
118
  },
@@ -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
  }>;
@@ -1,8 +1,8 @@
1
- import { AIAgent, Agent, PromptTemplate, } from "@aigne/core";
1
+ import { Agent, AIAgent, PromptTemplate, } from "@aigne/core";
2
2
  import { checkArguments } from "@aigne/core/utils/type-utils.js";
3
3
  import fastq from "fastq";
4
4
  import { z } from "zod";
5
- import { FULL_PLAN_PROMPT_TEMPLATE, SYNTHESIZE_PLAN_USER_PROMPT_TEMPLATE, SYNTHESIZE_STEP_PROMPT_TEMPLATE, TASK_PROMPT_TEMPLATE, getFullPlanSchema, } from "./orchestrator-prompts.js";
5
+ import { FULL_PLAN_PROMPT_TEMPLATE, getFullPlanSchema, SYNTHESIZE_PLAN_USER_PROMPT_TEMPLATE, SYNTHESIZE_STEP_PROMPT_TEMPLATE, TASK_PROMPT_TEMPLATE, } from "./orchestrator-prompts.js";
6
6
  /**
7
7
  * Default maximum number of iterations to prevent infinite loops
8
8
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aigne/agent-library",
3
- "version": "1.17.8",
3
+ "version": "1.19.0",
4
4
  "description": "Collection of agent libraries for AIGNE framework",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -39,20 +39,20 @@
39
39
  }
40
40
  },
41
41
  "dependencies": {
42
- "drizzle-orm": "^0.43.1",
42
+ "drizzle-orm": "^0.44.2",
43
43
  "fastq": "^1.19.1",
44
44
  "jsonata": "^2.0.6",
45
45
  "jsonschema": "^1.5.0",
46
46
  "to-json-schema": "^0.2.5",
47
47
  "uuid": "^11.1.0",
48
- "yaml": "^2.7.1",
49
- "zod": "^3.24.4",
50
- "@aigne/core": "^1.29.0",
51
- "@aigne/sqlite": "^0.1.1",
52
- "@aigne/openai": "^0.6.3"
48
+ "yaml": "^2.8.0",
49
+ "zod": "^3.25.67",
50
+ "@aigne/core": "^1.31.0",
51
+ "@aigne/openai": "^0.7.1",
52
+ "@aigne/sqlite": "^0.3.0"
53
53
  },
54
54
  "devDependencies": {
55
- "@types/bun": "^1.2.12",
55
+ "@types/bun": "^1.2.17",
56
56
  "@types/to-json-schema": "^0.2.4",
57
57
  "npm-run-all": "^4.1.5",
58
58
  "rimraf": "^6.0.1",