@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
@@ -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 @@
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
  }>;
@@ -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";
@@ -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,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
+ export class AgenticMemoryRetriever extends DefaultMemoryRetriever {
24
+ }
25
+ export 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
  */
@@ -147,7 +147,7 @@ export class OrchestratorAgent extends Agent {
147
147
  const agent = this.skills.find((skill) => skill.name === task.agent);
148
148
  if (!agent)
149
149
  throw new Error(`Agent ${task.agent} not found`);
150
- const prompt = PromptTemplate.from(TASK_PROMPT_TEMPLATE).format({
150
+ const prompt = await PromptTemplate.from(TASK_PROMPT_TEMPLATE).format({
151
151
  objective: planResult.objective,
152
152
  step,
153
153
  task,