@aigne/core 1.12.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 (197) hide show
  1. package/CHANGELOG.md +28 -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/loader/index.js +2 -0
  34. package/lib/cjs/memory/default-memory.d.ts +16 -0
  35. package/lib/cjs/memory/default-memory.js +70 -0
  36. package/lib/cjs/memory/index.d.ts +3 -0
  37. package/lib/cjs/memory/index.js +19 -0
  38. package/lib/cjs/memory/memory.d.ts +89 -0
  39. package/lib/cjs/memory/memory.js +132 -0
  40. package/lib/cjs/memory/recorder.d.ts +86 -0
  41. package/lib/cjs/memory/recorder.js +50 -0
  42. package/lib/cjs/memory/retriever.d.ts +99 -0
  43. package/lib/cjs/memory/retriever.js +51 -0
  44. package/lib/cjs/models/bedrock-chat-model.d.ts +79 -0
  45. package/lib/cjs/models/bedrock-chat-model.js +303 -0
  46. package/lib/cjs/models/chat-model.d.ts +279 -1
  47. package/lib/cjs/models/chat-model.js +62 -0
  48. package/lib/cjs/models/claude-chat-model.d.ts +49 -3
  49. package/lib/cjs/models/claude-chat-model.js +34 -2
  50. package/lib/cjs/models/deepseek-chat-model.d.ts +16 -0
  51. package/lib/cjs/models/deepseek-chat-model.js +16 -0
  52. package/lib/cjs/models/gemini-chat-model.d.ts +15 -0
  53. package/lib/cjs/models/gemini-chat-model.js +15 -0
  54. package/lib/cjs/models/ollama-chat-model.d.ts +16 -0
  55. package/lib/cjs/models/ollama-chat-model.js +16 -0
  56. package/lib/cjs/models/open-router-chat-model.d.ts +16 -0
  57. package/lib/cjs/models/open-router-chat-model.js +16 -0
  58. package/lib/cjs/models/openai-chat-model.d.ts +70 -3
  59. package/lib/cjs/models/openai-chat-model.js +147 -102
  60. package/lib/cjs/models/xai-chat-model.d.ts +16 -0
  61. package/lib/cjs/models/xai-chat-model.js +16 -0
  62. package/lib/cjs/prompt/prompt-builder.d.ts +4 -4
  63. package/lib/cjs/prompt/prompt-builder.js +21 -20
  64. package/lib/cjs/prompt/prompts/memory-message-template.d.ts +1 -0
  65. package/lib/cjs/prompt/prompts/memory-message-template.js +10 -0
  66. package/lib/cjs/prompt/template.js +5 -1
  67. package/lib/cjs/server/error.d.ts +11 -0
  68. package/lib/cjs/server/error.js +11 -0
  69. package/lib/cjs/server/index.d.ts +2 -0
  70. package/lib/cjs/server/index.js +18 -0
  71. package/lib/cjs/server/server.d.ts +89 -8
  72. package/lib/cjs/server/server.js +58 -0
  73. package/lib/cjs/utils/fs.d.ts +2 -0
  74. package/lib/cjs/utils/fs.js +25 -0
  75. package/lib/cjs/utils/prompts.d.ts +1 -0
  76. package/lib/cjs/utils/prompts.js +11 -2
  77. package/lib/cjs/utils/type-utils.d.ts +2 -0
  78. package/lib/cjs/utils/type-utils.js +26 -0
  79. package/lib/dts/agents/agent.d.ts +522 -15
  80. package/lib/dts/agents/ai-agent.d.ts +210 -52
  81. package/lib/dts/agents/mcp-agent.d.ts +112 -0
  82. package/lib/dts/agents/team-agent.d.ts +99 -0
  83. package/lib/dts/agents/user-agent.d.ts +6 -4
  84. package/lib/dts/aigne/aigne.d.ts +263 -16
  85. package/lib/dts/aigne/context.d.ts +24 -8
  86. package/lib/dts/aigne/message-queue.d.ts +26 -4
  87. package/lib/dts/aigne/usage.d.ts +9 -0
  88. package/lib/dts/client/client.d.ts +81 -3
  89. package/lib/dts/client/index.d.ts +1 -0
  90. package/lib/dts/index.d.ts +0 -1
  91. package/lib/dts/loader/agent-js.d.ts +1 -1
  92. package/lib/dts/loader/agent-yaml.d.ts +3 -2
  93. package/lib/dts/loader/index.d.ts +4 -4
  94. package/lib/dts/memory/default-memory.d.ts +16 -0
  95. package/lib/dts/memory/index.d.ts +3 -0
  96. package/lib/dts/memory/memory.d.ts +89 -0
  97. package/lib/dts/memory/recorder.d.ts +86 -0
  98. package/lib/dts/memory/retriever.d.ts +99 -0
  99. package/lib/dts/models/bedrock-chat-model.d.ts +79 -0
  100. package/lib/dts/models/chat-model.d.ts +279 -1
  101. package/lib/dts/models/claude-chat-model.d.ts +49 -3
  102. package/lib/dts/models/deepseek-chat-model.d.ts +16 -0
  103. package/lib/dts/models/gemini-chat-model.d.ts +15 -0
  104. package/lib/dts/models/ollama-chat-model.d.ts +16 -0
  105. package/lib/dts/models/open-router-chat-model.d.ts +16 -0
  106. package/lib/dts/models/openai-chat-model.d.ts +70 -3
  107. package/lib/dts/models/xai-chat-model.d.ts +16 -0
  108. package/lib/dts/prompt/prompt-builder.d.ts +4 -4
  109. package/lib/dts/prompt/prompts/memory-message-template.d.ts +1 -0
  110. package/lib/dts/server/error.d.ts +11 -0
  111. package/lib/dts/server/index.d.ts +2 -0
  112. package/lib/dts/server/server.d.ts +89 -8
  113. package/lib/dts/utils/fs.d.ts +2 -0
  114. package/lib/dts/utils/prompts.d.ts +1 -0
  115. package/lib/dts/utils/type-utils.d.ts +2 -0
  116. package/lib/esm/agents/agent.d.ts +522 -15
  117. package/lib/esm/agents/agent.js +351 -35
  118. package/lib/esm/agents/ai-agent.d.ts +210 -52
  119. package/lib/esm/agents/ai-agent.js +183 -25
  120. package/lib/esm/agents/mcp-agent.d.ts +112 -0
  121. package/lib/esm/agents/mcp-agent.js +79 -1
  122. package/lib/esm/agents/team-agent.d.ts +99 -0
  123. package/lib/esm/agents/team-agent.js +94 -0
  124. package/lib/esm/agents/user-agent.d.ts +6 -4
  125. package/lib/esm/agents/user-agent.js +17 -6
  126. package/lib/esm/aigne/aigne.d.ts +263 -16
  127. package/lib/esm/aigne/aigne.js +132 -22
  128. package/lib/esm/aigne/context.d.ts +24 -8
  129. package/lib/esm/aigne/context.js +9 -22
  130. package/lib/esm/aigne/message-queue.d.ts +26 -4
  131. package/lib/esm/aigne/message-queue.js +42 -8
  132. package/lib/esm/aigne/usage.d.ts +9 -0
  133. package/lib/esm/aigne/usage.js +3 -0
  134. package/lib/esm/client/client.d.ts +81 -3
  135. package/lib/esm/client/client.js +38 -0
  136. package/lib/esm/client/index.d.ts +1 -0
  137. package/lib/esm/client/index.js +1 -0
  138. package/lib/esm/index.d.ts +0 -1
  139. package/lib/esm/index.js +0 -1
  140. package/lib/esm/loader/agent-js.d.ts +1 -1
  141. package/lib/esm/loader/agent-js.js +2 -2
  142. package/lib/esm/loader/agent-yaml.d.ts +3 -2
  143. package/lib/esm/loader/agent-yaml.js +2 -1
  144. package/lib/esm/loader/index.d.ts +4 -4
  145. package/lib/esm/loader/index.js +2 -0
  146. package/lib/esm/memory/default-memory.d.ts +16 -0
  147. package/lib/esm/memory/default-memory.js +63 -0
  148. package/lib/esm/memory/index.d.ts +3 -0
  149. package/lib/esm/memory/index.js +3 -0
  150. package/lib/esm/memory/memory.d.ts +89 -0
  151. package/lib/esm/memory/memory.js +127 -0
  152. package/lib/esm/memory/recorder.d.ts +86 -0
  153. package/lib/esm/memory/recorder.js +46 -0
  154. package/lib/esm/memory/retriever.d.ts +99 -0
  155. package/lib/esm/memory/retriever.js +47 -0
  156. package/lib/esm/models/bedrock-chat-model.d.ts +79 -0
  157. package/lib/esm/models/bedrock-chat-model.js +298 -0
  158. package/lib/esm/models/chat-model.d.ts +279 -1
  159. package/lib/esm/models/chat-model.js +62 -0
  160. package/lib/esm/models/claude-chat-model.d.ts +49 -3
  161. package/lib/esm/models/claude-chat-model.js +35 -3
  162. package/lib/esm/models/deepseek-chat-model.d.ts +16 -0
  163. package/lib/esm/models/deepseek-chat-model.js +16 -0
  164. package/lib/esm/models/gemini-chat-model.d.ts +15 -0
  165. package/lib/esm/models/gemini-chat-model.js +15 -0
  166. package/lib/esm/models/ollama-chat-model.d.ts +16 -0
  167. package/lib/esm/models/ollama-chat-model.js +16 -0
  168. package/lib/esm/models/open-router-chat-model.d.ts +16 -0
  169. package/lib/esm/models/open-router-chat-model.js +16 -0
  170. package/lib/esm/models/openai-chat-model.d.ts +70 -3
  171. package/lib/esm/models/openai-chat-model.js +147 -102
  172. package/lib/esm/models/xai-chat-model.d.ts +16 -0
  173. package/lib/esm/models/xai-chat-model.js +16 -0
  174. package/lib/esm/prompt/prompt-builder.d.ts +4 -4
  175. package/lib/esm/prompt/prompt-builder.js +22 -21
  176. package/lib/esm/prompt/prompts/memory-message-template.d.ts +1 -0
  177. package/lib/esm/prompt/prompts/memory-message-template.js +7 -0
  178. package/lib/esm/prompt/template.js +5 -1
  179. package/lib/esm/server/error.d.ts +11 -0
  180. package/lib/esm/server/error.js +11 -0
  181. package/lib/esm/server/index.d.ts +2 -0
  182. package/lib/esm/server/index.js +2 -0
  183. package/lib/esm/server/server.d.ts +89 -8
  184. package/lib/esm/server/server.js +58 -0
  185. package/lib/esm/utils/fs.d.ts +2 -0
  186. package/lib/esm/utils/fs.js +21 -0
  187. package/lib/esm/utils/prompts.d.ts +1 -0
  188. package/lib/esm/utils/prompts.js +10 -2
  189. package/lib/esm/utils/type-utils.d.ts +2 -0
  190. package/lib/esm/utils/type-utils.js +24 -0
  191. package/package.json +21 -11
  192. package/lib/cjs/agents/memory.d.ts +0 -26
  193. package/lib/cjs/agents/memory.js +0 -45
  194. package/lib/dts/agents/memory.d.ts +0 -26
  195. package/lib/esm/agents/memory.d.ts +0 -26
  196. package/lib/esm/agents/memory.js +0 -41
  197. /package/{LICENSE → LICENSE.md} +0 -0
@@ -21,6 +21,9 @@ const OPENAI_CHAT_MODEL_CAPABILITIES = {
21
21
  "o4-mini": { supportsParallelToolCalls: false, supportsTemperature: false },
22
22
  "o3-mini": { supportsParallelToolCalls: false, supportsTemperature: false },
23
23
  };
24
+ /**
25
+ * @hidden
26
+ */
24
27
  exports.openAIChatModelOptionsSchema = zod_1.z.object({
25
28
  apiKey: zod_1.z.string().optional(),
26
29
  baseURL: zod_1.z.string().optional(),
@@ -36,6 +39,25 @@ exports.openAIChatModelOptionsSchema = zod_1.z.object({
36
39
  })
37
40
  .optional(),
38
41
  });
42
+ /**
43
+ * Implementation of the ChatModel interface for OpenAI's API
44
+ *
45
+ * This model provides access to OpenAI's capabilities including:
46
+ * - Text generation
47
+ * - Tool use with parallel tool calls
48
+ * - JSON structured output
49
+ * - Image understanding
50
+ *
51
+ * Default model: 'gpt-4o-mini'
52
+ *
53
+ * @example
54
+ * Here's how to create and use an OpenAI chat model:
55
+ * {@includeCode ../../test/models/openai-chat-model.test.ts#example-openai-chat-model}
56
+ *
57
+ * @example
58
+ * Here's an example with streaming response:
59
+ * {@includeCode ../../test/models/openai-chat-model.test.ts#example-openai-chat-model-streaming}
60
+ */
39
61
  class OpenAIChatModel extends chat_model_js_1.ChatModel {
40
62
  options;
41
63
  constructor(options) {
@@ -46,6 +68,9 @@ class OpenAIChatModel extends chat_model_js_1.ChatModel {
46
68
  const preset = options?.model ? OPENAI_CHAT_MODEL_CAPABILITIES[options.model] : undefined;
47
69
  Object.assign(this, preset);
48
70
  }
71
+ /**
72
+ * @hidden
73
+ */
49
74
  _client;
50
75
  apiKeyEnvName = "OPENAI_API_KEY";
51
76
  apiKeyDefault;
@@ -54,6 +79,7 @@ class OpenAIChatModel extends chat_model_js_1.ChatModel {
54
79
  supportsToolsUseWithJsonSchema = true;
55
80
  supportsParallelToolCalls = true;
56
81
  supportsToolsEmptyParameters = true;
82
+ supportsToolStreaming = true;
57
83
  supportsTemperature = true;
58
84
  get client() {
59
85
  const apiKey = this.options?.apiKey || process.env[this.apiKeyEnvName] || this.apiKeyDefault;
@@ -68,7 +94,15 @@ class OpenAIChatModel extends chat_model_js_1.ChatModel {
68
94
  get modelOptions() {
69
95
  return this.options?.modelOptions;
70
96
  }
71
- async process(input, _context, options) {
97
+ /**
98
+ * Process the input and generate a response
99
+ * @param input The input to process
100
+ * @returns The generated response
101
+ */
102
+ process(input) {
103
+ return this._process(input);
104
+ }
105
+ async _process(input) {
72
106
  const messages = await this.getRunMessages(input);
73
107
  const body = {
74
108
  model: this.options?.model || CHAT_MODEL_OPENAI_DEFAULT_MODEL,
@@ -94,10 +128,10 @@ class OpenAIChatModel extends chat_model_js_1.ChatModel {
94
128
  parallel_tool_calls: this.getParallelToolCalls(input),
95
129
  response_format: responseFormat,
96
130
  });
97
- if (options?.streaming && input.responseFormat?.type !== "json_schema") {
98
- return await extractResultFromStream(stream, false, true);
131
+ if (input.responseFormat?.type !== "json_schema") {
132
+ return await this.extractResultFromStream(stream, false, true);
99
133
  }
100
- const result = await extractResultFromStream(stream, jsonMode);
134
+ const result = await this.extractResultFromStream(stream, jsonMode);
101
135
  if (!this.supportsToolsUseWithJsonSchema &&
102
136
  !result.toolCalls?.length &&
103
137
  input.responseFormat?.type === "json_schema" &&
@@ -163,16 +197,118 @@ class OpenAIChatModel extends chat_model_js_1.ChatModel {
163
197
  ...body,
164
198
  response_format: resolvedResponseFormat,
165
199
  });
166
- return extractResultFromStream(res, jsonMode);
200
+ return this.extractResultFromStream(res, jsonMode);
201
+ }
202
+ async extractResultFromStream(stream, jsonMode, streaming) {
203
+ const result = new ReadableStream({
204
+ start: async (controller) => {
205
+ try {
206
+ let text = "";
207
+ let refusal = "";
208
+ const toolCalls = [];
209
+ let model;
210
+ for await (const chunk of stream) {
211
+ const choice = chunk.choices?.[0];
212
+ if (!model) {
213
+ model = chunk.model;
214
+ controller.enqueue({
215
+ delta: {
216
+ json: {
217
+ model,
218
+ },
219
+ },
220
+ });
221
+ }
222
+ if (choice?.delta.tool_calls?.length) {
223
+ for (const call of choice.delta.tool_calls) {
224
+ if (this.supportsToolStreaming && call.index !== undefined) {
225
+ handleToolCallDelta(toolCalls, call);
226
+ }
227
+ else {
228
+ handleCompleteToolCall(toolCalls, call);
229
+ }
230
+ }
231
+ }
232
+ if (choice?.delta.content) {
233
+ text += choice.delta.content;
234
+ if (!jsonMode) {
235
+ controller.enqueue({
236
+ delta: {
237
+ text: {
238
+ text: choice.delta.content,
239
+ },
240
+ },
241
+ });
242
+ }
243
+ }
244
+ if (choice?.delta.refusal) {
245
+ refusal += choice.delta.refusal;
246
+ if (!jsonMode) {
247
+ controller.enqueue({
248
+ delta: {
249
+ text: { text: choice.delta.refusal },
250
+ },
251
+ });
252
+ }
253
+ }
254
+ if (chunk.usage) {
255
+ controller.enqueue({
256
+ delta: {
257
+ json: {
258
+ usage: {
259
+ inputTokens: chunk.usage.prompt_tokens,
260
+ outputTokens: chunk.usage.completion_tokens,
261
+ },
262
+ },
263
+ },
264
+ });
265
+ }
266
+ }
267
+ text = text || refusal;
268
+ if (jsonMode && text) {
269
+ controller.enqueue({
270
+ delta: {
271
+ json: {
272
+ json: (0, json_schema_js_1.parseJSON)(text),
273
+ },
274
+ },
275
+ });
276
+ }
277
+ if (toolCalls.length) {
278
+ controller.enqueue({
279
+ delta: {
280
+ json: {
281
+ toolCalls: toolCalls.map(({ args, ...c }) => ({
282
+ ...c,
283
+ function: { ...c.function, arguments: (0, json_schema_js_1.parseJSON)(args) },
284
+ })),
285
+ },
286
+ },
287
+ });
288
+ }
289
+ controller.close();
290
+ }
291
+ catch (error) {
292
+ controller.error(error);
293
+ }
294
+ },
295
+ });
296
+ return streaming ? result : await (0, stream_utils_js_1.agentResponseStreamToObject)(result);
167
297
  }
168
298
  }
169
299
  exports.OpenAIChatModel = OpenAIChatModel;
300
+ /**
301
+ * @hidden
302
+ */
170
303
  exports.ROLE_MAP = {
171
304
  system: "system",
172
305
  user: "user",
173
306
  agent: "assistant",
174
307
  tool: "tool",
175
308
  };
309
+ /**
310
+ * @hidden
311
+ */
176
312
  async function contentsFromInputMessages(messages) {
177
313
  return messages.map((i) => ({
178
314
  role: exports.ROLE_MAP[i.role],
@@ -202,6 +338,9 @@ async function contentsFromInputMessages(messages) {
202
338
  name: i.name,
203
339
  }));
204
340
  }
341
+ /**
342
+ * @hidden
343
+ */
205
344
  function toolsFromInputTools(tools, options) {
206
345
  return tools?.length
207
346
  ? tools.map((i) => {
@@ -220,6 +359,9 @@ function toolsFromInputTools(tools, options) {
220
359
  })
221
360
  : undefined;
222
361
  }
362
+ /**
363
+ * @hidden
364
+ */
223
365
  function jsonSchemaToOpenAIJsonSchema(schema) {
224
366
  if (schema?.type === "object") {
225
367
  const { required, properties } = schema;
@@ -245,103 +387,6 @@ function jsonSchemaToOpenAIJsonSchema(schema) {
245
387
  }
246
388
  return schema;
247
389
  }
248
- async function extractResultFromStream(stream, jsonMode, streaming) {
249
- const result = new ReadableStream({
250
- async start(controller) {
251
- try {
252
- let text = "";
253
- let refusal = "";
254
- const toolCalls = [];
255
- let model;
256
- for await (const chunk of stream) {
257
- const choice = chunk.choices?.[0];
258
- if (!model) {
259
- model = chunk.model;
260
- controller.enqueue({
261
- delta: {
262
- json: {
263
- model,
264
- },
265
- },
266
- });
267
- }
268
- if (choice?.delta.tool_calls?.length) {
269
- for (const call of choice.delta.tool_calls) {
270
- // Gemini not support tool call delta
271
- if (call.index !== undefined) {
272
- handleToolCallDelta(toolCalls, call);
273
- }
274
- else {
275
- handleCompleteToolCall(toolCalls, call);
276
- }
277
- }
278
- }
279
- if (choice?.delta.content) {
280
- text += choice.delta.content;
281
- if (!jsonMode) {
282
- controller.enqueue({
283
- delta: {
284
- text: {
285
- text: choice.delta.content,
286
- },
287
- },
288
- });
289
- }
290
- }
291
- if (choice?.delta.refusal) {
292
- refusal += choice.delta.refusal;
293
- if (!jsonMode) {
294
- controller.enqueue({
295
- delta: {
296
- text: { text: choice.delta.refusal },
297
- },
298
- });
299
- }
300
- }
301
- if (chunk.usage) {
302
- controller.enqueue({
303
- delta: {
304
- json: {
305
- usage: {
306
- inputTokens: chunk.usage.prompt_tokens,
307
- outputTokens: chunk.usage.completion_tokens,
308
- },
309
- },
310
- },
311
- });
312
- }
313
- }
314
- text = text || refusal;
315
- if (jsonMode && text) {
316
- controller.enqueue({
317
- delta: {
318
- json: {
319
- json: (0, json_schema_js_1.parseJSON)(text),
320
- },
321
- },
322
- });
323
- }
324
- if (toolCalls.length) {
325
- controller.enqueue({
326
- delta: {
327
- json: {
328
- toolCalls: toolCalls.map(({ args, ...c }) => ({
329
- ...c,
330
- function: { ...c.function, arguments: (0, json_schema_js_1.parseJSON)(args) },
331
- })),
332
- },
333
- },
334
- });
335
- }
336
- controller.close();
337
- }
338
- catch (error) {
339
- controller.error(error);
340
- }
341
- },
342
- });
343
- return streaming ? result : await (0, stream_utils_js_1.agentResponseStreamToObject)(result);
344
- }
345
390
  function handleToolCallDelta(toolCalls, call) {
346
391
  toolCalls[call.index] ??= {
347
392
  id: call.id || (0, nanoid_1.nanoid)(),
@@ -1,4 +1,20 @@
1
1
  import { OpenAIChatModel, type OpenAIChatModelOptions } from "./openai-chat-model.js";
2
+ /**
3
+ * Implementation of the ChatModel interface for X.AI's API (Grok)
4
+ *
5
+ * This model uses OpenAI-compatible API format to interact with X.AI models,
6
+ * providing access to models like Grok.
7
+ *
8
+ * Default model: 'grok-2-latest'
9
+ *
10
+ * @example
11
+ * Here's how to create and use an X.AI chat model:
12
+ * {@includeCode ../../test/models/xai-chat-model.test.ts#example-xai-chat-model}
13
+ *
14
+ * @example
15
+ * Here's an example with streaming response:
16
+ * {@includeCode ../../test/models/xai-chat-model.test.ts#example-xai-chat-model-streaming}
17
+ */
2
18
  export declare class XAIChatModel extends OpenAIChatModel {
3
19
  constructor(options?: OpenAIChatModelOptions);
4
20
  protected apiKeyEnvName: string;
@@ -4,6 +4,22 @@ exports.XAIChatModel = void 0;
4
4
  const openai_chat_model_js_1 = require("./openai-chat-model.js");
5
5
  const XAI_DEFAULT_CHAT_MODEL = "grok-2-latest";
6
6
  const XAI_BASE_URL = "https://api.x.ai/v1";
7
+ /**
8
+ * Implementation of the ChatModel interface for X.AI's API (Grok)
9
+ *
10
+ * This model uses OpenAI-compatible API format to interact with X.AI models,
11
+ * providing access to models like Grok.
12
+ *
13
+ * Default model: 'grok-2-latest'
14
+ *
15
+ * @example
16
+ * Here's how to create and use an X.AI chat model:
17
+ * {@includeCode ../../test/models/xai-chat-model.test.ts#example-xai-chat-model}
18
+ *
19
+ * @example
20
+ * Here's an example with streaming response:
21
+ * {@includeCode ../../test/models/xai-chat-model.test.ts#example-xai-chat-model-streaming}
22
+ */
7
23
  class XAIChatModel extends openai_chat_model_js_1.OpenAIChatModel {
8
24
  constructor(options) {
9
25
  super({
@@ -1,20 +1,19 @@
1
1
  import type { GetPromptResult } from "@modelcontextprotocol/sdk/types.js";
2
2
  import { Agent, type Message } from "../agents/agent.js";
3
3
  import type { AIAgent } from "../agents/ai-agent.js";
4
- import type { AgentMemory } from "../agents/memory.js";
5
4
  import type { Context } from "../aigne/context.js";
5
+ import type { MemoryAgent } from "../memory/memory.js";
6
6
  import type { ChatModel, ChatModelInput } from "../models/chat-model.js";
7
7
  import { ChatMessagesTemplate } from "./template.js";
8
8
  export declare const MESSAGE_KEY = "$message";
9
- export declare const DEFAULT_MAX_HISTORY_MESSAGES = 10;
10
9
  export declare function createMessage<I extends Message>(message: string | I): I;
11
10
  export declare function getMessage(input: Message): string | undefined;
12
11
  export interface PromptBuilderOptions {
13
12
  instructions?: string | ChatMessagesTemplate;
14
13
  }
15
14
  export interface PromptBuilderBuildOptions {
16
- memory?: AgentMemory;
17
- context?: Context;
15
+ memory?: MemoryAgent | MemoryAgent[];
16
+ context: Context;
18
17
  agent?: AIAgent;
19
18
  input?: Message;
20
19
  model?: ChatModel;
@@ -37,6 +36,7 @@ export declare class PromptBuilder {
37
36
  toolAgents?: Agent[];
38
37
  }>;
39
38
  private buildMessages;
39
+ private convertMemoriesToMessages;
40
40
  private buildResponseFormat;
41
41
  private buildTools;
42
42
  }
@@ -1,16 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PromptBuilder = exports.DEFAULT_MAX_HISTORY_MESSAGES = exports.MESSAGE_KEY = void 0;
3
+ exports.PromptBuilder = exports.MESSAGE_KEY = void 0;
4
4
  exports.createMessage = createMessage;
5
5
  exports.getMessage = getMessage;
6
6
  const promises_1 = require("node:fs/promises");
7
+ const yaml_1 = require("yaml");
7
8
  const zod_1 = require("zod");
8
9
  const agent_js_1 = require("../agents/agent.js");
9
10
  const json_schema_js_1 = require("../utils/json-schema.js");
10
11
  const type_utils_js_1 = require("../utils/type-utils.js");
12
+ const memory_message_template_js_1 = require("./prompts/memory-message-template.js");
11
13
  const template_js_1 = require("./template.js");
12
14
  exports.MESSAGE_KEY = "$message";
13
- exports.DEFAULT_MAX_HISTORY_MESSAGES = 10;
14
15
  function createMessage(message) {
15
16
  return typeof message === "string"
16
17
  ? { [exports.MESSAGE_KEY]: message }
@@ -72,26 +73,20 @@ class PromptBuilder {
72
73
  instructions;
73
74
  async build(options) {
74
75
  return {
75
- messages: this.buildMessages(options),
76
+ messages: await this.buildMessages(options),
76
77
  responseFormat: this.buildResponseFormat(options),
77
78
  ...this.buildTools(options),
78
79
  };
79
80
  }
80
- buildMessages(options) {
81
+ async buildMessages(options) {
81
82
  const { input } = options;
82
83
  const messages = (typeof this.instructions === "string"
83
84
  ? template_js_1.ChatMessagesTemplate.from([template_js_1.SystemMessageTemplate.from(this.instructions)])
84
85
  : this.instructions)?.format(options.input) ?? [];
85
- const memory = options.memory ?? options.agent?.memory;
86
- if (memory?.enabled) {
87
- const k = memory.maxMemoriesInChat ?? exports.DEFAULT_MAX_HISTORY_MESSAGES;
88
- const histories = memory.memories.slice(-k);
89
- if (histories?.length)
90
- messages.push(...histories.map((i) => ({
91
- role: i.role,
92
- content: convertMessageToContent(i.content),
93
- name: i.source,
94
- })));
86
+ for (const memory of (0, type_utils_js_1.orArrayToArray)(options.memory ?? options.agent?.memories)) {
87
+ const memories = (await memory.retrieve({ search: input && getMessage(input) }, options.context))?.memories;
88
+ if (memories?.length)
89
+ messages.push(...this.convertMemoriesToMessages(memories, options));
95
90
  }
96
91
  const content = input && getMessage(input);
97
92
  // add user input if it's not the same as the last message
@@ -100,6 +95,15 @@ class PromptBuilder {
100
95
  }
101
96
  return messages;
102
97
  }
98
+ convertMemoriesToMessages(memories, options) {
99
+ const str = (0, yaml_1.stringify)(memories.map((i) => i.content));
100
+ return [
101
+ {
102
+ role: "system",
103
+ content: template_js_1.PromptTemplate.from(options.agent?.memoryPromptTemplate || memory_message_template_js_1.MEMORY_MESSAGE_TEMPLATE).format({ memories: str }),
104
+ },
105
+ ];
106
+ }
103
107
  buildResponseFormat(options) {
104
108
  const outputSchema = options.outputSchema || options.agent?.outputSchema;
105
109
  if (!outputSchema)
@@ -117,10 +121,11 @@ class PromptBuilder {
117
121
  : undefined;
118
122
  }
119
123
  buildTools(options) {
120
- const toolAgents = (options.context?.skills ?? [])
124
+ const toolAgents = (0, type_utils_js_1.unique)((options.context?.skills ?? [])
121
125
  .concat(options.agent?.skills ?? [])
126
+ .concat(options.agent?.memoryAgentsAsTools ? options.agent.memories : [])
122
127
  // TODO: support nested tools?
123
- .flatMap((i) => (i.isInvokable ? i.skills.concat(i) : i.skills));
128
+ .flatMap((i) => (i.isInvokable ? i.skills.concat(i) : i.skills)), (i) => i.name);
124
129
  const tools = toolAgents.map((i) => ({
125
130
  type: "function",
126
131
  function: {
@@ -175,7 +180,3 @@ function isFromPath(value) {
175
180
  function isEmptyObjectType(schema) {
176
181
  return schema instanceof zod_1.ZodObject && Object.keys(schema.shape).length === 0;
177
182
  }
178
- function convertMessageToContent(i) {
179
- const str = i[exports.MESSAGE_KEY];
180
- return !(0, type_utils_js_1.isNil)(str) ? (typeof str === "string" ? str : JSON.stringify(str)) : JSON.stringify(i);
181
- }
@@ -0,0 +1 @@
1
+ export declare const MEMORY_MESSAGE_TEMPLATE = "Here are some useful memories to consider:\n\n<memories>\n{{memories}}\n</memories>\n";
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MEMORY_MESSAGE_TEMPLATE = void 0;
4
+ exports.MEMORY_MESSAGE_TEMPLATE = `\
5
+ Here are some useful memories to consider:
6
+
7
+ <memories>
8
+ {{memories}}
9
+ </memories>
10
+ `;
@@ -5,8 +5,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ChatMessagesTemplate = exports.ToolMessageTemplate = exports.AgentMessageTemplate = exports.UserMessageTemplate = exports.SystemMessageTemplate = exports.ChatMessageTemplate = exports.PromptTemplate = void 0;
7
7
  exports.parseChatMessages = parseChatMessages;
8
+ const node_util_1 = require("node:util");
8
9
  const mustache_1 = __importDefault(require("mustache"));
9
10
  const zod_1 = require("zod");
11
+ const type_utils_js_1 = require("../utils/type-utils.js");
10
12
  class PromptTemplate {
11
13
  template;
12
14
  static from(template) {
@@ -88,7 +90,9 @@ class ToolMessageTemplate extends ChatMessageTemplate {
88
90
  return new ToolMessageTemplate(content, toolCallId, name);
89
91
  }
90
92
  constructor(content, toolCallId, name) {
91
- super("tool", typeof content === "string" ? content : JSON.stringify(content), name);
93
+ super("tool", typeof content === "string"
94
+ ? content
95
+ : (0, type_utils_js_1.tryOrThrow)(() => JSON.stringify(content), `Failed to stringify tool content. toolCallId: ${toolCallId}, content: ${(0, node_util_1.inspect)(content)}`), name);
92
96
  this.toolCallId = toolCallId;
93
97
  }
94
98
  format(variables) {
@@ -1,4 +1,15 @@
1
+ /**
2
+ * Custom error class for AIGNEServer HTTP-related errors.
3
+ * Extends the standard Error class with an HTTP status code property.
4
+ * This allows error responses to include appropriate HTTP status codes.
5
+ */
1
6
  export declare class ServerError extends Error {
2
7
  status: number;
8
+ /**
9
+ * Creates a new ServerError instance.
10
+ *
11
+ * @param status - The HTTP status code for this error (e.g., 400, 404, 500)
12
+ * @param message - The error message describing what went wrong
13
+ */
3
14
  constructor(status: number, message: string);
4
15
  }
@@ -1,8 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ServerError = void 0;
4
+ /**
5
+ * Custom error class for AIGNEServer HTTP-related errors.
6
+ * Extends the standard Error class with an HTTP status code property.
7
+ * This allows error responses to include appropriate HTTP status codes.
8
+ */
4
9
  class ServerError extends Error {
5
10
  status;
11
+ /**
12
+ * Creates a new ServerError instance.
13
+ *
14
+ * @param status - The HTTP status code for this error (e.g., 400, 404, 500)
15
+ * @param message - The error message describing what went wrong
16
+ */
6
17
  constructor(status, message) {
7
18
  super(message);
8
19
  this.status = status;
@@ -0,0 +1,2 @@
1
+ export * from "./error.js";
2
+ export * from "./server.js";
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./error.js"), exports);
18
+ __exportStar(require("./server.js"), exports);