@aigne/core 1.13.0 → 1.15.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 (200) hide show
  1. package/CHANGELOG.md +27 -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 +184 -27
  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 +95 -1
  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 +9 -23
  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 +60 -3
  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/stream-utils.d.ts +0 -1
  77. package/lib/cjs/utils/stream-utils.js +19 -25
  78. package/lib/cjs/utils/type-utils.d.ts +1 -0
  79. package/lib/cjs/utils/type-utils.js +14 -0
  80. package/lib/dts/agents/agent.d.ts +522 -15
  81. package/lib/dts/agents/ai-agent.d.ts +210 -52
  82. package/lib/dts/agents/mcp-agent.d.ts +112 -0
  83. package/lib/dts/agents/team-agent.d.ts +99 -0
  84. package/lib/dts/agents/user-agent.d.ts +6 -4
  85. package/lib/dts/aigne/aigne.d.ts +263 -16
  86. package/lib/dts/aigne/context.d.ts +24 -8
  87. package/lib/dts/aigne/message-queue.d.ts +26 -4
  88. package/lib/dts/aigne/usage.d.ts +9 -0
  89. package/lib/dts/client/client.d.ts +81 -3
  90. package/lib/dts/client/index.d.ts +1 -0
  91. package/lib/dts/index.d.ts +0 -1
  92. package/lib/dts/loader/agent-js.d.ts +1 -1
  93. package/lib/dts/loader/agent-yaml.d.ts +3 -2
  94. package/lib/dts/loader/index.d.ts +4 -4
  95. package/lib/dts/memory/default-memory.d.ts +16 -0
  96. package/lib/dts/memory/index.d.ts +3 -0
  97. package/lib/dts/memory/memory.d.ts +89 -0
  98. package/lib/dts/memory/recorder.d.ts +86 -0
  99. package/lib/dts/memory/retriever.d.ts +99 -0
  100. package/lib/dts/models/bedrock-chat-model.d.ts +12 -3
  101. package/lib/dts/models/chat-model.d.ts +278 -1
  102. package/lib/dts/models/claude-chat-model.d.ts +49 -3
  103. package/lib/dts/models/deepseek-chat-model.d.ts +16 -0
  104. package/lib/dts/models/gemini-chat-model.d.ts +14 -0
  105. package/lib/dts/models/ollama-chat-model.d.ts +16 -0
  106. package/lib/dts/models/open-router-chat-model.d.ts +16 -0
  107. package/lib/dts/models/openai-chat-model.d.ts +67 -3
  108. package/lib/dts/models/xai-chat-model.d.ts +16 -0
  109. package/lib/dts/prompt/prompt-builder.d.ts +4 -4
  110. package/lib/dts/prompt/prompts/memory-message-template.d.ts +1 -0
  111. package/lib/dts/server/error.d.ts +11 -0
  112. package/lib/dts/server/index.d.ts +2 -0
  113. package/lib/dts/server/server.d.ts +89 -8
  114. package/lib/dts/utils/fs.d.ts +2 -0
  115. package/lib/dts/utils/prompts.d.ts +1 -0
  116. package/lib/dts/utils/stream-utils.d.ts +0 -1
  117. package/lib/dts/utils/type-utils.d.ts +1 -0
  118. package/lib/esm/agents/agent.d.ts +522 -15
  119. package/lib/esm/agents/agent.js +351 -35
  120. package/lib/esm/agents/ai-agent.d.ts +210 -52
  121. package/lib/esm/agents/ai-agent.js +185 -28
  122. package/lib/esm/agents/mcp-agent.d.ts +112 -0
  123. package/lib/esm/agents/mcp-agent.js +79 -1
  124. package/lib/esm/agents/team-agent.d.ts +99 -0
  125. package/lib/esm/agents/team-agent.js +96 -2
  126. package/lib/esm/agents/user-agent.d.ts +6 -4
  127. package/lib/esm/agents/user-agent.js +17 -6
  128. package/lib/esm/aigne/aigne.d.ts +263 -16
  129. package/lib/esm/aigne/aigne.js +132 -22
  130. package/lib/esm/aigne/context.d.ts +24 -8
  131. package/lib/esm/aigne/context.js +11 -24
  132. package/lib/esm/aigne/message-queue.d.ts +26 -4
  133. package/lib/esm/aigne/message-queue.js +42 -8
  134. package/lib/esm/aigne/usage.d.ts +9 -0
  135. package/lib/esm/aigne/usage.js +3 -0
  136. package/lib/esm/client/client.d.ts +81 -3
  137. package/lib/esm/client/client.js +38 -0
  138. package/lib/esm/client/index.d.ts +1 -0
  139. package/lib/esm/client/index.js +1 -0
  140. package/lib/esm/index.d.ts +0 -1
  141. package/lib/esm/index.js +0 -1
  142. package/lib/esm/loader/agent-js.d.ts +1 -1
  143. package/lib/esm/loader/agent-js.js +2 -2
  144. package/lib/esm/loader/agent-yaml.d.ts +3 -2
  145. package/lib/esm/loader/agent-yaml.js +2 -1
  146. package/lib/esm/loader/index.d.ts +4 -4
  147. package/lib/esm/memory/default-memory.d.ts +16 -0
  148. package/lib/esm/memory/default-memory.js +63 -0
  149. package/lib/esm/memory/index.d.ts +3 -0
  150. package/lib/esm/memory/index.js +3 -0
  151. package/lib/esm/memory/memory.d.ts +89 -0
  152. package/lib/esm/memory/memory.js +127 -0
  153. package/lib/esm/memory/recorder.d.ts +86 -0
  154. package/lib/esm/memory/recorder.js +46 -0
  155. package/lib/esm/memory/retriever.d.ts +99 -0
  156. package/lib/esm/memory/retriever.js +47 -0
  157. package/lib/esm/models/bedrock-chat-model.d.ts +12 -3
  158. package/lib/esm/models/bedrock-chat-model.js +56 -26
  159. package/lib/esm/models/chat-model.d.ts +278 -1
  160. package/lib/esm/models/chat-model.js +54 -0
  161. package/lib/esm/models/claude-chat-model.d.ts +49 -3
  162. package/lib/esm/models/claude-chat-model.js +35 -3
  163. package/lib/esm/models/deepseek-chat-model.d.ts +16 -0
  164. package/lib/esm/models/deepseek-chat-model.js +16 -0
  165. package/lib/esm/models/gemini-chat-model.d.ts +14 -0
  166. package/lib/esm/models/gemini-chat-model.js +14 -0
  167. package/lib/esm/models/ollama-chat-model.d.ts +16 -0
  168. package/lib/esm/models/ollama-chat-model.js +16 -0
  169. package/lib/esm/models/open-router-chat-model.d.ts +16 -0
  170. package/lib/esm/models/open-router-chat-model.js +16 -0
  171. package/lib/esm/models/openai-chat-model.d.ts +67 -3
  172. package/lib/esm/models/openai-chat-model.js +47 -2
  173. package/lib/esm/models/xai-chat-model.d.ts +16 -0
  174. package/lib/esm/models/xai-chat-model.js +16 -0
  175. package/lib/esm/prompt/prompt-builder.d.ts +4 -4
  176. package/lib/esm/prompt/prompt-builder.js +20 -19
  177. package/lib/esm/prompt/prompts/memory-message-template.d.ts +1 -0
  178. package/lib/esm/prompt/prompts/memory-message-template.js +7 -0
  179. package/lib/esm/prompt/template.js +5 -1
  180. package/lib/esm/server/error.d.ts +11 -0
  181. package/lib/esm/server/error.js +11 -0
  182. package/lib/esm/server/index.d.ts +2 -0
  183. package/lib/esm/server/index.js +2 -0
  184. package/lib/esm/server/server.d.ts +89 -8
  185. package/lib/esm/server/server.js +60 -3
  186. package/lib/esm/utils/fs.d.ts +2 -0
  187. package/lib/esm/utils/fs.js +21 -0
  188. package/lib/esm/utils/prompts.d.ts +1 -0
  189. package/lib/esm/utils/prompts.js +10 -2
  190. package/lib/esm/utils/stream-utils.d.ts +0 -1
  191. package/lib/esm/utils/stream-utils.js +19 -24
  192. package/lib/esm/utils/type-utils.d.ts +1 -0
  193. package/lib/esm/utils/type-utils.js +13 -0
  194. package/package.json +14 -11
  195. package/lib/cjs/agents/memory.d.ts +0 -26
  196. package/lib/cjs/agents/memory.js +0 -45
  197. package/lib/dts/agents/memory.d.ts +0 -26
  198. package/lib/esm/agents/memory.d.ts +0 -26
  199. package/lib/esm/agents/memory.js +0 -41
  200. /package/{LICENSE → LICENSE.md} +0 -0
@@ -1,70 +1,228 @@
1
- import { z } from "zod";
1
+ import { type ZodObject, type ZodType, z } from "zod";
2
2
  import type { Context } from "../aigne/context.js";
3
+ import { type DefaultMemoryOptions } from "../memory/default-memory.js";
3
4
  import { ChatModel } from "../models/chat-model.js";
4
5
  import type { ChatModelInput } from "../models/chat-model.js";
5
6
  import { PromptBuilder } from "../prompt/prompt-builder.js";
6
7
  import { Agent, type AgentOptions, type AgentProcessAsyncGenerator, type Message } from "./agent.js";
7
- export interface AIAgentOptions<I extends Message = Message, O extends Message = Message> extends AgentOptions<I, O> {
8
+ /**
9
+ * Configuration options for an AI Agent
10
+ *
11
+ * These options extend the base agent options with AI-specific parameters
12
+ * like model configuration, prompt instructions, and tool choice.
13
+ *
14
+ * @template I The input message type the agent accepts
15
+ * @template O The output message type the agent returns
16
+ */
17
+ export interface AIAgentOptions<I extends Message = Message, O extends Message = Message> extends Omit<AgentOptions<I, O>, "memory"> {
18
+ /**
19
+ * The language model to use for this agent
20
+ *
21
+ * If not provided, the agent will use the model from the context
22
+ */
8
23
  model?: ChatModel;
24
+ /**
25
+ * Instructions to guide the AI model's behavior
26
+ *
27
+ * Can be a simple string or a full PromptBuilder instance for
28
+ * more complex prompt templates
29
+ */
9
30
  instructions?: string | PromptBuilder;
31
+ /**
32
+ * Custom key to use for text output in the response
33
+ *
34
+ * Defaults to $message if not specified
35
+ */
10
36
  outputKey?: string;
11
- toolChoice?: AIAgentToolChoice;
37
+ /**
38
+ * Controls how the agent uses tools during execution
39
+ *
40
+ * @default AIAgentToolChoice.auto
41
+ */
42
+ toolChoice?: AIAgentToolChoice | Agent;
43
+ /**
44
+ * Whether to catch errors from tool execution and continue processing.
45
+ * If set to false, the agent will throw an error if a tool fails.
46
+ *
47
+ * @default true
48
+ */
49
+ catchToolsError?: boolean;
50
+ /**
51
+ * Whether to include memory agents as tools for the AI model
52
+ *
53
+ * When set to true, memory agents will be made available as tools
54
+ * that the model can call directly to retrieve or store information.
55
+ * This enables the agent to explicitly interact with its memories.
56
+ *
57
+ * @default false
58
+ */
59
+ memoryAgentsAsTools?: boolean;
60
+ /**
61
+ * Custom prompt template for formatting memory content
62
+ *
63
+ * Allows customization of how memories are presented to the AI model.
64
+ * If not provided, the default template from MEMORY_MESSAGE_TEMPLATE will be used.
65
+ *
66
+ * The template receives a {{memories}} variable containing serialized memory content.
67
+ */
68
+ memoryPromptTemplate?: string;
69
+ memory?: AgentOptions<I, O>["memory"] | DefaultMemoryOptions | true;
12
70
  }
13
- export type AIAgentToolChoice = "auto" | "none" | "required" | "router" | Agent;
14
- export declare const aiAgentToolChoiceSchema: z.ZodUnion<[z.ZodLiteral<"auto">, z.ZodLiteral<"none">, z.ZodLiteral<"required">, z.ZodLiteral<"router">, z.ZodType<Agent<Message, Message>, z.ZodTypeDef, Agent<Message, Message>>]>;
15
- export declare const aiAgentOptionsSchema: z.ZodObject<{
16
- model: z.ZodOptional<z.ZodType<ChatModel, z.ZodTypeDef, ChatModel>>;
17
- instructions: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodType<PromptBuilder, z.ZodTypeDef, PromptBuilder>]>>;
18
- outputKey: z.ZodOptional<z.ZodString>;
19
- toolChoice: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<"auto">, z.ZodLiteral<"none">, z.ZodLiteral<"required">, z.ZodLiteral<"router">, z.ZodType<Agent<Message, Message>, z.ZodTypeDef, Agent<Message, Message>>]>>;
20
- enableHistory: z.ZodOptional<z.ZodBoolean>;
21
- maxHistoryMessages: z.ZodOptional<z.ZodNumber>;
22
- includeInputInOutput: z.ZodOptional<z.ZodBoolean>;
23
- subscribeTopic: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">]>>;
24
- publishTopic: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">, z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnknown>]>>;
25
- name: z.ZodOptional<z.ZodString>;
26
- description: z.ZodOptional<z.ZodString>;
27
- skills: z.ZodOptional<z.ZodArray<z.ZodUnion<[z.ZodType<Agent<Message, Message>, z.ZodTypeDef, Agent<Message, Message>>, z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnknown>]>, "many">>;
28
- disableLogging: z.ZodOptional<z.ZodBoolean>;
29
- memory: z.ZodOptional<z.ZodUnion<[z.ZodBoolean, z.ZodAny, z.ZodAny]>>;
30
- }, "strip", z.ZodTypeAny, {
31
- description?: string | undefined;
32
- memory?: any;
33
- name?: string | undefined;
34
- includeInputInOutput?: boolean | undefined;
35
- subscribeTopic?: string | string[] | undefined;
36
- publishTopic?: string | string[] | ((...args: unknown[]) => unknown) | undefined;
37
- skills?: (Agent<Message, Message> | ((...args: unknown[]) => unknown))[] | undefined;
38
- toolChoice?: Agent<Message, Message> | "auto" | "none" | "required" | "router" | undefined;
39
- model?: ChatModel | undefined;
40
- instructions?: string | PromptBuilder | undefined;
41
- outputKey?: string | undefined;
42
- enableHistory?: boolean | undefined;
43
- maxHistoryMessages?: number | undefined;
44
- disableLogging?: boolean | undefined;
45
- }, {
46
- description?: string | undefined;
47
- memory?: any;
48
- name?: string | undefined;
49
- includeInputInOutput?: boolean | undefined;
50
- subscribeTopic?: string | string[] | undefined;
51
- publishTopic?: string | string[] | ((...args: unknown[]) => unknown) | undefined;
52
- skills?: (Agent<Message, Message> | ((...args: unknown[]) => unknown))[] | undefined;
53
- toolChoice?: Agent<Message, Message> | "auto" | "none" | "required" | "router" | undefined;
54
- model?: ChatModel | undefined;
55
- instructions?: string | PromptBuilder | undefined;
56
- outputKey?: string | undefined;
57
- enableHistory?: boolean | undefined;
58
- maxHistoryMessages?: number | undefined;
59
- disableLogging?: boolean | undefined;
71
+ /**
72
+ * Tool choice options for AI agents
73
+ *
74
+ * Controls how the agent decides to use tools during execution
75
+ */
76
+ export declare enum AIAgentToolChoice {
77
+ /**
78
+ * Let the model decide when to use tools
79
+ */
80
+ auto = "auto",
81
+ /**
82
+ * Disable tool usage
83
+ */
84
+ none = "none",
85
+ /**
86
+ * Force tool usage
87
+ */
88
+ required = "required",
89
+ /**
90
+ * Choose exactly one tool and route directly to it
91
+ */
92
+ router = "router"
93
+ }
94
+ /**
95
+ * Zod schema for validating AIAgentToolChoice values
96
+ *
97
+ * Used to ensure that toolChoice receives valid values
98
+ *
99
+ * @hidden
100
+ */
101
+ export declare const aiAgentToolChoiceSchema: z.ZodUnion<[z.ZodNativeEnum<typeof AIAgentToolChoice>, ZodType<Agent<Message, Message>, z.ZodTypeDef, Agent<Message, Message>>]>;
102
+ /**
103
+ * Zod schema for validating AIAgentOptions
104
+ *
105
+ * Extends the base agent options schema with AI-specific parameters
106
+ *
107
+ * @hidden
108
+ */
109
+ export declare const aiAgentOptionsSchema: ZodObject<{
110
+ [key in keyof AIAgentOptions]: ZodType<AIAgentOptions[key]>;
60
111
  }>;
112
+ /**
113
+ * AI-powered agent that leverages language models
114
+ *
115
+ * AIAgent connects to language models to process inputs and generate responses,
116
+ * with support for streaming, function calling, and tool usage.
117
+ *
118
+ * Key features:
119
+ * - Connect to any language model
120
+ * - Use customizable instructions and prompts
121
+ * - Execute tools/function calls
122
+ * - Support streaming responses
123
+ * - Router mode for specialized agents
124
+ *
125
+ * @template I The input message type the agent accepts
126
+ * @template O The output message type the agent returns
127
+ *
128
+ * @example
129
+ * Basic AIAgent creation:
130
+ * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-basic}
131
+ */
61
132
  export declare class AIAgent<I extends Message = Message, O extends Message = Message> extends Agent<I, O> {
133
+ /**
134
+ * Create an AIAgent with the specified options
135
+ *
136
+ * Factory method that provides a convenient way to create new AI agents
137
+ *
138
+ * @param options Configuration options for the AI agent
139
+ * @returns A new AIAgent instance
140
+ *
141
+ * @example
142
+ * AI agent with custom instructions:
143
+ * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-instructions}
144
+ */
62
145
  static from<I extends Message, O extends Message>(options: AIAgentOptions<I, O>): AIAgent<I, O>;
146
+ /**
147
+ * Create an AIAgent instance
148
+ *
149
+ * @param options Configuration options for the AI agent
150
+ */
63
151
  constructor(options: AIAgentOptions<I, O>);
152
+ /**
153
+ * The language model used by this agent
154
+ *
155
+ * If not set on the agent, the model from the context will be used
156
+ */
64
157
  model?: ChatModel;
158
+ /**
159
+ * Instructions for the language model
160
+ *
161
+ * Contains system messages, user templates, and other prompt elements
162
+ * that guide the model's behavior
163
+ *
164
+ * @example
165
+ * Custom prompt builder:
166
+ * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-prompt-builder}
167
+ */
65
168
  instructions: PromptBuilder;
169
+ /**
170
+ * Custom key to use for text output in the response
171
+ *
172
+ * @example
173
+ * Setting a custom output key:
174
+ * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-custom-output-key}
175
+ */
66
176
  outputKey?: string;
67
- toolChoice?: AIAgentToolChoice;
177
+ /**
178
+ * Controls how the agent uses tools during execution
179
+ *
180
+ * @example
181
+ * Automatic tool choice:
182
+ * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-tool-choice-auto}
183
+ *
184
+ * @example
185
+ * Router tool choice:
186
+ * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-router}
187
+ */
188
+ toolChoice?: AIAgentToolChoice | Agent;
189
+ /**
190
+ * Whether to include memory agents as tools for the AI model
191
+ *
192
+ * When set to true, memory agents will be made available as tools
193
+ * that the model can call directly to retrieve or store information.
194
+ * This enables the agent to explicitly interact with its memories.
195
+ */
196
+ memoryAgentsAsTools?: boolean;
197
+ /**
198
+ * Custom prompt template for formatting memory content
199
+ *
200
+ * Allows customization of how memories are presented to the AI model.
201
+ * If not provided, the default template from MEMORY_MESSAGE_TEMPLATE will be used.
202
+ *
203
+ * The template receives a {{memories}} variable containing serialized memory content.
204
+ */
205
+ memoryPromptTemplate?: string;
206
+ /**
207
+ * Whether to catch error from tool execution and continue processing.
208
+ * If set to false, the agent will throw an error if a tool fails
209
+ *
210
+ * @default true
211
+ */
212
+ catchToolsError: boolean;
213
+ /**
214
+ * Process an input message and generate a response
215
+ *
216
+ * @protected
217
+ */
68
218
  process(input: I, context: Context): AgentProcessAsyncGenerator<O>;
69
- processRouter(input: I, model: ChatModel, modelInput: ChatModelInput, context: Context, toolsMap: Map<string, Agent>): AgentProcessAsyncGenerator<O>;
219
+ /**
220
+ * Process router mode requests
221
+ *
222
+ * In router mode, the agent sends a single request to the model to determine
223
+ * which tool to use, then routes the request directly to that tool
224
+ *
225
+ * @protected
226
+ */
227
+ _processRouter(input: I, model: ChatModel, modelInput: ChatModelInput, context: Context, toolsMap: Map<string, Agent>): AgentProcessAsyncGenerator<O>;
70
228
  }
@@ -1,41 +1,112 @@
1
1
  import { z } from "zod";
2
+ import { DefaultMemory } from "../memory/default-memory.js";
3
+ import { MemoryAgent } from "../memory/memory.js";
2
4
  import { ChatModel } from "../models/chat-model.js";
3
5
  import { MESSAGE_KEY, PromptBuilder } from "../prompt/prompt-builder.js";
4
6
  import { AgentMessageTemplate, ToolMessageTemplate } from "../prompt/template.js";
5
- import { readableStreamToAsyncIterator } from "../utils/stream-utils.js";
6
- import { isEmpty } from "../utils/type-utils.js";
7
- import { Agent, } from "./agent.js";
7
+ import { checkArguments, isEmpty } from "../utils/type-utils.js";
8
+ import { Agent, agentOptionsSchema, } from "./agent.js";
8
9
  import { isTransferAgentOutput } from "./types.js";
9
- export const aiAgentToolChoiceSchema = z.union([
10
- z.literal("auto"),
11
- z.literal("none"),
12
- z.literal("required"),
13
- z.literal("router"),
14
- z.instanceof(Agent),
15
- ], { message: "aiAgentToolChoice must be 'auto', 'none', 'required', 'router', or an Agent" });
16
- export const aiAgentOptionsSchema = z.object({
10
+ /**
11
+ * Tool choice options for AI agents
12
+ *
13
+ * Controls how the agent decides to use tools during execution
14
+ */
15
+ export var AIAgentToolChoice;
16
+ (function (AIAgentToolChoice) {
17
+ /**
18
+ * Let the model decide when to use tools
19
+ */
20
+ AIAgentToolChoice["auto"] = "auto";
21
+ /**
22
+ * Disable tool usage
23
+ */
24
+ AIAgentToolChoice["none"] = "none";
25
+ /**
26
+ * Force tool usage
27
+ */
28
+ AIAgentToolChoice["required"] = "required";
29
+ /**
30
+ * Choose exactly one tool and route directly to it
31
+ */
32
+ AIAgentToolChoice["router"] = "router";
33
+ })(AIAgentToolChoice || (AIAgentToolChoice = {}));
34
+ /**
35
+ * Zod schema for validating AIAgentToolChoice values
36
+ *
37
+ * Used to ensure that toolChoice receives valid values
38
+ *
39
+ * @hidden
40
+ */
41
+ export const aiAgentToolChoiceSchema = z.union([z.nativeEnum(AIAgentToolChoice), z.instanceof(Agent)], {
42
+ message: `aiAgentToolChoice must be ${Object.values(AIAgentToolChoice).join(", ")}, or an Agent`,
43
+ });
44
+ /**
45
+ * Zod schema for validating AIAgentOptions
46
+ *
47
+ * Extends the base agent options schema with AI-specific parameters
48
+ *
49
+ * @hidden
50
+ */
51
+ export const aiAgentOptionsSchema = agentOptionsSchema.extend({
17
52
  model: z.instanceof(ChatModel).optional(),
18
53
  instructions: z.union([z.string(), z.instanceof(PromptBuilder)]).optional(),
19
54
  outputKey: z.string().optional(),
20
55
  toolChoice: aiAgentToolChoiceSchema.optional(),
21
- enableHistory: z.boolean().optional(),
22
- maxHistoryMessages: z.number().optional(),
23
- includeInputInOutput: z.boolean().optional(),
24
- subscribeTopic: z.union([z.string(), z.array(z.string())]).optional(),
25
- publishTopic: z.union([z.string(), z.array(z.string()), z.function()]).optional(),
26
- name: z.string().optional(),
27
- description: z.string().optional(),
28
- skills: z.array(z.union([z.instanceof(Agent), z.function()])).optional(),
29
- disableLogging: z.boolean().optional(),
30
- memory: z.union([z.boolean(), z.any(), z.any()]).optional(),
56
+ memoryAgentsAsTools: z.boolean().optional(),
57
+ memoryPromptTemplate: z.string().optional(),
31
58
  });
59
+ /**
60
+ * AI-powered agent that leverages language models
61
+ *
62
+ * AIAgent connects to language models to process inputs and generate responses,
63
+ * with support for streaming, function calling, and tool usage.
64
+ *
65
+ * Key features:
66
+ * - Connect to any language model
67
+ * - Use customizable instructions and prompts
68
+ * - Execute tools/function calls
69
+ * - Support streaming responses
70
+ * - Router mode for specialized agents
71
+ *
72
+ * @template I The input message type the agent accepts
73
+ * @template O The output message type the agent returns
74
+ *
75
+ * @example
76
+ * Basic AIAgent creation:
77
+ * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-basic}
78
+ */
32
79
  export class AIAgent extends Agent {
80
+ /**
81
+ * Create an AIAgent with the specified options
82
+ *
83
+ * Factory method that provides a convenient way to create new AI agents
84
+ *
85
+ * @param options Configuration options for the AI agent
86
+ * @returns A new AIAgent instance
87
+ *
88
+ * @example
89
+ * AI agent with custom instructions:
90
+ * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-instructions}
91
+ */
33
92
  static from(options) {
34
93
  return new AIAgent(options);
35
94
  }
95
+ /**
96
+ * Create an AIAgent instance
97
+ *
98
+ * @param options Configuration options for the AI agent
99
+ */
36
100
  constructor(options) {
37
- aiAgentOptionsSchema.parse(options);
38
- super(options);
101
+ super({
102
+ ...options,
103
+ memory: !options.memory
104
+ ? undefined
105
+ : Array.isArray(options.memory) || options.memory instanceof MemoryAgent
106
+ ? options.memory
107
+ : new DefaultMemory(options.memory === true ? {} : options.memory),
108
+ });
109
+ checkArguments("AIAgent", aiAgentOptionsSchema, options);
39
110
  this.model = options.model;
40
111
  this.instructions =
41
112
  typeof options.instructions === "string"
@@ -43,11 +114,77 @@ export class AIAgent extends Agent {
43
114
  : (options.instructions ?? new PromptBuilder());
44
115
  this.outputKey = options.outputKey;
45
116
  this.toolChoice = options.toolChoice;
117
+ this.memoryAgentsAsTools = options.memoryAgentsAsTools;
118
+ this.memoryPromptTemplate = options.memoryPromptTemplate;
119
+ if (typeof options.catchToolsError === "boolean")
120
+ this.catchToolsError = options.catchToolsError;
46
121
  }
122
+ /**
123
+ * The language model used by this agent
124
+ *
125
+ * If not set on the agent, the model from the context will be used
126
+ */
47
127
  model;
128
+ /**
129
+ * Instructions for the language model
130
+ *
131
+ * Contains system messages, user templates, and other prompt elements
132
+ * that guide the model's behavior
133
+ *
134
+ * @example
135
+ * Custom prompt builder:
136
+ * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-prompt-builder}
137
+ */
48
138
  instructions;
139
+ /**
140
+ * Custom key to use for text output in the response
141
+ *
142
+ * @example
143
+ * Setting a custom output key:
144
+ * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-custom-output-key}
145
+ */
49
146
  outputKey;
147
+ /**
148
+ * Controls how the agent uses tools during execution
149
+ *
150
+ * @example
151
+ * Automatic tool choice:
152
+ * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-tool-choice-auto}
153
+ *
154
+ * @example
155
+ * Router tool choice:
156
+ * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-router}
157
+ */
50
158
  toolChoice;
159
+ /**
160
+ * Whether to include memory agents as tools for the AI model
161
+ *
162
+ * When set to true, memory agents will be made available as tools
163
+ * that the model can call directly to retrieve or store information.
164
+ * This enables the agent to explicitly interact with its memories.
165
+ */
166
+ memoryAgentsAsTools;
167
+ /**
168
+ * Custom prompt template for formatting memory content
169
+ *
170
+ * Allows customization of how memories are presented to the AI model.
171
+ * If not provided, the default template from MEMORY_MESSAGE_TEMPLATE will be used.
172
+ *
173
+ * The template receives a {{memories}} variable containing serialized memory content.
174
+ */
175
+ memoryPromptTemplate;
176
+ /**
177
+ * Whether to catch error from tool execution and continue processing.
178
+ * If set to false, the agent will throw an error if a tool fails
179
+ *
180
+ * @default true
181
+ */
182
+ catchToolsError = true;
183
+ /**
184
+ * Process an input message and generate a response
185
+ *
186
+ * @protected
187
+ */
51
188
  async *process(input, context) {
52
189
  const model = this.model ?? context.model;
53
190
  if (!model)
@@ -60,7 +197,7 @@ export class AIAgent extends Agent {
60
197
  });
61
198
  const toolsMap = new Map(toolAgents?.map((i) => [i.name, i]));
62
199
  if (this.toolChoice === "router") {
63
- yield* this.processRouter(input, model, modelInput, context, toolsMap);
200
+ yield* this._processRouter(input, model, modelInput, context, toolsMap);
64
201
  return;
65
202
  }
66
203
  const toolCallMessages = [];
@@ -68,7 +205,7 @@ export class AIAgent extends Agent {
68
205
  for (;;) {
69
206
  const modelOutput = {};
70
207
  const stream = await context.invoke(model, { ...modelInput, messages: modelInput.messages.concat(toolCallMessages) }, { streaming: true });
71
- for await (const value of readableStreamToAsyncIterator(stream)) {
208
+ for await (const value of stream) {
72
209
  if (value.delta.text?.text) {
73
210
  yield { delta: { text: { [outputKey]: value.delta.text.text } } };
74
211
  }
@@ -85,7 +222,19 @@ export class AIAgent extends Agent {
85
222
  if (!tool)
86
223
  throw new Error(`Tool not found: ${call.function.name}`);
87
224
  // NOTE: should pass both arguments (model generated) and input (user provided) to the tool
88
- const output = await context.invoke(tool, { ...call.function.arguments, ...input }, { disableTransfer: true });
225
+ const output = await context
226
+ .invoke(tool, { ...input, ...call.function.arguments }, { disableTransfer: true })
227
+ .catch((error) => {
228
+ if (!this.catchToolsError) {
229
+ return Promise.reject(error);
230
+ }
231
+ return {
232
+ isError: true,
233
+ error: {
234
+ message: error.message,
235
+ },
236
+ };
237
+ });
89
238
  // NOTE: Return transfer output immediately
90
239
  if (isTransferAgentOutput(output)) {
91
240
  return output;
@@ -111,7 +260,15 @@ export class AIAgent extends Agent {
111
260
  return;
112
261
  }
113
262
  }
114
- async *processRouter(input, model, modelInput, context, toolsMap) {
263
+ /**
264
+ * Process router mode requests
265
+ *
266
+ * In router mode, the agent sends a single request to the model to determine
267
+ * which tool to use, then routes the request directly to that tool
268
+ *
269
+ * @protected
270
+ */
271
+ async *_processRouter(input, model, modelInput, context, toolsMap) {
115
272
  const { toolCalls: [call] = [], } = await context.invoke(model, modelInput);
116
273
  if (!call) {
117
274
  throw new Error("Router toolChoice requires exactly one tool to be executed");
@@ -120,6 +277,6 @@ export class AIAgent extends Agent {
120
277
  if (!tool)
121
278
  throw new Error(`Tool not found: ${call.function.name}`);
122
279
  const stream = await context.invoke(tool, { ...call.function.arguments, ...input }, { streaming: true });
123
- yield* readableStreamToAsyncIterator(stream);
280
+ yield* stream;
124
281
  }
125
282
  }