llmz 0.6.0 → 0.6.2

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 (110) hide show
  1. package/DOCS.md +1 -3
  2. package/dist/_baseForOwn-CFhWe_W6.js +48 -0
  3. package/dist/_baseForOwn-buOZDFbK.cjs +103 -0
  4. package/dist/_baseIteratee-CF4qP2a8.cjs +2377 -0
  5. package/dist/_baseIteratee-P_firB7b.js +2138 -0
  6. package/dist/_getPrototype-CG7Dxrrz.js +6 -0
  7. package/dist/_getPrototype-DQDlNVVM.cjs +10 -0
  8. package/dist/_overArg-C5Hy7oCi.cjs +196 -0
  9. package/dist/_overArg-CRYbj1NH.js +155 -0
  10. package/dist/citations.d.ts +11 -11
  11. package/dist/component-BwixNVH8.cjs +73 -0
  12. package/dist/component-DGG7d_Mz.js +44 -0
  13. package/dist/context.d.ts +8 -8
  14. package/dist/custom-client-BPmEoWKu.cjs +2618 -0
  15. package/dist/custom-client-NUoxrFQh.js +2547 -0
  16. package/dist/dual-modes-D_p-jedw.js +2750 -0
  17. package/dist/dual-modes-wAOAlaBS.cjs +2840 -0
  18. package/dist/errors-C962uJdS.cjs +220 -0
  19. package/dist/errors-Cg1G0Awu.js +161 -0
  20. package/dist/execute-BEaq3jkV.cjs +1003 -0
  21. package/dist/execute-DYvFRs54.js +1001 -0
  22. package/dist/exit-BGi0Kk0y.cjs +428 -0
  23. package/dist/exit-CDdxDBRT.js +417 -0
  24. package/dist/index.cjs +1786 -1489
  25. package/dist/index.d.ts +10 -9
  26. package/dist/index.js +1721 -1479
  27. package/dist/index.workerd.js +17534 -16875
  28. package/dist/isEmpty-BhJRCqIF.js +52 -0
  29. package/dist/isEmpty-LY533Wmh.cjs +57 -0
  30. package/dist/isPlainObject-CSxXVKCk.cjs +56 -0
  31. package/dist/isPlainObject-D39AzPO2.js +51 -0
  32. package/dist/jsx-BWvT6ukg.cjs +75 -0
  33. package/dist/jsx-CIgdGGVs.js +52 -0
  34. package/dist/jsx.d.ts +2 -2
  35. package/dist/prompts/chat-mode/system.md.d.ts +1 -1
  36. package/dist/prompts/chat-mode/user.md.d.ts +1 -1
  37. package/dist/prompts/worker-mode/system.md.d.ts +1 -1
  38. package/dist/prompts/worker-mode/user.md.d.ts +1 -1
  39. package/dist/quickjs-variant-BYhMBpwU.js +45 -0
  40. package/dist/quickjs-variant-CsIwTVFC.cjs +56 -0
  41. package/dist/quickjs-variant.workerd.d.ts +1 -1
  42. package/dist/result.d.ts +12 -12
  43. package/dist/rolldown-runtime-EAsCxrDo.js +14 -0
  44. package/dist/runtime/interpret-result.d.ts +1 -1
  45. package/dist/snapshots.d.ts +5 -5
  46. package/dist/stack-traces-BIE_5Xwf.js +21 -0
  47. package/dist/stack-traces-ntw_qhoy.cjs +26 -0
  48. package/dist/tool-CAo-BQHs.js +643 -0
  49. package/dist/tool-DdPZb0JW.cjs +654 -0
  50. package/dist/tool.d.ts +3 -3
  51. package/dist/truncator-B6aaJaN1.cjs +276 -0
  52. package/dist/truncator-DZqEqnpD.js +253 -0
  53. package/dist/typings-BwAz_TM9.cjs +784 -0
  54. package/dist/typings-CrBa7Tyy.js +743 -0
  55. package/dist/uniq-BYQ7GWwb.js +183 -0
  56. package/dist/uniq-G872RWmE.cjs +200 -0
  57. package/dist/utils-UBeAFeEI.js +950 -0
  58. package/dist/utils-ZpJm00ed.cjs +1075 -0
  59. package/dist/vm/errors.d.ts +2 -2
  60. package/dist/vm-BjkJqSQH.cjs +3438 -0
  61. package/dist/vm-C5vf1LH3.js +3436 -0
  62. package/package.json +7 -7
  63. package/dist/chunk-34GJUS6U.js +0 -3266
  64. package/dist/chunk-3UZKLXAD.cjs +0 -3249
  65. package/dist/chunk-4POZJQXN.js +0 -1530
  66. package/dist/chunk-5WBNTV42.cjs +0 -1530
  67. package/dist/chunk-5ZF6NTYI.cjs +0 -33
  68. package/dist/chunk-72ZWBNZV.js +0 -173
  69. package/dist/chunk-DDSJTR6Q.cjs +0 -257
  70. package/dist/chunk-GDJTKI7J.js +0 -792
  71. package/dist/chunk-GLXADNTR.js +0 -199
  72. package/dist/chunk-GOWPACSK.cjs +0 -199
  73. package/dist/chunk-HB2G32AK.js +0 -257
  74. package/dist/chunk-HC2QZTVT.cjs +0 -3266
  75. package/dist/chunk-HEAQAEFZ.cjs +0 -173
  76. package/dist/chunk-HMMM32RG.cjs +0 -792
  77. package/dist/chunk-I56MPOVG.cjs +0 -62
  78. package/dist/chunk-KIN7Y247.cjs +0 -32
  79. package/dist/chunk-KTDBAJBB.cjs +0 -1685
  80. package/dist/chunk-KWQTYXAT.js +0 -62
  81. package/dist/chunk-LOX7GOR6.js +0 -1685
  82. package/dist/chunk-PK72FAKD.cjs +0 -175
  83. package/dist/chunk-PZE6PIPG.cjs +0 -621
  84. package/dist/chunk-RGUG3UMF.cjs +0 -26
  85. package/dist/chunk-TDALRNGL.js +0 -621
  86. package/dist/chunk-UGHFNCPD.js +0 -26
  87. package/dist/chunk-WSVDMGMR.js +0 -175
  88. package/dist/chunk-XTEHT2TK.js +0 -33
  89. package/dist/chunk-YEAWWJSJ.js +0 -32
  90. package/dist/chunk-YRS7KRKP.js +0 -3249
  91. package/dist/component-2NYFY6CW.cjs +0 -14
  92. package/dist/component-ASNZHQUR.js +0 -14
  93. package/dist/dual-modes-S5TJ5JVJ.js +0 -10
  94. package/dist/dual-modes-TCMWBZIH.cjs +0 -10
  95. package/dist/execute-FF7D46TY.js +0 -1109
  96. package/dist/execute-IK6O4SU2.cjs +0 -1109
  97. package/dist/exit-MX56VN2C.cjs +0 -8
  98. package/dist/exit-UQ3EUX5D.js +0 -8
  99. package/dist/jsx-DDZ63UUF.js +0 -13
  100. package/dist/jsx-ULPWX5TW.cjs +0 -13
  101. package/dist/tool-KD7FL45V.js +0 -11
  102. package/dist/tool-VE2YHIY2.cjs +0 -11
  103. package/dist/truncator-73RCL52Y.js +0 -12
  104. package/dist/truncator-FZNLYSDL.cjs +0 -12
  105. package/dist/typings-E2RROCLT.js +0 -10
  106. package/dist/typings-LQOBZXSO.cjs +0 -10
  107. package/dist/utils-IATCUNKF.js +0 -43
  108. package/dist/utils-ITB4NEL7.cjs +0 -43
  109. package/dist/vm-6D3IIIU7.cjs +0 -12
  110. package/dist/vm-QO5FSGPN.js +0 -12
@@ -1,621 +0,0 @@
1
- import {
2
- getTypings
3
- } from "./chunk-GDJTKI7J.js";
4
- import {
5
- fromJSONSchemaCompat,
6
- isJsonSchema,
7
- isValidIdentifier,
8
- isZuiSchema
9
- } from "./chunk-GLXADNTR.js";
10
- import {
11
- isEmpty_default,
12
- uniq_default
13
- } from "./chunk-34GJUS6U.js";
14
-
15
- // src/tool.ts
16
- import { z as z2, transforms } from "@bpinternal/zui";
17
-
18
- // src/convert.ts
19
- import { z } from "@bpinternal/zui";
20
- function convertObjectToZuiLiterals(obj, nested = false) {
21
- if (typeof obj === "string") {
22
- return z.literal(obj).catch(() => obj);
23
- }
24
- if (typeof obj === "number") {
25
- return z.literal(obj).catch(() => obj);
26
- }
27
- if (typeof obj === "boolean") {
28
- return z.literal(obj).catch(() => obj);
29
- }
30
- if (Array.isArray(obj)) {
31
- if (obj.length === 0) {
32
- return z.tuple([]).catch(() => obj);
33
- }
34
- const items = obj.map((child) => convertObjectToZuiLiterals(child, true));
35
- return z.tuple(items).catch(() => obj);
36
- }
37
- if (obj !== null && typeof obj === "object") {
38
- const shape = {};
39
- for (const [key, value] of Object.entries(obj)) {
40
- shape[key] = convertObjectToZuiLiterals(value, true);
41
- }
42
- if (nested) {
43
- return z.object(shape).catch(() => obj);
44
- }
45
- if (Object.keys(shape).length === 0) {
46
- return z.object({}).catch(() => obj);
47
- }
48
- return shape;
49
- }
50
- if (obj === void 0) {
51
- return z.undefined().catch(() => void 0);
52
- }
53
- if (obj === null) {
54
- return z.null().catch(() => null);
55
- }
56
- throw new Error(`Unsupported object type ${typeof obj}, ${obj})`);
57
- }
58
-
59
- // src/tool.ts
60
- var Tool = class _Tool {
61
- _staticInputValues;
62
- name;
63
- aliases = [];
64
- description;
65
- metadata;
66
- input;
67
- output;
68
- retry;
69
- MAX_RETRIES = 1e3;
70
- /**
71
- * Sets static input values that will be automatically applied to all tool calls.
72
- *
73
- * Static values allow you to pre-configure certain parameters that shouldn't change
74
- * between calls, effectively removing them from the LLM's control while ensuring
75
- * they're always present when the tool executes.
76
- *
77
- * @param values - Partial input values to apply statically. Set to null/undefined to clear.
78
- * @returns The tool instance for method chaining
79
- *
80
- * @example
81
- * ```typescript
82
- * // Create a tool with configurable parameters
83
- * const searchTool = new Tool({
84
- * name: 'search',
85
- * input: z.object({
86
- * query: z.string(),
87
- * maxResults: z.number().default(10),
88
- * includeSnippets: z.boolean().default(true),
89
- * }),
90
- * handler: async ({ query, maxResults, includeSnippets }) => {
91
- * // Implementation
92
- * },
93
- * })
94
- *
95
- * // Create a restricted version with static values
96
- * const restrictedSearch = searchTool.setStaticInputValues({
97
- * maxResults: 5, // Always limit to 5 results
98
- * includeSnippets: false, // Never include snippets
99
- * })
100
- *
101
- * // LLM can only control 'query' parameter now
102
- * // The tool will always use maxResults: 5, includeSnippets: false
103
- * ```
104
- *
105
- * @example
106
- * ```typescript
107
- * // Clear static values
108
- * const unrestricted = restrictedTool.setStaticInputValues(null)
109
- * ```
110
- */
111
- setStaticInputValues(values) {
112
- if (values === null || values === void 0) {
113
- this._staticInputValues = void 0;
114
- return this;
115
- }
116
- const input = this.input ? fromJSONSchemaCompat(this.input) : z2.any();
117
- if (z2.is.zuiObject(input) && typeof values !== "object") {
118
- throw new Error(
119
- `Invalid static input values for tool ${this.name}. Expected an object, but got type "${typeof values}"`
120
- );
121
- }
122
- if (z2.is.zuiArray(input) && !Array.isArray(values)) {
123
- throw new Error(
124
- `Invalid static input values for tool ${this.name}. Expected an array, but got type "${typeof values}"`
125
- );
126
- }
127
- this._staticInputValues = values;
128
- return this;
129
- }
130
- /**
131
- * Gets the computed input schema with static values applied.
132
- *
133
- * This property returns the final input schema that will be used for validation,
134
- * including any static input values that have been set via setStaticInputValues().
135
- *
136
- * @returns The Zui schema for input validation
137
- * @internal
138
- */
139
- get zInput() {
140
- let input;
141
- if (this.input) {
142
- try {
143
- input = transforms.fromJSONSchema(this.input);
144
- } catch {
145
- input = transforms.fromJSONSchemaLegacy(this.input);
146
- }
147
- } else {
148
- input = z2.any();
149
- }
150
- if (!isEmpty_default(this._staticInputValues)) {
151
- if (z2.is.zuiObject(input)) {
152
- const inputExtensions = convertObjectToZuiLiterals(this._staticInputValues);
153
- input = input.extend(inputExtensions);
154
- } else if (z2.is.zuiArray(input)) {
155
- const inputExtensions = convertObjectToZuiLiterals(this._staticInputValues);
156
- input = z2.array(input.element.extend(inputExtensions));
157
- } else {
158
- const inputExtensions = convertObjectToZuiLiterals(
159
- this._staticInputValues
160
- );
161
- input = inputExtensions;
162
- }
163
- }
164
- return input;
165
- }
166
- /**
167
- * Gets the output schema for validation.
168
- *
169
- * @returns The Zui schema for output validation
170
- * @internal
171
- */
172
- get zOutput() {
173
- let output = z2.void();
174
- if (this.output) {
175
- try {
176
- output = transforms.fromJSONSchema(this.output);
177
- } catch {
178
- output = transforms.fromJSONSchemaLegacy(this.output);
179
- }
180
- }
181
- return z2.promise(output);
182
- }
183
- /**
184
- * Renames the tool and updates its aliases.
185
- *
186
- * @param name - New name for the tool (must be a valid identifier)
187
- * @returns The tool instance for method chaining
188
- * @throws Error if the name is not a valid identifier
189
- *
190
- * @example
191
- * ```typescript
192
- * const weatherTool = new Tool({ name: 'getWeather', ... })
193
- * weatherTool.rename('getCurrentWeather')
194
- * console.log(weatherTool.name) // 'getCurrentWeather'
195
- * ```
196
- */
197
- rename(name) {
198
- const before = this.name;
199
- if (!isValidIdentifier(name)) {
200
- throw new Error(
201
- `Invalid name for tool ${name}. A tool name must start with a letter and contain only letters, numbers, and underscores. It must be 1-50 characters long.`
202
- );
203
- }
204
- this.name = name;
205
- this.aliases = uniq_default([name, ...this.aliases.map((alias) => alias === before ? name : alias)]);
206
- return this;
207
- }
208
- /**
209
- * Creates a new tool based on this one with modified properties.
210
- *
211
- * Clone allows you to create variations of existing tools with different names,
212
- * schemas, handlers, or other configuration. This is useful for creating specialized
213
- * versions of tools or adding additional functionality.
214
- *
215
- * @param props - Properties to override in the cloned tool
216
- * @returns A new Tool instance with the specified modifications
217
- * @throws Error if cloning fails due to invalid configuration
218
- *
219
- * @example
220
- * ```typescript
221
- * // Create a basic search tool
222
- * const basicSearch = new Tool({
223
- * name: 'search',
224
- * input: z.object({ query: z.string() }),
225
- * output: z.object({ results: z.array(z.string()) }),
226
- * handler: async ({ query }) => ({ results: await search(query) }),
227
- * })
228
- *
229
- * // Clone with enhanced output schema
230
- * const enhancedSearch = basicSearch.clone({
231
- * name: 'enhancedSearch',
232
- * description: 'Search with additional metadata',
233
- * output: (original) => original!.extend({
234
- * totalResults: z.number(),
235
- * searchTime: z.number(),
236
- * }),
237
- * handler: async ({ query }) => {
238
- * const startTime = Date.now()
239
- * const results = await search(query)
240
- * return {
241
- * results: results.items,
242
- * totalResults: results.total,
243
- * searchTime: Date.now() - startTime,
244
- * }
245
- * },
246
- * })
247
- * ```
248
- *
249
- * @example
250
- * ```typescript
251
- * // Clone with restricted access
252
- * const restrictedTool = adminTool.clone({
253
- * name: 'userTool',
254
- * handler: async (input, ctx) => {
255
- * // Add authorization check
256
- * if (!isAuthorized(ctx.callId)) {
257
- * throw new Error('Unauthorized access')
258
- * }
259
- * return adminTool.execute(input, ctx)
260
- * },
261
- * })
262
- * ```
263
- */
264
- clone(props = {}) {
265
- var _a, _b;
266
- try {
267
- let zInput;
268
- if (this.input) {
269
- try {
270
- zInput = transforms.fromJSONSchema(this.input);
271
- } catch {
272
- zInput = transforms.fromJSONSchemaLegacy(this.input);
273
- }
274
- }
275
- let zOutput;
276
- if (this.output) {
277
- try {
278
- zOutput = transforms.fromJSONSchema(this.output);
279
- } catch {
280
- zOutput = transforms.fromJSONSchemaLegacy(this.output);
281
- }
282
- }
283
- return new _Tool({
284
- name: props.name ?? this.name,
285
- aliases: props.aliases ?? [...this.aliases],
286
- description: props.description ?? this.description,
287
- metadata: JSON.parse(JSON.stringify(props.metadata ?? this.metadata)),
288
- input: typeof props.input === "function" ? (_a = props.input) == null ? void 0 : _a.call(props, zInput) : z2.is.zuiType(props.input) ? props.input : zInput,
289
- output: typeof props.output === "function" ? (_b = props.output) == null ? void 0 : _b.call(props, zOutput) : z2.is.zuiType(props.output) ? props.output : zOutput,
290
- handler: props.handler ?? this._handler,
291
- retry: props.retry ?? this.retry
292
- }).setStaticInputValues(props.staticInputValues ?? this._staticInputValues);
293
- } catch (e) {
294
- throw new Error(`Failed to clone tool "${this.name}": ${e}`);
295
- }
296
- }
297
- _handler;
298
- /**
299
- * Creates a new Tool instance.
300
- *
301
- * @param props - Tool configuration properties
302
- * @param props.name - Unique tool name (must be valid TypeScript identifier)
303
- * @param props.description - Human-readable description for the LLM
304
- * @param props.input - Zui/Zod schema for input validation (optional)
305
- * @param props.output - Zui/Zod schema for output validation (optional)
306
- * @param props.handler - Async function that implements the tool logic
307
- * @param props.aliases - Alternative names for the tool (optional)
308
- * @param props.metadata - Additional metadata for the tool (optional)
309
- * @param props.staticInputValues - Default input values (optional)
310
- * @param props.retry - Custom retry logic function (optional)
311
- *
312
- * @throws Error if name is not a valid identifier
313
- * @throws Error if description is not a string
314
- * @throws Error if metadata is not an object
315
- * @throws Error if handler is not a function
316
- * @throws Error if aliases contains invalid identifiers
317
- * @throws Error if input/output schemas are invalid
318
- *
319
- * @example
320
- * ```typescript
321
- * const weatherTool = new Tool({
322
- * name: 'getCurrentWeather',
323
- * description: 'Fetches current weather data for a given city',
324
- * aliases: ['weather', 'getWeather'], // Alternative names
325
- *
326
- * input: z.object({
327
- * city: z.string().min(1).describe('City name to get weather for'),
328
- * units: z.enum(['celsius', 'fahrenheit']).default('celsius'),
329
- * includeHourly: z.boolean().default(false),
330
- * }),
331
- *
332
- * output: z.object({
333
- * temperature: z.number(),
334
- * description: z.string(),
335
- * humidity: z.number().min(0).max(100),
336
- * hourlyForecast: z.array(z.object({
337
- * hour: z.number(),
338
- * temp: z.number(),
339
- * condition: z.string(),
340
- * })).optional(),
341
- * }),
342
- *
343
- * async handler({ city, units, includeHourly }) {
344
- * const response = await fetch(`/api/weather?city=${encodeURIComponent(city)}&units=${units}`)
345
- * const data = await response.json()
346
- *
347
- * const result = {
348
- * temperature: data.main.temp,
349
- * description: data.weather[0].description,
350
- * humidity: data.main.humidity,
351
- * }
352
- *
353
- * if (includeHourly) {
354
- * result.hourlyForecast = data.hourly?.slice(0, 24) || []
355
- * }
356
- *
357
- * return result
358
- * },
359
- *
360
- * // Optional: Add retry logic for network errors
361
- * retry: ({ attempt, error }) => {
362
- * return attempt < 3 && error.message.includes('network')
363
- * },
364
- *
365
- * // Optional: Add metadata
366
- * metadata: {
367
- * category: 'weather',
368
- * rateLimit: 100,
369
- * cacheable: true,
370
- * },
371
- * })
372
- * ```
373
- */
374
- constructor(props) {
375
- if (!isValidIdentifier(props.name)) {
376
- throw new Error(
377
- `Invalid name for tool ${props.name}. A tool name must start with a letter and contain only letters, numbers, and underscores. It must be 1-50 characters long.`
378
- );
379
- }
380
- if (props.description !== void 0 && typeof props.description !== "string") {
381
- throw new Error(
382
- `Invalid description for tool ${props.name}. Expected a string, but got type "${typeof props.description}"`
383
- );
384
- }
385
- if (props.metadata !== void 0 && typeof props.metadata !== "object") {
386
- throw new Error(
387
- `Invalid metadata for tool ${props.name}. Expected an object, but got type "${typeof props.metadata}"`
388
- );
389
- }
390
- if (typeof props.handler !== "function") {
391
- throw new Error(
392
- `Invalid handler for tool ${props.name}. Expected a function, but got type "${typeof props.handler}"`
393
- );
394
- }
395
- if (props.aliases !== void 0 && !Array.isArray(props.aliases)) {
396
- throw new Error(
397
- `Invalid aliases for tool ${props.name}. Expected an array, but got type "${typeof props.aliases}"`
398
- );
399
- }
400
- if (props.aliases && props.aliases.some((alias) => !isValidIdentifier(alias))) {
401
- throw new Error(`Invalid aliases for tool ${props.name}. Expected an array of valid identifiers.`);
402
- }
403
- if (typeof props.input !== "undefined") {
404
- if (isZuiSchema(props.input)) {
405
- try {
406
- this.input = transforms.toJSONSchema(props.input);
407
- } catch {
408
- this.input = transforms.toJSONSchemaLegacy(props.input);
409
- }
410
- } else if (isJsonSchema(props.input)) {
411
- this.input = props.input;
412
- } else {
413
- throw new Error(
414
- `Invalid input schema for tool ${props.name}. Expected a ZodType or JSONSchema, but got type "${typeof props.input}"`
415
- );
416
- }
417
- }
418
- if (typeof props.output !== "undefined") {
419
- if (isZuiSchema(props.output)) {
420
- try {
421
- this.output = transforms.toJSONSchema(props.output);
422
- } catch {
423
- this.output = transforms.toJSONSchemaLegacy(props.output);
424
- }
425
- } else if (isJsonSchema(props.output)) {
426
- this.output = props.output;
427
- } else {
428
- throw new Error(
429
- `Invalid output schema for tool ${props.name}. Expected a ZodType or JSONSchema, but got type "${typeof props.output}"`
430
- );
431
- }
432
- }
433
- this.name = props.name;
434
- this.aliases = uniq_default([props.name, ...props.aliases ?? []]);
435
- this.description = props.description;
436
- this.metadata = props.metadata ?? {};
437
- this._handler = props.handler;
438
- this.setStaticInputValues(props.staticInputValues);
439
- this.retry = props.retry;
440
- }
441
- async _executeHandler(input, ctx, chat, yieldedCount, setYieldedCount) {
442
- var _a;
443
- const handler = this._handler(input, ctx);
444
- const isGen = typeof handler === "object" && handler !== null && "next" in handler;
445
- if (!isGen) {
446
- return handler;
447
- }
448
- let yieldIndex = 0;
449
- while (true) {
450
- const { value, done } = await handler.next();
451
- if (done) {
452
- return value;
453
- }
454
- if (yieldIndex >= yieldedCount) {
455
- setYieldedCount(yieldIndex + 1);
456
- await ((_a = chat == null ? void 0 : chat.handler) == null ? void 0 : _a.call(chat, value));
457
- }
458
- yieldIndex++;
459
- }
460
- }
461
- /**
462
- * Executes the tool with the given input and context.
463
- *
464
- * This method handles input validation, retry logic, output validation, and error handling.
465
- * It's called internally by the LLMz execution engine when generated code calls the tool.
466
- *
467
- * @param input - Input data to pass to the tool handler
468
- * @param ctx - Tool call context containing call ID and other metadata
469
- * @returns Promise resolving to the tool's output
470
- * @throws Error if input validation fails
471
- * @throws Error if tool execution fails after all retries
472
- *
473
- * @example
474
- * ```typescript
475
- * // Direct tool execution (usually done by LLMz internally)
476
- * const result = await weatherTool.execute(
477
- * { city: 'San Francisco', units: 'fahrenheit' },
478
- * { callId: 'call_123' }
479
- * )
480
- * console.log(result.temperature) // 72
481
- * ```
482
- *
483
- * @internal This method is primarily used internally by the LLMz execution engine
484
- */
485
- async execute(rawInput, ctx, chat) {
486
- var _a;
487
- const isZodObject = this.zInput._def.typeName === "ZodObject";
488
- const input = isZodObject ? rawInput ?? {} : rawInput;
489
- const pInput = this.zInput.safeParse(input);
490
- if (!pInput.success) {
491
- throw new Error(`Tool "${this.name}" received invalid input: ${pInput.error.message}`);
492
- }
493
- let attempt = 0;
494
- let yieldedCount = 0;
495
- while (attempt < this.MAX_RETRIES) {
496
- try {
497
- const result = await this._executeHandler(pInput.data, ctx, chat, yieldedCount, (n) => {
498
- yieldedCount = n;
499
- });
500
- const pOutput = this.zOutput.safeParse(result);
501
- return pOutput.success ? pOutput.data : result;
502
- } catch (err) {
503
- const shouldRetry = await ((_a = this.retry) == null ? void 0 : _a.call(this, {
504
- input: pInput.data,
505
- attempt: ++attempt,
506
- error: err
507
- }));
508
- if (!shouldRetry) {
509
- throw err;
510
- }
511
- }
512
- }
513
- throw new Error(
514
- `Tool "${this.name}" failed after ${this.MAX_RETRIES} attempts. Last error: ${JSON.stringify(input)}`
515
- );
516
- }
517
- /**
518
- * Generates TypeScript type definitions for this tool.
519
- *
520
- * This method creates TypeScript function declarations that are included in the
521
- * LLM's context to help it understand how to call the tool correctly. The generated
522
- * types include parameter types, return types, and JSDoc comments with descriptions.
523
- *
524
- * @returns Promise resolving to TypeScript declaration string
525
- */
526
- async getTypings() {
527
- let input;
528
- if (this.input) {
529
- try {
530
- input = transforms.fromJSONSchema(this.input);
531
- } catch {
532
- input = transforms.fromJSONSchemaLegacy(this.input);
533
- }
534
- }
535
- let output;
536
- if (!this.output || Object.keys(this.output).length === 0) {
537
- output = z2.void();
538
- } else {
539
- try {
540
- output = transforms.fromJSONSchema(this.output);
541
- } catch {
542
- output = transforms.fromJSONSchemaLegacy(this.output);
543
- }
544
- }
545
- if (input && z2.is.zuiObject(input.naked()) && typeof this._staticInputValues === "object" && !isEmpty_default(this._staticInputValues)) {
546
- const inputExtensions = convertObjectToZuiLiterals(this._staticInputValues);
547
- input = input.extend(inputExtensions);
548
- } else if (this._staticInputValues !== void 0) {
549
- input = convertObjectToZuiLiterals(this._staticInputValues);
550
- }
551
- const fnType = z2.function(input, z2.promise(output)).title(this.name).describe(this.description ?? "");
552
- return getTypings(fnType, {
553
- declaration: true
554
- });
555
- }
556
- /**
557
- * Ensures all tools in an array have unique names by appending numbers to duplicates.
558
- *
559
- * When multiple tools have the same name, this method renames them by appending
560
- * incrementing numbers (tool1, tool2, etc.) to avoid conflicts. Tools with already
561
- * unique names are left unchanged.
562
- *
563
- * You usually don't need to call this method directly, as LLMz will automatically detect and rename tools with conflicting names.
564
- *
565
- * @param tools - Array of tools to process for unique names
566
- * @returns Array of tools with guaranteed unique names
567
- *
568
- * @example
569
- * ```typescript
570
- * const tools = [
571
- * new Tool({ name: 'search', handler: async () => {} }),
572
- * new Tool({ name: 'search', handler: async () => {} }),
573
- * new Tool({ name: 'unique', handler: async () => {} }),
574
- * new Tool({ name: 'search', handler: async () => {} }),
575
- * ]
576
- *
577
- * const uniqueTools = Tool.withUniqueNames(tools)
578
- * console.log(uniqueTools.map(t => t.name))
579
- * // Output: ['search1', 'search1', 'unique', 'search']
580
- * // Note: The last occurrence keeps the original name
581
- * ```
582
- *
583
- * @static
584
- */
585
- static withUniqueNames = (tools) => {
586
- const names = /* @__PURE__ */ new Set();
587
- return tools.map((tool) => {
588
- if (tools.filter((t) => t.name === tool.name).length === 1) {
589
- return tool;
590
- }
591
- let counter = 1;
592
- let toolName = tool.name + counter;
593
- while (names.has(toolName)) {
594
- toolName = `${tool.name}${++counter}`;
595
- }
596
- names.add(toolName);
597
- return tool.rename(toolName);
598
- });
599
- };
600
- /**
601
- * Converts the tool to its JSON representation.
602
- *
603
- * @returns JSON representation of the Tool instance
604
- */
605
- toJSON() {
606
- return {
607
- name: this.name,
608
- aliases: [...this.aliases],
609
- description: this.description,
610
- metadata: this.metadata,
611
- input: this.input,
612
- output: this.output,
613
- staticInputValues: this._staticInputValues,
614
- maxRetries: this.MAX_RETRIES
615
- };
616
- }
617
- };
618
-
619
- export {
620
- Tool
621
- };
@@ -1,26 +0,0 @@
1
- // src/quickjs-variant.ts
2
- var getVariant = async () => {
3
- const module = await import("@jitl/quickjs-singlefile-browser-release-sync");
4
- return module.default;
5
- };
6
- var BundledReleaseSyncVariant = {
7
- type: "sync",
8
- importFFI: async () => {
9
- const variant = await getVariant();
10
- return variant.importFFI();
11
- },
12
- importModuleLoader: async () => {
13
- const variant = await getVariant();
14
- return variant.importModuleLoader();
15
- }
16
- };
17
- var _activeVariant = BundledReleaseSyncVariant;
18
- var configureQuickJS = (variant) => {
19
- _activeVariant = variant;
20
- };
21
- var getQuickJSVariant = () => _activeVariant;
22
-
23
- export {
24
- configureQuickJS,
25
- getQuickJSVariant
26
- };