ai 7.0.180 → 7.0.181

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 (42) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/{default-stop-condition-vtYEJcnz.js → default-stop-condition-D8PwkeWe.js} +52 -27
  3. package/dist/default-stop-condition-D8PwkeWe.js.map +1 -0
  4. package/dist/{index-CM_8u8gB.d.ts → index-CKEJqCzY.d.ts} +69 -4
  5. package/dist/index-CKEJqCzY.d.ts.map +1 -0
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js +192 -119
  8. package/dist/index.js.map +1 -1
  9. package/dist/internal/index.d.ts +8 -4
  10. package/dist/internal/index.d.ts.map +1 -1
  11. package/dist/internal/index.js +1 -1
  12. package/docs/03-agents/04-loop-control.mdx +35 -1
  13. package/docs/03-agents/08-terminal-ui.mdx +10 -0
  14. package/docs/03-ai-sdk-core/65-lifecycle-callbacks.mdx +6 -0
  15. package/docs/04-ai-sdk-ui/21-error-handling.mdx +21 -0
  16. package/docs/07-reference/01-ai-sdk-core/01-generate-text.mdx +19 -0
  17. package/docs/07-reference/01-ai-sdk-core/02-stream-text.mdx +25 -0
  18. package/docs/07-reference/01-ai-sdk-core/16-tool-loop-agent.mdx +7 -0
  19. package/docs/07-reference/06-ai-sdk-tui/01-run-agent-tui.mdx +3 -0
  20. package/package.json +4 -4
  21. package/src/agent/default-stop-condition.ts +12 -3
  22. package/src/agent/tool-loop-agent-settings.ts +11 -0
  23. package/src/agent/tool-loop-agent.ts +3 -1
  24. package/src/extract/restricted-telemetry-dispatcher.ts +9 -5
  25. package/src/generate-text/default-generate-text-result.ts +4 -0
  26. package/src/generate-text/generate-text-events.ts +7 -0
  27. package/src/generate-text/generate-text-result.ts +9 -0
  28. package/src/generate-text/generate-text.ts +37 -5
  29. package/src/generate-text/index.ts +1 -0
  30. package/src/generate-text/steering.ts +19 -5
  31. package/src/generate-text/stopped-by.ts +43 -0
  32. package/src/generate-text/stream-language-model-call.ts +21 -2
  33. package/src/generate-text/stream-text-result.ts +18 -0
  34. package/src/generate-text/stream-text.ts +59 -6
  35. package/src/logger/create-log-warnings.ts +17 -0
  36. package/src/model/as-language-model-v3.ts +3 -0
  37. package/src/model/as-language-model-v4.ts +5 -1
  38. package/src/model/resolve-model.ts +8 -3
  39. package/src/prompt/convert-to-language-model-prompt.ts +15 -6
  40. package/src/util/log-v2-compatibility-warning.ts +5 -2
  41. package/dist/default-stop-condition-vtYEJcnz.js.map +0 -1
  42. package/dist/index-CM_8u8gB.d.ts.map +0 -1
@@ -21,7 +21,8 @@ import {
21
21
  type UserModelMessage,
22
22
  } from '@ai-sdk/provider-utils';
23
23
  import { ToolChoiceViolationError } from '../error';
24
- import { logWarnings } from '../logger/log-warnings';
24
+ import { createLogWarnings } from '../logger/create-log-warnings';
25
+ import type { LogWarningsFunction } from '../logger/log-warnings';
25
26
  import { resolveLanguageModel } from '../model/resolve-model';
26
27
  import type { ModelMessage } from '../prompt';
27
28
  import { cloneModelMessages } from '../prompt/clone-model-message';
@@ -108,6 +109,11 @@ import {
108
109
  type SteeringNotDeliveredReason,
109
110
  type SteeringRun,
110
111
  } from './steering';
112
+ import {
113
+ getModelStoppedBy,
114
+ getPendingToolCallStoppedBy,
115
+ type StoppedBy,
116
+ } from './stopped-by';
111
117
  import {
112
118
  isStepCount,
113
119
  isStopConditionMet,
@@ -241,6 +247,7 @@ export type GenerateTextInclude = {
241
247
  * @param experimental_onToolCallFinish - Deprecated alias for `onToolExecutionEnd`.
242
248
  * @param onStepFinish - Callback that is called when each step (LLM call) is finished, including intermediate steps.
243
249
  * @param onStepError - Callback that is called when a step that started fails before it produces a step result, i.e. when the provider call throws or rejects, or when the call is aborted or times out.
250
+ * @param onWarning - Callback that receives the warnings of the call instead of the global warning logger.
244
251
  * @param onEnd - Callback that is called when all steps are finished and the response is complete.
245
252
  * @param onFinish - Deprecated alias for `onEnd`.
246
253
  *
@@ -333,6 +340,7 @@ async function generateTextInternal<
333
340
  onStepEnd,
334
341
  onStepError,
335
342
  onStepFinish,
343
+ onWarning,
336
344
  onFinish,
337
345
  onEnd = onFinish,
338
346
  ...settings
@@ -599,6 +607,13 @@ async function generateTextInternal<
599
607
  NoInfer<OUTPUT>
600
608
  >;
601
609
 
610
+ /**
611
+ * Callback that receives the warnings of the call, e.g. unsupported
612
+ * settings or deprecated prompt parts. When it is set, the warnings are
613
+ * not sent to the global warning logger (`AI_SDK_LOG_WARNINGS`).
614
+ */
615
+ onWarning?: LogWarningsFunction;
616
+
602
617
  /**
603
618
  * Callback that is called when each step (LLM call) ends, including intermediate steps.
604
619
  *
@@ -664,7 +679,7 @@ async function generateTextInternal<
664
679
 
665
680
  const resolvedToolCallConcurrency =
666
681
  prepareToolCallConcurrency(toolCallConcurrency);
667
- const model = resolveLanguageModel(modelArg);
682
+ const model = resolveLanguageModel(modelArg, onWarning);
668
683
  const resolvedToolCallers = resolveToolCallerConfiguration({
669
684
  tools,
670
685
  toolCallers: experimental_toolCallers,
@@ -686,6 +701,7 @@ async function generateTextInternal<
686
701
  onToolExecutionEnd ?? experimental_onToolCallFinish;
687
702
  const resolvedOnStepEnd = onStepEnd ?? onStepFinish;
688
703
 
704
+ const logCallWarnings = createLogWarnings(onWarning);
689
705
  const unsupportedTimeoutWarnings: Warning[] = [];
690
706
 
691
707
  if (getFirstChunkTimeoutMs(timeout) != null) {
@@ -706,7 +722,7 @@ async function generateTextInternal<
706
722
  }
707
723
 
708
724
  if (unsupportedTimeoutWarnings.length > 0) {
709
- logWarnings({
725
+ logCallWarnings({
710
726
  warnings: unsupportedTimeoutWarnings,
711
727
  provider: model.provider,
712
728
  model: model.modelId,
@@ -969,6 +985,7 @@ async function generateTextInternal<
969
985
 
970
986
  // why waiting steering messages are not delivered when the loop ends:
971
987
  let steeringEndReason: SteeringNotDeliveredReason = 'finished';
988
+ let stoppedBy: StoppedBy = 'model';
972
989
 
973
990
  const shouldStartNextStep = async () => {
974
991
  if (steps[steps.length - 1].finishReason === 'interrupted') {
@@ -981,6 +998,7 @@ async function generateTextInternal<
981
998
  clientToolCalls.length
982
999
  ) {
983
1000
  steeringEndReason = 'waiting-for-tool-results';
1001
+ stoppedBy = getPendingToolCallStoppedBy(steps[steps.length - 1]);
984
1002
  return false;
985
1003
  }
986
1004
 
@@ -999,6 +1017,7 @@ async function generateTextInternal<
999
1017
  !steeringRun?.hasPendingMessages() &&
1000
1018
  (isTruncated || !steeringRun?.promoteQueuedMessage())
1001
1019
  ) {
1020
+ stoppedBy = getModelStoppedBy(steps[steps.length - 1]);
1002
1021
  return false;
1003
1022
  }
1004
1023
 
@@ -1012,6 +1031,7 @@ async function generateTextInternal<
1012
1031
  // continue until a stop condition is met:
1013
1032
  if (await isStopConditionMet({ stopConditions, steps })) {
1014
1033
  steeringEndReason = 'stop-condition';
1034
+ stoppedBy = 'stop-condition';
1015
1035
  return false;
1016
1036
  }
1017
1037
 
@@ -1096,6 +1116,7 @@ async function generateTextInternal<
1096
1116
 
1097
1117
  const stepModel = resolveLanguageModel(
1098
1118
  prepareStepResult?.model ?? model,
1119
+ onWarning,
1099
1120
  );
1100
1121
 
1101
1122
  const stepInstructions =
@@ -1174,6 +1195,7 @@ async function generateTextInternal<
1174
1195
  ).map(({ message }) => message),
1175
1196
  ];
1176
1197
 
1198
+ const promptWarnings: Warning[] = [];
1177
1199
  const promptMessages = await convertToLanguageModelPrompt({
1178
1200
  prompt: {
1179
1201
  instructions: stepInstructions,
@@ -1183,8 +1205,13 @@ async function generateTextInternal<
1183
1205
  download,
1184
1206
  abortSignal: mergedAbortSignal,
1185
1207
  provider: stepModel.provider.split('.')[0],
1208
+ warnings: promptWarnings,
1186
1209
  });
1187
1210
 
1211
+ if (promptWarnings.length > 0) {
1212
+ logCallWarnings({ warnings: promptWarnings });
1213
+ }
1214
+
1188
1215
  const stepProviderOptions = mergeObjects(
1189
1216
  providerOptions,
1190
1217
  prepareStepResult?.providerOptions,
@@ -1781,7 +1808,10 @@ async function generateTextInternal<
1781
1808
  rawFinishReason: currentModelResponse.finishReason.raw,
1782
1809
  usage: stepUsage,
1783
1810
  performance: stepPerformance,
1784
- warnings: currentModelResponse.warnings,
1811
+ warnings: [
1812
+ ...promptWarnings,
1813
+ ...(currentModelResponse.warnings ?? []),
1814
+ ],
1785
1815
  providerMetadata: currentModelResponse.providerMetadata,
1786
1816
  request: stepRequest,
1787
1817
  response: stepResponse,
@@ -1789,7 +1819,7 @@ async function generateTextInternal<
1789
1819
  steeringMessages: stepSteeringMessages,
1790
1820
  });
1791
1821
 
1792
- logWarnings({
1822
+ logCallWarnings({
1793
1823
  warnings: currentModelResponse.warnings ?? [],
1794
1824
  provider: stepModel.provider,
1795
1825
  model: stepModel.modelId,
@@ -1864,6 +1894,7 @@ async function generateTextInternal<
1864
1894
  runtimeContext: lastStep.runtimeContext,
1865
1895
  finishReason: lastStep.finishReason,
1866
1896
  rawFinishReason: lastStep.rawFinishReason,
1897
+ stoppedBy,
1867
1898
  usage: totalUsage,
1868
1899
  totalUsage,
1869
1900
  content: steps.flatMap(step => step.content),
@@ -1925,6 +1956,7 @@ async function generateTextInternal<
1925
1956
  steps,
1926
1957
  totalUsage,
1927
1958
  output: resolvedOutput,
1959
+ stoppedBy,
1928
1960
  });
1929
1961
  } catch (error) {
1930
1962
  const wrappedError = wrapGatewayError(error);
@@ -74,6 +74,7 @@ export {
74
74
  isStepCount as stepCountIs,
75
75
  type StopCondition,
76
76
  } from './stop-condition';
77
+ export type { StoppedBy } from './stopped-by';
77
78
  export {
78
79
  streamLanguageModelCall as experimental_streamLanguageModelCall,
79
80
  type LanguageModelStreamPart,
@@ -154,6 +154,7 @@ type PendingSteer = {
154
154
 
155
155
  class DefaultSteering implements Steering {
156
156
  private state: 'idle' | 'running' | 'ended' = 'idle';
157
+ private endReason: SteeringNotDeliveredReason = 'finished';
157
158
  private pending: Array<PendingSteer> = [];
158
159
  private queued: Array<PendingSteer> = [];
159
160
  private taken: Array<PendingSteer> = [];
@@ -227,7 +228,7 @@ class DefaultSteering implements Steering {
227
228
  type: 'not-delivered',
228
229
  id,
229
230
  message: userMessage,
230
- reason: 'finished',
231
+ reason: this.endReason,
231
232
  })
232
233
  : new Promise<SteeringOutcome>(resolve => {
233
234
  target.push({ id, message: userMessage, resolve });
@@ -329,6 +330,7 @@ class DefaultSteering implements Steering {
329
330
  this.pending = [];
330
331
  this.queued = [];
331
332
  this.state = 'ended';
333
+ this.endReason = reason;
332
334
  this.interruptRequested = false;
333
335
  this.onInterrupt = undefined;
334
336
 
@@ -340,8 +342,9 @@ class DefaultSteering implements Steering {
340
342
  }
341
343
  }
342
344
 
343
- // prepareStep can map messages to new objects, e.g. to add provider options,
344
- // so a message also counts as sent when a user message has the same content:
345
+ // prepareStep can map messages to new objects, e.g. to add provider options or
346
+ // to turn text into a text part, so a message also counts as sent when a user
347
+ // message has the same content parts, ignoring the provider options of parts:
345
348
  function isSent({
346
349
  message,
347
350
  sentMessages,
@@ -349,13 +352,24 @@ function isSent({
349
352
  message: UserModelMessage;
350
353
  sentMessages: ReadonlyArray<ModelMessage>;
351
354
  }): boolean {
352
- const content = JSON.stringify(message.content);
355
+ const content = normalizeContent(message.content);
353
356
 
354
357
  return sentMessages.some(
355
358
  sentMessage =>
356
359
  sentMessage === message ||
357
360
  (sentMessage.role === 'user' &&
358
- JSON.stringify(sentMessage.content) === content),
361
+ normalizeContent(sentMessage.content) === content),
362
+ );
363
+ }
364
+
365
+ function normalizeContent(content: UserModelMessage['content']): string {
366
+ const parts =
367
+ typeof content === 'string'
368
+ ? [{ type: 'text' as const, text: content }]
369
+ : content;
370
+
371
+ return JSON.stringify(
372
+ parts.map(({ providerOptions: _providerOptions, ...part }) => part),
359
373
  );
360
374
  }
361
375
 
@@ -0,0 +1,43 @@
1
+ import type { Context, ToolSet } from '@ai-sdk/provider-utils';
2
+ import { isToolExecutionAllowedFinishReason } from './is-tool-execution-allowed-finish-reason';
3
+ import type { StepResult } from './step-result';
4
+
5
+ /**
6
+ * Why a generation stopped its tool loop:
7
+ *
8
+ * - `model`: the model finished without tool calls that continue the loop,
9
+ * e.g. it gave a final answer, hit the output limit, or its call was
10
+ * interrupted. `finishReason` tells how the last model call finished.
11
+ * - `stop-condition`: a `stopWhen` condition was met.
12
+ * - `tool-without-execute`: a tool call needs a result from a tool without an
13
+ * `execute` function.
14
+ * - `approval`: a tool call needs an approval.
15
+ */
16
+ export type StoppedBy =
17
+ | 'model'
18
+ | 'stop-condition'
19
+ | 'tool-without-execute'
20
+ | 'approval';
21
+
22
+ type FinishedStep = Pick<
23
+ StepResult<ToolSet, Context>,
24
+ 'finishReason' | 'content'
25
+ >;
26
+
27
+ export function getPendingToolCallStoppedBy(step: FinishedStep): StoppedBy {
28
+ if (!isToolExecutionAllowedFinishReason(step.finishReason)) {
29
+ return 'model';
30
+ }
31
+
32
+ return hasPendingApproval(step) ? 'approval' : 'tool-without-execute';
33
+ }
34
+
35
+ export function getModelStoppedBy(step: FinishedStep): StoppedBy {
36
+ return hasPendingApproval(step) ? 'approval' : 'model';
37
+ }
38
+
39
+ function hasPendingApproval({ content }: FinishedStep): boolean {
40
+ return content.some(
41
+ part => part.type === 'tool-approval-request' && part.isAutomatic !== true,
42
+ );
43
+ }
@@ -280,6 +280,7 @@ export async function streamLanguageModelCall<
280
280
  // a Prompt or a standardized Prompt.
281
281
  onStart?: (args: {
282
282
  promptMessages: LanguageModelV4Prompt;
283
+ promptWarnings: Array<CallWarning>;
283
284
  }) => Promise<void> | void;
284
285
  } & Prompt &
285
286
  LanguageModelCallOptions): Promise<{
@@ -310,6 +311,7 @@ export async function streamLanguageModelCall<
310
311
  allowSystemInMessages,
311
312
  } as Prompt);
312
313
 
314
+ const promptWarnings: Array<CallWarning> = [];
313
315
  const promptMessages = await convertToLanguageModelPrompt({
314
316
  prompt: {
315
317
  instructions: standardizedPrompt.instructions,
@@ -319,6 +321,7 @@ export async function streamLanguageModelCall<
319
321
  download,
320
322
  abortSignal,
321
323
  provider: resolvedModel.provider.split('.')[0],
324
+ warnings: promptWarnings,
322
325
  });
323
326
 
324
327
  const stepTools = await prepareTools({
@@ -333,7 +336,7 @@ export async function streamLanguageModelCall<
333
336
  });
334
337
 
335
338
  await notify({
336
- event: { promptMessages },
339
+ event: { promptMessages, promptWarnings },
337
340
  callbacks: onStart,
338
341
  });
339
342
 
@@ -403,6 +406,7 @@ export async function streamLanguageModelCall<
403
406
  request,
404
407
  onLanguageModelCallEnd,
405
408
  collectContent,
409
+ promptWarnings,
406
410
  }),
407
411
  );
408
412
 
@@ -434,6 +438,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform<
434
438
  request,
435
439
  onLanguageModelCallEnd,
436
440
  collectContent,
441
+ promptWarnings,
437
442
  }: {
438
443
  tools: TOOLS | undefined;
439
444
  instructions: Instructions | undefined;
@@ -452,6 +457,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform<
452
457
  request?: { url?: string };
453
458
  onLanguageModelCallEnd?: Arrayable<OnLanguageModelCallEndCallback<TOOLS>>;
454
459
  collectContent: boolean;
460
+ promptWarnings: Array<CallWarning>;
455
461
  }) {
456
462
  // keep track of parsed tool calls so provider-emitted approval requests can reference them
457
463
  // keep track of tool inputs for provider-side tool results
@@ -474,11 +480,23 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform<
474
480
  // repair or refine them.
475
481
  const withholdToolParts = toolChoice.type === 'none';
476
482
 
483
+ let hasStarted = false;
484
+
477
485
  return new TransformStream<
478
486
  LanguageModelV4StreamPart,
479
487
  LanguageModelStreamPart<TOOLS>
480
488
  >({
481
489
  async transform(chunk, controller) {
490
+ if (!hasStarted && chunk.type !== 'stream-start') {
491
+ hasStarted = true;
492
+ if (promptWarnings.length > 0) {
493
+ controller.enqueue({
494
+ type: 'model-call-start',
495
+ warnings: promptWarnings,
496
+ });
497
+ }
498
+ }
499
+
482
500
  if (isOutputChunk(chunk)) {
483
501
  const outputChunkTimestampMs = now();
484
502
 
@@ -881,8 +899,9 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform<
881
899
  case 'stream-start': {
882
900
  controller.enqueue({
883
901
  type: 'model-call-start',
884
- warnings: chunk.warnings,
902
+ warnings: [...promptWarnings, ...chunk.warnings],
885
903
  });
904
+ hasStarted = true;
886
905
  break;
887
906
  }
888
907
 
@@ -49,6 +49,7 @@ import type {
49
49
  StaticToolResult,
50
50
  TypedToolResult,
51
51
  } from './tool-result';
52
+ import type { StoppedBy } from './stopped-by';
52
53
 
53
54
  export type UIMessageStreamOptions<UI_MESSAGE extends UIMessage> = {
54
55
  /**
@@ -266,6 +267,17 @@ export interface StreamTextResult<
266
267
  */
267
268
  readonly rawFinishReason: PromiseLike<string | undefined>;
268
269
 
270
+ /**
271
+ * Why the generation stopped its tool loop. Unlike `finishReason`, which
272
+ * describes the last model call, it tells whether the model, a stop
273
+ * condition, a tool without an `execute` function, or a tool approval ended
274
+ * the loop. `streamText` and `ToolLoopAgent` always set it. Like
275
+ * `finishReason`, it rejects when the stream is aborted.
276
+ *
277
+ * Automatically consumes the stream.
278
+ */
279
+ readonly stoppedBy?: PromiseLike<StoppedBy | undefined>;
280
+
269
281
  /**
270
282
  * The total token usage of the generated response.
271
283
  * When there are multiple steps, the usage is the sum of all step usages.
@@ -618,6 +630,12 @@ export type TextStreamFinishPart = {
618
630
  type: 'finish';
619
631
  finishReason: FinishReason;
620
632
  rawFinishReason: string | undefined;
633
+
634
+ /**
635
+ * Why the generation stopped its tool loop. `streamText` and
636
+ * `ToolLoopAgent` always set it.
637
+ */
638
+ stoppedBy?: StoppedBy;
621
639
  totalUsage: LanguageModelUsage;
622
640
  };
623
641
 
@@ -25,7 +25,8 @@ import {
25
25
  } from '@ai-sdk/provider-utils';
26
26
  import type { ServerResponse } from 'node:http';
27
27
  import { NoOutputGeneratedError, ToolChoiceViolationError } from '../error';
28
- import { logWarnings } from '../logger/log-warnings';
28
+ import { createLogWarnings } from '../logger/create-log-warnings';
29
+ import type { LogWarningsFunction } from '../logger/log-warnings';
29
30
  import { resolveLanguageModel } from '../model/resolve-model';
30
31
  import { cloneModelMessages } from '../prompt/clone-model-message';
31
32
  import { createToolModelOutput } from '../prompt/create-tool-model-output';
@@ -144,6 +145,11 @@ import {
144
145
  type SteeringNotDeliveredReason,
145
146
  type SteeringRun,
146
147
  } from './steering';
148
+ import {
149
+ getModelStoppedBy,
150
+ getPendingToolCallStoppedBy,
151
+ type StoppedBy,
152
+ } from './stopped-by';
147
153
  import {
148
154
  isStepCount,
149
155
  isStopConditionMet,
@@ -380,6 +386,7 @@ type StreamTextOptions<
380
386
  * @param onStepEnd - Callback that is called when each step (LLM call) ends, including intermediate steps.
381
387
  * @param onStepError - Callback that is called when a step that started fails before it produces a step result, i.e. when the provider call throws or rejects, or when the model stream ends without output. A provider `error` chunk still ends the step with `onStepEnd`, and an abort or timeout ends it with `onAbort`.
382
388
  * @param onStepFinish - Deprecated alias for `onStepEnd`.
389
+ * @param onWarning - Callback that receives the warnings of the call instead of the global warning logger.
383
390
  * @param onEnd - Callback that is called when all steps are finished and the response is complete.
384
391
  * @param onFinish - Deprecated alias for `onEnd`.
385
392
  *
@@ -507,6 +514,7 @@ function streamTextInternal<
507
514
  onStepEnd,
508
515
  onStepError,
509
516
  onStepFinish,
517
+ onWarning,
510
518
  onStart,
511
519
  experimental_onStart,
512
520
  onStepStart,
@@ -788,6 +796,13 @@ function streamTextInternal<
788
796
  NoInfer<OUTPUT>
789
797
  >;
790
798
 
799
+ /**
800
+ * Callback that receives the warnings of the call, e.g. unsupported
801
+ * settings or deprecated prompt parts. When it is set, the warnings are
802
+ * not sent to the global warning logger (`AI_SDK_LOG_WARNINGS`).
803
+ */
804
+ onWarning?: LogWarningsFunction;
805
+
791
806
  /**
792
807
  * Callback that is called when each step (LLM call) ends, including intermediate steps.
793
808
  *
@@ -957,7 +972,7 @@ function streamTextInternal<
957
972
  const resolvedOnStepEnd = onStepEnd ?? onStepFinish;
958
973
  return new DefaultStreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>({
959
974
  retention,
960
- model: resolveLanguageModel(model),
975
+ model: resolveLanguageModel(model, onWarning),
961
976
  telemetry,
962
977
  headers,
963
978
  settings,
@@ -1008,6 +1023,7 @@ function streamTextInternal<
1008
1023
  onAbort,
1009
1024
  onStepFinish: resolvedOnStepEnd,
1010
1025
  onStepError,
1026
+ onWarning,
1011
1027
  onStart: resolvedOnStart,
1012
1028
  onStepStart: resolvedOnStepStart,
1013
1029
  onLanguageModelCallStart: resolvedOnLanguageModelCallStart,
@@ -1355,6 +1371,7 @@ class DefaultStreamTextResult<
1355
1371
  private readonly _rawFinishReason = new DelayedPromise<
1356
1372
  Awaited<StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['rawFinishReason']>
1357
1373
  >();
1374
+ private readonly _stoppedBy = new DelayedPromise<StoppedBy | undefined>();
1358
1375
  private readonly _steps = new DelayedPromise<
1359
1376
  Awaited<StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['steps']>
1360
1377
  >();
@@ -1433,6 +1450,7 @@ class DefaultStreamTextResult<
1433
1450
  onAbort,
1434
1451
  onStepFinish,
1435
1452
  onStepError,
1453
+ onWarning,
1436
1454
  onStart,
1437
1455
  onStepStart,
1438
1456
  onLanguageModelCallStart,
@@ -1520,6 +1538,7 @@ class DefaultStreamTextResult<
1520
1538
  NoInfer<RUNTIME_CONTEXT>,
1521
1539
  NoInfer<OUTPUT>
1522
1540
  >;
1541
+ onWarning: undefined | LogWarningsFunction;
1523
1542
  onStart:
1524
1543
  | undefined
1525
1544
  | GenerateTextOnStartCallback<
@@ -1568,13 +1587,17 @@ class DefaultStreamTextResult<
1568
1587
  // needs the updated steps to determine if another step is needed.
1569
1588
  let stepFinish!: DelayedPromise<void>;
1570
1589
 
1590
+ const logCallWarnings = createLogWarnings(onWarning);
1591
+
1571
1592
  let recordedContent: Array<ContentPart<TOOLS>> = [];
1572
1593
  let recordedFinishReason: FinishReason | undefined = undefined;
1573
1594
  let recordedRawFinishReason: string | undefined = undefined;
1595
+ let recordedStoppedBy: StoppedBy | undefined = undefined;
1574
1596
  let recordedTotalUsage: LanguageModelUsage | undefined = undefined;
1575
1597
  let recordedRequest: Omit<LanguageModelRequestMetadata, 'messages'> = {};
1576
1598
  let recordedRequestMessages: Array<ModelMessage> = [];
1577
1599
  let recordedWarnings: Array<CallWarning> = [];
1600
+ let recordedPromptWarnings: Array<CallWarning> = [];
1578
1601
  let recordedSteps: StepResult<TOOLS, RUNTIME_CONTEXT>[] = [];
1579
1602
  const initialResponseMessages: Array<ResponseMessage> = [];
1580
1603
  let stepMessagesForNextStep: Array<ModelMessage> | undefined;
@@ -1895,8 +1918,10 @@ class DefaultStreamTextResult<
1895
1918
  callbacks: [onStepFinish, telemetryDispatcher.onStepEnd],
1896
1919
  });
1897
1920
 
1898
- logWarnings({
1899
- warnings: recordedWarnings,
1921
+ logCallWarnings({
1922
+ warnings: recordedWarnings.filter(
1923
+ warning => !recordedPromptWarnings.includes(warning),
1924
+ ),
1900
1925
  provider: currentStepModel.provider,
1901
1926
  model: currentStepModel.modelId,
1902
1927
  });
@@ -1916,6 +1941,7 @@ class DefaultStreamTextResult<
1916
1941
  recordedTotalUsage = part.totalUsage;
1917
1942
  recordedFinishReason = part.finishReason;
1918
1943
  recordedRawFinishReason = part.rawFinishReason;
1944
+ recordedStoppedBy = part.stoppedBy;
1919
1945
  }
1920
1946
  },
1921
1947
 
@@ -1964,6 +1990,7 @@ class DefaultStreamTextResult<
1964
1990
  // from finish:
1965
1991
  self._finishReason.resolve(finishReason);
1966
1992
  self._rawFinishReason.resolve(recordedRawFinishReason);
1993
+ self._stoppedBy.resolve(recordedStoppedBy);
1967
1994
  self._totalUsage.resolve(totalUsage);
1968
1995
 
1969
1996
  // aggregate results:
@@ -2020,6 +2047,7 @@ class DefaultStreamTextResult<
2020
2047
  runtimeContext: finalStep.runtimeContext,
2021
2048
  finishReason: finalStep.finishReason,
2022
2049
  rawFinishReason: finalStep.rawFinishReason,
2050
+ stoppedBy: recordedStoppedBy,
2023
2051
  usage: totalUsage,
2024
2052
  totalUsage,
2025
2053
  content,
@@ -2659,6 +2687,7 @@ class DefaultStreamTextResult<
2659
2687
 
2660
2688
  const stepModel = resolveLanguageModel(
2661
2689
  prepareStepResult?.model ?? model,
2690
+ onWarning,
2662
2691
  );
2663
2692
  currentStepModel = stepModel;
2664
2693
 
@@ -2817,7 +2846,7 @@ class DefaultStreamTextResult<
2817
2846
  runInStepTracingChannelContext(() =>
2818
2847
  retry(async () =>
2819
2848
  streamLanguageModelCall({
2820
- model: prepareStepResult?.model ?? model,
2849
+ model: stepModel,
2821
2850
  tools: stepModelTools as TOOLS,
2822
2851
  toolOrder: stepToolOrder,
2823
2852
  toolChoice: prepareStepResult?.toolChoice ?? toolChoice,
@@ -2849,7 +2878,13 @@ class DefaultStreamTextResult<
2849
2878
  | undefined
2850
2879
  | OnLanguageModelCallEndCallback<TOOLS>,
2851
2880
  ),
2852
- onStart: async ({ promptMessages }) => {
2881
+ onStart: async ({ promptMessages, promptWarnings }) => {
2882
+ recordedPromptWarnings = promptWarnings;
2883
+ // retries convert the prompt again, log its warnings once per step:
2884
+ if (!stepStart.notified && promptWarnings.length > 0) {
2885
+ logCallWarnings({ warnings: promptWarnings });
2886
+ }
2887
+
2853
2888
  if (stepStart.notified) {
2854
2889
  return;
2855
2890
  }
@@ -3610,6 +3645,7 @@ class DefaultStreamTextResult<
3610
3645
  // the stream ends:
3611
3646
  let steeringEndReason: SteeringNotDeliveredReason =
3612
3647
  'finished';
3648
+ let stoppedBy: StoppedBy = 'model';
3613
3649
 
3614
3650
  const shouldStartNextStep = async () => {
3615
3651
  if (stepFinishReason === 'interrupted') {
@@ -3623,6 +3659,9 @@ class DefaultStreamTextResult<
3623
3659
  deniedToolApprovalResponses.length
3624
3660
  ) {
3625
3661
  steeringEndReason = 'waiting-for-tool-results';
3662
+ stoppedBy = getPendingToolCallStoppedBy(
3663
+ recordedSteps[recordedSteps.length - 1],
3664
+ );
3626
3665
  return false;
3627
3666
  }
3628
3667
 
@@ -3641,6 +3680,9 @@ class DefaultStreamTextResult<
3641
3680
  !steeringRun?.hasPendingMessages() &&
3642
3681
  (isTruncated || !steeringRun?.promoteQueuedMessage())
3643
3682
  ) {
3683
+ stoppedBy = getModelStoppedBy(
3684
+ recordedSteps[recordedSteps.length - 1],
3685
+ );
3644
3686
  return false;
3645
3687
  }
3646
3688
 
@@ -3659,6 +3701,7 @@ class DefaultStreamTextResult<
3659
3701
  })
3660
3702
  ) {
3661
3703
  steeringEndReason = 'stop-condition';
3704
+ stoppedBy = 'stop-condition';
3662
3705
  return false;
3663
3706
  }
3664
3707
 
@@ -3679,6 +3722,7 @@ class DefaultStreamTextResult<
3679
3722
  type: 'finish',
3680
3723
  finishReason: stepFinishReason,
3681
3724
  rawFinishReason: stepRawFinishReason,
3725
+ stoppedBy,
3682
3726
  totalUsage: combinedUsage,
3683
3727
  });
3684
3728
 
@@ -3852,6 +3896,14 @@ class DefaultStreamTextResult<
3852
3896
  return this._rawFinishReason.promise;
3853
3897
  }
3854
3898
 
3899
+ get stoppedBy() {
3900
+ // when any of the promises are accessed, the stream is consumed
3901
+ // so it resolves without needing to consume the stream separately
3902
+ if (this.retention.replay) this.consumeStream();
3903
+
3904
+ return this._stoppedBy.promise;
3905
+ }
3906
+
3855
3907
  /**
3856
3908
  * Split out a new stream from the original stream.
3857
3909
  * The original stream is replaced to allow for further splitting,
@@ -3944,6 +3996,7 @@ class DefaultStreamTextResult<
3944
3996
  private rejectResultPromises(error: unknown) {
3945
3997
  this.rejectResultPromise({ delayedPromise: this._finishReason, error });
3946
3998
  this.rejectResultPromise({ delayedPromise: this._rawFinishReason, error });
3999
+ this.rejectResultPromise({ delayedPromise: this._stoppedBy, error });
3947
4000
  this.rejectResultPromise({ delayedPromise: this._totalUsage, error });
3948
4001
  this.rejectResultPromise({ delayedPromise: this._steps, error });
3949
4002
  this.rejectResultPromise({
@@ -0,0 +1,17 @@
1
+ import { notify } from '../util/notify';
2
+ import { logWarnings, type LogWarningsFunction } from './log-warnings';
3
+
4
+ export function createLogWarnings(
5
+ onWarning: LogWarningsFunction | undefined,
6
+ ): LogWarningsFunction {
7
+ if (onWarning == null) {
8
+ return logWarnings;
9
+ }
10
+
11
+ return options => {
12
+ if (options.warnings.length > 0) {
13
+ // like the other callbacks, errors in onWarning do not break the call:
14
+ void notify({ event: options, callbacks: onWarning });
15
+ }
16
+ };
17
+ }