llmz 0.0.4 → 0.0.6

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 (41) hide show
  1. package/README.md +4 -0
  2. package/dist/chat.d.ts +17 -0
  3. package/dist/{chunk-LVKZYKTP.cjs → chunk-4I7UPBLN.cjs} +2 -2
  4. package/dist/{chunk-W6U2VXSF.cjs → chunk-6WT5VZBG.cjs} +348 -12
  5. package/dist/{chunk-5NVNEEYW.cjs → chunk-BEPRLBPK.cjs} +60 -16
  6. package/dist/chunk-CH5T6SPC.cjs +694 -0
  7. package/dist/{chunk-4EWY34YA.js → chunk-D3ESDRLH.js} +60 -16
  8. package/dist/{chunk-JK2LZW2G.cjs → chunk-EJRCDWBA.cjs} +45 -6
  9. package/dist/{chunk-ZCPQ3QOW.js → chunk-HP7RKM25.js} +45 -6
  10. package/dist/{chunk-S6WICIDW.js → chunk-S6FOL2HY.js} +2 -2
  11. package/dist/{chunk-TJQVC4CE.js → chunk-WLUVY5QU.js} +341 -5
  12. package/dist/chunk-XJNRORSK.js +694 -0
  13. package/dist/{component-LQDU72LX.js → component-R2Y74VUI.js} +3 -1
  14. package/dist/component-TSNW3SC7.cjs +16 -0
  15. package/dist/component.d.ts +6 -19
  16. package/dist/component.default.d.ts +131 -151
  17. package/dist/context.d.ts +13 -5
  18. package/dist/{dual-modes-YE4S2AIL.cjs → dual-modes-UHNDHNIF.cjs} +3 -4
  19. package/dist/{dual-modes-QHBOFWHM.js → dual-modes-ZUQKPJFH.js} +2 -3
  20. package/dist/{exit-IDKGZD7M.cjs → exit-KJ4COC5N.cjs} +2 -2
  21. package/dist/{exit-F6ZUL2NV.js → exit-OIYZLBVJ.js} +1 -1
  22. package/dist/exit.d.ts +5 -1
  23. package/dist/getter.d.ts +1 -1
  24. package/dist/index.cjs +85 -128
  25. package/dist/index.d.ts +11 -8
  26. package/dist/index.js +80 -123
  27. package/dist/llmz-CPMVYIOJ.cjs +581 -0
  28. package/dist/llmz-LAN4WDFW.js +581 -0
  29. package/dist/llmz.d.ts +8 -10
  30. package/dist/result.d.ts +33 -0
  31. package/dist/types.d.ts +1 -33
  32. package/dist/{vm-GJ5R72AP.cjs → vm-2DLG7V4G.cjs} +2 -2
  33. package/dist/{vm-ZUQOSRRM.js → vm-FLBMZUA2.js} +1 -1
  34. package/package.json +1 -1
  35. package/dist/chunk-4KB5WXHR.js +0 -92
  36. package/dist/chunk-6YWYCVAB.cjs +0 -92
  37. package/dist/chunk-EFGXTO64.js +0 -344
  38. package/dist/chunk-VAF2H6UD.cjs +0 -344
  39. package/dist/component-HQ5YQNRX.cjs +0 -14
  40. package/dist/llmz-AS5TGCQS.js +0 -1108
  41. package/dist/llmz-R6XZG3JQ.cjs +0 -1108
@@ -0,0 +1,581 @@
1
+ import {
2
+ runAsyncFunction
3
+ } from "./chunk-D3ESDRLH.js";
4
+ import {
5
+ Context,
6
+ ErrorExecutionResult,
7
+ PartialExecutionResult,
8
+ Snapshot,
9
+ SuccessExecutionResult
10
+ } from "./chunk-XJNRORSK.js";
11
+ import "./chunk-WLUVY5QU.js";
12
+ import "./chunk-QBXIE6EY.js";
13
+ import "./chunk-UNMKB2DA.js";
14
+ import {
15
+ AssignmentError,
16
+ CodeExecutionError,
17
+ InvalidCodeError,
18
+ LoopExceededError,
19
+ Signals,
20
+ SnapshotSignal,
21
+ ThinkSignal,
22
+ VMSignal
23
+ } from "./chunk-JKVVQN2P.js";
24
+ import {
25
+ cleanStackTrace
26
+ } from "./chunk-JQBT7UWN.js";
27
+ import "./chunk-S6FOL2HY.js";
28
+ import "./chunk-HP7RKM25.js";
29
+ import "./chunk-ORQP26SZ.js";
30
+ import {
31
+ truncateWrappedContent
32
+ } from "./chunk-QT4QF3YA.js";
33
+ import {
34
+ init,
35
+ stripInvalidIdentifiers
36
+ } from "./chunk-5TRUJES5.js";
37
+ import {
38
+ clamp_default,
39
+ isEqual_default,
40
+ isPlainObject_default,
41
+ omit_default
42
+ } from "./chunk-7WRN4E42.js";
43
+
44
+ // src/llmz.ts
45
+ import { Cognitive } from "@botpress/cognitive";
46
+ import { z } from "@bpinternal/zui";
47
+ import ms from "ms";
48
+ import { ulid } from "ulid";
49
+ var getErrorMessage = (err) => err instanceof Error ? err.message : JSON.stringify(err);
50
+ var SLOW_TOOL_WARNING = ms("15s");
51
+ var RESPONSE_LENGTH_BUFFER = {
52
+ MIN_TOKENS: 1e3,
53
+ MAX_TOKENS: 16e3,
54
+ PERCENTAGE: 0.1
55
+ };
56
+ var getModelOutputLimit = (inputLength) => clamp_default(
57
+ RESPONSE_LENGTH_BUFFER.PERCENTAGE * inputLength,
58
+ RESPONSE_LENGTH_BUFFER.MIN_TOKENS,
59
+ RESPONSE_LENGTH_BUFFER.MAX_TOKENS
60
+ );
61
+ var executeContext = async (props) => {
62
+ var _a, _b;
63
+ await init();
64
+ const result = await _executeContext(props);
65
+ try {
66
+ (_b = (_a = result.context.chat) == null ? void 0 : _a.onExecutionDone) == null ? void 0 : _b.call(_a, result);
67
+ } catch {
68
+ }
69
+ return result;
70
+ };
71
+ var _executeContext = async (props) => {
72
+ var _a, _b, _c, _d;
73
+ const { signal, onIterationEnd, onTrace, onExit, onBeforeExecution } = props;
74
+ const cognitive = props.client instanceof Cognitive ? props.client : new Cognitive({ client: props.client });
75
+ const cleanups = [];
76
+ const ctx = new Context({
77
+ chat: props.chat,
78
+ instructions: props.instructions,
79
+ objects: props.objects,
80
+ tools: props.tools,
81
+ loop: (_a = props.options) == null ? void 0 : _a.loop,
82
+ temperature: (_b = props.options) == null ? void 0 : _b.temperature,
83
+ model: (_c = props.options) == null ? void 0 : _c.model,
84
+ timeout: (_d = props.options) == null ? void 0 : _d.timeout,
85
+ exits: props.exits,
86
+ snapshot: props.snapshot
87
+ });
88
+ try {
89
+ while (true) {
90
+ if (ctx.iterations.length >= ctx.loop) {
91
+ return new ErrorExecutionResult(ctx, new LoopExceededError());
92
+ }
93
+ const iteration = await ctx.nextIteration();
94
+ if (signal == null ? void 0 : signal.aborted) {
95
+ iteration.end({
96
+ type: "aborted",
97
+ aborted: {
98
+ reason: signal.reason ?? "The operation was aborted"
99
+ }
100
+ });
101
+ return new ErrorExecutionResult(ctx, signal.reason ?? "The operation was aborted");
102
+ }
103
+ cleanups.push(
104
+ iteration.traces.onPush((traces) => {
105
+ for (const trace of traces) {
106
+ onTrace == null ? void 0 : onTrace({ trace, iteration: ctx.iterations.length });
107
+ }
108
+ })
109
+ );
110
+ try {
111
+ await executeIteration({
112
+ iteration,
113
+ ctx,
114
+ cognitive,
115
+ abortSignal: signal,
116
+ onExit,
117
+ onBeforeExecution
118
+ });
119
+ } catch (err) {
120
+ iteration.end({
121
+ type: "execution_error",
122
+ execution_error: {
123
+ message: "An unexpected error occurred: " + getErrorMessage(err),
124
+ stack: cleanStackTrace(err.stack ?? "No stack trace available")
125
+ }
126
+ });
127
+ }
128
+ try {
129
+ await (onIterationEnd == null ? void 0 : onIterationEnd(iteration));
130
+ } catch (err) {
131
+ console.error(err);
132
+ }
133
+ if (iteration.status.type === "exit_success") {
134
+ const exitName = iteration.status.exit_success.exit_name;
135
+ return new SuccessExecutionResult(ctx, {
136
+ exit: iteration.exits.find((x) => x.name === exitName),
137
+ result: iteration.status.exit_success.return_value
138
+ });
139
+ }
140
+ if (iteration.status.type === "callback_requested") {
141
+ return new PartialExecutionResult(
142
+ ctx,
143
+ iteration.status.callback_requested.signal,
144
+ Snapshot.fromSignal(iteration.status.callback_requested.signal)
145
+ );
146
+ }
147
+ if (iteration.status.type === "thinking_requested" || iteration.status.type === "exit_error" || iteration.status.type === "execution_error" || iteration.status.type === "invalid_code_error") {
148
+ continue;
149
+ }
150
+ return new ErrorExecutionResult(ctx, iteration.error ?? `Unknown error. Status: ${iteration.status.type}`);
151
+ }
152
+ } catch (error) {
153
+ return new ErrorExecutionResult(ctx, error ?? "Unknown error");
154
+ } finally {
155
+ for (const cleanup of cleanups) {
156
+ try {
157
+ cleanup();
158
+ } catch {
159
+ }
160
+ }
161
+ }
162
+ };
163
+ var executeIteration = async ({
164
+ iteration,
165
+ ctx,
166
+ cognitive,
167
+ abortSignal,
168
+ onExit,
169
+ onBeforeExecution
170
+ }) => {
171
+ var _a, _b, _c, _d, _e;
172
+ let startedAt = Date.now();
173
+ const traces = iteration.traces;
174
+ const modelLimit = 128e3;
175
+ const responseLengthBuffer = getModelOutputLimit(modelLimit);
176
+ const messages = truncateWrappedContent({
177
+ messages: iteration.messages,
178
+ tokenLimit: modelLimit - responseLengthBuffer,
179
+ throwOnFailure: false
180
+ }).filter(
181
+ (x) => (
182
+ // Filter out empty messages, as they are not valid inputs for the LLM
183
+ // This can happen when a message is truncated and the content is empty
184
+ x.content.trim().length > 0
185
+ )
186
+ );
187
+ traces.push({
188
+ type: "llm_call_started",
189
+ started_at: startedAt,
190
+ ended_at: startedAt,
191
+ model: ctx.model ?? ""
192
+ });
193
+ const output = await cognitive.generateContent({
194
+ signal: abortSignal,
195
+ systemPrompt: (_a = messages.find((x) => x.role === "system")) == null ? void 0 : _a.content,
196
+ model: ctx.model,
197
+ temperature: ctx.temperature,
198
+ responseFormat: "text",
199
+ messages: messages.filter((x) => x.role === "user" || x.role === "assistant").map(
200
+ (x) => ({
201
+ role: x.role === "user" ? "user" : "assistant",
202
+ type: "text",
203
+ content: x.content
204
+ })
205
+ ),
206
+ stopSequences: ctx.version.getStopTokens()
207
+ });
208
+ const out = ((_c = (_b = output.output.choices) == null ? void 0 : _b[0]) == null ? void 0 : _c.type) === "text" && typeof ((_d = output.output.choices) == null ? void 0 : _d[0].content) === "string" ? output.output.choices[0].content : null;
209
+ if (!out) {
210
+ throw new Error("No output from LLM");
211
+ }
212
+ const assistantResponse = ctx.version.parseAssistantResponse(out);
213
+ iteration.code = assistantResponse.code.trim();
214
+ if (typeof onBeforeExecution === "function") {
215
+ try {
216
+ await onBeforeExecution(iteration);
217
+ } catch (err) {
218
+ if (err instanceof ThinkSignal) {
219
+ return iteration.end({
220
+ type: "thinking_requested",
221
+ thinking_requested: {
222
+ variables: err.context,
223
+ reason: err.reason
224
+ }
225
+ });
226
+ }
227
+ return iteration.end({
228
+ type: "execution_error",
229
+ execution_error: {
230
+ message: `Error in onBeforeExecution hook: ${getErrorMessage(err)}`,
231
+ stack: cleanStackTrace(err.stack ?? "No stack trace available")
232
+ }
233
+ });
234
+ }
235
+ }
236
+ iteration.llm = {
237
+ cached: output.meta.cached || false,
238
+ ended_at: Date.now(),
239
+ started_at: startedAt,
240
+ status: "success",
241
+ tokens: output.meta.tokens.input + output.meta.tokens.output,
242
+ spend: output.meta.cost.input + output.meta.cost.output,
243
+ output: assistantResponse.raw,
244
+ model: `${output.meta.model.integration}:${output.meta.model.model}`
245
+ };
246
+ traces.push({
247
+ type: "llm_call_success",
248
+ started_at: startedAt,
249
+ ended_at: iteration.llm.ended_at,
250
+ model: ctx.model ?? "",
251
+ code: iteration.code
252
+ });
253
+ const vmContext = { ...stripInvalidIdentifiers(iteration.variables) };
254
+ for (const obj of iteration.objects) {
255
+ const internalValues = {};
256
+ const instance = {};
257
+ for (const { name, value, writable, type } of obj.properties ?? []) {
258
+ internalValues[name] = value;
259
+ const initialValue = value;
260
+ const schema = type ?? z.any();
261
+ Object.defineProperty(instance, name, {
262
+ enumerable: true,
263
+ configurable: true,
264
+ get() {
265
+ return internalValues[name];
266
+ },
267
+ set(value2) {
268
+ if (isEqual_default(value2, internalValues[name])) {
269
+ return;
270
+ }
271
+ if (!writable) {
272
+ throw new AssignmentError(`Property ${obj.name}.${name} is read-only and cannot be modified`);
273
+ }
274
+ if (value2 === internalValues[name]) {
275
+ return;
276
+ }
277
+ const parsed = schema.safeParse(value2);
278
+ if (!parsed.success) {
279
+ throw new AssignmentError(
280
+ `Invalid value for Object property ${obj.name}.${name}: ${getErrorMessage(parsed.error)}`
281
+ );
282
+ }
283
+ internalValues[name] = parsed.data;
284
+ traces.push({
285
+ type: "property",
286
+ started_at: Date.now(),
287
+ object: obj.name,
288
+ property: name,
289
+ value: parsed.data
290
+ });
291
+ iteration.trackMutation({ object: obj.name, property: name, before: initialValue, after: parsed.data });
292
+ }
293
+ });
294
+ }
295
+ for (const tool of obj.tools ?? []) {
296
+ instance[tool.name] = wrapTool({ tool, traces, object: obj.name });
297
+ }
298
+ Object.preventExtensions(instance);
299
+ Object.seal(instance);
300
+ vmContext[obj.name] = instance;
301
+ }
302
+ for (const tool of iteration.tools) {
303
+ const wrapped = wrapTool({ tool, traces });
304
+ for (const key of [tool.name, ...tool.aliases ?? []]) {
305
+ vmContext[key] = wrapped;
306
+ }
307
+ }
308
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
309
+ traces.push({
310
+ type: "abort_signal",
311
+ started_at: Date.now(),
312
+ reason: "The operation was aborted by user."
313
+ });
314
+ return iteration.end({
315
+ type: "aborted",
316
+ aborted: {
317
+ reason: (abortSignal == null ? void 0 : abortSignal.reason) ?? "The operation was aborted"
318
+ }
319
+ });
320
+ }
321
+ startedAt = Date.now();
322
+ const result = await runAsyncFunction(vmContext, iteration.code, traces, abortSignal, ctx.timeout).catch(
323
+ (err) => {
324
+ return {
325
+ success: false,
326
+ error: err,
327
+ lines_executed: [],
328
+ traces: [],
329
+ variables: {}
330
+ };
331
+ }
332
+ );
333
+ if (result.error && result.error instanceof InvalidCodeError) {
334
+ return iteration.end({
335
+ type: "invalid_code_error",
336
+ invalid_code_error: {
337
+ message: result.error.message
338
+ }
339
+ });
340
+ }
341
+ traces.push({
342
+ type: "code_execution",
343
+ lines_executed: result.lines_executed ?? 0,
344
+ started_at: startedAt,
345
+ ended_at: Date.now()
346
+ });
347
+ if (result.error && result.error instanceof CodeExecutionError) {
348
+ return iteration.end({
349
+ type: "execution_error",
350
+ execution_error: {
351
+ message: result.error.message,
352
+ stack: cleanStackTrace(result.error.stacktrace ?? result.error.stack ?? "No stack trace available")
353
+ }
354
+ });
355
+ }
356
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
357
+ return iteration.end({
358
+ type: "aborted",
359
+ aborted: {
360
+ reason: (abortSignal == null ? void 0 : abortSignal.reason) ?? "The operation was aborted"
361
+ }
362
+ });
363
+ }
364
+ if (!result.success) {
365
+ return iteration.end({
366
+ type: "execution_error",
367
+ execution_error: {
368
+ message: ((_e = result == null ? void 0 : result.error) == null ? void 0 : _e.message) ?? "Unknown error occurred",
369
+ stack: cleanStackTrace(result.error.stack ?? "No stack trace available")
370
+ }
371
+ });
372
+ }
373
+ if (result.signal instanceof ThinkSignal) {
374
+ return iteration.end({
375
+ type: "thinking_requested",
376
+ thinking_requested: {
377
+ variables: result.signal.context,
378
+ reason: result.signal.reason
379
+ }
380
+ });
381
+ }
382
+ if (result.signal instanceof SnapshotSignal) {
383
+ return iteration.end({
384
+ type: "callback_requested",
385
+ callback_requested: {
386
+ signal: result.signal
387
+ }
388
+ });
389
+ }
390
+ const validActions = [...iteration.exits.map((x) => x.name.toLowerCase()), "think"];
391
+ let returnValue = result.success && result.return_value ? result.return_value : null;
392
+ const returnAction = returnValue == null ? void 0 : returnValue.action;
393
+ const returnExit = iteration.exits.find((x) => x.name.toLowerCase() === (returnAction == null ? void 0 : returnAction.toLowerCase())) ?? iteration.exits.find((x) => x.aliases.some((a) => a.toLowerCase() === (returnAction == null ? void 0 : returnAction.toLowerCase())));
394
+ if (returnAction === "think") {
395
+ const variables = omit_default(returnValue ?? {}, "action");
396
+ if (isPlainObject_default(variables) && Object.keys(variables).length > 0) {
397
+ return iteration.end({
398
+ type: "thinking_requested",
399
+ thinking_requested: {
400
+ variables,
401
+ reason: "Thinking requested"
402
+ }
403
+ });
404
+ }
405
+ return iteration.end({
406
+ type: "thinking_requested",
407
+ thinking_requested: {
408
+ reason: "Thinking requested",
409
+ variables: iteration.variables
410
+ }
411
+ });
412
+ }
413
+ if (!returnAction) {
414
+ return iteration.end({
415
+ type: "exit_error",
416
+ exit_error: {
417
+ exit: "n/a",
418
+ message: `Code did not return an action. Valid actions are: ${validActions.join(", ")}`,
419
+ return_value: returnValue
420
+ }
421
+ });
422
+ }
423
+ if (!returnExit) {
424
+ return iteration.end({
425
+ type: "exit_error",
426
+ exit_error: {
427
+ exit: returnAction,
428
+ message: `Exit "${returnAction}" not found. Valid actions are: ${validActions.join(", ")}`,
429
+ return_value: returnValue
430
+ }
431
+ });
432
+ }
433
+ if (returnExit.zSchema) {
434
+ const parsed = returnExit.zSchema.safeParse(returnValue == null ? void 0 : returnValue.value);
435
+ if (!parsed.success) {
436
+ return iteration.end({
437
+ type: "exit_error",
438
+ exit_error: {
439
+ exit: returnExit.name,
440
+ message: `Invalid return value for exit ${returnExit.name}: ${getErrorMessage(parsed.error)}`,
441
+ return_value: returnValue
442
+ }
443
+ });
444
+ }
445
+ returnValue = { action: returnExit.name, value: parsed.data };
446
+ }
447
+ try {
448
+ await (onExit == null ? void 0 : onExit({
449
+ exit: returnExit,
450
+ result: returnValue == null ? void 0 : returnValue.value
451
+ }));
452
+ } catch (err) {
453
+ return iteration.end({
454
+ type: "exit_error",
455
+ exit_error: {
456
+ exit: returnExit.name,
457
+ message: `Error executing exit ${returnExit.name}: ${getErrorMessage(err)}`,
458
+ return_value: returnValue
459
+ }
460
+ });
461
+ }
462
+ return iteration.end({
463
+ type: "exit_success",
464
+ exit_success: {
465
+ exit_name: returnExit.name,
466
+ return_value: returnValue == null ? void 0 : returnValue.value
467
+ }
468
+ });
469
+ };
470
+ function wrapTool({ tool, traces, object }) {
471
+ const getToolInput = (input) => tool.zInput.safeParse(input).data ?? input;
472
+ return function(input) {
473
+ const toolCallId = `tcall_${ulid()}`;
474
+ const alertSlowTool = setTimeout(
475
+ () => traces.push({
476
+ type: "tool_slow",
477
+ tool_name: tool.name,
478
+ tool_call_id: toolCallId,
479
+ started_at: Date.now(),
480
+ input: getToolInput(input),
481
+ object,
482
+ duration: SLOW_TOOL_WARNING
483
+ }),
484
+ SLOW_TOOL_WARNING
485
+ );
486
+ const cancelSlowTool = () => clearTimeout(alertSlowTool);
487
+ const toolStart = Date.now();
488
+ let output;
489
+ let error;
490
+ let success = true;
491
+ const handleSignals = (error2) => {
492
+ if (output === error2) {
493
+ return true;
494
+ }
495
+ if (error2 instanceof SnapshotSignal) {
496
+ error2.toolCall = {
497
+ name: tool.name,
498
+ inputSchema: tool.input,
499
+ outputSchema: tool.output,
500
+ input
501
+ };
502
+ error2.message = Signals.serializeError(error2);
503
+ }
504
+ if (error2 instanceof ThinkSignal) {
505
+ traces.push({
506
+ type: "think_signal",
507
+ started_at: Date.now(),
508
+ line: 0,
509
+ ended_at: Date.now()
510
+ });
511
+ success = true;
512
+ output = error2;
513
+ return true;
514
+ }
515
+ return false;
516
+ };
517
+ try {
518
+ const result = tool.execute(input, {
519
+ callId: toolCallId
520
+ });
521
+ if (result instanceof Promise || (result == null ? void 0 : result.then) && (result == null ? void 0 : result.catch)) {
522
+ return result.then((res) => {
523
+ output = res;
524
+ success = true;
525
+ return res;
526
+ }).catch((err) => {
527
+ if (!handleSignals(err)) {
528
+ success = false;
529
+ error = err;
530
+ }
531
+ throw err;
532
+ }).finally(() => {
533
+ cancelSlowTool();
534
+ traces.push({
535
+ type: "tool_call",
536
+ tool_call_id: toolCallId,
537
+ started_at: toolStart,
538
+ ended_at: Date.now(),
539
+ tool_name: tool.name,
540
+ object,
541
+ input: getToolInput(input),
542
+ output,
543
+ error,
544
+ success
545
+ });
546
+ });
547
+ }
548
+ success = true;
549
+ output = result;
550
+ } catch (err) {
551
+ if (!handleSignals(err)) {
552
+ success = false;
553
+ error = err;
554
+ }
555
+ }
556
+ cancelSlowTool();
557
+ traces.push({
558
+ type: "tool_call",
559
+ tool_call_id: toolCallId,
560
+ started_at: toolStart,
561
+ ended_at: Date.now(),
562
+ tool_name: tool.name,
563
+ object,
564
+ input: getToolInput(input),
565
+ output,
566
+ error,
567
+ success
568
+ });
569
+ if (!success) {
570
+ throw error;
571
+ }
572
+ if (output instanceof VMSignal) {
573
+ throw output;
574
+ }
575
+ return output;
576
+ };
577
+ }
578
+ export {
579
+ _executeContext,
580
+ executeContext
581
+ };
package/dist/llmz.d.ts CHANGED
@@ -1,13 +1,13 @@
1
1
  import { Cognitive, type BotpressClientLike } from '@botpress/cognitive';
2
- import { Component } from './component.js';
2
+ import { Chat } from './chat.js';
3
3
  import { Context, Iteration } from './context.js';
4
- import { Exit } from './exit.js';
4
+ import { Exit, ExitResult } from './exit.js';
5
5
  import { ValueOrGetter } from './getter.js';
6
6
  import { type ObjectInstance } from './objects.js';
7
7
  import { Snapshot } from './snapshots.js';
8
8
  import { type Tool } from './tool.js';
9
- import { TranscriptMessage } from './transcript.js';
10
- import { ExecutionResult, Trace } from './types.js';
9
+ import { Trace } from './types.js';
10
+ import { ExecutionResult } from './result.js';
11
11
  export type ExecutionHooks = {
12
12
  /**
13
13
  * Called after each iteration ends
@@ -19,24 +19,22 @@ export type ExecutionHooks = {
19
19
  trace: Trace;
20
20
  iteration: number;
21
21
  }) => void;
22
- onExit?: <T = unknown>(exit: Exit<T>, value: T) => Promise<void> | void;
22
+ onExit?: <T = unknown>(result: ExitResult<T>) => Promise<void> | void;
23
23
  onBeforeExecution?: (iteration: Iteration) => Promise<void> | void;
24
24
  };
25
25
  type Options = Partial<Pick<Context, 'loop' | 'temperature' | 'model' | 'timeout'>>;
26
26
  export type ExecutionProps = {
27
+ chat?: Chat;
27
28
  instructions?: ValueOrGetter<string, Context>;
28
- components?: ValueOrGetter<Component[], Context>;
29
29
  objects?: ValueOrGetter<ObjectInstance[], Context>;
30
30
  tools?: ValueOrGetter<Tool[], Context>;
31
31
  exits?: ValueOrGetter<Exit[], Context>;
32
- transcript?: ValueOrGetter<TranscriptMessage[], Context>;
33
32
  options?: Options;
34
33
  /** An instance of a Botpress Client, or an instance of Cognitive Client (@botpress/cognitive) */
35
34
  client: Cognitive | BotpressClientLike;
36
35
  signal?: AbortSignal;
37
36
  snapshot?: Snapshot;
38
37
  } & ExecutionHooks;
39
- export declare const llmz: {
40
- executeContext: (props: ExecutionProps) => Promise<ExecutionResult>;
41
- };
38
+ export declare const executeContext: (props: ExecutionProps) => Promise<ExecutionResult>;
39
+ export declare const _executeContext: (props: ExecutionProps) => Promise<ExecutionResult>;
42
40
  export {};
@@ -0,0 +1,33 @@
1
+ import { Context, Iteration } from './context.js';
2
+ import { SnapshotSignal } from './errors.js';
3
+ import { Exit, ExitResult } from './exit.js';
4
+ import { Snapshot } from './snapshots.js';
5
+ export declare abstract class ExecutionResult {
6
+ readonly status: 'success' | 'error' | 'interrupted';
7
+ readonly context: Context;
8
+ protected constructor(status: 'success' | 'error' | 'interrupted', context: Context);
9
+ isSuccess(): this is SuccessExecutionResult;
10
+ isError(): this is ErrorExecutionResult;
11
+ isInterrupted(): this is PartialExecutionResult;
12
+ is<T>(exit: Exit<T>): this is SuccessExecutionResult<T>;
13
+ get output(): unknown | null;
14
+ get iteration(): Iteration | null;
15
+ get iterations(): Iteration[];
16
+ }
17
+ export declare class SuccessExecutionResult<TOutput = unknown> extends ExecutionResult {
18
+ readonly result: ExitResult<TOutput>;
19
+ constructor(context: Context, result: ExitResult<TOutput>);
20
+ get output(): TOutput;
21
+ get iteration(): Iteration;
22
+ }
23
+ export declare class ErrorExecutionResult extends ExecutionResult {
24
+ readonly error: unknown;
25
+ constructor(context: Context, error: unknown);
26
+ get output(): null;
27
+ }
28
+ export declare class PartialExecutionResult extends ExecutionResult {
29
+ readonly signal: SnapshotSignal;
30
+ readonly snapshot: Snapshot;
31
+ constructor(context: Context, signal: SnapshotSignal, snapshot: Snapshot);
32
+ get output(): null;
33
+ }
package/dist/types.d.ts CHANGED
@@ -1,6 +1,4 @@
1
- import { Iteration, type Context } from './context.js';
2
- import { type SnapshotSignal, type VMSignal } from './errors.js';
3
- import { type Snapshot } from './snapshots.js';
1
+ import { type VMSignal } from './errors.js';
4
2
  export declare namespace Traces {
5
3
  type Comment = TraceTemplate<'comment', {
6
4
  comment: string;
@@ -100,36 +98,6 @@ export type ObjectMutation = {
100
98
  before: any;
101
99
  after: any;
102
100
  };
103
- export type SuccessExecutionResult = {
104
- status: 'success';
105
- iterations: Iteration[];
106
- context: Context;
107
- };
108
- export type PartialExecutionResult = {
109
- status: 'interrupted';
110
- iterations: Iteration[];
111
- context: Context;
112
- signal: SnapshotSignal;
113
- snapshot: Snapshot;
114
- };
115
- export type ErrorExecutionResult = {
116
- status: 'error';
117
- iterations: Iteration[];
118
- context: Context;
119
- error: string;
120
- };
121
- export type ExecutionResult = SuccessExecutionResult | PartialExecutionResult | ErrorExecutionResult;
122
- export declare function expectStatus<T extends ExecutionResult['status']>(execution: ExecutionResult, status: T): asserts execution is Extract<ExecutionResult, {
123
- status: T;
124
- }>;
125
- export type Tool = {
126
- name: string;
127
- aliases?: string[];
128
- description?: string;
129
- input?: unknown;
130
- output?: unknown;
131
- metadata?: Record<string, any>;
132
- };
133
101
  export type ZuiType<Output = any, Input = Output> = {
134
102
  readonly __type__: 'ZuiType';
135
103
  readonly _output: Output;