@ai-sdk/workflow 1.0.0-beta.2 → 1.0.0-beta.21

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/index.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  // src/workflow-agent.ts
2
2
  import {
3
- Output
3
+ Output,
4
+ experimental_filterActiveTools as filterActiveTools2
4
5
  } from "ai";
5
6
  import {
6
7
  convertToLanguageModelPrompt,
@@ -9,6 +10,11 @@ import {
9
10
  standardizePrompt
10
11
  } from "ai/internal";
11
12
 
13
+ // src/stream-text-iterator.ts
14
+ import {
15
+ experimental_filterActiveTools as filterActiveTools
16
+ } from "ai";
17
+
12
18
  // src/do-stream-step.ts
13
19
  import {
14
20
  experimental_streamLanguageModelCall as streamModelCall
@@ -77,18 +83,7 @@ function resolveSerializableTools(tools) {
77
83
  async function doStreamStep(conversationPrompt, modelInit, writable, serializedTools, options) {
78
84
  "use step";
79
85
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
80
- let model;
81
- if (typeof modelInit === "string") {
82
- model = gateway.languageModel(modelInit);
83
- } else if (typeof modelInit === "function") {
84
- model = await modelInit();
85
- } else if (typeof modelInit === "object" && modelInit !== null && "modelId" in modelInit) {
86
- model = modelInit;
87
- } else {
88
- throw new Error(
89
- 'Invalid "model initialization" argument. Must be a string, a LanguageModel instance, or a function that returns a LanguageModel instance.'
90
- );
91
- }
86
+ const model = typeof modelInit === "string" ? gateway.languageModel(modelInit) : modelInit;
92
87
  const tools = serializedTools ? resolveSerializableTools(serializedTools) : void 0;
93
88
  const { stream: modelStream } = await streamModelCall({
94
89
  model,
@@ -198,7 +193,8 @@ async function doStreamStep(conversationPrompt, modelInit, writable, serializedT
198
193
  },
199
194
  functionId: void 0,
200
195
  metadata: void 0,
201
- context: void 0,
196
+ runtimeContext: void 0,
197
+ toolsContext: {},
202
198
  content: [
203
199
  ...text ? [{ type: "text", text }] : [],
204
200
  ...toolCalls.filter((tc) => !tc.invalid).map((tc) => ({
@@ -276,7 +272,6 @@ async function* streamTextIterator({
276
272
  writable,
277
273
  model,
278
274
  stopConditions,
279
- maxSteps,
280
275
  onStepFinish,
281
276
  onStepStart,
282
277
  onError,
@@ -289,7 +284,7 @@ async function* streamTextIterator({
289
284
  repairToolCall,
290
285
  responseFormat
291
286
  }) {
292
- var _a;
287
+ var _a, _b;
293
288
  let conversationPrompt = [...prompt];
294
289
  let currentModel = model;
295
290
  let currentGenerationSettings = generationSettings != null ? generationSettings : {};
@@ -302,11 +297,7 @@ async function* streamTextIterator({
302
297
  let stepNumber = 0;
303
298
  let lastStep;
304
299
  let lastStepWasToolCalls = false;
305
- const effectiveMaxSteps = maxSteps != null ? maxSteps : Infinity;
306
300
  while (!done) {
307
- if (stepNumber >= effectiveMaxSteps) {
308
- break;
309
- }
310
301
  if ((_a = currentGenerationSettings.abortSignal) == null ? void 0 : _a.aborted) {
311
302
  break;
312
303
  }
@@ -417,11 +408,15 @@ async function* streamTextIterator({
417
408
  await onStepStart({
418
409
  stepNumber,
419
410
  model: currentModel,
420
- messages: conversationPrompt
411
+ messages: conversationPrompt,
412
+ steps: [...steps]
421
413
  });
422
414
  }
423
415
  try {
424
- const effectiveTools = currentActiveTools && currentActiveTools.length > 0 ? filterToolSet(tools, currentActiveTools) : tools;
416
+ const effectiveTools = currentActiveTools && currentActiveTools.length > 0 ? (_b = filterActiveTools({
417
+ tools,
418
+ activeTools: currentActiveTools
419
+ })) != null ? _b : tools : tools;
425
420
  const serializedTools = serializeToolSet(effectiveTools);
426
421
  const { toolCalls, finish, step, providerExecutedToolResults } = await doStreamStep(
427
422
  conversationPrompt,
@@ -525,15 +520,6 @@ async function* streamTextIterator({
525
520
  }
526
521
  return conversationPrompt;
527
522
  }
528
- function filterToolSet(tools, activeTools) {
529
- const filtered = {};
530
- for (const toolName of activeTools) {
531
- if (toolName in tools) {
532
- filtered[toolName] = tools[toolName];
533
- }
534
- }
535
- return filtered;
536
- }
537
523
  function sanitizeProviderMetadataForToolCall(metadata) {
538
524
  if (metadata == null) return void 0;
539
525
  const meta = metadata;
@@ -559,12 +545,18 @@ function sanitizeProviderMetadataForToolCall(metadata) {
559
545
  var WorkflowAgent = class {
560
546
  constructor(options) {
561
547
  var _a, _b;
548
+ this.id = options.id;
562
549
  this.model = options.model;
563
550
  this.tools = (_a = options.tools) != null ? _a : {};
564
551
  this.instructions = (_b = options.instructions) != null ? _b : options.system;
565
552
  this.toolChoice = options.toolChoice;
566
553
  this.telemetry = options.experimental_telemetry;
567
554
  this.experimentalContext = options.experimental_context;
555
+ this.stopWhen = options.stopWhen;
556
+ this.activeTools = options.activeTools;
557
+ this.output = options.output;
558
+ this.experimentalRepairToolCall = options.experimental_repairToolCall;
559
+ this.experimentalDownload = options.experimental_download;
568
560
  this.prepareStep = options.prepareStep;
569
561
  this.constructorOnStepFinish = options.onStepFinish;
570
562
  this.constructorOnFinish = options.onFinish;
@@ -592,14 +584,16 @@ var WorkflowAgent = class {
592
584
  throw new Error("Not implemented");
593
585
  }
594
586
  async stream(options) {
595
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
587
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B;
596
588
  let effectiveModel = this.model;
597
589
  let effectiveInstructions = (_a = options.system) != null ? _a : this.instructions;
590
+ let effectivePrompt = options.prompt;
598
591
  let effectiveMessages = options.messages;
599
592
  let effectiveGenerationSettings = { ...this.generationSettings };
600
593
  let effectiveExperimentalContext = (_b = options.experimental_context) != null ? _b : this.experimentalContext;
601
594
  let effectiveToolChoiceFromPrepare = (_c = options.toolChoice) != null ? _c : this.toolChoice;
602
595
  let effectiveTelemetryFromPrepare = (_d = options.experimental_telemetry) != null ? _d : this.telemetry;
596
+ const resolvedMessagesForPrepareCall = (_e = effectiveMessages != null ? effectiveMessages : typeof effectivePrompt === "string" ? [{ role: "user", content: effectivePrompt }] : effectivePrompt) != null ? _e : [];
603
597
  if (this.prepareCall) {
604
598
  const prepared = await this.prepareCall({
605
599
  model: effectiveModel,
@@ -608,14 +602,16 @@ var WorkflowAgent = class {
608
602
  toolChoice: effectiveToolChoiceFromPrepare,
609
603
  experimental_telemetry: effectiveTelemetryFromPrepare,
610
604
  experimental_context: effectiveExperimentalContext,
611
- messages: effectiveMessages,
605
+ messages: resolvedMessagesForPrepareCall,
612
606
  ...effectiveGenerationSettings
613
607
  });
614
608
  if (prepared.model !== void 0) effectiveModel = prepared.model;
615
609
  if (prepared.instructions !== void 0)
616
610
  effectiveInstructions = prepared.instructions;
617
- if (prepared.messages !== void 0)
611
+ if (prepared.messages !== void 0) {
618
612
  effectiveMessages = prepared.messages;
613
+ effectivePrompt = void 0;
614
+ }
619
615
  if (prepared.experimental_context !== void 0)
620
616
  effectiveExperimentalContext = prepared.experimental_context;
621
617
  if (prepared.toolChoice !== void 0)
@@ -645,7 +641,7 @@ var WorkflowAgent = class {
645
641
  }
646
642
  const prompt = await standardizePrompt({
647
643
  system: effectiveInstructions,
648
- messages: effectiveMessages
644
+ ...effectivePrompt != null ? { prompt: effectivePrompt } : { messages: effectiveMessages }
649
645
  });
650
646
  const { approvedToolApprovals, deniedToolApprovals } = collectToolApprovalsFromMessages(prompt.messages);
651
647
  if (approvedToolApprovals.length > 0 || deniedToolApprovals.length > 0) {
@@ -741,10 +737,10 @@ var WorkflowAgent = class {
741
737
  const modelPrompt = await convertToLanguageModelPrompt({
742
738
  prompt,
743
739
  supportedUrls: {},
744
- download: options.experimental_download
740
+ download: (_f = options.experimental_download) != null ? _f : this.experimentalDownload
745
741
  });
746
742
  const effectiveAbortSignal = mergeAbortSignals(
747
- (_e = options.abortSignal) != null ? _e : effectiveGenerationSettings.abortSignal,
743
+ (_g = options.abortSignal) != null ? _g : effectiveGenerationSettings.abortSignal,
748
744
  options.timeout != null ? AbortSignal.timeout(options.timeout) : void 0
749
745
  );
750
746
  const mergedGenerationSettings = {
@@ -804,7 +800,11 @@ var WorkflowAgent = class {
804
800
  );
805
801
  const effectiveToolChoice = effectiveToolChoiceFromPrepare;
806
802
  const effectiveTelemetry = effectiveTelemetryFromPrepare;
807
- const effectiveTools = options.activeTools && options.activeTools.length > 0 ? filterTools(this.tools, options.activeTools) : this.tools;
803
+ const effectiveActiveTools = (_h = options.activeTools) != null ? _h : this.activeTools;
804
+ const effectiveTools = effectiveActiveTools && effectiveActiveTools.length > 0 ? (_i = filterActiveTools2({
805
+ tools: this.tools,
806
+ activeTools: effectiveActiveTools
807
+ })) != null ? _i : this.tools : this.tools;
808
808
  let experimentalContext = effectiveExperimentalContext;
809
809
  const steps = [];
810
810
  let lastStepToolCalls = [];
@@ -812,61 +812,68 @@ var WorkflowAgent = class {
812
812
  if (mergedOnStart) {
813
813
  await mergedOnStart({
814
814
  model: effectiveModel,
815
- messages: effectiveMessages
815
+ messages: prompt.messages
816
816
  });
817
817
  }
818
- const executeToolWithCallbacks = async (toolCall, tools, messages2, context) => {
818
+ const executeToolWithCallbacks = async (toolCall, tools, messages2, context, currentStepNumber = 0) => {
819
+ const toolCallEvent = {
820
+ type: "tool-call",
821
+ toolCallId: toolCall.toolCallId,
822
+ toolName: toolCall.toolName,
823
+ input: toolCall.input
824
+ };
819
825
  if (mergedOnToolCallStart) {
820
826
  await mergedOnToolCallStart({
821
- toolCall: {
822
- type: "tool-call",
823
- toolCallId: toolCall.toolCallId,
824
- toolName: toolCall.toolName,
825
- input: toolCall.input
826
- }
827
+ toolCall: toolCallEvent,
828
+ stepNumber: currentStepNumber
827
829
  });
828
830
  }
831
+ const startTime = Date.now();
829
832
  let result;
830
833
  try {
831
834
  result = await executeTool(toolCall, tools, messages2, context);
832
835
  } catch (err) {
836
+ const durationMs2 = Date.now() - startTime;
833
837
  if (mergedOnToolCallFinish) {
834
838
  await mergedOnToolCallFinish({
835
- toolCall: {
836
- type: "tool-call",
837
- toolCallId: toolCall.toolCallId,
838
- toolName: toolCall.toolName,
839
- input: toolCall.input
840
- },
839
+ toolCall: toolCallEvent,
840
+ stepNumber: currentStepNumber,
841
+ durationMs: durationMs2,
842
+ success: false,
841
843
  error: err
842
844
  });
843
845
  }
844
846
  throw err;
845
847
  }
848
+ const durationMs = Date.now() - startTime;
846
849
  if (mergedOnToolCallFinish) {
847
850
  const isError = result.output && "type" in result.output && (result.output.type === "error-text" || result.output.type === "error-json");
848
- await mergedOnToolCallFinish({
849
- toolCall: {
850
- type: "tool-call",
851
- toolCallId: toolCall.toolCallId,
852
- toolName: toolCall.toolName,
853
- input: toolCall.input
854
- },
855
- ...isError ? {
851
+ if (isError) {
852
+ await mergedOnToolCallFinish({
853
+ toolCall: toolCallEvent,
854
+ stepNumber: currentStepNumber,
855
+ durationMs,
856
+ success: false,
856
857
  error: "value" in result.output ? result.output.value : void 0
857
- } : {
858
- result: result.output && "value" in result.output ? result.output.value : void 0
859
- }
860
- });
858
+ });
859
+ } else {
860
+ await mergedOnToolCallFinish({
861
+ toolCall: toolCallEvent,
862
+ stepNumber: currentStepNumber,
863
+ durationMs,
864
+ success: true,
865
+ output: result.output && "value" in result.output ? result.output.value : void 0
866
+ });
867
+ }
861
868
  }
862
869
  return result;
863
870
  };
864
- if ((_f = mergedGenerationSettings.abortSignal) == null ? void 0 : _f.aborted) {
871
+ if ((_j = mergedGenerationSettings.abortSignal) == null ? void 0 : _j.aborted) {
865
872
  if (options.onAbort) {
866
873
  await options.onAbort({ steps });
867
874
  }
868
875
  return {
869
- messages: options.messages,
876
+ messages: prompt.messages,
870
877
  steps,
871
878
  toolCalls: [],
872
879
  toolResults: [],
@@ -878,19 +885,18 @@ var WorkflowAgent = class {
878
885
  tools: effectiveTools,
879
886
  writable: options.writable,
880
887
  prompt: modelPrompt,
881
- stopConditions: options.stopWhen,
882
- maxSteps: options.maxSteps,
888
+ stopConditions: (_k = options.stopWhen) != null ? _k : this.stopWhen,
883
889
  onStepFinish: mergedOnStepFinish,
884
890
  onStepStart: mergedOnStepStart,
885
891
  onError: options.onError,
886
- prepareStep: (_g = options.prepareStep) != null ? _g : this.prepareStep,
892
+ prepareStep: (_l = options.prepareStep) != null ? _l : this.prepareStep,
887
893
  generationSettings: mergedGenerationSettings,
888
894
  toolChoice: effectiveToolChoice,
889
895
  experimental_context: experimentalContext,
890
896
  experimental_telemetry: effectiveTelemetry,
891
- includeRawChunks: (_h = options.includeRawChunks) != null ? _h : false,
892
- repairToolCall: options.experimental_repairToolCall,
893
- responseFormat: await ((_i = options.output) == null ? void 0 : _i.responseFormat)
897
+ includeRawChunks: (_m = options.includeRawChunks) != null ? _m : false,
898
+ repairToolCall: (_n = options.experimental_repairToolCall) != null ? _n : this.experimentalRepairToolCall,
899
+ responseFormat: await ((_p = (_o = options.output) != null ? _o : this.output) == null ? void 0 : _p.responseFormat)
894
900
  });
895
901
  let finalMessages;
896
902
  let encounteredError;
@@ -898,7 +904,7 @@ var WorkflowAgent = class {
898
904
  try {
899
905
  let result = await iterator.next();
900
906
  while (!result.done) {
901
- if ((_j = mergedGenerationSettings.abortSignal) == null ? void 0 : _j.aborted) {
907
+ if ((_q = mergedGenerationSettings.abortSignal) == null ? void 0 : _q.aborted) {
902
908
  wasAborted = true;
903
909
  if (options.onAbort) {
904
910
  await options.onAbort({ steps });
@@ -912,6 +918,7 @@ var WorkflowAgent = class {
912
918
  context,
913
919
  providerExecutedToolResults
914
920
  } = result.value;
921
+ const currentStepNumber = steps.length;
915
922
  if (step) {
916
923
  steps.push(step);
917
924
  }
@@ -952,7 +959,8 @@ var WorkflowAgent = class {
952
959
  toolCall,
953
960
  effectiveTools,
954
961
  iterMessages,
955
- experimentalContext
962
+ experimentalContext,
963
+ currentStepNumber
956
964
  )
957
965
  )
958
966
  );
@@ -991,8 +999,8 @@ var WorkflowAgent = class {
991
999
  await mergedOnFinish({
992
1000
  steps,
993
1001
  messages: messages2,
994
- text: (_k = lastStep == null ? void 0 : lastStep.text) != null ? _k : "",
995
- finishReason: (_l = lastStep == null ? void 0 : lastStep.finishReason) != null ? _l : "other",
1002
+ text: (_r = lastStep == null ? void 0 : lastStep.text) != null ? _r : "",
1003
+ finishReason: (_s = lastStep == null ? void 0 : lastStep.finishReason) != null ? _s : "other",
996
1004
  totalUsage: aggregateUsage(steps),
997
1005
  experimental_context: experimentalContext,
998
1006
  output: void 0
@@ -1016,8 +1024,8 @@ var WorkflowAgent = class {
1016
1024
  }
1017
1025
  }
1018
1026
  if (options.writable) {
1019
- const sendFinish = (_m = options.sendFinish) != null ? _m : true;
1020
- const preventClose = (_n = options.preventClose) != null ? _n : false;
1027
+ const sendFinish = (_t = options.sendFinish) != null ? _t : true;
1028
+ const preventClose = (_u = options.preventClose) != null ? _u : false;
1021
1029
  if (sendFinish || !preventClose) {
1022
1030
  await closeStream(options.writable, preventClose, sendFinish);
1023
1031
  }
@@ -1036,7 +1044,8 @@ var WorkflowAgent = class {
1036
1044
  toolCall,
1037
1045
  effectiveTools,
1038
1046
  iterMessages,
1039
- experimentalContext
1047
+ experimentalContext,
1048
+ currentStepNumber
1040
1049
  )
1041
1050
  )
1042
1051
  );
@@ -1110,14 +1119,15 @@ var WorkflowAgent = class {
1110
1119
  await options.onError({ error });
1111
1120
  }
1112
1121
  }
1113
- const messages = finalMessages != null ? finalMessages : options.messages;
1122
+ const messages = finalMessages != null ? finalMessages : prompt.messages;
1123
+ const effectiveOutput = (_v = options.output) != null ? _v : this.output;
1114
1124
  let experimentalOutput = void 0;
1115
- if (options.output && steps.length > 0) {
1125
+ if (effectiveOutput && steps.length > 0) {
1116
1126
  const lastStep = steps[steps.length - 1];
1117
1127
  const text = lastStep.text;
1118
1128
  if (text) {
1119
1129
  try {
1120
- experimentalOutput = await options.output.parseCompleteOutput(
1130
+ experimentalOutput = await effectiveOutput.parseCompleteOutput(
1121
1131
  { text },
1122
1132
  {
1123
1133
  response: lastStep.response,
@@ -1137,8 +1147,8 @@ var WorkflowAgent = class {
1137
1147
  await mergedOnFinish({
1138
1148
  steps,
1139
1149
  messages,
1140
- text: (_o = lastStep == null ? void 0 : lastStep.text) != null ? _o : "",
1141
- finishReason: (_p = lastStep == null ? void 0 : lastStep.finishReason) != null ? _p : "other",
1150
+ text: (_w = lastStep == null ? void 0 : lastStep.text) != null ? _w : "",
1151
+ finishReason: (_x = lastStep == null ? void 0 : lastStep.finishReason) != null ? _x : "other",
1142
1152
  totalUsage: aggregateUsage(steps),
1143
1153
  experimental_context: experimentalContext,
1144
1154
  output: experimentalOutput
@@ -1146,8 +1156,8 @@ var WorkflowAgent = class {
1146
1156
  }
1147
1157
  if (encounteredError) {
1148
1158
  if (options.writable) {
1149
- const sendFinish = (_q = options.sendFinish) != null ? _q : true;
1150
- const preventClose = (_r = options.preventClose) != null ? _r : false;
1159
+ const sendFinish = (_y = options.sendFinish) != null ? _y : true;
1160
+ const preventClose = (_z = options.preventClose) != null ? _z : false;
1151
1161
  if (sendFinish || !preventClose) {
1152
1162
  await closeStream(options.writable, preventClose, sendFinish);
1153
1163
  }
@@ -1155,8 +1165,8 @@ var WorkflowAgent = class {
1155
1165
  throw encounteredError;
1156
1166
  }
1157
1167
  if (options.writable) {
1158
- const sendFinish = (_s = options.sendFinish) != null ? _s : true;
1159
- const preventClose = (_t = options.preventClose) != null ? _t : false;
1168
+ const sendFinish = (_A = options.sendFinish) != null ? _A : true;
1169
+ const preventClose = (_B = options.preventClose) != null ? _B : false;
1160
1170
  if (sendFinish || !preventClose) {
1161
1171
  await closeStream(options.writable, preventClose, sendFinish);
1162
1172
  }
@@ -1257,15 +1267,6 @@ function aggregateUsage(steps) {
1257
1267
  totalTokens: inputTokens + outputTokens
1258
1268
  };
1259
1269
  }
1260
- function filterTools(tools, activeTools) {
1261
- const filtered = {};
1262
- for (const toolName of activeTools) {
1263
- if (toolName in tools) {
1264
- filtered[toolName] = tools[toolName];
1265
- }
1266
- }
1267
- return filtered;
1268
- }
1269
1270
  function getErrorMessage(error) {
1270
1271
  if (error == null) {
1271
1272
  return "unknown error";