llmz 0.0.13 → 0.0.15

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 (52) hide show
  1. package/CLAUDE.md +363 -0
  2. package/README.md +61 -34
  3. package/dist/abort-signal.d.ts +40 -0
  4. package/dist/chat.d.ts +325 -0
  5. package/dist/{chunk-KH6JQYQA.js → chunk-2D2DE7CD.js} +2 -2
  6. package/dist/chunk-3G3BS5IA.cjs +256 -0
  7. package/dist/{chunk-SNDVQU5A.js → chunk-3JYCCI4S.js} +1 -1
  8. package/dist/chunk-A7QHWVD7.js +493 -0
  9. package/dist/{chunk-IH2WQFO5.js → chunk-EE6NVDID.js} +1 -1
  10. package/dist/{chunk-4L6D2A6O.cjs → chunk-FZJHYLM2.cjs} +14 -14
  11. package/dist/{chunk-JGVAZO4X.cjs → chunk-GZPN7RGH.cjs} +2 -2
  12. package/dist/{chunk-SHJDRZF5.cjs → chunk-PIDLNYIP.cjs} +25 -25
  13. package/dist/{chunk-PRVFVXT4.js → chunk-RBRTK37G.js} +383 -4
  14. package/dist/{chunk-HJKOSEH2.cjs → chunk-TCRRSS44.cjs} +397 -18
  15. package/dist/chunk-VPTFUOIK.js +256 -0
  16. package/dist/{chunk-276Q6EWP.cjs → chunk-WHNOR4ZU.cjs} +3 -0
  17. package/dist/chunk-XGJOEQMW.cjs +493 -0
  18. package/dist/{chunk-4MNIJGK6.js → chunk-ZORRILUV.js} +3 -0
  19. package/dist/context.d.ts +412 -4
  20. package/dist/{dual-modes-T53P72CH.js → dual-modes-7FI4T35O.js} +3 -3
  21. package/dist/{dual-modes-VLIGPIHX.cjs → dual-modes-OFHV2C3X.cjs} +4 -4
  22. package/dist/exit-XAYKJ6TR.cjs +8 -0
  23. package/dist/{exit-YORW76T3.js → exit-YLO7BY7Z.js} +2 -2
  24. package/dist/exit.d.ts +369 -2
  25. package/dist/index.cjs +253 -28
  26. package/dist/index.d.ts +71 -1
  27. package/dist/index.js +242 -17
  28. package/dist/{llmz-ROOX7RYI.js → llmz-67EZPJ4E.js} +113 -39
  29. package/dist/{llmz-QLZBDG2Z.cjs → llmz-WVNKAMCP.cjs} +123 -49
  30. package/dist/llmz.d.ts +142 -5
  31. package/dist/objects.d.ts +350 -1
  32. package/dist/result.d.ts +809 -6
  33. package/dist/snapshots.d.ts +181 -1
  34. package/dist/{tool-QP4MVRWI.cjs → tool-O4SFRIE4.cjs} +4 -4
  35. package/dist/{tool-N6ODRRGH.js → tool-PCOYOCRH.js} +3 -3
  36. package/dist/tool.d.ts +470 -2
  37. package/dist/{truncator-IY2MXOMC.js → truncator-BSP6PQPC.js} +2 -2
  38. package/dist/truncator-W3NXBLYJ.cjs +10 -0
  39. package/dist/types.d.ts +3 -0
  40. package/dist/{typings-GDMY6VY2.js → typings-WYHEFCYB.js} +2 -2
  41. package/dist/{typings-2CPHOFDN.cjs → typings-Y45GMPZT.cjs} +3 -3
  42. package/dist/utils-L5QAQXV2.cjs +39 -0
  43. package/dist/{utils-N24IHDFA.js → utils-RQHQ2KOG.js} +1 -1
  44. package/docs/TODO.md +919 -0
  45. package/package.json +3 -3
  46. package/dist/chunk-C6WNNTEV.cjs +0 -212
  47. package/dist/chunk-GWFYZDUR.cjs +0 -105
  48. package/dist/chunk-JAGB2AOU.js +0 -212
  49. package/dist/chunk-JMSZKB4T.js +0 -105
  50. package/dist/exit-TRXEU4OU.cjs +0 -8
  51. package/dist/truncator-DUMWEGQO.cjs +0 -10
  52. package/dist/utils-A7WNEFTA.cjs +0 -39
@@ -7,10 +7,10 @@ var _chunkBEPRLBPKcjs = require('./chunk-BEPRLBPK.cjs');
7
7
 
8
8
 
9
9
 
10
- var _chunkHJKOSEH2cjs = require('./chunk-HJKOSEH2.cjs');
11
- require('./chunk-SHJDRZF5.cjs');
12
- require('./chunk-C6WNNTEV.cjs');
13
- require('./chunk-4L6D2A6O.cjs');
10
+ var _chunkTCRRSS44cjs = require('./chunk-TCRRSS44.cjs');
11
+ require('./chunk-PIDLNYIP.cjs');
12
+ require('./chunk-XGJOEQMW.cjs');
13
+ require('./chunk-FZJHYLM2.cjs');
14
14
 
15
15
 
16
16
 
@@ -24,16 +24,16 @@ var _chunkJDABP4SDcjs = require('./chunk-JDABP4SD.cjs');
24
24
 
25
25
 
26
26
  var _chunkIKSIOIIPcjs = require('./chunk-IKSIOIIP.cjs');
27
- require('./chunk-GWFYZDUR.cjs');
27
+ require('./chunk-3G3BS5IA.cjs');
28
28
  require('./chunk-ZRCU35UV.cjs');
29
29
  require('./chunk-KMZDFWYZ.cjs');
30
30
 
31
31
 
32
- var _chunkJGVAZO4Xcjs = require('./chunk-JGVAZO4X.cjs');
32
+ var _chunkGZPN7RGHcjs = require('./chunk-GZPN7RGH.cjs');
33
33
 
34
34
 
35
35
 
36
- var _chunk276Q6EWPcjs = require('./chunk-276Q6EWP.cjs');
36
+ var _chunkWHNOR4ZUcjs = require('./chunk-WHNOR4ZU.cjs');
37
37
 
38
38
 
39
39
 
@@ -46,6 +46,37 @@ var _cognitive = require('@botpress/cognitive');
46
46
  var _zui = require('@bpinternal/zui');
47
47
  var _ms = require('ms'); var _ms2 = _interopRequireDefault(_ms);
48
48
  var _ulid = require('ulid');
49
+
50
+ // src/abort-signal.ts
51
+ function createJoinedAbortController(signals) {
52
+ const controller = new AbortController();
53
+ const validSignals = signals.filter((signal) => signal != null);
54
+ if (validSignals.length === 0) {
55
+ return controller;
56
+ }
57
+ for (const signal of validSignals) {
58
+ if (signal.aborted) {
59
+ controller.abort(signal.reason);
60
+ return controller;
61
+ }
62
+ }
63
+ const abortListeners = [];
64
+ for (const signal of validSignals) {
65
+ const listener = () => {
66
+ controller.abort(signal.reason);
67
+ cleanup();
68
+ };
69
+ signal.addEventListener("abort", listener);
70
+ abortListeners.push(() => signal.removeEventListener("abort", listener));
71
+ }
72
+ const cleanup = () => {
73
+ abortListeners.forEach((removeListener) => removeListener());
74
+ };
75
+ controller.signal.addEventListener("abort", cleanup, { once: true });
76
+ return controller;
77
+ }
78
+
79
+ // src/llmz.ts
49
80
  var getErrorMessage = (err) => err instanceof Error ? err.message : JSON.stringify(err);
50
81
  var SLOW_TOOL_WARNING = _ms2.default.call(void 0, "15s");
51
82
  var RESPONSE_LENGTH_BUFFER = {
@@ -60,7 +91,7 @@ var getModelOutputLimit = (inputLength) => _chunkUQOBUJIQcjs.clamp_default.call(
60
91
  );
61
92
  var executeContext = async (props) => {
62
93
  var _a, _b;
63
- await _chunk276Q6EWPcjs.init.call(void 0, );
94
+ await _chunkWHNOR4ZUcjs.init.call(void 0, );
64
95
  const result = await _executeContext(props);
65
96
  try {
66
97
  (_b = (_a = result.context.chat) == null ? void 0 : _a.onExecutionDone) == null ? void 0 : _b.call(_a, result);
@@ -70,10 +101,11 @@ var executeContext = async (props) => {
70
101
  };
71
102
  var _executeContext = async (props) => {
72
103
  var _a, _b, _c, _d;
73
- const { signal, onIterationEnd, onTrace, onExit, onBeforeExecution } = props;
104
+ const controller = createJoinedAbortController([props.signal]);
105
+ const { onIterationEnd, onTrace, onExit, onBeforeExecution, onAfterTool, onBeforeTool } = props;
74
106
  const cognitive = _cognitive.Cognitive.isCognitiveClient(props.client) ? props.client : new (0, _cognitive.Cognitive)({ client: props.client });
75
107
  const cleanups = [];
76
- const ctx = new (0, _chunkHJKOSEH2cjs.Context)({
108
+ const ctx = new (0, _chunkTCRRSS44cjs.Context)({
77
109
  chat: props.chat,
78
110
  instructions: props.instructions,
79
111
  objects: props.objects,
@@ -88,17 +120,17 @@ var _executeContext = async (props) => {
88
120
  try {
89
121
  while (true) {
90
122
  if (ctx.iterations.length >= ctx.loop) {
91
- return new (0, _chunkHJKOSEH2cjs.ErrorExecutionResult)(ctx, new (0, _chunkJDABP4SDcjs.LoopExceededError)());
123
+ return new (0, _chunkTCRRSS44cjs.ErrorExecutionResult)(ctx, new (0, _chunkJDABP4SDcjs.LoopExceededError)());
92
124
  }
93
125
  const iteration = await ctx.nextIteration();
94
- if (signal == null ? void 0 : signal.aborted) {
126
+ if (controller.signal.aborted) {
95
127
  iteration.end({
96
128
  type: "aborted",
97
129
  aborted: {
98
- reason: _nullishCoalesce(signal.reason, () => ( "The operation was aborted"))
130
+ reason: _nullishCoalesce(controller.signal.reason, () => ( "The operation was aborted"))
99
131
  }
100
132
  });
101
- return new (0, _chunkHJKOSEH2cjs.ErrorExecutionResult)(ctx, _nullishCoalesce(signal.reason, () => ( "The operation was aborted")));
133
+ return new (0, _chunkTCRRSS44cjs.ErrorExecutionResult)(ctx, _nullishCoalesce(controller.signal.reason, () => ( "The operation was aborted")));
102
134
  }
103
135
  cleanups.push(
104
136
  iteration.traces.onPush((traces) => {
@@ -112,9 +144,11 @@ var _executeContext = async (props) => {
112
144
  iteration,
113
145
  ctx,
114
146
  cognitive,
115
- abortSignal: signal,
147
+ controller,
116
148
  onExit,
117
- onBeforeExecution
149
+ onBeforeExecution,
150
+ onAfterTool,
151
+ onBeforeTool
118
152
  });
119
153
  } catch (err) {
120
154
  iteration.end({
@@ -126,31 +160,31 @@ var _executeContext = async (props) => {
126
160
  });
127
161
  }
128
162
  try {
129
- await (onIterationEnd == null ? void 0 : onIterationEnd(iteration));
163
+ await (onIterationEnd == null ? void 0 : onIterationEnd(iteration, controller));
130
164
  } catch (err) {
131
165
  console.error(err);
132
166
  }
133
167
  if (iteration.status.type === "exit_success") {
134
168
  const exitName = iteration.status.exit_success.exit_name;
135
- return new (0, _chunkHJKOSEH2cjs.SuccessExecutionResult)(ctx, {
169
+ return new (0, _chunkTCRRSS44cjs.SuccessExecutionResult)(ctx, {
136
170
  exit: iteration.exits.find((x) => x.name === exitName),
137
171
  result: iteration.status.exit_success.return_value
138
172
  });
139
173
  }
140
174
  if (iteration.status.type === "callback_requested") {
141
- return new (0, _chunkHJKOSEH2cjs.PartialExecutionResult)(
175
+ return new (0, _chunkTCRRSS44cjs.PartialExecutionResult)(
142
176
  ctx,
143
177
  iteration.status.callback_requested.signal,
144
- _chunkHJKOSEH2cjs.Snapshot.fromSignal(iteration.status.callback_requested.signal)
178
+ _chunkTCRRSS44cjs.Snapshot.fromSignal(iteration.status.callback_requested.signal)
145
179
  );
146
180
  }
147
181
  if (iteration.status.type === "thinking_requested" || iteration.status.type === "exit_error" || iteration.status.type === "execution_error" || iteration.status.type === "invalid_code_error") {
148
182
  continue;
149
183
  }
150
- return new (0, _chunkHJKOSEH2cjs.ErrorExecutionResult)(ctx, _nullishCoalesce(iteration.error, () => ( `Unknown error. Status: ${iteration.status.type}`)));
184
+ return new (0, _chunkTCRRSS44cjs.ErrorExecutionResult)(ctx, _nullishCoalesce(iteration.error, () => ( `Unknown error. Status: ${iteration.status.type}`)));
151
185
  }
152
186
  } catch (error) {
153
- return new (0, _chunkHJKOSEH2cjs.ErrorExecutionResult)(ctx, _nullishCoalesce(error, () => ( "Unknown error")));
187
+ return new (0, _chunkTCRRSS44cjs.ErrorExecutionResult)(ctx, _nullishCoalesce(error, () => ( "Unknown error")));
154
188
  } finally {
155
189
  for (const cleanup of cleanups) {
156
190
  try {
@@ -164,9 +198,11 @@ var executeIteration = async ({
164
198
  iteration,
165
199
  ctx,
166
200
  cognitive,
167
- abortSignal,
201
+ controller,
168
202
  onExit,
169
- onBeforeExecution
203
+ onBeforeExecution,
204
+ onBeforeTool,
205
+ onAfterTool
170
206
  }) => {
171
207
  var _a, _b, _c, _d, _e;
172
208
  let startedAt = Date.now();
@@ -174,7 +210,7 @@ var executeIteration = async ({
174
210
  const model = await cognitive.getModelDetails(_nullishCoalesce(ctx.model, () => ( "best")));
175
211
  const modelLimit = model.input.maxTokens;
176
212
  const responseLengthBuffer = getModelOutputLimit(modelLimit);
177
- const messages = _chunkJGVAZO4Xcjs.truncateWrappedContent.call(void 0, {
213
+ const messages = _chunkGZPN7RGHcjs.truncateWrappedContent.call(void 0, {
178
214
  messages: iteration.messages,
179
215
  tokenLimit: modelLimit - responseLengthBuffer,
180
216
  throwOnFailure: true
@@ -192,7 +228,7 @@ var executeIteration = async ({
192
228
  model: model.ref
193
229
  });
194
230
  const output = await cognitive.generateContent({
195
- signal: abortSignal,
231
+ signal: controller.signal,
196
232
  systemPrompt: (_a = messages.find((x) => x.role === "system")) == null ? void 0 : _a.content,
197
233
  model: model.ref,
198
234
  temperature: ctx.temperature,
@@ -208,7 +244,10 @@ var executeIteration = async ({
208
244
  iteration.code = assistantResponse.code.trim();
209
245
  if (typeof onBeforeExecution === "function") {
210
246
  try {
211
- await onBeforeExecution(iteration);
247
+ const hookRes = await onBeforeExecution(iteration, controller);
248
+ if (typeof (hookRes == null ? void 0 : hookRes.code) === "string" && hookRes.code.trim().length > 0) {
249
+ iteration.code = hookRes.code.trim();
250
+ }
212
251
  } catch (err) {
213
252
  if (err instanceof _chunkJDABP4SDcjs.ThinkSignal) {
214
253
  return iteration.end({
@@ -245,7 +284,7 @@ var executeIteration = async ({
245
284
  model: model.ref,
246
285
  code: iteration.code
247
286
  });
248
- const vmContext = { ..._chunk276Q6EWPcjs.stripInvalidIdentifiers.call(void 0, iteration.variables) };
287
+ const vmContext = { ..._chunkWHNOR4ZUcjs.stripInvalidIdentifiers.call(void 0, iteration.variables) };
249
288
  for (const obj of iteration.objects) {
250
289
  const internalValues = {};
251
290
  const instance = {};
@@ -288,19 +327,27 @@ var executeIteration = async ({
288
327
  });
289
328
  }
290
329
  for (const tool of _nullishCoalesce(obj.tools, () => ( []))) {
291
- instance[tool.name] = wrapTool({ tool, traces, object: obj.name });
330
+ instance[tool.name] = wrapTool({
331
+ tool,
332
+ traces,
333
+ object: obj.name,
334
+ iteration,
335
+ beforeHook: onBeforeTool,
336
+ afterHook: onAfterTool,
337
+ controller
338
+ });
292
339
  }
293
340
  Object.preventExtensions(instance);
294
341
  Object.seal(instance);
295
342
  vmContext[obj.name] = instance;
296
343
  }
297
344
  for (const tool of iteration.tools) {
298
- const wrapped = wrapTool({ tool, traces });
345
+ const wrapped = wrapTool({ tool, traces, iteration, beforeHook: onBeforeTool, afterHook: onAfterTool, controller });
299
346
  for (const key of [tool.name, ..._nullishCoalesce(tool.aliases, () => ( []))]) {
300
347
  vmContext[key] = wrapped;
301
348
  }
302
349
  }
303
- if (abortSignal == null ? void 0 : abortSignal.aborted) {
350
+ if (controller.signal.aborted) {
304
351
  traces.push({
305
352
  type: "abort_signal",
306
353
  started_at: Date.now(),
@@ -309,22 +356,26 @@ var executeIteration = async ({
309
356
  return iteration.end({
310
357
  type: "aborted",
311
358
  aborted: {
312
- reason: _nullishCoalesce((abortSignal == null ? void 0 : abortSignal.reason), () => ( "The operation was aborted"))
359
+ reason: _nullishCoalesce(controller.signal.reason, () => ( "The operation was aborted"))
313
360
  }
314
361
  });
315
362
  }
316
363
  startedAt = Date.now();
317
- const result = await _chunkBEPRLBPKcjs.runAsyncFunction.call(void 0, vmContext, iteration.code, traces, abortSignal, ctx.timeout).catch(
318
- (err) => {
319
- return {
320
- success: false,
321
- error: err,
322
- lines_executed: [],
323
- traces: [],
324
- variables: {}
325
- };
326
- }
327
- );
364
+ const result = await _chunkBEPRLBPKcjs.runAsyncFunction.call(void 0,
365
+ vmContext,
366
+ iteration.code,
367
+ traces,
368
+ controller.signal,
369
+ ctx.timeout
370
+ ).catch((err) => {
371
+ return {
372
+ success: false,
373
+ error: err,
374
+ lines_executed: [],
375
+ traces: [],
376
+ variables: {}
377
+ };
378
+ });
328
379
  if (result.error && result.error instanceof _chunkJDABP4SDcjs.InvalidCodeError) {
329
380
  return iteration.end({
330
381
  type: "invalid_code_error",
@@ -348,11 +399,11 @@ var executeIteration = async ({
348
399
  }
349
400
  });
350
401
  }
351
- if (abortSignal == null ? void 0 : abortSignal.aborted) {
402
+ if (controller.signal.aborted) {
352
403
  return iteration.end({
353
404
  type: "aborted",
354
405
  aborted: {
355
- reason: _nullishCoalesce((abortSignal == null ? void 0 : abortSignal.reason), () => ( "The operation was aborted"))
406
+ reason: _nullishCoalesce(controller.signal.reason, () => ( "The operation was aborted"))
356
407
  }
357
408
  });
358
409
  }
@@ -462,7 +513,7 @@ var executeIteration = async ({
462
513
  }
463
514
  });
464
515
  };
465
- function wrapTool({ tool, traces, object }) {
516
+ function wrapTool({ tool, traces, object, iteration, beforeHook, afterHook, controller }) {
466
517
  const getToolInput = (input) => _nullishCoalesce(tool.zInput.safeParse(input).data, () => ( input));
467
518
  return function(input) {
468
519
  const toolCallId = `tcall_${_ulid.ulid.call(void 0, )}`;
@@ -510,9 +561,32 @@ function wrapTool({ tool, traces, object }) {
510
561
  return false;
511
562
  };
512
563
  try {
513
- const result = tool.execute(input, {
514
- callId: toolCallId
515
- });
564
+ const withHooks = async (input2) => {
565
+ const beforeRes = await (beforeHook == null ? void 0 : beforeHook({
566
+ iteration,
567
+ tool,
568
+ input: input2,
569
+ controller
570
+ }));
571
+ if (typeof (beforeRes == null ? void 0 : beforeRes.input) !== "undefined") {
572
+ input2 = beforeRes.input;
573
+ }
574
+ let output2 = await tool.execute(input2, {
575
+ callId: toolCallId
576
+ });
577
+ const afterRes = await (afterHook == null ? void 0 : afterHook({
578
+ iteration,
579
+ tool,
580
+ input: input2,
581
+ output: output2,
582
+ controller
583
+ }));
584
+ if (typeof (afterRes == null ? void 0 : afterRes.output) !== "undefined") {
585
+ output2 = afterRes.output;
586
+ }
587
+ return output2;
588
+ };
589
+ const result = withHooks(input);
516
590
  if (result instanceof Promise || (result == null ? void 0 : result.then) && (result == null ? void 0 : result.catch)) {
517
591
  return result.then((res) => {
518
592
  output = res;
package/dist/llmz.d.ts CHANGED
@@ -10,29 +10,166 @@ import { type Tool } from './tool.js';
10
10
  import { Trace } from './types.js';
11
11
  export type ExecutionHooks = {
12
12
  /**
13
- * Called after each iteration ends
13
+ * NON-BLOCKING HOOK
14
+ * This hook will not block the execution of the iteration.
15
+ * NON-MUTATION HOOK
16
+ * This hook can't mutate traces.
14
17
  *
15
- * **Warning**: This should not be a long task as it blocks the execution
18
+ * This hook is called for each trace that is generated during the iteration.
19
+ * It is useful for logging, debugging, or monitoring the execution of the iteration.
16
20
  */
17
- onIterationEnd?: (iteration: Iteration) => Promise<void> | void;
18
21
  onTrace?: (event: {
19
22
  trace: Trace;
20
23
  iteration: number;
21
24
  }) => void;
25
+ /**
26
+ * BLOCKING HOOK
27
+ * This hook will block the execution of the iteration until it resolves.
28
+ * NON-MUTATION HOOK
29
+ * This hook can't mutate the result or status of the iteration.
30
+ *
31
+ * This hook will be called after each iteration ends, regardless of the status.
32
+ * This is useful for logging, cleanup or to prevent or delay the next iteration from starting.
33
+ */
34
+ onIterationEnd?: (iteration: Iteration, controller: AbortController) => Promise<void> | void;
35
+ /**
36
+ * BLOCKING HOOK
37
+ * This hook will block the execution of the iteration until it resolves.
38
+ * NON-MUTATION HOOK
39
+ * This hook can't mutate the exit result.
40
+ *
41
+ * This hook is called when an exit is reached in the iteration.
42
+ * It is useful for logging, sending notifications, or performing actions based on the exit.
43
+ * It can also be used to throw an error and preventing the exit from being successful.
44
+ * If this hook throws an error, the execution will keep iterating with the error as context.
45
+ */
22
46
  onExit?: <T = unknown>(result: ExitResult<T>) => Promise<void> | void;
23
- onBeforeExecution?: (iteration: Iteration) => Promise<void> | void;
47
+ /**
48
+ * BLOCKING HOOK
49
+ * This hook will block the execution of the iteration until it resolves.
50
+ * MUTATION HOOK
51
+ * This hook can mutate the code to run in the iteration.
52
+ *
53
+ * This hook is called after the LLM generates the code for the iteration, but before it is executed.
54
+ * It is useful for modifying the code to run, or for guarding against certain code patterns.
55
+ */
56
+ onBeforeExecution?: (iteration: Iteration, controller: AbortController) => Promise<{
57
+ code?: string;
58
+ } | void>;
59
+ /**
60
+ * BLOCKING HOOK
61
+ * This hook will block the execution of the iteration until it resolves.
62
+ * MUTATION HOOK
63
+ * This hook can mutate the input to the tool.
64
+ *
65
+ * This hook is called before any tool is executed.
66
+ * It is useful for modifying the input to a tool or prevent a tool from executing.
67
+ */
68
+ onBeforeTool?: (event: {
69
+ iteration: Iteration;
70
+ tool: Tool;
71
+ input: any;
72
+ controller: AbortController;
73
+ }) => Promise<{
74
+ input?: any;
75
+ } | void>;
76
+ /**
77
+ * BLOCKING HOOK
78
+ * This hook will block the execution of the iteration until it resolves.
79
+ * MUTATION HOOK
80
+ * This hook can mutate the output of the tool.
81
+ *
82
+ * This hook is called after a tool is executed.
83
+ * It is useful for modifying the output of a tool or for logging purposes.
84
+ */
85
+ onAfterTool?: (event: {
86
+ iteration: Iteration;
87
+ tool: Tool;
88
+ input: any;
89
+ output: any;
90
+ controller: AbortController;
91
+ }) => Promise<{
92
+ output?: any;
93
+ } | void>;
24
94
  };
25
95
  type Options = Partial<Pick<Context, 'loop' | 'temperature' | 'model' | 'timeout'>>;
26
96
  export type ExecutionProps = {
97
+ /**
98
+ * If provided, the execution will be run in "Chat Mode".
99
+ * In this mode, the execution will be able to send messages to the chat and will also have access to a chat transcript.
100
+ * The execution can still end with a custom Exit, but a special ListenExit will be added to give back the chat control to the user.
101
+ *
102
+ * If `chat` is not provided, the execution will run in "Worker Mode", where it will not have access to a chat transcript.
103
+ * In Worker Mode, the execution will iterate until it reaches an Exit or runs out of iterations.
104
+ */
27
105
  chat?: Chat;
106
+ /**
107
+ * Instructions for the LLM to follow.
108
+ * This is a system prompt that will be used to guide the LLM's behavior.
109
+ * It can be a simple string or a function that returns a string based on the current context (dynamic instructions).
110
+ * Dynamic instructions are evaluated at the start of each iteration, allowing for context-aware instructions.
111
+ */
28
112
  instructions?: ValueOrGetter<string, Context>;
113
+ /**
114
+ * Objects available in the context.
115
+ * Objects are useful to scope related tools together and to provide data to the VM.
116
+ * Objects can contain "properties" that can be read and written to, as well as "tools" that can be executed.
117
+ * Properties are type-safe and can be defined using a Zui schema.
118
+ * Properties can be marked as read-only or writable.
119
+ * The sandbox will ensure that properties are only modified if they are writable, and will also ensure that the values are valid according to the schema.
120
+ *
121
+ * Objects can be a static array of objects or a function that returns an array based on the current context.
122
+ * Dynamic objects are evaluated at the start of each iteration, allowing for context-aware objects.
123
+ *
124
+ * Example:
125
+ * An object "user" with properties "name" (string, writable) and "age" (number, read-only) will allow the LLM to see both properties and their values,
126
+ * and executing the code `user.name = 'John'` will succeed, while `user.age = 30` will throw an error as the property is read-only.
127
+ * Similarly, `user.name = 123` will throw an error as the value is not a string.
128
+ */
29
129
  objects?: ValueOrGetter<ObjectInstance[], Context>;
130
+ /**
131
+ * Tools available in the context.
132
+ * Tools are functions that can be executed by the LLM to perform actions or retrieve data.
133
+ * Tools can be defined with input and output schemas using Zui, and can be scoped to an object.
134
+ * Tools can also have aliases, which are alternative names for the tool that can be used to call it.
135
+ *
136
+ * Tools can be a static array of tools or a function that returns an array based on the current context.
137
+ * Dynamic tools are evaluated at the start of each iteration, allowing for context-aware tools.
138
+ */
30
139
  tools?: ValueOrGetter<Tool[], Context>;
140
+ /**
141
+ * Exits available in the context.
142
+ * Exits define the possible endpoints for the execution. Every execution will either end with an exit, or run out of iterations.
143
+ *
144
+ * When `chat` is provided, the built-in "ListenExit" is automatically added.
145
+ * When `exits` is not provided, the built-in "DefaultExit" is automatically added.
146
+ *
147
+ * Each exit has a name and can have aliases, which are alternative names for the exit that can be used to call it.
148
+ * Exits can also have a Zui schema to validate the return value when the exit is reached.
149
+ *
150
+ * Exits can be a static array of exits or a function that returns an array based on the current context.
151
+ * Dynamic exits are evaluated at the start of each iteration, allowing for context-aware exits.
152
+ */
31
153
  exits?: ValueOrGetter<Exit[], Context>;
32
154
  options?: Options;
33
- /** An instance of a Botpress Client, or an instance of Cognitive Client (@botpress/cognitive) */
155
+ /**
156
+ * An instance of a Botpress Client, or an instance of Cognitive Client (@botpress/cognitive).
157
+ * This is used to generate content using the LLM and to access the Botpress API.
158
+ */
34
159
  client: Cognitive | BotpressClientLike;
160
+ /**
161
+ * When provided, the execution will immediately stop when the signal is aborted.
162
+ * This will stop the LLM generation, as well as kill the VM sandbox execution.
163
+ * Aborted iterations will end with IterationStatuses.Aborted and the execution will be marked as failed.
164
+ */
35
165
  signal?: AbortSignal;
166
+ /**
167
+ * A snapshot is a saved state of the execution context.
168
+ * It can be used to resume the execution of a context at a later time.
169
+ * This is useful for long-running executions that may need to be paused and resumed later.
170
+ * The snapshot MUST be settled, which means it has to be resolved or rejected.
171
+ * Providing an unsettled snapshot will throw an error.
172
+ */
36
173
  snapshot?: Snapshot;
37
174
  } & ExecutionHooks;
38
175
  export declare const executeContext: (props: ExecutionProps) => Promise<ExecutionResult>;