llmz 0.2.3 → 0.3.1

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.
package/dist/context.d.ts CHANGED
@@ -456,7 +456,7 @@ export declare class Iteration implements Serializable<Iteration.JSON> {
456
456
  end(status: IterationStatus): void;
457
457
  toJSON(): {
458
458
  id: string;
459
- messages: LLMzPrompts.Message[];
459
+ messages: import("@botpress/cognitive").CognitiveMessage[];
460
460
  code: string | undefined;
461
461
  model: Models | Models[];
462
462
  temperature: number;
@@ -600,7 +600,7 @@ export declare class Context implements Serializable<Context.JSON> {
600
600
  id: string;
601
601
  iterations: {
602
602
  id: string;
603
- messages: LLMzPrompts.Message[];
603
+ messages: import("@botpress/cognitive").CognitiveMessage[];
604
604
  code: string | undefined;
605
605
  model: Models | Models[];
606
606
  temperature: number;
@@ -1,7 +1,8 @@
1
1
  import { Model } from '@botpress/cognitive';
2
2
  import { RuntimeCognitive } from './runtime/types.js';
3
- export type RuntimeGenerateContentInput = Parameters<RuntimeCognitive['generateContent']>[0];
4
- export type RuntimeGenerateContentOutput = Awaited<ReturnType<RuntimeCognitive['generateContent']>>;
3
+ export type RuntimeGenerateContentInput = Parameters<RuntimeCognitive['generateText']>[0];
4
+ export type RuntimeGenerateContentOptions = Parameters<RuntimeCognitive['generateText']>[1];
5
+ export type RuntimeGenerateContentOutput = Awaited<ReturnType<RuntimeCognitive['generateText']>>;
5
6
  /**
6
7
  * Internal escape hatch for supplying a custom model client that bypasses Cognitive.
7
8
  *
@@ -14,5 +15,5 @@ export declare abstract class _CustomModelClient implements RuntimeCognitive {
14
15
  private readonly ['$$COGNITIVE'];
15
16
  static isCustomClient(obj: any): obj is _CustomModelClient;
16
17
  abstract getModelDetails(model: string): Promise<Model>;
17
- abstract generateContent(input: RuntimeGenerateContentInput): Promise<RuntimeGenerateContentOutput>;
18
+ abstract generateText(input: RuntimeGenerateContentInput, options?: RuntimeGenerateContentOptions): Promise<RuntimeGenerateContentOutput>;
18
19
  }
@@ -135,7 +135,7 @@ var generateCode = async ({
135
135
  onRunStart,
136
136
  onRunComplete
137
137
  }) => {
138
- var _a, _b, _c, _d;
138
+ var _a, _b;
139
139
  const startedAt = Date.now();
140
140
  const traces = iteration.traces;
141
141
  const modelRef = Array.isArray(iteration.model) ? iteration.model[0] : iteration.model;
@@ -166,20 +166,18 @@ var generateCode = async ({
166
166
  type: "llm_call_started",
167
167
  started_at: startedAt,
168
168
  ended_at: startedAt,
169
- model: model.ref
169
+ model: model.id
170
170
  });
171
171
  const input = {
172
- signal: controller.signal,
173
- systemPrompt: (_a = messages.find((x) => x.role === "system")) == null ? void 0 : _a.content,
174
172
  model: iteration.model,
175
173
  temperature: iteration.temperature,
176
174
  responseFormat: "text",
177
175
  reasoningEffort: iteration.reasoningEffort,
178
- messages: messages.filter((x) => x.role !== "system"),
176
+ messages,
179
177
  stopSequences: ctx.version.getStopTokens(),
180
178
  meta: metadata ? { metadata } : void 0
181
179
  };
182
- let output;
180
+ let responseMetadata;
183
181
  let raw;
184
182
  let assistantResponse;
185
183
  let timeToFirstToken;
@@ -224,18 +222,20 @@ var generateCode = async ({
224
222
  }
225
223
  }
226
224
  };
227
- if (typeof cognitive.generateContentStream === "function") {
225
+ if (typeof cognitive.generateTextStream === "function") {
228
226
  const parser = new (0, _chunkOVRDJMZJcjs.StreamingMessageParser)();
229
227
  const fence = new LeadingFenceFilter();
230
228
  const streamController = createJoinedAbortController([controller.signal]);
231
229
  const requestedAt = Date.now();
232
- const stream = cognitive.generateContentStream({
233
- ...input,
234
- signal: streamController.signal,
235
- // Passed through to the cognitive v2 request: fall back to the next
236
- // model/provider when the first token takes too long
237
- ...ctx.maxTimeToFirstToken ? { options: { maxTimeToFirstToken: ctx.maxTimeToFirstToken } } : {}
238
- });
230
+ const stream = cognitive.generateTextStream(
231
+ {
232
+ ...input,
233
+ // Passed through to the cognitive request: fall back to the next
234
+ // model/provider when the first token takes too long
235
+ ...ctx.maxTimeToFirstToken ? { options: { maxTimeToFirstToken: ctx.maxTimeToFirstToken } } : {}
236
+ },
237
+ { signal: streamController.signal }
238
+ );
239
239
  const inactivityTimeout = Math.max(STREAM_INACTIVITY_TIMEOUT, _nullishCoalesce(ctx.maxTimeToFirstToken, () => ( 0)));
240
240
  const nextChunk = async () => {
241
241
  let timer;
@@ -260,9 +260,11 @@ var generateCode = async ({
260
260
  throw new (0, _chunkPK72FAKDcjs.CognitiveError)(`LLM generation failed: ${_chunkGOWPACSKcjs.getErrorMessage.call(void 0, thrown)}`);
261
261
  }
262
262
  if (chunk.done) {
263
- output = chunk.value;
264
263
  break;
265
264
  }
265
+ if ((_a = chunk.value) == null ? void 0 : _a.metadata) {
266
+ responseMetadata = chunk.value.metadata;
267
+ }
266
268
  const delta = (_b = chunk.value) == null ? void 0 : _b.output;
267
269
  if (!delta) {
268
270
  continue;
@@ -272,6 +274,9 @@ var generateCode = async ({
272
274
  raw += delta;
273
275
  await dispatchSends(parser.push(fence.push(delta)));
274
276
  }
277
+ if (!responseMetadata) {
278
+ throw new (0, _chunkPK72FAKDcjs.CognitiveError)("LLM streaming completed without metadata");
279
+ }
275
280
  const remaining = fence.flush();
276
281
  if (remaining) {
277
282
  await dispatchSends(parser.push(remaining));
@@ -279,15 +284,15 @@ var generateCode = async ({
279
284
  await dispatchSends(parser.finish());
280
285
  assistantResponse = _chunkOVRDJMZJcjs.toParsedAssistantResponse.call(void 0, parser.items, raw);
281
286
  } else {
282
- output = await cognitive.generateContent(input).catch((thrown) => {
287
+ const response = await cognitive.generateText(input, { signal: controller.signal }).catch((thrown) => {
283
288
  throw new (0, _chunkPK72FAKDcjs.CognitiveError)(`LLM generation failed: ${_chunkGOWPACSKcjs.getErrorMessage.call(void 0, thrown)}`);
284
289
  });
285
- const out = typeof ((_d = (_c = output.output.choices) == null ? void 0 : _c[0]) == null ? void 0 : _d.content) === "string" ? output.output.choices[0].content : null;
286
- if (!out) {
290
+ if (!response.output) {
287
291
  throw new (0, _chunkPK72FAKDcjs.CognitiveError)("LLM did not return any text output");
288
292
  }
289
- raw = out;
290
- assistantResponse = ctx.version.parseAssistantResponse(out);
293
+ responseMetadata = response.metadata;
294
+ raw = response.output;
295
+ assistantResponse = ctx.version.parseAssistantResponse(raw);
291
296
  for (const send of assistantResponse.sends) {
292
297
  await (onSend == null ? void 0 : onSend(send));
293
298
  }
@@ -295,29 +300,35 @@ var generateCode = async ({
295
300
  iteration.code = assistantResponse.code;
296
301
  iteration.sends = assistantResponse.sends;
297
302
  iteration.next = assistantResponse.next;
303
+ const usage = responseMetadata.usage;
298
304
  iteration.llm = {
299
- cached: output.meta.cached || false,
305
+ cached: responseMetadata.cached || false,
300
306
  ended_at: Date.now(),
301
307
  started_at: startedAt,
302
308
  status: "success",
303
- tokens: output.meta.tokens.input + output.meta.tokens.output,
304
- spend: output.meta.cost.input + output.meta.cost.output,
309
+ tokens: usage.inputTokens + usage.outputTokens,
310
+ spend: _nullishCoalesce(responseMetadata.cost, () => ( usage.inputCost + usage.outputCost)),
305
311
  output: assistantResponse.raw,
306
- model: `${output.meta.model.integration}:${output.meta.model.model}`,
312
+ model: `${responseMetadata.provider}:${responseMetadata.model}`,
307
313
  time_to_first_token: timeToFirstToken,
308
314
  time_to_last_token: timeToLastToken,
309
- usage: output.output.usage
315
+ usage: {
316
+ inputTokens: usage.inputTokens,
317
+ inputCost: usage.inputCost,
318
+ outputTokens: usage.outputTokens,
319
+ outputCost: usage.outputCost
320
+ }
310
321
  };
311
322
  if (iteration.tokens) {
312
- iteration.tokens.input = output.meta.tokens.input;
313
- iteration.tokens.output = output.meta.tokens.output;
314
- iteration.tokens.total = output.meta.tokens.input + output.meta.tokens.output;
323
+ iteration.tokens.input = usage.inputTokens;
324
+ iteration.tokens.output = usage.outputTokens;
325
+ iteration.tokens.total = usage.inputTokens + usage.outputTokens;
315
326
  }
316
327
  traces.push({
317
328
  type: "llm_call_success",
318
329
  started_at: startedAt,
319
330
  ended_at: iteration.llm.ended_at,
320
- model: model.ref,
331
+ model: model.id,
321
332
  code: _nullishCoalesce(iteration.code, () => ( ""))
322
333
  });
323
334
  };
@@ -728,7 +739,7 @@ var executeContextInternal = async (props) => {
728
739
  const controller = createJoinedAbortController([props.signal]);
729
740
  const { onIterationStart, onIterationEnd, onTrace, onExit, onBeforeExecution, onAfterTool, onBeforeTool } = props;
730
741
  const client = _nullishCoalesce(props.client, () => ( new (0, _client.Client)()));
731
- const cognitive = _cognitive.Cognitive.isCognitiveClient(client) || _chunkKG5E3UZZcjs._CustomModelClient.isCustomClient(client) ? client : _cognitive.CognitiveBeta.isBetaClient(client) ? _cognitive.cognitiveFromBeta.call(void 0, client) : new (0, _cognitive.Cognitive)({ client, __experimental_beta: true });
742
+ const cognitive = _cognitive.Cognitive.isCognitiveClient(client) || _chunkKG5E3UZZcjs._CustomModelClient.isCustomClient(client) ? client : new (0, _cognitive.Cognitive)({ client });
732
743
  const ctx = new (0, _chunkKG5E3UZZcjs.Context)({
733
744
  chat: props.chat,
734
745
  instructions: props.instructions,
@@ -52,7 +52,7 @@ import {
52
52
 
53
53
  // src/runtime/execute.ts
54
54
  import { Client } from "@botpress/client";
55
- import { Cognitive, CognitiveBeta, cognitiveFromBeta } from "@botpress/cognitive";
55
+ import { Cognitive } from "@botpress/cognitive";
56
56
 
57
57
  // src/abort-signal.ts
58
58
  function createJoinedAbortController(signals) {
@@ -135,7 +135,7 @@ var generateCode = async ({
135
135
  onRunStart,
136
136
  onRunComplete
137
137
  }) => {
138
- var _a, _b, _c, _d;
138
+ var _a, _b;
139
139
  const startedAt = Date.now();
140
140
  const traces = iteration.traces;
141
141
  const modelRef = Array.isArray(iteration.model) ? iteration.model[0] : iteration.model;
@@ -166,20 +166,18 @@ var generateCode = async ({
166
166
  type: "llm_call_started",
167
167
  started_at: startedAt,
168
168
  ended_at: startedAt,
169
- model: model.ref
169
+ model: model.id
170
170
  });
171
171
  const input = {
172
- signal: controller.signal,
173
- systemPrompt: (_a = messages.find((x) => x.role === "system")) == null ? void 0 : _a.content,
174
172
  model: iteration.model,
175
173
  temperature: iteration.temperature,
176
174
  responseFormat: "text",
177
175
  reasoningEffort: iteration.reasoningEffort,
178
- messages: messages.filter((x) => x.role !== "system"),
176
+ messages,
179
177
  stopSequences: ctx.version.getStopTokens(),
180
178
  meta: metadata ? { metadata } : void 0
181
179
  };
182
- let output;
180
+ let responseMetadata;
183
181
  let raw;
184
182
  let assistantResponse;
185
183
  let timeToFirstToken;
@@ -224,18 +222,20 @@ var generateCode = async ({
224
222
  }
225
223
  }
226
224
  };
227
- if (typeof cognitive.generateContentStream === "function") {
225
+ if (typeof cognitive.generateTextStream === "function") {
228
226
  const parser = new StreamingMessageParser();
229
227
  const fence = new LeadingFenceFilter();
230
228
  const streamController = createJoinedAbortController([controller.signal]);
231
229
  const requestedAt = Date.now();
232
- const stream = cognitive.generateContentStream({
233
- ...input,
234
- signal: streamController.signal,
235
- // Passed through to the cognitive v2 request: fall back to the next
236
- // model/provider when the first token takes too long
237
- ...ctx.maxTimeToFirstToken ? { options: { maxTimeToFirstToken: ctx.maxTimeToFirstToken } } : {}
238
- });
230
+ const stream = cognitive.generateTextStream(
231
+ {
232
+ ...input,
233
+ // Passed through to the cognitive request: fall back to the next
234
+ // model/provider when the first token takes too long
235
+ ...ctx.maxTimeToFirstToken ? { options: { maxTimeToFirstToken: ctx.maxTimeToFirstToken } } : {}
236
+ },
237
+ { signal: streamController.signal }
238
+ );
239
239
  const inactivityTimeout = Math.max(STREAM_INACTIVITY_TIMEOUT, ctx.maxTimeToFirstToken ?? 0);
240
240
  const nextChunk = async () => {
241
241
  let timer;
@@ -260,9 +260,11 @@ var generateCode = async ({
260
260
  throw new CognitiveError(`LLM generation failed: ${getErrorMessage(thrown)}`);
261
261
  }
262
262
  if (chunk.done) {
263
- output = chunk.value;
264
263
  break;
265
264
  }
265
+ if ((_a = chunk.value) == null ? void 0 : _a.metadata) {
266
+ responseMetadata = chunk.value.metadata;
267
+ }
266
268
  const delta = (_b = chunk.value) == null ? void 0 : _b.output;
267
269
  if (!delta) {
268
270
  continue;
@@ -272,6 +274,9 @@ var generateCode = async ({
272
274
  raw += delta;
273
275
  await dispatchSends(parser.push(fence.push(delta)));
274
276
  }
277
+ if (!responseMetadata) {
278
+ throw new CognitiveError("LLM streaming completed without metadata");
279
+ }
275
280
  const remaining = fence.flush();
276
281
  if (remaining) {
277
282
  await dispatchSends(parser.push(remaining));
@@ -279,15 +284,15 @@ var generateCode = async ({
279
284
  await dispatchSends(parser.finish());
280
285
  assistantResponse = toParsedAssistantResponse(parser.items, raw);
281
286
  } else {
282
- output = await cognitive.generateContent(input).catch((thrown) => {
287
+ const response = await cognitive.generateText(input, { signal: controller.signal }).catch((thrown) => {
283
288
  throw new CognitiveError(`LLM generation failed: ${getErrorMessage(thrown)}`);
284
289
  });
285
- const out = typeof ((_d = (_c = output.output.choices) == null ? void 0 : _c[0]) == null ? void 0 : _d.content) === "string" ? output.output.choices[0].content : null;
286
- if (!out) {
290
+ if (!response.output) {
287
291
  throw new CognitiveError("LLM did not return any text output");
288
292
  }
289
- raw = out;
290
- assistantResponse = ctx.version.parseAssistantResponse(out);
293
+ responseMetadata = response.metadata;
294
+ raw = response.output;
295
+ assistantResponse = ctx.version.parseAssistantResponse(raw);
291
296
  for (const send of assistantResponse.sends) {
292
297
  await (onSend == null ? void 0 : onSend(send));
293
298
  }
@@ -295,29 +300,35 @@ var generateCode = async ({
295
300
  iteration.code = assistantResponse.code;
296
301
  iteration.sends = assistantResponse.sends;
297
302
  iteration.next = assistantResponse.next;
303
+ const usage = responseMetadata.usage;
298
304
  iteration.llm = {
299
- cached: output.meta.cached || false,
305
+ cached: responseMetadata.cached || false,
300
306
  ended_at: Date.now(),
301
307
  started_at: startedAt,
302
308
  status: "success",
303
- tokens: output.meta.tokens.input + output.meta.tokens.output,
304
- spend: output.meta.cost.input + output.meta.cost.output,
309
+ tokens: usage.inputTokens + usage.outputTokens,
310
+ spend: responseMetadata.cost ?? usage.inputCost + usage.outputCost,
305
311
  output: assistantResponse.raw,
306
- model: `${output.meta.model.integration}:${output.meta.model.model}`,
312
+ model: `${responseMetadata.provider}:${responseMetadata.model}`,
307
313
  time_to_first_token: timeToFirstToken,
308
314
  time_to_last_token: timeToLastToken,
309
- usage: output.output.usage
315
+ usage: {
316
+ inputTokens: usage.inputTokens,
317
+ inputCost: usage.inputCost,
318
+ outputTokens: usage.outputTokens,
319
+ outputCost: usage.outputCost
320
+ }
310
321
  };
311
322
  if (iteration.tokens) {
312
- iteration.tokens.input = output.meta.tokens.input;
313
- iteration.tokens.output = output.meta.tokens.output;
314
- iteration.tokens.total = output.meta.tokens.input + output.meta.tokens.output;
323
+ iteration.tokens.input = usage.inputTokens;
324
+ iteration.tokens.output = usage.outputTokens;
325
+ iteration.tokens.total = usage.inputTokens + usage.outputTokens;
315
326
  }
316
327
  traces.push({
317
328
  type: "llm_call_success",
318
329
  started_at: startedAt,
319
330
  ended_at: iteration.llm.ended_at,
320
- model: model.ref,
331
+ model: model.id,
321
332
  code: iteration.code ?? ""
322
333
  });
323
334
  };
@@ -728,7 +739,7 @@ var executeContextInternal = async (props) => {
728
739
  const controller = createJoinedAbortController([props.signal]);
729
740
  const { onIterationStart, onIterationEnd, onTrace, onExit, onBeforeExecution, onAfterTool, onBeforeTool } = props;
730
741
  const client = props.client ?? new Client();
731
- const cognitive = Cognitive.isCognitiveClient(client) || _CustomModelClient.isCustomClient(client) ? client : CognitiveBeta.isBetaClient(client) ? cognitiveFromBeta(client) : new Cognitive({ client, __experimental_beta: true });
742
+ const cognitive = Cognitive.isCognitiveClient(client) || _CustomModelClient.isCustomClient(client) ? client : new Cognitive({ client });
732
743
  const ctx = new Context({
733
744
  chat: props.chat,
734
745
  instructions: props.instructions,
package/dist/index.cjs CHANGED
@@ -69,7 +69,7 @@ var _chunkGOWPACSKcjs = require('./chunk-GOWPACSK.cjs');
69
69
  var _chunkHC2QZTVTcjs = require('./chunk-HC2QZTVT.cjs');
70
70
 
71
71
  // package.json
72
- var version = "0.2.3";
72
+ var version = "0.3.1";
73
73
 
74
74
  // src/objects.ts
75
75
  var _zui = require('@bpinternal/zui');
@@ -1527,11 +1527,11 @@ var utils = {
1527
1527
  stripTruncationTags: _chunkHEAQAEFZcjs.stripTruncationTags
1528
1528
  };
1529
1529
  var execute = async (props) => {
1530
- const { executeContext } = await Promise.resolve().then(() => _interopRequireWildcard(require("./execute-MRZZ4AYY.cjs")));
1530
+ const { executeContext } = await Promise.resolve().then(() => _interopRequireWildcard(require("./execute-2H4F7GFE.cjs")));
1531
1531
  return executeContext(props);
1532
1532
  };
1533
1533
  var init = async () => {
1534
- await Promise.resolve().then(() => _interopRequireWildcard(require("./execute-MRZZ4AYY.cjs")));
1534
+ await Promise.resolve().then(() => _interopRequireWildcard(require("./execute-2H4F7GFE.cjs")));
1535
1535
  await Promise.resolve().then(() => _interopRequireWildcard(require("./component-2NYFY6CW.cjs")));
1536
1536
  await Promise.resolve().then(() => _interopRequireWildcard(require("./tool-VE2YHIY2.cjs")));
1537
1537
  await Promise.resolve().then(() => _interopRequireWildcard(require("./exit-MX56VN2C.cjs")));
package/dist/index.js CHANGED
@@ -69,7 +69,7 @@ import {
69
69
  } from "./chunk-34GJUS6U.js";
70
70
 
71
71
  // package.json
72
- var version = "0.2.3";
72
+ var version = "0.3.1";
73
73
 
74
74
  // src/objects.ts
75
75
  import { z } from "@bpinternal/zui";
@@ -1527,11 +1527,11 @@ var utils = {
1527
1527
  stripTruncationTags
1528
1528
  };
1529
1529
  var execute = async (props) => {
1530
- const { executeContext } = await import("./execute-DSGJ2UNL.js");
1530
+ const { executeContext } = await import("./execute-DPCZ6PKH.js");
1531
1531
  return executeContext(props);
1532
1532
  };
1533
1533
  var init = async () => {
1534
- await import("./execute-DSGJ2UNL.js");
1534
+ await import("./execute-DPCZ6PKH.js");
1535
1535
  await import("./component-ASNZHQUR.js");
1536
1536
  await import("./tool-KD7FL45V.js");
1537
1537
  await import("./exit-UQ3EUX5D.js");
@@ -14768,20 +14768,18 @@ ${rest}`;
14768
14768
  type: "llm_call_started",
14769
14769
  started_at: startedAt,
14770
14770
  ended_at: startedAt,
14771
- model: model.ref
14771
+ model: model.id
14772
14772
  });
14773
14773
  const input = {
14774
- signal: controller.signal,
14775
- systemPrompt: messages.find((x) => x.role === "system")?.content,
14776
14774
  model: iteration.model,
14777
14775
  temperature: iteration.temperature,
14778
14776
  responseFormat: "text",
14779
14777
  reasoningEffort: iteration.reasoningEffort,
14780
- messages: messages.filter((x) => x.role !== "system"),
14778
+ messages,
14781
14779
  stopSequences: ctx.version.getStopTokens(),
14782
14780
  meta: metadata ? { metadata } : void 0
14783
14781
  };
14784
- let output;
14782
+ let responseMetadata;
14785
14783
  let raw;
14786
14784
  let assistantResponse;
14787
14785
  let timeToFirstToken;
@@ -14826,18 +14824,20 @@ ${rest}`;
14826
14824
  }
14827
14825
  }
14828
14826
  };
14829
- if (typeof cognitive.generateContentStream === "function") {
14827
+ if (typeof cognitive.generateTextStream === "function") {
14830
14828
  const parser = new StreamingMessageParser();
14831
14829
  const fence = new LeadingFenceFilter();
14832
14830
  const streamController = createJoinedAbortController([controller.signal]);
14833
14831
  const requestedAt = Date.now();
14834
- const stream = cognitive.generateContentStream({
14835
- ...input,
14836
- signal: streamController.signal,
14837
- // Passed through to the cognitive v2 request: fall back to the next
14838
- // model/provider when the first token takes too long
14839
- ...ctx.maxTimeToFirstToken ? { options: { maxTimeToFirstToken: ctx.maxTimeToFirstToken } } : {}
14840
- });
14832
+ const stream = cognitive.generateTextStream(
14833
+ {
14834
+ ...input,
14835
+ // Passed through to the cognitive request: fall back to the next
14836
+ // model/provider when the first token takes too long
14837
+ ...ctx.maxTimeToFirstToken ? { options: { maxTimeToFirstToken: ctx.maxTimeToFirstToken } } : {}
14838
+ },
14839
+ { signal: streamController.signal }
14840
+ );
14841
14841
  const inactivityTimeout = Math.max(STREAM_INACTIVITY_TIMEOUT, ctx.maxTimeToFirstToken ?? 0);
14842
14842
  const nextChunk = async () => {
14843
14843
  let timer;
@@ -14862,9 +14862,11 @@ ${rest}`;
14862
14862
  throw new CognitiveError(`LLM generation failed: ${getErrorMessage(thrown)}`);
14863
14863
  }
14864
14864
  if (chunk.done) {
14865
- output = chunk.value;
14866
14865
  break;
14867
14866
  }
14867
+ if (chunk.value?.metadata) {
14868
+ responseMetadata = chunk.value.metadata;
14869
+ }
14868
14870
  const delta = chunk.value?.output;
14869
14871
  if (!delta) {
14870
14872
  continue;
@@ -14874,6 +14876,9 @@ ${rest}`;
14874
14876
  raw += delta;
14875
14877
  await dispatchSends(parser.push(fence.push(delta)));
14876
14878
  }
14879
+ if (!responseMetadata) {
14880
+ throw new CognitiveError("LLM streaming completed without metadata");
14881
+ }
14877
14882
  const remaining = fence.flush();
14878
14883
  if (remaining) {
14879
14884
  await dispatchSends(parser.push(remaining));
@@ -14881,15 +14886,15 @@ ${rest}`;
14881
14886
  await dispatchSends(parser.finish());
14882
14887
  assistantResponse = toParsedAssistantResponse(parser.items, raw);
14883
14888
  } else {
14884
- output = await cognitive.generateContent(input).catch((thrown) => {
14889
+ const response = await cognitive.generateText(input, { signal: controller.signal }).catch((thrown) => {
14885
14890
  throw new CognitiveError(`LLM generation failed: ${getErrorMessage(thrown)}`);
14886
14891
  });
14887
- const out = typeof output.output.choices?.[0]?.content === "string" ? output.output.choices[0].content : null;
14888
- if (!out) {
14892
+ if (!response.output) {
14889
14893
  throw new CognitiveError("LLM did not return any text output");
14890
14894
  }
14891
- raw = out;
14892
- assistantResponse = ctx.version.parseAssistantResponse(out);
14895
+ responseMetadata = response.metadata;
14896
+ raw = response.output;
14897
+ assistantResponse = ctx.version.parseAssistantResponse(raw);
14893
14898
  for (const send of assistantResponse.sends) {
14894
14899
  await onSend?.(send);
14895
14900
  }
@@ -14897,29 +14902,35 @@ ${rest}`;
14897
14902
  iteration.code = assistantResponse.code;
14898
14903
  iteration.sends = assistantResponse.sends;
14899
14904
  iteration.next = assistantResponse.next;
14905
+ const usage = responseMetadata.usage;
14900
14906
  iteration.llm = {
14901
- cached: output.meta.cached || false,
14907
+ cached: responseMetadata.cached || false,
14902
14908
  ended_at: Date.now(),
14903
14909
  started_at: startedAt,
14904
14910
  status: "success",
14905
- tokens: output.meta.tokens.input + output.meta.tokens.output,
14906
- spend: output.meta.cost.input + output.meta.cost.output,
14911
+ tokens: usage.inputTokens + usage.outputTokens,
14912
+ spend: responseMetadata.cost ?? usage.inputCost + usage.outputCost,
14907
14913
  output: assistantResponse.raw,
14908
- model: `${output.meta.model.integration}:${output.meta.model.model}`,
14914
+ model: `${responseMetadata.provider}:${responseMetadata.model}`,
14909
14915
  time_to_first_token: timeToFirstToken,
14910
14916
  time_to_last_token: timeToLastToken,
14911
- usage: output.output.usage
14917
+ usage: {
14918
+ inputTokens: usage.inputTokens,
14919
+ inputCost: usage.inputCost,
14920
+ outputTokens: usage.outputTokens,
14921
+ outputCost: usage.outputCost
14922
+ }
14912
14923
  };
14913
14924
  if (iteration.tokens) {
14914
- iteration.tokens.input = output.meta.tokens.input;
14915
- iteration.tokens.output = output.meta.tokens.output;
14916
- iteration.tokens.total = output.meta.tokens.input + output.meta.tokens.output;
14925
+ iteration.tokens.input = usage.inputTokens;
14926
+ iteration.tokens.output = usage.outputTokens;
14927
+ iteration.tokens.total = usage.inputTokens + usage.outputTokens;
14917
14928
  }
14918
14929
  traces.push({
14919
14930
  type: "llm_call_success",
14920
14931
  started_at: startedAt,
14921
14932
  ended_at: iteration.llm.ended_at,
14922
- model: model.ref,
14933
+ model: model.id,
14923
14934
  code: iteration.code ?? ""
14924
14935
  });
14925
14936
  };
@@ -15353,7 +15364,7 @@ __export(execute_exports, {
15353
15364
  executeContext: () => executeContext
15354
15365
  });
15355
15366
  import { Client } from "@botpress/client";
15356
- import { Cognitive, CognitiveBeta, cognitiveFromBeta } from "@botpress/cognitive";
15367
+ import { Cognitive } from "@botpress/cognitive";
15357
15368
  var executeContext, executeContextInternal, executeIterationStartHook, executeIterationWithErrorHandling, transformIterationResult, executeIteration;
15358
15369
  var init_execute = __esm({
15359
15370
  "src/runtime/execute.ts"() {
@@ -15385,7 +15396,7 @@ var init_execute = __esm({
15385
15396
  const controller = createJoinedAbortController([props.signal]);
15386
15397
  const { onIterationStart, onIterationEnd, onTrace, onExit, onBeforeExecution, onAfterTool, onBeforeTool } = props;
15387
15398
  const client = props.client ?? new Client();
15388
- const cognitive = Cognitive.isCognitiveClient(client) || _CustomModelClient.isCustomClient(client) ? client : CognitiveBeta.isBetaClient(client) ? cognitiveFromBeta(client) : new Cognitive({ client, __experimental_beta: true });
15399
+ const cognitive = Cognitive.isCognitiveClient(client) || _CustomModelClient.isCustomClient(client) ? client : new Cognitive({ client });
15389
15400
  const ctx = new Context({
15390
15401
  chat: props.chat,
15391
15402
  instructions: props.instructions,
@@ -15748,7 +15759,7 @@ var init_execute = __esm({
15748
15759
  });
15749
15760
 
15750
15761
  // package.json
15751
- var version = "0.2.3";
15762
+ var version = "0.3.1";
15752
15763
 
15753
15764
  // src/index.ts
15754
15765
  init_tool();
@@ -1,4 +1,4 @@
1
- import { type GenerateContentInput } from '@botpress/cognitive';
1
+ import { type CognitiveMessage } from '@botpress/cognitive';
2
2
  import { Component } from '../component.js';
3
3
  import { Exit } from '../exit.js';
4
4
  import type { ParsedItem } from '../message-stream/types.js';
@@ -29,10 +29,7 @@ export type ParsedAssistantResponse = {
29
29
  next?: ParsedNext;
30
30
  };
31
31
  export declare namespace LLMzPrompts {
32
- type Message = GenerateContentInput['messages'][number] | {
33
- role: 'system';
34
- content: string;
35
- };
32
+ type Message = CognitiveMessage;
36
33
  /**
37
34
  * The raw (pre-truncation, unwrapped) content of each named section of the
38
35
  * system prompt. Used to measure the context size of each part of the prompt.
@@ -51,7 +48,7 @@ export declare namespace LLMzPrompts {
51
48
  message: Message;
52
49
  parts: SystemPromptParts;
53
50
  };
54
- type MessageContent = Extract<GenerateContentInput['messages'][number]['content'], any[]>[number];
51
+ type MessageContent = Extract<CognitiveMessage['content'], any[]>[number];
55
52
  type InitialStateProps = {
56
53
  instructions?: string;
57
54
  transcript: TranscriptArray;
package/dist/result.d.ts CHANGED
@@ -408,7 +408,7 @@ export declare class SuccessExecutionResult<TOutput = unknown> extends Execution
408
408
  id: string;
409
409
  iterations: {
410
410
  id: string;
411
- messages: import("./index.js").LLMzPrompts.Message[];
411
+ messages: import("@botpress/cognitive").CognitiveMessage[];
412
412
  code: string | undefined;
413
413
  model: import("@botpress/cognitive").Models | import("@botpress/cognitive").Models[];
414
414
  temperature: number;
@@ -573,7 +573,7 @@ export declare class ErrorExecutionResult extends ExecutionResult implements Ser
573
573
  id: string;
574
574
  iterations: {
575
575
  id: string;
576
- messages: import("./index.js").LLMzPrompts.Message[];
576
+ messages: import("@botpress/cognitive").CognitiveMessage[];
577
577
  code: string | undefined;
578
578
  model: import("@botpress/cognitive").Models | import("@botpress/cognitive").Models[];
579
579
  temperature: number;
@@ -758,7 +758,7 @@ export declare class PartialExecutionResult extends ExecutionResult implements S
758
758
  id: string;
759
759
  iterations: {
760
760
  id: string;
761
- messages: import("./index.js").LLMzPrompts.Message[];
761
+ messages: import("@botpress/cognitive").CognitiveMessage[];
762
762
  code: string | undefined;
763
763
  model: import("@botpress/cognitive").Models | import("@botpress/cognitive").Models[];
764
764
  temperature: number;