@aigne/core 1.13.0 → 1.14.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 (195) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +13 -26
  3. package/README.zh.md +24 -37
  4. package/lib/cjs/agents/agent.d.ts +522 -15
  5. package/lib/cjs/agents/agent.js +357 -36
  6. package/lib/cjs/agents/ai-agent.d.ts +210 -52
  7. package/lib/cjs/agents/ai-agent.js +182 -24
  8. package/lib/cjs/agents/mcp-agent.d.ts +112 -0
  9. package/lib/cjs/agents/mcp-agent.js +79 -1
  10. package/lib/cjs/agents/team-agent.d.ts +99 -0
  11. package/lib/cjs/agents/team-agent.js +94 -0
  12. package/lib/cjs/agents/user-agent.d.ts +6 -4
  13. package/lib/cjs/agents/user-agent.js +16 -5
  14. package/lib/cjs/aigne/aigne.d.ts +263 -16
  15. package/lib/cjs/aigne/aigne.js +130 -20
  16. package/lib/cjs/aigne/context.d.ts +24 -8
  17. package/lib/cjs/aigne/context.js +8 -22
  18. package/lib/cjs/aigne/message-queue.d.ts +26 -4
  19. package/lib/cjs/aigne/message-queue.js +42 -7
  20. package/lib/cjs/aigne/usage.d.ts +9 -0
  21. package/lib/cjs/aigne/usage.js +3 -0
  22. package/lib/cjs/client/client.d.ts +81 -3
  23. package/lib/cjs/client/client.js +38 -0
  24. package/lib/cjs/client/index.d.ts +1 -0
  25. package/lib/cjs/client/index.js +17 -0
  26. package/lib/cjs/index.d.ts +0 -1
  27. package/lib/cjs/index.js +0 -1
  28. package/lib/cjs/loader/agent-js.d.ts +1 -1
  29. package/lib/cjs/loader/agent-js.js +2 -2
  30. package/lib/cjs/loader/agent-yaml.d.ts +3 -2
  31. package/lib/cjs/loader/agent-yaml.js +2 -1
  32. package/lib/cjs/loader/index.d.ts +4 -4
  33. package/lib/cjs/memory/default-memory.d.ts +16 -0
  34. package/lib/cjs/memory/default-memory.js +70 -0
  35. package/lib/cjs/memory/index.d.ts +3 -0
  36. package/lib/cjs/memory/index.js +19 -0
  37. package/lib/cjs/memory/memory.d.ts +89 -0
  38. package/lib/cjs/memory/memory.js +132 -0
  39. package/lib/cjs/memory/recorder.d.ts +86 -0
  40. package/lib/cjs/memory/recorder.js +50 -0
  41. package/lib/cjs/memory/retriever.d.ts +99 -0
  42. package/lib/cjs/memory/retriever.js +51 -0
  43. package/lib/cjs/models/bedrock-chat-model.d.ts +12 -3
  44. package/lib/cjs/models/bedrock-chat-model.js +54 -24
  45. package/lib/cjs/models/chat-model.d.ts +278 -1
  46. package/lib/cjs/models/chat-model.js +54 -0
  47. package/lib/cjs/models/claude-chat-model.d.ts +49 -3
  48. package/lib/cjs/models/claude-chat-model.js +34 -2
  49. package/lib/cjs/models/deepseek-chat-model.d.ts +16 -0
  50. package/lib/cjs/models/deepseek-chat-model.js +16 -0
  51. package/lib/cjs/models/gemini-chat-model.d.ts +14 -0
  52. package/lib/cjs/models/gemini-chat-model.js +14 -0
  53. package/lib/cjs/models/ollama-chat-model.d.ts +16 -0
  54. package/lib/cjs/models/ollama-chat-model.js +16 -0
  55. package/lib/cjs/models/open-router-chat-model.d.ts +16 -0
  56. package/lib/cjs/models/open-router-chat-model.js +16 -0
  57. package/lib/cjs/models/openai-chat-model.d.ts +67 -3
  58. package/lib/cjs/models/openai-chat-model.js +47 -2
  59. package/lib/cjs/models/xai-chat-model.d.ts +16 -0
  60. package/lib/cjs/models/xai-chat-model.js +16 -0
  61. package/lib/cjs/prompt/prompt-builder.d.ts +4 -4
  62. package/lib/cjs/prompt/prompt-builder.js +19 -18
  63. package/lib/cjs/prompt/prompts/memory-message-template.d.ts +1 -0
  64. package/lib/cjs/prompt/prompts/memory-message-template.js +10 -0
  65. package/lib/cjs/prompt/template.js +5 -1
  66. package/lib/cjs/server/error.d.ts +11 -0
  67. package/lib/cjs/server/error.js +11 -0
  68. package/lib/cjs/server/index.d.ts +2 -0
  69. package/lib/cjs/server/index.js +18 -0
  70. package/lib/cjs/server/server.d.ts +89 -8
  71. package/lib/cjs/server/server.js +58 -0
  72. package/lib/cjs/utils/fs.d.ts +2 -0
  73. package/lib/cjs/utils/fs.js +25 -0
  74. package/lib/cjs/utils/prompts.d.ts +1 -0
  75. package/lib/cjs/utils/prompts.js +11 -2
  76. package/lib/cjs/utils/type-utils.d.ts +1 -0
  77. package/lib/cjs/utils/type-utils.js +14 -0
  78. package/lib/dts/agents/agent.d.ts +522 -15
  79. package/lib/dts/agents/ai-agent.d.ts +210 -52
  80. package/lib/dts/agents/mcp-agent.d.ts +112 -0
  81. package/lib/dts/agents/team-agent.d.ts +99 -0
  82. package/lib/dts/agents/user-agent.d.ts +6 -4
  83. package/lib/dts/aigne/aigne.d.ts +263 -16
  84. package/lib/dts/aigne/context.d.ts +24 -8
  85. package/lib/dts/aigne/message-queue.d.ts +26 -4
  86. package/lib/dts/aigne/usage.d.ts +9 -0
  87. package/lib/dts/client/client.d.ts +81 -3
  88. package/lib/dts/client/index.d.ts +1 -0
  89. package/lib/dts/index.d.ts +0 -1
  90. package/lib/dts/loader/agent-js.d.ts +1 -1
  91. package/lib/dts/loader/agent-yaml.d.ts +3 -2
  92. package/lib/dts/loader/index.d.ts +4 -4
  93. package/lib/dts/memory/default-memory.d.ts +16 -0
  94. package/lib/dts/memory/index.d.ts +3 -0
  95. package/lib/dts/memory/memory.d.ts +89 -0
  96. package/lib/dts/memory/recorder.d.ts +86 -0
  97. package/lib/dts/memory/retriever.d.ts +99 -0
  98. package/lib/dts/models/bedrock-chat-model.d.ts +12 -3
  99. package/lib/dts/models/chat-model.d.ts +278 -1
  100. package/lib/dts/models/claude-chat-model.d.ts +49 -3
  101. package/lib/dts/models/deepseek-chat-model.d.ts +16 -0
  102. package/lib/dts/models/gemini-chat-model.d.ts +14 -0
  103. package/lib/dts/models/ollama-chat-model.d.ts +16 -0
  104. package/lib/dts/models/open-router-chat-model.d.ts +16 -0
  105. package/lib/dts/models/openai-chat-model.d.ts +67 -3
  106. package/lib/dts/models/xai-chat-model.d.ts +16 -0
  107. package/lib/dts/prompt/prompt-builder.d.ts +4 -4
  108. package/lib/dts/prompt/prompts/memory-message-template.d.ts +1 -0
  109. package/lib/dts/server/error.d.ts +11 -0
  110. package/lib/dts/server/index.d.ts +2 -0
  111. package/lib/dts/server/server.d.ts +89 -8
  112. package/lib/dts/utils/fs.d.ts +2 -0
  113. package/lib/dts/utils/prompts.d.ts +1 -0
  114. package/lib/dts/utils/type-utils.d.ts +1 -0
  115. package/lib/esm/agents/agent.d.ts +522 -15
  116. package/lib/esm/agents/agent.js +351 -35
  117. package/lib/esm/agents/ai-agent.d.ts +210 -52
  118. package/lib/esm/agents/ai-agent.js +183 -25
  119. package/lib/esm/agents/mcp-agent.d.ts +112 -0
  120. package/lib/esm/agents/mcp-agent.js +79 -1
  121. package/lib/esm/agents/team-agent.d.ts +99 -0
  122. package/lib/esm/agents/team-agent.js +94 -0
  123. package/lib/esm/agents/user-agent.d.ts +6 -4
  124. package/lib/esm/agents/user-agent.js +17 -6
  125. package/lib/esm/aigne/aigne.d.ts +263 -16
  126. package/lib/esm/aigne/aigne.js +132 -22
  127. package/lib/esm/aigne/context.d.ts +24 -8
  128. package/lib/esm/aigne/context.js +9 -22
  129. package/lib/esm/aigne/message-queue.d.ts +26 -4
  130. package/lib/esm/aigne/message-queue.js +42 -8
  131. package/lib/esm/aigne/usage.d.ts +9 -0
  132. package/lib/esm/aigne/usage.js +3 -0
  133. package/lib/esm/client/client.d.ts +81 -3
  134. package/lib/esm/client/client.js +38 -0
  135. package/lib/esm/client/index.d.ts +1 -0
  136. package/lib/esm/client/index.js +1 -0
  137. package/lib/esm/index.d.ts +0 -1
  138. package/lib/esm/index.js +0 -1
  139. package/lib/esm/loader/agent-js.d.ts +1 -1
  140. package/lib/esm/loader/agent-js.js +2 -2
  141. package/lib/esm/loader/agent-yaml.d.ts +3 -2
  142. package/lib/esm/loader/agent-yaml.js +2 -1
  143. package/lib/esm/loader/index.d.ts +4 -4
  144. package/lib/esm/memory/default-memory.d.ts +16 -0
  145. package/lib/esm/memory/default-memory.js +63 -0
  146. package/lib/esm/memory/index.d.ts +3 -0
  147. package/lib/esm/memory/index.js +3 -0
  148. package/lib/esm/memory/memory.d.ts +89 -0
  149. package/lib/esm/memory/memory.js +127 -0
  150. package/lib/esm/memory/recorder.d.ts +86 -0
  151. package/lib/esm/memory/recorder.js +46 -0
  152. package/lib/esm/memory/retriever.d.ts +99 -0
  153. package/lib/esm/memory/retriever.js +47 -0
  154. package/lib/esm/models/bedrock-chat-model.d.ts +12 -3
  155. package/lib/esm/models/bedrock-chat-model.js +56 -26
  156. package/lib/esm/models/chat-model.d.ts +278 -1
  157. package/lib/esm/models/chat-model.js +54 -0
  158. package/lib/esm/models/claude-chat-model.d.ts +49 -3
  159. package/lib/esm/models/claude-chat-model.js +35 -3
  160. package/lib/esm/models/deepseek-chat-model.d.ts +16 -0
  161. package/lib/esm/models/deepseek-chat-model.js +16 -0
  162. package/lib/esm/models/gemini-chat-model.d.ts +14 -0
  163. package/lib/esm/models/gemini-chat-model.js +14 -0
  164. package/lib/esm/models/ollama-chat-model.d.ts +16 -0
  165. package/lib/esm/models/ollama-chat-model.js +16 -0
  166. package/lib/esm/models/open-router-chat-model.d.ts +16 -0
  167. package/lib/esm/models/open-router-chat-model.js +16 -0
  168. package/lib/esm/models/openai-chat-model.d.ts +67 -3
  169. package/lib/esm/models/openai-chat-model.js +47 -2
  170. package/lib/esm/models/xai-chat-model.d.ts +16 -0
  171. package/lib/esm/models/xai-chat-model.js +16 -0
  172. package/lib/esm/prompt/prompt-builder.d.ts +4 -4
  173. package/lib/esm/prompt/prompt-builder.js +20 -19
  174. package/lib/esm/prompt/prompts/memory-message-template.d.ts +1 -0
  175. package/lib/esm/prompt/prompts/memory-message-template.js +7 -0
  176. package/lib/esm/prompt/template.js +5 -1
  177. package/lib/esm/server/error.d.ts +11 -0
  178. package/lib/esm/server/error.js +11 -0
  179. package/lib/esm/server/index.d.ts +2 -0
  180. package/lib/esm/server/index.js +2 -0
  181. package/lib/esm/server/server.d.ts +89 -8
  182. package/lib/esm/server/server.js +58 -0
  183. package/lib/esm/utils/fs.d.ts +2 -0
  184. package/lib/esm/utils/fs.js +21 -0
  185. package/lib/esm/utils/prompts.d.ts +1 -0
  186. package/lib/esm/utils/prompts.js +10 -2
  187. package/lib/esm/utils/type-utils.d.ts +1 -0
  188. package/lib/esm/utils/type-utils.js +13 -0
  189. package/package.json +14 -11
  190. package/lib/cjs/agents/memory.d.ts +0 -26
  191. package/lib/cjs/agents/memory.js +0 -45
  192. package/lib/dts/agents/memory.d.ts +0 -26
  193. package/lib/esm/agents/memory.d.ts +0 -26
  194. package/lib/esm/agents/memory.js +0 -41
  195. /package/{LICENSE → LICENSE.md} +0 -0
@@ -0,0 +1,127 @@
1
+ import { v7 } from "uuid";
2
+ import { z } from "zod";
3
+ import { Agent } from "../agents/agent.js";
4
+ import { checkArguments, remove } from "../utils/type-utils.js";
5
+ export const newMemoryId = () => v7();
6
+ /**
7
+ * A specialized agent responsible for managing, storing, and retrieving memories within the agent system.
8
+ *
9
+ * MemoryAgent serves as a bridge between application logic and memory storage/retrieval mechanisms.
10
+ * It delegates the actual memory operations to specialized recorder and retriever agents that
11
+ * are attached as skills. This agent doesn't directly process messages like other agents but
12
+ * instead provides memory management capabilities to the system.
13
+ */
14
+ export class MemoryAgent extends Agent {
15
+ /**
16
+ * Creates a new MemoryAgent instance.
17
+ */
18
+ constructor(options) {
19
+ checkArguments("MemoryAgent", memoryAgentOptionsSchema, options);
20
+ super({
21
+ subscribeTopic: options.subscribeTopic,
22
+ skills: options.skills,
23
+ });
24
+ this.recorder = options.recorder;
25
+ this.retriever = options.retriever;
26
+ this.autoUpdate = options.autoUpdate;
27
+ }
28
+ _retriever;
29
+ /**
30
+ * Agent used for retrieving memories from storage.
31
+ *
32
+ * This retriever is automatically added to the agent's skills when set.
33
+ * Setting a new retriever will remove any previously set retriever from skills.
34
+ */
35
+ get retriever() {
36
+ return this._retriever;
37
+ }
38
+ set retriever(value) {
39
+ if (this._retriever)
40
+ remove(this.skills, [this._retriever]);
41
+ this._retriever = value;
42
+ if (value)
43
+ this.skills.push(value);
44
+ }
45
+ _recorder;
46
+ /**
47
+ * Agent used for recording and storing new memories.
48
+ *
49
+ * This recorder is automatically added to the agent's skills when set.
50
+ * Setting a new recorder will remove any previously set recorder from skills.
51
+ */
52
+ get recorder() {
53
+ return this._recorder;
54
+ }
55
+ set recorder(value) {
56
+ if (this._recorder)
57
+ remove(this.skills, [this._recorder]);
58
+ this._recorder = value;
59
+ if (value)
60
+ this.skills.push(value);
61
+ }
62
+ /**
63
+ * Controls whether to automatically update the memory when agent call completes.
64
+ *
65
+ * When true, the agent will automatically record any relevant information
66
+ * after completing operations, creating a history of interactions.
67
+ */
68
+ autoUpdate;
69
+ /**
70
+ * Indicates whether this agent can be directly called.
71
+ *
72
+ * MemoryAgent is designed to be used as a supporting component rather than
73
+ * being directly invoked for processing, so this returns false.
74
+ */
75
+ get isCallable() {
76
+ return false;
77
+ }
78
+ /**
79
+ * The standard message processing method required by the Agent interface.
80
+ *
81
+ * MemoryAgent doesn't directly process messages like other agents, so this method
82
+ * throws an error when called. Use the specialized retrieve() and record() methods instead.
83
+ */
84
+ async process(_input, _context) {
85
+ throw new Error("Method not implemented.");
86
+ }
87
+ /**
88
+ * Retrieves memories based on the provided input criteria.
89
+ *
90
+ * Delegates the actual retrieval operation to the configured retriever agent.
91
+ *
92
+ * @param input - The retrieval parameters (can include search terms, limits, etc.)
93
+ * @param context - The execution context
94
+ * @returns A promise resolving to the retrieved memories
95
+ * @throws Error - If no retriever has been initialized
96
+ */
97
+ async retrieve(input, context) {
98
+ if (!this.retriever)
99
+ throw new Error("MemoryAgent retriever not initialized");
100
+ return context.invoke(this.retriever, input);
101
+ }
102
+ /**
103
+ * Records new memories based on the provided input content.
104
+ *
105
+ * Delegates the actual recording operation to the configured recorder agent.
106
+ *
107
+ * @param input - The content to be recorded as memories
108
+ * @param context - The execution context
109
+ * @returns A promise resolving to the recorded memories
110
+ * @throws Error - If no recorder has been initialized
111
+ */
112
+ async record(input, context) {
113
+ if (!this.recorder)
114
+ throw new Error("MemoryAgent recorder not initialized");
115
+ return context.invoke(this.recorder, input);
116
+ }
117
+ async onMessage({ role, source, message, context }) {
118
+ this.record({ content: [{ role, source, content: message }] }, context);
119
+ }
120
+ }
121
+ const memoryAgentOptionsSchema = z.object({
122
+ retriever: z.custom().optional(),
123
+ recorder: z.custom().optional(),
124
+ autoUpdate: z.boolean().optional(),
125
+ subscribeTopic: z.union([z.string(), z.array(z.string())]).optional(),
126
+ skills: z.array(z.custom()).optional(),
127
+ });
@@ -0,0 +1,86 @@
1
+ import { type ZodType, z } from "zod";
2
+ import { Agent, type AgentOptions, type Message } from "../agents/agent.js";
3
+ import type { Memory } from "./memory.js";
4
+ /**
5
+ * Input for memory recording operations.
6
+ *
7
+ * This interface represents the data needed to record new memories
8
+ * in the system. The content array can contain any type of data that
9
+ * should be stored as memories.
10
+ */
11
+ export interface MemoryRecorderInput extends Message {
12
+ /**
13
+ * Array of content items to record as memories.
14
+ * Each item in this array will typically be converted into a separate memory entry.
15
+ */
16
+ content: unknown[];
17
+ }
18
+ /**
19
+ * @hidden
20
+ */
21
+ export declare const memoryRecorderInputSchema: ZodType<MemoryRecorderInput>;
22
+ /**
23
+ * Output from memory recording operations.
24
+ *
25
+ * This interface represents the result of recording new memories,
26
+ * including the newly created memory objects with their IDs and timestamps.
27
+ */
28
+ export interface MemoryRecorderOutput extends Message {
29
+ /**
30
+ * Array of newly created memory objects.
31
+ * Each memory includes a unique ID, the stored content, and a creation timestamp.
32
+ */
33
+ memories: Memory[];
34
+ }
35
+ /**
36
+ * @hidden
37
+ */
38
+ export declare const memoryRecorderOutputSchema: z.ZodObject<{
39
+ memories: z.ZodArray<z.ZodObject<{
40
+ id: z.ZodString;
41
+ content: ZodType<{}, z.ZodTypeDef, {}>;
42
+ createdAt: z.ZodString;
43
+ }, "strip", z.ZodTypeAny, {
44
+ content: {};
45
+ id: string;
46
+ createdAt: string;
47
+ }, {
48
+ content: {};
49
+ id: string;
50
+ createdAt: string;
51
+ }>, "many">;
52
+ }, "strip", z.ZodTypeAny, {
53
+ memories: {
54
+ content: {};
55
+ id: string;
56
+ createdAt: string;
57
+ }[];
58
+ }, {
59
+ memories: {
60
+ content: {};
61
+ id: string;
62
+ createdAt: string;
63
+ }[];
64
+ }>;
65
+ /**
66
+ * Abstract base class for agents that record and store memories.
67
+ *
68
+ * The MemoryRecorder serves as a foundation for implementing specific memory storage
69
+ * mechanisms. Implementations of this class are responsible for:
70
+ *
71
+ * 1. Converting input content into standardized memory objects
72
+ * 2. Assigning unique IDs to new memories
73
+ * 3. Storing memories in an appropriate backend (database, file system, etc.)
74
+ * 4. Ensuring proper timestamping of memories
75
+ *
76
+ * Custom implementations should extend this class and provide concrete
77
+ * implementations of the process method to handle the actual storage logic.
78
+ */
79
+ export declare abstract class MemoryRecorder extends Agent<MemoryRecorderInput, MemoryRecorderOutput> {
80
+ /**
81
+ * Creates a new MemoryRecorder instance with predefined input and output schemas.
82
+ *
83
+ * @param options - Configuration options for the memory recorder agent
84
+ */
85
+ constructor(options: Omit<AgentOptions<MemoryRecorderInput, MemoryRecorderOutput>, "inputSchema" | "outputSchema">);
86
+ }
@@ -0,0 +1,46 @@
1
+ import { z } from "zod";
2
+ import { Agent } from "../agents/agent.js";
3
+ /**
4
+ * @hidden
5
+ */
6
+ export const memoryRecorderInputSchema = z.object({
7
+ content: z.array(z.unknown()),
8
+ });
9
+ /**
10
+ * @hidden
11
+ */
12
+ export const memoryRecorderOutputSchema = z.object({
13
+ memories: z.array(z.object({
14
+ id: z.string(),
15
+ content: z.custom(),
16
+ createdAt: z.string().datetime(),
17
+ })),
18
+ });
19
+ /**
20
+ * Abstract base class for agents that record and store memories.
21
+ *
22
+ * The MemoryRecorder serves as a foundation for implementing specific memory storage
23
+ * mechanisms. Implementations of this class are responsible for:
24
+ *
25
+ * 1. Converting input content into standardized memory objects
26
+ * 2. Assigning unique IDs to new memories
27
+ * 3. Storing memories in an appropriate backend (database, file system, etc.)
28
+ * 4. Ensuring proper timestamping of memories
29
+ *
30
+ * Custom implementations should extend this class and provide concrete
31
+ * implementations of the process method to handle the actual storage logic.
32
+ */
33
+ export class MemoryRecorder extends Agent {
34
+ /**
35
+ * Creates a new MemoryRecorder instance with predefined input and output schemas.
36
+ *
37
+ * @param options - Configuration options for the memory recorder agent
38
+ */
39
+ constructor(options) {
40
+ super({
41
+ ...options,
42
+ inputSchema: memoryRecorderInputSchema,
43
+ outputSchema: memoryRecorderOutputSchema,
44
+ });
45
+ }
46
+ }
@@ -0,0 +1,99 @@
1
+ import { z } from "zod";
2
+ import { Agent, type AgentOptions, type Message } from "../agents/agent.js";
3
+ import type { Memory } from "./memory.js";
4
+ /**
5
+ * Input for memory retrieval operations.
6
+ *
7
+ * This interface defines the parameters that can be used to query and filter
8
+ * memories when retrieving them from storage.
9
+ */
10
+ export interface MemoryRetrieverInput extends Message {
11
+ /**
12
+ * Maximum number of memories to retrieve.
13
+ * Used for pagination or limiting result set size.
14
+ */
15
+ limit?: number;
16
+ /**
17
+ * Search term to filter memories by.
18
+ * How the search is implemented depends on the specific retriever implementation.
19
+ */
20
+ search?: string;
21
+ }
22
+ /**
23
+ * Output from memory retrieval operations.
24
+ *
25
+ * This interface represents the result of retrieving memories from storage,
26
+ * containing an array of memory objects that match the query criteria.
27
+ */
28
+ export interface MemoryRetrieverOutput extends Message {
29
+ /**
30
+ * Array of retrieved memory objects.
31
+ * Each memory includes its ID, content, and creation timestamp.
32
+ */
33
+ memories: Memory[];
34
+ }
35
+ /**
36
+ * @hidden
37
+ */
38
+ export declare const memoryRetrieverInputSchema: z.ZodObject<{
39
+ limit: z.ZodOptional<z.ZodNumber>;
40
+ search: z.ZodOptional<z.ZodString>;
41
+ }, "strip", z.ZodTypeAny, {
42
+ limit?: number | undefined;
43
+ search?: string | undefined;
44
+ }, {
45
+ limit?: number | undefined;
46
+ search?: string | undefined;
47
+ }>;
48
+ /**
49
+ * @hidden
50
+ */
51
+ export declare const memoryRetrieverOutputSchema: z.ZodObject<{
52
+ memories: z.ZodArray<z.ZodObject<{
53
+ id: z.ZodString;
54
+ content: z.ZodType<{}, z.ZodTypeDef, {}>;
55
+ createdAt: z.ZodString;
56
+ }, "strip", z.ZodTypeAny, {
57
+ content: {};
58
+ id: string;
59
+ createdAt: string;
60
+ }, {
61
+ content: {};
62
+ id: string;
63
+ createdAt: string;
64
+ }>, "many">;
65
+ }, "strip", z.ZodTypeAny, {
66
+ memories: {
67
+ content: {};
68
+ id: string;
69
+ createdAt: string;
70
+ }[];
71
+ }, {
72
+ memories: {
73
+ content: {};
74
+ id: string;
75
+ createdAt: string;
76
+ }[];
77
+ }>;
78
+ /**
79
+ * Abstract base class for agents that retrieve memories from storage.
80
+ *
81
+ * The MemoryRetriever serves as a foundation for implementing specific memory
82
+ * retrieval mechanisms. Implementations of this class are responsible for:
83
+ *
84
+ * 1. Querying a memory storage backend to find relevant memories
85
+ * 2. Filtering memories based on search criteria
86
+ * 3. Limiting the number of results returned
87
+ * 4. Potentially implementing sorting, ranking, or relevance-based retrieval
88
+ *
89
+ * Custom implementations should extend this class and provide concrete
90
+ * implementations of the process method to handle the actual retrieval logic.
91
+ */
92
+ export declare abstract class MemoryRetriever extends Agent<MemoryRetrieverInput, MemoryRetrieverOutput> {
93
+ /**
94
+ * Creates a new MemoryRetriever instance with predefined input and output schemas.
95
+ *
96
+ * @param options - Configuration options for the memory retriever agent
97
+ */
98
+ constructor(options: Omit<AgentOptions<MemoryRetrieverInput, MemoryRetrieverOutput>, "inputSchema" | "outputSchema">);
99
+ }
@@ -0,0 +1,47 @@
1
+ import { z } from "zod";
2
+ import { Agent } from "../agents/agent.js";
3
+ /**
4
+ * @hidden
5
+ */
6
+ export const memoryRetrieverInputSchema = z.object({
7
+ limit: z.number().optional(),
8
+ search: z.string().optional(),
9
+ });
10
+ /**
11
+ * @hidden
12
+ */
13
+ export const memoryRetrieverOutputSchema = z.object({
14
+ memories: z.array(z.object({
15
+ id: z.string(),
16
+ content: z.custom(),
17
+ createdAt: z.string().datetime(),
18
+ })),
19
+ });
20
+ /**
21
+ * Abstract base class for agents that retrieve memories from storage.
22
+ *
23
+ * The MemoryRetriever serves as a foundation for implementing specific memory
24
+ * retrieval mechanisms. Implementations of this class are responsible for:
25
+ *
26
+ * 1. Querying a memory storage backend to find relevant memories
27
+ * 2. Filtering memories based on search criteria
28
+ * 3. Limiting the number of results returned
29
+ * 4. Potentially implementing sorting, ranking, or relevance-based retrieval
30
+ *
31
+ * Custom implementations should extend this class and provide concrete
32
+ * implementations of the process method to handle the actual retrieval logic.
33
+ */
34
+ export class MemoryRetriever extends Agent {
35
+ /**
36
+ * Creates a new MemoryRetriever instance with predefined input and output schemas.
37
+ *
38
+ * @param options - Configuration options for the memory retriever agent
39
+ */
40
+ constructor(options) {
41
+ super({
42
+ ...options,
43
+ inputSchema: memoryRetrieverInputSchema,
44
+ outputSchema: memoryRetrieverOutputSchema,
45
+ });
46
+ }
47
+ }
@@ -1,8 +1,10 @@
1
1
  import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
2
2
  import { z } from "zod";
3
- import type { AgentInvokeOptions, AgentResponse } from "../agents/agent.js";
4
- import type { Context } from "../aigne/context.js";
3
+ import type { AgentResponse } from "../agents/agent.js";
5
4
  import { ChatModel, type ChatModelInput, type ChatModelOptions, type ChatModelOutput } from "./chat-model.js";
5
+ /**
6
+ * @hidden
7
+ */
6
8
  export declare function extractLastJsonObject(text: string): string | null;
7
9
  export interface BedrockChatModelOptions {
8
10
  accessKeyId?: string;
@@ -11,6 +13,9 @@ export interface BedrockChatModelOptions {
11
13
  model?: string;
12
14
  modelOptions?: ChatModelOptions;
13
15
  }
16
+ /**
17
+ * @hidden
18
+ */
14
19
  export declare const bedrockChatModelOptionsSchema: z.ZodObject<{
15
20
  region: z.ZodOptional<z.ZodString>;
16
21
  model: z.ZodOptional<z.ZodString>;
@@ -62,9 +67,13 @@ export declare const bedrockChatModelOptionsSchema: z.ZodObject<{
62
67
  export declare class BedrockChatModel extends ChatModel {
63
68
  options?: BedrockChatModelOptions | undefined;
64
69
  constructor(options?: BedrockChatModelOptions | undefined);
70
+ /**
71
+ * @hidden
72
+ */
65
73
  protected _client?: BedrockRuntimeClient;
66
74
  get client(): BedrockRuntimeClient;
67
75
  get modelOptions(): ChatModelOptions | undefined;
68
- process(input: ChatModelInput, _context: Context, options?: AgentInvokeOptions): Promise<AgentResponse<ChatModelOutput>>;
76
+ process(input: ChatModelInput): Promise<AgentResponse<ChatModelOutput>>;
69
77
  private extractResultFromStream;
78
+ private requestStructuredOutput;
70
79
  }
@@ -1,15 +1,22 @@
1
- import { BedrockRuntimeClient, ConverseStreamCommand, } from "@aws-sdk/client-bedrock-runtime";
1
+ import { BedrockRuntimeClient, ConverseCommand, ConverseStreamCommand, } from "@aws-sdk/client-bedrock-runtime";
2
2
  import { nanoid } from "nanoid";
3
3
  import { z } from "zod";
4
4
  import { parseJSON } from "../utils/json-schema.js";
5
- import { getJsonOutputPrompt } from "../utils/prompts.js";
5
+ import { mergeUsage } from "../utils/model-utils.js";
6
+ import { getJsonToolInputPrompt } from "../utils/prompts.js";
6
7
  import { agentResponseStreamToObject } from "../utils/stream-utils.js";
7
8
  import { checkArguments, isNonNullable } from "../utils/type-utils.js";
8
9
  import { ChatModel, } from "./chat-model.js";
10
+ /**
11
+ * @hidden
12
+ */
9
13
  export function extractLastJsonObject(text) {
10
14
  return text.replace(/<thinking>[\s\S]*?<\/thinking>/g, "").trim();
11
15
  }
12
16
  const BEDROCK_DEFAULT_CHAT_MODEL = "us.amazon.nova-lite-v1:0";
17
+ /**
18
+ * @hidden
19
+ */
13
20
  export const bedrockChatModelOptionsSchema = z.object({
14
21
  region: z.string().optional(),
15
22
  model: z.string().optional(),
@@ -32,6 +39,9 @@ export class BedrockChatModel extends ChatModel {
32
39
  super();
33
40
  this.options = options;
34
41
  }
42
+ /**
43
+ * @hidden
44
+ */
35
45
  _client;
36
46
  get client() {
37
47
  const credentials = this.options?.accessKeyId && this.options?.secretAccessKey
@@ -49,7 +59,7 @@ export class BedrockChatModel extends ChatModel {
49
59
  get modelOptions() {
50
60
  return this.options?.modelOptions;
51
61
  }
52
- async process(input, _context, options) {
62
+ async process(input) {
53
63
  const modelId = input.modelOptions?.model ?? this.modelOptions?.model ?? BEDROCK_DEFAULT_CHAT_MODEL;
54
64
  const { messages, system } = getRunMessages(input);
55
65
  const toolConfig = convertTools(input);
@@ -66,13 +76,17 @@ export class BedrockChatModel extends ChatModel {
66
76
  const command = new ConverseStreamCommand(body);
67
77
  const response = await this.client.send(command);
68
78
  const jsonMode = input.responseFormat?.type === "json_schema";
69
- if (options?.streaming && !jsonMode) {
70
- return this.extractResultFromStream(response.stream, modelId, false, true);
79
+ if (!jsonMode) {
80
+ return this.extractResultFromStream(response.stream, modelId, true);
81
+ }
82
+ const result = await this.extractResultFromStream(response.stream, modelId, false);
83
+ if (!result.toolCalls?.length && jsonMode && result.text) {
84
+ const output = await this.requestStructuredOutput(body, input.responseFormat);
85
+ return { ...output, usage: mergeUsage(result.usage, output.usage) };
71
86
  }
72
- const result = await this.extractResultFromStream(response.stream, modelId, jsonMode, false);
73
87
  return result;
74
88
  }
75
- async extractResultFromStream(stream, modelId, jsonMode, streaming) {
89
+ async extractResultFromStream(stream, modelId, streaming) {
76
90
  if (!stream)
77
91
  throw new Error("Unable to get AI model response.");
78
92
  const result = new ReadableStream({
@@ -80,7 +94,6 @@ export class BedrockChatModel extends ChatModel {
80
94
  try {
81
95
  controller.enqueue({ delta: { json: { model: modelId } } });
82
96
  const toolCalls = [];
83
- let text = "";
84
97
  let usage;
85
98
  for await (const chunk of stream) {
86
99
  if (chunk.contentBlockStart?.start?.toolUse) {
@@ -103,10 +116,7 @@ export class BedrockChatModel extends ChatModel {
103
116
  const block = chunk.contentBlockDelta;
104
117
  const delta = block.delta;
105
118
  if (delta?.text) {
106
- text += delta.text;
107
- if (!jsonMode) {
108
- controller.enqueue({ delta: { text: { text: delta.text } } });
109
- }
119
+ controller.enqueue({ delta: { text: { text: delta.text } } });
110
120
  }
111
121
  if (delta?.toolUse) {
112
122
  if (block.contentBlockIndex === undefined)
@@ -121,14 +131,6 @@ export class BedrockChatModel extends ChatModel {
121
131
  usage = chunk.metadata.usage;
122
132
  }
123
133
  }
124
- if (jsonMode && text) {
125
- const match = extractLastJsonObject(text);
126
- if (!match)
127
- throw new Error("Failed to extract JSON object from model output");
128
- controller.enqueue({
129
- delta: { json: { json: parseJSON(match) } },
130
- });
131
- }
132
134
  if (toolCalls.length) {
133
135
  controller.enqueue({
134
136
  delta: {
@@ -153,8 +155,41 @@ export class BedrockChatModel extends ChatModel {
153
155
  });
154
156
  return streaming ? result : await agentResponseStreamToObject(result);
155
157
  }
158
+ async requestStructuredOutput(body, responseFormat) {
159
+ if (responseFormat?.type !== "json_schema") {
160
+ throw new Error("Expected json_schema response format");
161
+ }
162
+ const system = [
163
+ ...(body.system ?? []),
164
+ {
165
+ text: `Use the generate_json tool to generate a json result. ${getJsonToolInputPrompt(responseFormat.jsonSchema.schema)}`,
166
+ },
167
+ ];
168
+ const toolConfig = {
169
+ tools: [
170
+ {
171
+ toolSpec: {
172
+ name: "generate_json",
173
+ description: "Generate a json result by given context",
174
+ inputSchema: { json: responseFormat.jsonSchema.schema },
175
+ },
176
+ },
177
+ ],
178
+ toolChoice: { tool: { name: "generate_json" } },
179
+ };
180
+ const command = new ConverseCommand({ ...body, system, toolConfig });
181
+ const response = await this.client.send(command);
182
+ const jsonTool = response.output?.message?.content?.find((i) => i.toolUse?.name === "generate_json");
183
+ if (!jsonTool)
184
+ throw new Error("Json tool not found");
185
+ return {
186
+ json: jsonTool.toolUse?.input,
187
+ model: body.modelId,
188
+ usage: response.usage,
189
+ };
190
+ }
156
191
  }
157
- const getRunMessages = ({ messages: msgs, responseFormat, }) => {
192
+ const getRunMessages = ({ messages: msgs, }) => {
158
193
  const system = [];
159
194
  const messages = [];
160
195
  for (const msg of msgs) {
@@ -216,11 +251,6 @@ const getRunMessages = ({ messages: msgs, responseFormat, }) => {
216
251
  if (messages.at(0)?.role !== "user") {
217
252
  messages.unshift({ role: "user", content: [{ text: "." }] });
218
253
  }
219
- if (responseFormat?.type === "json_schema") {
220
- system.push({
221
- text: getJsonOutputPrompt(responseFormat.jsonSchema.schema),
222
- });
223
- }
224
254
  return { messages, system };
225
255
  };
226
256
  function convertContent(content) {