Repository navigation
Expand file tree
/
Copy pathstream-text.ts
More file actions
2714 lines (2427 loc) · 86.7 KB
/
Copy pathstream-text.ts
File metadata and controls
2714 lines (2427 loc) · 86.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
getErrorMessage,
LanguageModelV4,
SharedV4Warning,
UnsupportedFunctionalityError,
} from '@ai-sdk/provider';
import {
createIdGenerator,
DelayedPromise,
IdGenerator,
isAbortError,
ProviderOptions,
ToolApprovalResponse,
ToolContent,
} from '@ai-sdk/provider-utils';
import { ServerResponse } from 'node:http';
import { NoOutputGeneratedError } from '../error';
import { logWarnings } from '../logger/log-warnings';
import { resolveLanguageModel } from '../model/resolve-model';
import {
CallSettings,
getChunkTimeoutMs,
getStepTimeoutMs,
getTotalTimeoutMs,
TimeoutConfiguration,
} from '../prompt/call-settings';
import { createToolModelOutput } from '../prompt/create-tool-model-output';
import { prepareCallSettings } from '../prompt/prepare-call-settings';
import { prepareToolChoice } from '../prompt/prepare-tool-choice';
import { prepareTools } from '../prompt/prepare-tools';
import { Prompt } from '../prompt/prompt';
import { standardizePrompt } from '../prompt/standardize-prompt';
import { wrapGatewayError } from '../prompt/wrap-gateway-error';
import { getGlobalTelemetryIntegration } from '../telemetry/get-global-telemetry-integration';
import { TelemetrySettings } from '../telemetry/telemetry-settings';
import { createTextStreamResponse } from '../text-stream/create-text-stream-response';
import { pipeTextStreamToResponse } from '../text-stream/pipe-text-stream-to-response';
import { LanguageModelRequestMetadata } from '../types';
import {
CallWarning,
FinishReason,
LanguageModel,
ToolChoice,
} from '../types/language-model';
import { ProviderMetadata } from '../types/provider-metadata';
import {
addLanguageModelUsage,
createNullLanguageModelUsage,
LanguageModelUsage,
} from '../types/usage';
import { UIMessage } from '../ui';
import { createUIMessageStreamResponse } from '../ui-message-stream/create-ui-message-stream-response';
import { getResponseUIMessageId } from '../ui-message-stream/get-response-ui-message-id';
import { handleUIMessageStreamFinish } from '../ui-message-stream/handle-ui-message-stream-finish';
import { pipeUIMessageStreamToResponse } from '../ui-message-stream/pipe-ui-message-stream-to-response';
import {
InferUIMessageChunk,
UIMessageChunk,
} from '../ui-message-stream/ui-message-chunks';
import { UIMessageStreamResponseInit } from '../ui-message-stream/ui-message-stream-response-init';
import { InferUIMessageData, InferUIMessageMetadata } from '../ui/ui-messages';
import { asArray } from '../util/as-array';
import {
AsyncIterableStream,
createAsyncIterableStream,
} from '../util/async-iterable-stream';
import { consumeStream } from '../util/consume-stream';
import { createStitchableStream } from '../util/create-stitchable-stream';
import { DownloadFunction } from '../util/download/download-function';
import { mergeAbortSignals } from '../util/merge-abort-signals';
import { mergeObjects } from '../util/merge-objects';
import { notify } from '../util/notify';
import { now as originalNow } from '../util/now';
import { prepareRetries } from '../util/prepare-retries';
import { collectToolApprovals } from './collect-tool-approvals';
import { ContentPart } from './content-part';
import type {
OnFinishEvent,
OnStartEvent,
OnStepFinishEvent,
OnStepStartEvent,
OnToolCallFinishEvent,
OnToolCallStartEvent,
} from './core-events';
import { createExecuteToolsTransformation } from './create-execute-tools-transformation';
import { executeToolCall } from './execute-tool-call';
import { filterActiveTools } from './filter-active-tool';
import { invokeToolCallbacksFromStream } from './invoke-tool-callbacks-from-stream';
import { Output, text } from './output';
import {
InferCompleteOutput,
InferElementOutput,
InferPartialOutput,
} from './output-utils';
import { PrepareStepFunction } from './prepare-step';
import { convertToReasoningOutputs } from './reasoning-output';
import { ResponseMessage } from './response-message';
import { DefaultStepResult, StepResult } from './step-result';
import {
isStepCount,
isStopConditionMet,
StopCondition,
} from './stop-condition';
import { ModelCallStreamPart, streamModelCall } from './stream-model-call';
import {
ConsumeStreamOptions,
StreamTextResult,
TextStreamPart,
UIMessageStreamOptions,
} from './stream-text-result';
import { toResponseMessages } from './to-response-messages';
import { TypedToolCall } from './tool-call';
import { ToolCallRepairFunction } from './tool-call-repair-function';
import { ToolOutput } from './tool-output';
import { StaticToolOutputDenied } from './tool-output-denied';
import type { GenerationContext } from './generation-context';
import type { ToolSet } from '@ai-sdk/provider-utils';
const originalGenerateId = createIdGenerator({
prefix: 'aitxt',
size: 24,
});
const originalGenerateCallId = createIdGenerator({
prefix: 'call',
size: 24,
});
/**
* A transformation that is applied to the stream.
*
* @param stopStream - A function that stops the source stream.
* @param tools - The tools that are accessible to and can be called by the model. The model needs to support calling tools.
*/
export type StreamTextTransform<TOOLS extends ToolSet> = (options: {
tools: TOOLS; // for type inference
stopStream: () => void;
}) => TransformStream<TextStreamPart<TOOLS>, TextStreamPart<TOOLS>>;
/**
* Callback that is set using the `onError` option.
*
* @param event - The event that is passed to the callback.
*/
export type StreamTextOnErrorCallback = (event: {
error: unknown;
}) => PromiseLike<void> | void;
/**
* Callback that is set using the `onStepFinish` option.
*
* @param stepResult - The result of the step.
*/
export type StreamTextOnStepFinishCallback<
TOOLS extends ToolSet,
CONTEXT extends GenerationContext<TOOLS>,
> = (event: OnStepFinishEvent<TOOLS, CONTEXT>) => PromiseLike<void> | void;
/**
* Callback that is set using the `onChunk` option.
*
* @param event - The event that is passed to the callback.
*/
export type StreamTextOnChunkCallback<TOOLS extends ToolSet> = (event: {
chunk: Extract<
TextStreamPart<TOOLS>,
{
type:
| 'text-delta'
| 'reasoning-delta'
| 'custom'
| 'source'
| 'tool-call'
| 'tool-input-start'
| 'tool-input-delta'
| 'tool-result'
| 'raw';
}
>;
}) => PromiseLike<void> | void;
/**
* Callback that is set using the `onFinish` option.
*
* @param event - The event that is passed to the callback.
*/
export type StreamTextOnFinishCallback<
TOOLS extends ToolSet,
CONTEXT extends GenerationContext<TOOLS>,
> = (event: OnFinishEvent<TOOLS, CONTEXT>) => PromiseLike<void> | void;
/**
* Callback that is set using the `onAbort` option.
*
* @param event - The event that is passed to the callback.
*/
export type StreamTextOnAbortCallback<
TOOLS extends ToolSet,
CONTEXT extends GenerationContext<TOOLS>,
> = (event: {
/**
* Details for all previously finished steps.
*/
readonly steps: StepResult<TOOLS, CONTEXT>[];
}) => PromiseLike<void> | void;
/**
* Include settings for streamText (requestBody only).
*/
type StreamTextIncludeSettings = { requestBody?: boolean };
/**
* Callback that is set using the `experimental_onStart` option.
*
* Called when the streamText operation begins, before any LLM calls.
* Use this callback for logging, analytics, or initializing state at the
* start of a generation.
*
* @param event - The event object containing generation configuration.
*/
export type StreamTextOnStartCallback<
TOOLS extends ToolSet = ToolSet,
CONTEXT extends GenerationContext<TOOLS> = GenerationContext<TOOLS>,
OUTPUT extends Output = Output,
> = (
event: OnStartEvent<TOOLS, CONTEXT, OUTPUT, StreamTextIncludeSettings>,
) => PromiseLike<void> | void;
/**
* Callback that is set using the `experimental_onStepStart` option.
*
* Called when a step (LLM call) begins, before the provider is called.
* Each step represents a single LLM invocation. Multiple steps occur when
* using tool calls (the model may be called multiple times in a loop).
*
* @param event - The event object containing step configuration.
*/
export type StreamTextOnStepStartCallback<
TOOLS extends ToolSet = ToolSet,
CONTEXT extends GenerationContext<TOOLS> = GenerationContext<TOOLS>,
OUTPUT extends Output = Output,
> = (
event: OnStepStartEvent<TOOLS, CONTEXT, OUTPUT, StreamTextIncludeSettings>,
) => PromiseLike<void> | void;
export type StreamTextOnToolCallStartCallback<TOOLS extends ToolSet = ToolSet> =
(event: OnToolCallStartEvent<TOOLS>) => PromiseLike<void> | void;
export type StreamTextOnToolCallFinishCallback<
TOOLS extends ToolSet = ToolSet,
> = (event: OnToolCallFinishEvent<TOOLS>) => PromiseLike<void> | void;
/**
* Generate a text and call tools for a given prompt using a language model.
*
* This function streams the output. If you do not want to stream the output, use `generateText` instead.
*
* @param model - The language model to use.
* @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.
*
* @param system - A system message that will be part of the prompt.
* @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.
* @param messages - A list of messages. You can either use `prompt` or `messages` but not both.
*
* @param maxOutputTokens - Maximum number of tokens to generate.
* @param temperature - Temperature setting.
* The value is passed through to the provider. The range depends on the provider and model.
* It is recommended to set either `temperature` or `topP`, but not both.
* @param topP - Nucleus sampling.
* The value is passed through to the provider. The range depends on the provider and model.
* It is recommended to set either `temperature` or `topP`, but not both.
* @param topK - Only sample from the top K options for each subsequent token.
* Used to remove "long tail" low probability responses.
* Recommended for advanced use cases only. You usually only need to use temperature.
* @param presencePenalty - Presence penalty setting.
* It affects the likelihood of the model to repeat information that is already in the prompt.
* The value is passed through to the provider. The range depends on the provider and model.
* @param frequencyPenalty - Frequency penalty setting.
* It affects the likelihood of the model to repeatedly use the same words or phrases.
* The value is passed through to the provider. The range depends on the provider and model.
* @param stopSequences - Stop sequences.
* If set, the model will stop generating text when one of the stop sequences is generated.
* @param seed - The seed (integer) to use for random sampling.
* If set and supported by the model, calls will generate deterministic results.
*
* @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
* @param abortSignal - An optional abort signal that can be used to cancel the call.
* @param timeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout.
* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
*
* @param onChunk - Callback that is called for each chunk of the stream. The stream processing will pause until the callback promise is resolved.
* @param onError - Callback that is called when an error occurs during streaming. You can use it to log errors.
* @param onStepFinish - Callback that is called when each step (LLM call) is finished, including intermediate steps.
* @param onFinish - Callback that is called when all steps are finished and the response is complete.
*
* @returns
* A result object for accessing different stream types and additional information.
*/
export function streamText<
TOOLS extends ToolSet,
CONTEXT extends GenerationContext<TOOLS> = GenerationContext<TOOLS>,
OUTPUT extends Output = Output<string, string, never>,
>({
model,
tools,
toolChoice,
system,
prompt,
messages,
maxRetries,
abortSignal,
timeout,
headers,
stopWhen = isStepCount(1),
experimental_output,
output = experimental_output,
experimental_telemetry: telemetry,
prepareStep,
providerOptions,
experimental_activeTools,
activeTools = experimental_activeTools,
experimental_repairToolCall: repairToolCall,
experimental_transform: transform,
experimental_download: download,
includeRawChunks = false,
onChunk,
onError = ({ error }) => {
console.error(error);
},
onFinish,
onAbort,
onStepFinish,
experimental_onStart: onStart,
experimental_onStepStart: onStepStart,
experimental_onToolCallStart: onToolCallStart,
experimental_onToolCallFinish: onToolCallFinish,
experimental_context = {} as CONTEXT,
experimental_include: include,
_internal: {
now = originalNow,
generateId = originalGenerateId,
generateCallId = originalGenerateCallId,
} = {},
...settings
}: CallSettings &
Prompt & {
/**
* The language model to use.
*/
model: LanguageModel;
/**
* Timeout in milliseconds. The call will be aborted if it takes longer
* than the specified timeout. Can be used alongside abortSignal.
*
* Can be specified as a number (milliseconds) or as an object with `totalMs`.
*/
timeout?: TimeoutConfiguration<TOOLS>;
/**
* The tools that the model can call. The model needs to support calling tools.
*/
tools?: TOOLS;
/**
* The tool choice strategy. Default: 'auto'.
*/
toolChoice?: ToolChoice<TOOLS>;
/**
* Condition for stopping the generation when there are tool results in the last step.
* When the condition is an array, any of the conditions can be met to stop the generation.
*
* @default isStepCount(1)
*/
stopWhen?:
| StopCondition<NoInfer<TOOLS>, CONTEXT>
| Array<StopCondition<NoInfer<TOOLS>, CONTEXT>>;
/**
* Optional telemetry configuration (experimental).
*/
experimental_telemetry?: TelemetrySettings;
/**
* Additional provider-specific options. They are passed through
* to the provider from the AI SDK and enable provider-specific
* functionality that can be fully encapsulated in the provider.
*/
providerOptions?: ProviderOptions;
/**
* @deprecated Use `activeTools` instead.
*/
experimental_activeTools?: Array<keyof NoInfer<TOOLS>>;
/**
* Limits the tools that are available for the model to call without
* changing the tool call and result types in the result.
*/
activeTools?: Array<keyof NoInfer<TOOLS>>;
/**
* Optional specification for parsing structured outputs from the LLM response.
*/
output?: OUTPUT;
/**
* Optional specification for parsing structured outputs from the LLM response.
*
* @deprecated Use `output` instead.
*/
experimental_output?: OUTPUT;
/**
* Optional function that you can use to provide different settings for a step.
*
* @param options - The options for the step.
* @param options.steps - The steps that have been executed so far.
* @param options.stepNumber - The number of the step that is being executed.
* @param options.model - The model that is being used.
*
* @returns An object that contains the settings for the step.
* If you return undefined (or for undefined settings), the settings from the outer level will be used.
*/
prepareStep?: PrepareStepFunction<NoInfer<TOOLS>, CONTEXT>;
/**
* A function that attempts to repair a tool call that failed to parse.
*/
experimental_repairToolCall?: ToolCallRepairFunction<TOOLS>;
/**
* Optional stream transformations.
* They are applied in the order they are provided.
* The stream transformations must maintain the stream structure for streamText to work correctly.
*/
experimental_transform?:
| StreamTextTransform<TOOLS>
| Array<StreamTextTransform<TOOLS>>;
/**
* Custom download function to use for URLs.
*
* By default, files are downloaded if the model does not support the URL for the given media type.
*/
experimental_download?: DownloadFunction | undefined;
/**
* Whether to include raw chunks from the provider in the stream.
* When enabled, you will receive raw chunks with type 'raw' that contain the unprocessed data from the provider.
* This allows access to cutting-edge provider features not yet wrapped by the AI SDK.
* Defaults to false.
*/
includeRawChunks?: boolean;
/**
* Callback that is called for each chunk of the stream.
* The stream processing will pause until the callback promise is resolved.
*/
onChunk?: StreamTextOnChunkCallback<TOOLS>;
/**
* Callback that is invoked when an error occurs during streaming.
* You can use it to log errors.
* The stream processing will pause until the callback promise is resolved.
*/
onError?: StreamTextOnErrorCallback;
/**
* Callback that is called when the LLM response and all request tool executions
* (for tools that have an `execute` function) are finished.
*
* The usage is the combined usage of all steps.
*/
onFinish?: StreamTextOnFinishCallback<NoInfer<TOOLS>, NoInfer<CONTEXT>>;
onAbort?: StreamTextOnAbortCallback<NoInfer<TOOLS>, NoInfer<CONTEXT>>;
/**
* Callback that is called when each step (LLM call) is finished, including intermediate steps.
*/
onStepFinish?: StreamTextOnStepFinishCallback<
NoInfer<TOOLS>,
NoInfer<CONTEXT>
>;
/**
* Callback that is called when the streamText operation begins,
* before any LLM calls are made.
*/
experimental_onStart?: StreamTextOnStartCallback<
NoInfer<TOOLS>,
NoInfer<CONTEXT>,
NoInfer<OUTPUT>
>;
/**
* Callback that is called when a step (LLM call) begins,
* before the provider is called.
*/
experimental_onStepStart?: StreamTextOnStepStartCallback<
NoInfer<TOOLS>,
NoInfer<CONTEXT>,
NoInfer<OUTPUT>
>;
/**
* Callback that is called right before a tool's execute function runs.
*/
experimental_onToolCallStart?: StreamTextOnToolCallStartCallback<
NoInfer<TOOLS>
>;
/**
* Callback that is called right after a tool's execute function completes (or errors).
*/
experimental_onToolCallFinish?: StreamTextOnToolCallFinishCallback<
NoInfer<TOOLS>
>;
/**
* Context that is passed into tool execution.
*
* Experimental (can break in patch releases).
*
* @default undefined
*/
experimental_context?: CONTEXT;
/**
* Settings for controlling what data is included in step results.
* Disabling inclusion can help reduce memory usage when processing
* large payloads like images.
*
* By default, all data is included for backwards compatibility.
*/
experimental_include?: {
/**
* Whether to retain the request body in step results.
* The request body can be large when sending images or files.
* @default true
*/
requestBody?: boolean;
};
/**
* Internal. For test use only. May change without notice.
*/
_internal?: {
now?: () => number;
generateId?: IdGenerator;
generateCallId?: IdGenerator;
};
}): StreamTextResult<TOOLS, CONTEXT, OUTPUT> {
const totalTimeoutMs = getTotalTimeoutMs(timeout);
const stepTimeoutMs = getStepTimeoutMs(timeout);
const chunkTimeoutMs = getChunkTimeoutMs(timeout);
const stepAbortController =
stepTimeoutMs != null ? new AbortController() : undefined;
const chunkAbortController =
chunkTimeoutMs != null ? new AbortController() : undefined;
return new DefaultStreamTextResult<TOOLS, CONTEXT, OUTPUT>({
model: resolveLanguageModel(model),
telemetry,
headers,
settings,
maxRetries,
abortSignal: mergeAbortSignals(
abortSignal,
totalTimeoutMs != null ? AbortSignal.timeout(totalTimeoutMs) : undefined,
stepAbortController?.signal,
chunkAbortController?.signal,
),
stepTimeoutMs,
stepAbortController,
chunkTimeoutMs,
chunkAbortController,
system,
prompt,
messages,
tools,
toolChoice,
transforms: asArray(transform),
activeTools,
repairToolCall,
stopConditions: asArray(stopWhen),
output,
providerOptions,
prepareStep,
includeRawChunks,
timeout,
stopWhen,
originalAbortSignal: abortSignal,
onChunk,
onError,
onFinish,
onAbort,
onStepFinish,
onStart,
onStepStart,
onToolCallStart,
onToolCallFinish,
now,
generateId,
generateCallId,
experimental_context,
download,
include,
});
}
export type EnrichedStreamPart<TOOLS extends ToolSet, PARTIAL_OUTPUT> = {
part: TextStreamPart<TOOLS>;
partialOutput: PARTIAL_OUTPUT | undefined;
};
function createOutputTransformStream<
TOOLS extends ToolSet,
OUTPUT extends Output,
>(
output: OUTPUT,
): TransformStream<
TextStreamPart<TOOLS>,
EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>
> {
let firstTextChunkId: string | undefined = undefined;
let text = '';
let textChunk = '';
let textProviderMetadata: ProviderMetadata | undefined = undefined;
let lastPublishedJson = '';
function publishTextChunk({
controller,
partialOutput = undefined,
}: {
controller: TransformStreamDefaultController<
EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>
>;
partialOutput?: InferPartialOutput<OUTPUT>;
}) {
controller.enqueue({
part: {
type: 'text-delta',
id: firstTextChunkId!,
text: textChunk,
providerMetadata: textProviderMetadata,
},
partialOutput,
});
textChunk = '';
}
return new TransformStream<
TextStreamPart<TOOLS>,
EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>
>({
async transform(chunk, controller) {
// ensure that we publish the last text chunk before the step finish:
if (chunk.type === 'finish-step' && textChunk.length > 0) {
publishTextChunk({ controller });
}
if (
chunk.type !== 'text-delta' &&
chunk.type !== 'text-start' &&
chunk.type !== 'text-end'
) {
controller.enqueue({ part: chunk, partialOutput: undefined });
return;
}
// we have to pick a text chunk which contains the json text
// since we are streaming, we have to pick the first text chunk
if (firstTextChunkId == null) {
firstTextChunkId = chunk.id;
} else if (chunk.id !== firstTextChunkId) {
controller.enqueue({ part: chunk, partialOutput: undefined });
return;
}
if (chunk.type === 'text-start') {
controller.enqueue({ part: chunk, partialOutput: undefined });
return;
}
if (chunk.type === 'text-end') {
if (textChunk.length > 0) {
publishTextChunk({ controller });
}
controller.enqueue({ part: chunk, partialOutput: undefined });
return;
}
text += chunk.text;
textChunk += chunk.text;
textProviderMetadata = chunk.providerMetadata ?? textProviderMetadata;
// only publish if partial json can be parsed:
const result = await output.parsePartialOutput({ text });
// null should be allowed (valid JSON value) but undefined should not:
if (result !== undefined) {
// only send new json if it has changed:
const currentJson = JSON.stringify(result.partial);
if (currentJson !== lastPublishedJson) {
publishTextChunk({ controller, partialOutput: result.partial });
lastPublishedJson = currentJson;
}
}
},
});
}
class DefaultStreamTextResult<
TOOLS extends ToolSet,
CONTEXT extends GenerationContext<TOOLS>,
OUTPUT extends Output,
> implements StreamTextResult<TOOLS, CONTEXT, OUTPUT> {
private readonly _totalUsage = new DelayedPromise<
Awaited<StreamTextResult<TOOLS, CONTEXT, OUTPUT>['usage']>
>();
private readonly _finishReason = new DelayedPromise<
Awaited<StreamTextResult<TOOLS, CONTEXT, OUTPUT>['finishReason']>
>();
private readonly _rawFinishReason = new DelayedPromise<
Awaited<StreamTextResult<TOOLS, CONTEXT, OUTPUT>['rawFinishReason']>
>();
private readonly _steps = new DelayedPromise<
Awaited<StreamTextResult<TOOLS, CONTEXT, OUTPUT>['steps']>
>();
private readonly addStream: (
stream: ReadableStream<TextStreamPart<TOOLS>>,
) => void;
private readonly closeStream: () => void;
private baseStream: ReadableStream<
EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>
>;
private outputSpecification: OUTPUT | undefined;
private includeRawChunks: boolean;
private tools: TOOLS | undefined;
constructor({
model,
telemetry,
headers,
settings,
maxRetries: maxRetriesArg,
abortSignal,
stepTimeoutMs,
stepAbortController,
chunkTimeoutMs,
chunkAbortController,
system,
prompt,
messages,
tools,
toolChoice,
transforms,
activeTools,
repairToolCall,
stopConditions,
output,
providerOptions,
prepareStep,
includeRawChunks,
now,
generateId,
generateCallId,
timeout,
stopWhen,
originalAbortSignal,
onChunk,
onError,
onFinish,
onAbort,
onStepFinish,
onStart,
onStepStart,
onToolCallStart,
onToolCallFinish,
experimental_context,
download,
include,
}: {
model: LanguageModelV4;
telemetry: TelemetrySettings | undefined;
headers: Record<string, string | undefined> | undefined;
settings: Omit<CallSettings, 'abortSignal' | 'headers'>;
maxRetries: number | undefined;
abortSignal: AbortSignal | undefined;
stepTimeoutMs: number | undefined;
stepAbortController: AbortController | undefined;
chunkTimeoutMs: number | undefined;
chunkAbortController: AbortController | undefined;
system: Prompt['system'];
prompt: Prompt['prompt'];
messages: Prompt['messages'];
tools: TOOLS | undefined;
toolChoice: ToolChoice<TOOLS> | undefined;
transforms: Array<StreamTextTransform<TOOLS>>;
activeTools: Array<keyof TOOLS> | undefined;
repairToolCall: ToolCallRepairFunction<TOOLS> | undefined;
stopConditions: Array<StopCondition<NoInfer<TOOLS>, NoInfer<CONTEXT>>>;
output: OUTPUT | undefined;
providerOptions: ProviderOptions | undefined;
prepareStep:
| PrepareStepFunction<NoInfer<TOOLS>, NoInfer<CONTEXT>>
| undefined;
includeRawChunks: boolean;
now: () => number;
generateId: () => string;
generateCallId: () => string;
timeout: TimeoutConfiguration<TOOLS> | undefined;
stopWhen:
| StopCondition<NoInfer<TOOLS>, NoInfer<CONTEXT>>
| Array<StopCondition<NoInfer<TOOLS>, NoInfer<CONTEXT>>>
| undefined;
originalAbortSignal: AbortSignal | undefined;
experimental_context: CONTEXT;
download: DownloadFunction | undefined;
include: { requestBody?: boolean } | undefined;
// callbacks:
onChunk: undefined | StreamTextOnChunkCallback<TOOLS>;
onError: StreamTextOnErrorCallback;
onFinish:
| undefined
| StreamTextOnFinishCallback<NoInfer<TOOLS>, NoInfer<CONTEXT>>;
onAbort:
| undefined
| StreamTextOnAbortCallback<NoInfer<TOOLS>, NoInfer<CONTEXT>>;
onStepFinish:
| undefined
| StreamTextOnStepFinishCallback<NoInfer<TOOLS>, NoInfer<CONTEXT>>;
onStart:
| undefined
| StreamTextOnStartCallback<
NoInfer<TOOLS>,
NoInfer<CONTEXT>,
NoInfer<OUTPUT>
>;
onStepStart:
| undefined
| StreamTextOnStepStartCallback<
NoInfer<TOOLS>,
NoInfer<CONTEXT>,
NoInfer<OUTPUT>
>;
onToolCallStart: undefined | StreamTextOnToolCallStartCallback<TOOLS>;
onToolCallFinish: undefined | StreamTextOnToolCallFinishCallback<TOOLS>;
}) {
this.outputSpecification = output;
this.includeRawChunks = includeRawChunks;
this.tools = tools;
const createGlobalTelemetry = getGlobalTelemetryIntegration<
TOOLS,
OUTPUT
>();
const globalTelemetry = createGlobalTelemetry({
integrations: telemetry?.integrations,
});
// promise to ensure that the step has been fully processed by the event processor
// before a new step is started. This is required because the continuation condition
// needs the updated steps to determine if another step is needed.
let stepFinish!: DelayedPromise<void>;
let recordedContent: Array<ContentPart<TOOLS>> = [];
const recordedResponseMessages: Array<ResponseMessage> = [];
let recordedFinishReason: FinishReason | undefined = undefined;
let recordedRawFinishReason: string | undefined = undefined;
let recordedTotalUsage: LanguageModelUsage | undefined = undefined;
let recordedRequest: LanguageModelRequestMetadata = {};
let recordedWarnings: Array<CallWarning> = [];
const recordedSteps: StepResult<TOOLS, CONTEXT>[] = [];
// Track provider-executed tool calls that support deferred results
// (e.g., code_execution in programmatic tool calling scenarios).
// These tools may not return their results in the same turn as their call.
const pendingDeferredToolCalls = new Map<string, { toolName: string }>();
let activeTextContent: Record<
string,
{
type: 'text';
text: string;
providerMetadata: ProviderMetadata | undefined;
}
> = {};
let activeReasoningContent: Record<
string,
{
type: 'reasoning';
text: string;
providerMetadata: ProviderMetadata | undefined;
}
> = {};
const eventProcessor = new TransformStream<
EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>,
EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>
>({
async transform(chunk, controller) {
controller.enqueue(chunk); // forward the chunk to the next stream
const { part } = chunk;
if (
part.type === 'text-delta' ||
part.type === 'reasoning-delta' ||
part.type === 'custom' ||
part.type === 'source' ||
part.type === 'tool-call' ||
part.type === 'tool-result' ||
part.type === 'tool-input-start' ||
part.type === 'tool-input-delta' ||
part.type === 'raw'
) {
await onChunk?.({ chunk: part });
}
if (part.type === 'error') {
await onError({ error: wrapGatewayError(part.error) });
}
if (part.type === 'text-start') {
activeTextContent[part.id] = {
type: 'text',
text: '',
providerMetadata: part.providerMetadata,
};
recordedContent.push(activeTextContent[part.id]);
}
if (part.type === 'text-delta') {
const activeText = activeTextContent[part.id];
if (activeText == null) {
controller.enqueue({
part: {
type: 'error',
error: `text part ${part.id} not found`,
},
partialOutput: undefined,
});
return;
}
activeText.text += part.text;
activeText.providerMetadata =
part.providerMetadata ?? activeText.providerMetadata;
}
if (part.type === 'text-end') {
const activeText = activeTextContent[part.id];
if (activeText == null) {
controller.enqueue({
part: {
type: 'error',
error: `text part ${part.id} not found`,
},
partialOutput: undefined,
});
return;
}
activeText.providerMetadata =
part.providerMetadata ?? activeText.providerMetadata;
delete activeTextContent[part.id];
}
if (part.type === 'reasoning-start') {
activeReasoningContent[part.id] = {
type: 'reasoning',
text: '',
providerMetadata: part.providerMetadata,
};
recordedContent.push(activeReasoningContent[part.id]);
}
if (part.type === 'reasoning-delta') {
const activeReasoning = activeReasoningContent[part.id];
if (activeReasoning == null) {
controller.enqueue({
part: {
type: 'error',