Skip to content

pydantic_ai.ui.vercel_ai

Vercel AI protocol adapter for Pydantic AI agents.

This module provides classes for integrating Pydantic AI agents with the Vercel AI protocol, enabling streaming event-based communication for interactive AI applications.

Converted to Python from: https://github.com/vercel/ai/blob/ai%405.0.34/packages/ai/src/ui/ui-messages.ts

VercelAIAdapter dataclass

Bases: UIAdapter[RequestData, UIMessage, BaseChunk, AgentDepsT, OutputDataT]

UI adapter for the Vercel AI protocol.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/_adapter.py
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
@dataclass
class VercelAIAdapter(UIAdapter[RequestData, UIMessage, BaseChunk, AgentDepsT, OutputDataT]):
    """UI adapter for the Vercel AI protocol."""

    _: KW_ONLY
    sdk_version: Literal[5, 6] = 5
    """Vercel AI SDK version to target. Default is 5 for backwards compatibility.

    Setting `sdk_version=6` enables tool approval streaming for human-in-the-loop workflows.
    """
    server_message_id: str | None = None
    """Optional server-generated message ID to include in the `StartChunk`."""

    @classmethod
    def build_run_input(cls, body: bytes) -> RequestData:
        """Build a Vercel AI run input object from the request body."""
        return request_data_ta.validate_json(body)

    @classmethod
    async def from_request(
        cls,
        request: Request,
        *,
        agent: AbstractAgent[AgentDepsT, OutputDataT],
        sdk_version: Literal[5, 6] = 5,
        server_message_id: str | None = None,
        manage_system_prompt: Literal['server', 'client'] = 'server',
        allowed_file_url_schemes: frozenset[str] = frozenset({'http', 'https'}),
        **kwargs: Any,
    ) -> VercelAIAdapter[AgentDepsT, OutputDataT]:
        """Extends [`from_request`][pydantic_ai.ui.UIAdapter.from_request] with Vercel AI-specific parameters."""
        return await super().from_request(
            request,
            agent=agent,
            sdk_version=sdk_version,
            server_message_id=server_message_id,
            manage_system_prompt=manage_system_prompt,
            allowed_file_url_schemes=allowed_file_url_schemes,
            **kwargs,
        )

    @classmethod
    async def dispatch_request(
        cls,
        request: Request,
        *,
        agent: AbstractAgent[DispatchDepsT, DispatchOutputDataT],
        sdk_version: Literal[5, 6] = 5,
        server_message_id: str | None = None,
        message_history: Sequence[ModelMessage] | None = None,
        deferred_tool_results: DeferredToolResults | None = None,
        conversation_id: str | None = None,
        model: Model | KnownModelName | str | None = None,
        instructions: _instructions.AgentInstructions[DispatchDepsT] = None,
        deps: DispatchDepsT = None,
        output_type: OutputSpec[Any] | None = None,
        model_settings: ModelSettings | None = None,
        usage_limits: UsageLimits | None = None,
        usage: RunUsage | None = None,
        metadata: AgentMetadata[DispatchDepsT] | None = None,
        infer_name: bool = True,
        toolsets: Sequence[AbstractToolset[DispatchDepsT]] | None = None,
        capabilities: Sequence[AbstractCapability[DispatchDepsT]] | None = None,
        on_complete: OnCompleteFunc[BaseChunk] | None = None,
        manage_system_prompt: Literal['server', 'client'] = 'server',
        allowed_file_url_schemes: frozenset[str] = frozenset({'http', 'https'}),
        **kwargs: Any,
    ) -> Response:
        """Extends [`dispatch_request`][pydantic_ai.ui.UIAdapter.dispatch_request] with Vercel AI-specific parameters."""
        return await super().dispatch_request(
            request,
            agent=agent,
            sdk_version=sdk_version,
            server_message_id=server_message_id,
            message_history=message_history,
            deferred_tool_results=deferred_tool_results,
            conversation_id=conversation_id,
            model=model,
            instructions=instructions,
            deps=deps,
            output_type=output_type,
            model_settings=model_settings,
            usage_limits=usage_limits,
            usage=usage,
            metadata=metadata,
            infer_name=infer_name,
            toolsets=toolsets,
            capabilities=capabilities,
            on_complete=on_complete,
            manage_system_prompt=manage_system_prompt,
            allowed_file_url_schemes=allowed_file_url_schemes,
            **kwargs,
        )

    def build_event_stream(self) -> UIEventStream[RequestData, BaseChunk, AgentDepsT, OutputDataT]:
        """Build a Vercel AI event stream transformer."""
        return VercelAIEventStream(
            self.run_input, accept=self.accept, sdk_version=self.sdk_version, server_message_id=self.server_message_id
        )

    @cached_property
    def deferred_tool_results(self) -> DeferredToolResults | None:
        """Extract deferred tool results from Vercel AI messages with approval responses."""
        if self.sdk_version < 6:
            return None
        approvals: dict[str, bool | DeferredToolApprovalResult] = {}
        for tool_call_id, approval in iter_tool_approval_responses(self.run_input.messages):
            if approval.approved:
                approvals[tool_call_id] = True
            elif approval.reason:
                approvals[tool_call_id] = ToolDenied(message=approval.reason)
            else:
                approvals[tool_call_id] = False
        return DeferredToolResults(approvals=approvals) if approvals else None

    @cached_property
    def messages(self) -> list[ModelMessage]:
        """Pydantic AI messages from the Vercel AI run input."""
        return self.load_messages(self.run_input.messages)

    @cached_property
    def conversation_id(self) -> str | None:
        """Conversation ID from the top-level `id` field of the Vercel AI request body (the chat ID)."""
        return self.run_input.id

    @classmethod
    def load_messages(cls, messages: Sequence[UIMessage]) -> list[ModelMessage]:  # noqa: C901
        """Transform Vercel AI messages into Pydantic AI messages."""
        builder = MessagesBuilder()

        for msg in messages:
            if msg.role == 'system':
                for part in msg.parts:
                    if isinstance(part, TextUIPart):
                        builder.add(SystemPromptPart(content=part.text))
                    else:  # pragma: no cover
                        raise ValueError(f'Unsupported system message part type: {type(part)}')
            elif msg.role == 'user':
                user_prompt_content: str | list[UserContent] = []
                for part in msg.parts:
                    if isinstance(part, TextUIPart):
                        user_prompt_content.append(part.text)
                    elif isinstance(part, FileUIPart):
                        try:
                            file = BinaryContent.from_data_uri(part.url)
                        except ValueError:
                            # Check provider_metadata for UploadedFile data
                            provider_meta = load_provider_metadata(part.provider_metadata)
                            uploaded_file_id = provider_meta.get('file_id')
                            uploaded_file_provider = provider_meta.get('provider_name')
                            if uploaded_file_id and uploaded_file_provider:
                                file = UploadedFile(
                                    file_id=uploaded_file_id,
                                    provider_name=cast(UploadedFileProviderName, uploaded_file_provider),
                                    media_type=part.media_type,
                                    vendor_metadata=provider_meta.get('vendor_metadata'),
                                    identifier=provider_meta.get('identifier'),
                                )
                            else:
                                media_type_prefix = part.media_type.split('/', 1)[0]
                                match media_type_prefix:
                                    case 'image':
                                        file = ImageUrl(url=part.url, media_type=part.media_type)
                                    case 'video':
                                        file = VideoUrl(url=part.url, media_type=part.media_type)
                                    case 'audio':
                                        file = AudioUrl(url=part.url, media_type=part.media_type)
                                    case _:
                                        file = DocumentUrl(url=part.url, media_type=part.media_type)
                        user_prompt_content.append(file)
                    elif isinstance(part, DataUIPart):
                        # Contains custom data that shouldn't be sent to the model
                        pass
                    else:  # pragma: no cover
                        raise ValueError(f'Unsupported user message part type: {type(part)}')

                if user_prompt_content:  # pragma: no branch
                    if len(user_prompt_content) == 1 and isinstance(user_prompt_content[0], str):
                        user_prompt_content = user_prompt_content[0]
                    builder.add(UserPromptPart(content=user_prompt_content))

            elif msg.role == 'assistant':
                for part in msg.parts:
                    if isinstance(part, TextUIPart):
                        provider_meta = load_provider_metadata(part.provider_metadata)
                        builder.add(
                            TextPart(
                                content=part.text,
                                id=provider_meta.get('id'),
                                provider_name=provider_meta.get('provider_name'),
                                provider_details=provider_meta.get('provider_details'),
                            )
                        )
                    elif isinstance(part, ReasoningUIPart):
                        provider_meta = load_provider_metadata(part.provider_metadata)
                        builder.add(
                            ThinkingPart(
                                content=part.text,
                                id=provider_meta.get('id'),
                                signature=None if part.state == 'streaming' else provider_meta.get('signature'),
                                provider_name=provider_meta.get('provider_name'),
                                provider_details=provider_meta.get('provider_details'),
                            )
                        )
                    elif isinstance(part, FileUIPart):
                        try:
                            file = BinaryContent.from_data_uri(part.url)
                        except ValueError as e:  # pragma: no cover
                            # We don't yet handle non-data-URI file URLs returned by assistants, as no Pydantic AI models do this.
                            raise ValueError(
                                'Vercel AI integration can currently only handle assistant file parts with data URIs.'
                            ) from e
                        provider_meta = load_provider_metadata(part.provider_metadata)
                        builder.add(
                            FilePart(
                                content=file,
                                id=provider_meta.get('id'),
                                provider_name=provider_meta.get('provider_name'),
                                provider_details=provider_meta.get('provider_details'),
                            )
                        )
                    elif isinstance(part, ToolUIPart | DynamicToolUIPart):
                        if isinstance(part, DynamicToolUIPart):
                            tool_name = part.tool_name
                            builtin_tool = False
                        else:
                            tool_name = part.type.removeprefix('tool-')
                            builtin_tool = part.provider_executed

                        tool_call_id = part.tool_call_id

                        args: str | dict[str, Any] | None = part.input

                        if isinstance(args, str):
                            try:
                                parsed = json.loads(args)
                                if _is_str_dict(parsed):
                                    args = parsed
                            except json.JSONDecodeError:
                                pass
                        elif isinstance(args, dict) or args is None:
                            pass
                        else:
                            assert_never(args)

                        provider_meta = load_provider_metadata(part.call_provider_metadata)
                        part_id = provider_meta.get('id')
                        provider_name = provider_meta.get('provider_name')
                        provider_details = provider_meta.get('provider_details')

                        if builtin_tool:
                            # For builtin tools, we need to create 2 parts (BuiltinToolCall & BuiltinToolReturn) for a single Vercel ToolOutput
                            # The call and return metadata are combined in the output part.
                            # So we extract and return them to the respective parts
                            call_meta = return_meta = {}
                            has_tool_output = isinstance(
                                part, (ToolOutputAvailablePart, ToolOutputErrorPart, ToolOutputDeniedPart)
                            )

                            if has_tool_output:
                                call_meta, return_meta = cls._load_builtin_tool_meta(provider_meta)

                            builder.add(
                                NativeToolCallPart(
                                    tool_name=tool_name,
                                    tool_call_id=tool_call_id,
                                    args=args,
                                    id=call_meta.get('id') or part_id,
                                    provider_name=call_meta.get('provider_name') or provider_name,
                                    provider_details=call_meta.get('provider_details') or provider_details,
                                )
                            )

                            if has_tool_output:
                                if isinstance(part, ToolOutputErrorPart):
                                    output: Any = part.error_text
                                    outcome: Literal['success', 'failed', 'denied'] = 'failed'
                                elif isinstance(part, ToolOutputDeniedPart):
                                    output = _denial_reason(part)
                                    outcome = 'denied'
                                else:
                                    output = part.output if isinstance(part, ToolOutputAvailablePart) else None
                                    outcome = 'success'
                                builder.add(
                                    NativeToolReturnPart(
                                        tool_name=tool_name,
                                        tool_call_id=tool_call_id,
                                        content=output,
                                        provider_name=return_meta.get('provider_name') or provider_name,
                                        provider_details=return_meta.get('provider_details') or provider_details,
                                        outcome=outcome,
                                    )
                                )
                        else:
                            builder.add(
                                ToolCallPart(
                                    tool_name=tool_name,
                                    tool_call_id=tool_call_id,
                                    args=args,
                                    id=part_id,
                                    provider_name=provider_name,
                                    provider_details=provider_details,
                                )
                            )

                            if part.state == 'output-available':
                                builder.add(
                                    ToolReturnPart(tool_name=tool_name, tool_call_id=tool_call_id, content=part.output)
                                )
                            elif part.state == 'output-error':
                                builder.add(
                                    ToolReturnPart(
                                        tool_name=tool_name,
                                        tool_call_id=tool_call_id,
                                        content=part.error_text,
                                        outcome='failed',
                                    )
                                )
                            elif part.state == 'output-denied':
                                builder.add(
                                    ToolReturnPart(
                                        tool_name=tool_name,
                                        tool_call_id=tool_call_id,
                                        content=_denial_reason(part),
                                        outcome='denied',
                                    )
                                )
                    elif isinstance(part, DataUIPart):  # pragma: no cover
                        # Contains custom data that shouldn't be sent to the model
                        pass
                    elif isinstance(part, SourceUrlUIPart):  # pragma: no cover
                        # TODO: Once we support citations: https://github.com/pydantic/pydantic-ai/issues/3126
                        pass
                    elif isinstance(part, SourceDocumentUIPart):  # pragma: no cover
                        # TODO: Once we support citations: https://github.com/pydantic/pydantic-ai/issues/3126
                        pass
                    elif isinstance(part, StepStartUIPart):  # pragma: no cover
                        # Nothing to do here
                        pass
                    else:
                        assert_never(part)
            else:
                assert_never(msg.role)

        return builder.messages

    @staticmethod
    def _dump_builtin_tool_meta(
        call_provider_metadata: ProviderMetadata | None, return_provider_metadata: ProviderMetadata | None
    ) -> ProviderMetadata | None:
        """Use special keys (call_meta and return_meta) to dump combined provider metadata."""
        return dump_provider_metadata(call_meta=call_provider_metadata, return_meta=return_provider_metadata)

    @staticmethod
    def _load_builtin_tool_meta(
        provider_metadata: ProviderMetadata,
    ) -> tuple[dict[str, Any], dict[str, Any]]:
        """Use special keys (call_meta and return_meta) to load combined provider metadata."""
        return provider_metadata.get('call_meta') or {}, provider_metadata.get('return_meta') or {}

    @staticmethod
    def _dump_request_message(msg: ModelRequest) -> tuple[list[UIMessagePart], list[UIMessagePart]]:
        """Convert a ModelRequest into a UIMessage."""
        system_ui_parts: list[UIMessagePart] = []
        user_ui_parts: list[UIMessagePart] = []

        for part in msg.parts:
            if isinstance(part, SystemPromptPart):
                system_ui_parts.append(TextUIPart(text=part.content, state='done'))
            elif isinstance(part, UserPromptPart):
                user_ui_parts.extend(_convert_user_prompt_part(part))
            elif isinstance(part, ToolReturnPart):
                # Tool returns are merged into the tool call in the assistant message
                pass
            elif isinstance(part, RetryPromptPart):
                if part.tool_name:
                    # Tool-related retries are handled when processing ToolCallPart in ModelResponse
                    pass
                else:
                    # Non-tool retries (e.g., output validation errors) become user text
                    user_ui_parts.append(TextUIPart(text=part.model_response(), state='done'))
            else:
                assert_never(part)

        return system_ui_parts, user_ui_parts

    @classmethod
    def _dump_response_message(
        cls,
        msg: ModelResponse,
        tool_results: dict[str, ToolReturnPart | RetryPromptPart],
        sdk_version: Literal[5, 6] = 5,
    ) -> list[UIMessagePart]:
        """Convert a ModelResponse into a UIMessage."""
        ui_parts: list[UIMessagePart] = []

        # For builtin tools, returns can be in the same ModelResponse as calls
        local_builtin_returns: dict[str, NativeToolReturnPart] = {
            part.tool_call_id: part for part in msg.parts if isinstance(part, NativeToolReturnPart)
        }

        for part in msg.parts:
            if isinstance(part, NativeToolReturnPart):
                continue
            elif isinstance(part, TextPart):
                # Combine consecutive text parts
                if ui_parts and isinstance(ui_parts[-1], TextUIPart):
                    ui_parts[-1].text += part.content
                else:
                    provider_metadata = dump_provider_metadata(
                        id=part.id, provider_name=part.provider_name, provider_details=part.provider_details
                    )
                    ui_parts.append(TextUIPart(text=part.content, state='done', provider_metadata=provider_metadata))
            elif isinstance(part, ThinkingPart):
                provider_metadata = dump_provider_metadata(
                    id=part.id,
                    signature=part.signature,
                    provider_name=part.provider_name,
                    provider_details=part.provider_details,
                )
                ui_parts.append(ReasoningUIPart(text=part.content, state='done', provider_metadata=provider_metadata))
            elif isinstance(part, FilePart):
                ui_parts.append(
                    FileUIPart(
                        url=part.content.data_uri,
                        media_type=part.content.media_type,
                        provider_metadata=dump_provider_metadata(
                            id=part.id, provider_name=part.provider_name, provider_details=part.provider_details
                        ),
                    )
                )
            elif isinstance(part, NativeToolCallPart):
                tool_name = f'tool-{part.tool_name}'
                if builtin_return := local_builtin_returns.get(part.tool_call_id):
                    # Builtin tool calls are represented by two parts in pydantic_ai:
                    #   1. NativeToolCallPart (the tool request) -> part
                    #   2. NativeToolReturnPart (the tool's output) -> builtin_return
                    # The Vercel AI SDK only has a single ToolOutputPart (ToolOutputAvailablePart or ToolOutputErrorPart).
                    # So, we need to combine the metadata so that when we later convert back from Vercel AI to pydantic_ai,
                    # we can properly reconstruct both the call and return parts with their respective metadata.
                    # Note: This extra metadata handling is only needed for built-in tools, since normal tool returns
                    # (ToolReturnPart) do not include provider metadata.

                    call_meta = dump_provider_metadata(
                        wrapper_key=None,
                        id=part.id,
                        provider_name=part.provider_name,
                        provider_details=part.provider_details,
                    )
                    return_meta = dump_provider_metadata(
                        wrapper_key=None,
                        provider_name=builtin_return.provider_name,
                        provider_details=builtin_return.provider_details,
                    )
                    combined_provider_meta = cls._dump_builtin_tool_meta(call_meta, return_meta)

                    if builtin_return.outcome == 'denied':
                        ui_parts.append(
                            ToolOutputDeniedPart(
                                type=tool_name,
                                tool_call_id=part.tool_call_id,
                                input=part.args_as_dict(),
                                provider_executed=True,
                                call_provider_metadata=combined_provider_meta,
                                approval=ToolApprovalResponded(
                                    id=str(uuid.uuid4()),
                                    approved=False,
                                    reason=builtin_return.model_response_str(),
                                ),
                            )
                        )
                    elif (
                        builtin_return.outcome == 'failed'
                        or builtin_return.model_response_object().get('is_error') is True
                    ):
                        response_obj = builtin_return.model_response_object()
                        error_text = response_obj.get('error_text', builtin_return.model_response_str())
                        ui_parts.append(
                            ToolOutputErrorPart(
                                type=tool_name,
                                tool_call_id=part.tool_call_id,
                                input=part.args_as_dict(),
                                error_text=error_text,
                                provider_executed=True,
                                call_provider_metadata=combined_provider_meta,
                            )
                        )
                    else:
                        ui_parts.append(
                            ToolOutputAvailablePart(
                                type=tool_name,
                                tool_call_id=part.tool_call_id,
                                input=part.args_as_dict(),
                                output=tool_return_output(builtin_return),
                                provider_executed=True,
                                call_provider_metadata=combined_provider_meta,
                            )
                        )
                else:
                    call_provider_metadata = dump_provider_metadata(
                        id=part.id, provider_name=part.provider_name, provider_details=part.provider_details
                    )
                    # No result found → the tool call is deferred (awaiting approval or external result).
                    # On v6, emit `approval-requested` so the frontend can render approve/reject buttons on reload.
                    # On v5, fall back to `input-available` since approval states are v6-only.
                    # `approval.id` is not used for matching (tool_call_id is the match key),
                    # so we use tool_call_id for a stable, deterministic value in dump output.
                    if sdk_version >= 6:
                        ui_parts.append(
                            ToolApprovalRequestedPart(
                                type=tool_name,
                                tool_call_id=part.tool_call_id,
                                input=part.args_as_dict(),
                                provider_executed=True,
                                call_provider_metadata=call_provider_metadata,
                                approval=ToolApprovalRequested(id=part.tool_call_id),
                            )
                        )
                    else:
                        ui_parts.append(
                            ToolInputAvailablePart(
                                type=tool_name,
                                tool_call_id=part.tool_call_id,
                                input=part.args_as_dict(),
                                provider_executed=True,
                                call_provider_metadata=call_provider_metadata,
                            )
                        )
            elif isinstance(part, ToolCallPart):
                ui_parts.extend(cls._dump_tool_call_part(part, tool_results, sdk_version))
            elif isinstance(part, CompactionPart):  # pragma: no cover
                pass  # Compaction parts are not rendered in the UI
            else:
                assert_never(part)

        return ui_parts

    @staticmethod
    def _dump_tool_call_part(
        part: ToolCallPart,
        tool_results: dict[str, ToolReturnPart | RetryPromptPart],
        sdk_version: Literal[5, 6] = 5,
    ) -> list[UIMessagePart]:
        """Convert a ToolCallPart (with optional result) into UIMessageParts."""
        tool_result = tool_results.get(part.tool_call_id)
        call_provider_metadata = dump_provider_metadata(
            id=part.id, provider_name=part.provider_name, provider_details=part.provider_details
        )
        tool_type = f'tool-{part.tool_name}'
        ui_parts: list[UIMessagePart] = []

        if isinstance(tool_result, ToolReturnPart):
            if tool_result.outcome == 'denied':
                ui_parts.append(
                    ToolOutputDeniedPart(
                        type=tool_type,
                        tool_call_id=part.tool_call_id,
                        input=part.args_as_dict(),
                        provider_executed=False,
                        call_provider_metadata=call_provider_metadata,
                        approval=ToolApprovalResponded(
                            id=str(uuid.uuid4()),
                            approved=False,
                            reason=tool_result.model_response_str(),
                        ),
                    )
                )
            elif tool_result.outcome == 'failed':
                ui_parts.append(
                    ToolOutputErrorPart(
                        type=tool_type,
                        tool_call_id=part.tool_call_id,
                        input=part.args_as_dict(),
                        error_text=tool_result.model_response_str(),
                        provider_executed=False,
                        call_provider_metadata=call_provider_metadata,
                    )
                )
            else:
                ui_parts.append(
                    ToolOutputAvailablePart(
                        type=tool_type,
                        tool_call_id=part.tool_call_id,
                        input=part.args_as_dict(),
                        output=tool_return_output(tool_result),
                        provider_executed=False,
                        call_provider_metadata=call_provider_metadata,
                    )
                )
            # Check for Vercel AI chunks returned by tool calls via metadata.
            ui_parts.extend(_extract_metadata_ui_parts(tool_result))
        elif isinstance(tool_result, RetryPromptPart):
            ui_parts.append(
                ToolOutputErrorPart(
                    type=tool_type,
                    tool_call_id=part.tool_call_id,
                    input=part.args_as_dict(),
                    error_text=tool_result.model_response(),
                    provider_executed=False,
                    call_provider_metadata=call_provider_metadata,
                )
            )
        else:
            # No result found → the tool call is deferred (awaiting approval or external result).
            # On v6, emit `approval-requested` so the frontend can render approve/reject buttons on reload.
            # On v5, fall back to `input-available` since approval states are v6-only.
            # `approval.id` is not used for matching (tool_call_id is the match key),
            # so we use tool_call_id for a stable, deterministic value in dump output.
            if sdk_version >= 6:
                ui_parts.append(
                    ToolApprovalRequestedPart(
                        type=tool_type,
                        tool_call_id=part.tool_call_id,
                        input=part.args_as_dict(),
                        provider_executed=False,
                        call_provider_metadata=call_provider_metadata,
                        approval=ToolApprovalRequested(id=part.tool_call_id),
                    )
                )
            else:
                ui_parts.append(
                    ToolInputAvailablePart(
                        type=tool_type,
                        tool_call_id=part.tool_call_id,
                        input=part.args_as_dict(),
                        provider_executed=False,
                        call_provider_metadata=call_provider_metadata,
                    )
                )

        return ui_parts

    @classmethod
    def dump_messages(
        cls,
        messages: Sequence[ModelMessage],
        *,
        generate_message_id: Callable[[ModelRequest | ModelResponse, Literal['system', 'user', 'assistant'], int], str]
        | None = None,
        sdk_version: Literal[5, 6] = 5,
    ) -> list[UIMessage]:
        """Transform Pydantic AI messages into Vercel AI messages.

        When `sdk_version=6`, tool calls that have no corresponding result in the message history
        are automatically detected as deferred and emitted with `state='approval-requested'`, so the
        frontend can render approve/reject buttons on reload. On v5, such tool calls are emitted
        with `state='input-available'` (approval states are v6-only).

        Args:
            messages: A sequence of ModelMessage objects to convert
            generate_message_id: Optional custom function to generate message IDs. If provided,
                it receives the message, the role ('system', 'user', or 'assistant'), and the
                message index (incremented per UIMessage appended), and should return a unique
                string ID. If not provided, uses `provider_response_id` for responses,
                run_id-based IDs for messages with run_id, or a deterministic UUID5 fallback.
            sdk_version: Vercel AI SDK version to target. Defaults to 5 for backwards compatibility.
                Set to 6 to emit tool approval parts for deferred tool calls.

        Returns:
            A list of UIMessage objects in Vercel AI format
        """
        tool_results: dict[str, ToolReturnPart | RetryPromptPart] = {}

        for msg in messages:
            if isinstance(msg, ModelRequest):
                for part in msg.parts:
                    if isinstance(part, ToolReturnPart):
                        tool_results[part.tool_call_id] = part
                    elif isinstance(part, RetryPromptPart) and part.tool_name:
                        tool_results[part.tool_call_id] = part

        id_generator = generate_message_id or _generate_message_id
        result: list[UIMessage] = []
        message_index = 0

        for msg in messages:
            if isinstance(msg, ModelRequest):
                system_ui_parts, user_ui_parts = cls._dump_request_message(msg)
                if system_ui_parts:
                    result.append(
                        UIMessage(id=id_generator(msg, 'system', message_index), role='system', parts=system_ui_parts)
                    )
                    message_index += 1

                if user_ui_parts:
                    result.append(
                        UIMessage(id=id_generator(msg, 'user', message_index), role='user', parts=user_ui_parts)
                    )
                    message_index += 1

            elif isinstance(  # pragma: no branch
                msg, ModelResponse
            ):
                ui_parts: list[UIMessagePart] = cls._dump_response_message(msg, tool_results, sdk_version)
                if ui_parts:  # pragma: no branch
                    result.append(
                        UIMessage(id=id_generator(msg, 'assistant', message_index), role='assistant', parts=ui_parts)
                    )
                    message_index += 1
            else:
                assert_never(msg)

        return result

sdk_version class-attribute instance-attribute

sdk_version: Literal[5, 6] = 5

Vercel AI SDK version to target. Default is 5 for backwards compatibility.

Setting sdk_version=6 enables tool approval streaming for human-in-the-loop workflows.

server_message_id class-attribute instance-attribute

server_message_id: str | None = None

Optional server-generated message ID to include in the StartChunk.

build_run_input classmethod

build_run_input(body: bytes) -> RequestData

Build a Vercel AI run input object from the request body.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/_adapter.py
132
133
134
135
@classmethod
def build_run_input(cls, body: bytes) -> RequestData:
    """Build a Vercel AI run input object from the request body."""
    return request_data_ta.validate_json(body)

from_request async classmethod

from_request(
    request: Request,
    *,
    agent: AbstractAgent[AgentDepsT, OutputDataT],
    sdk_version: Literal[5, 6] = 5,
    server_message_id: str | None = None,
    manage_system_prompt: Literal[
        "server", "client"
    ] = "server",
    allowed_file_url_schemes: frozenset[str] = frozenset(
        {"http", "https"}
    ),
    **kwargs: Any
) -> VercelAIAdapter[AgentDepsT, OutputDataT]

Extends from_request with Vercel AI-specific parameters.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/_adapter.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
@classmethod
async def from_request(
    cls,
    request: Request,
    *,
    agent: AbstractAgent[AgentDepsT, OutputDataT],
    sdk_version: Literal[5, 6] = 5,
    server_message_id: str | None = None,
    manage_system_prompt: Literal['server', 'client'] = 'server',
    allowed_file_url_schemes: frozenset[str] = frozenset({'http', 'https'}),
    **kwargs: Any,
) -> VercelAIAdapter[AgentDepsT, OutputDataT]:
    """Extends [`from_request`][pydantic_ai.ui.UIAdapter.from_request] with Vercel AI-specific parameters."""
    return await super().from_request(
        request,
        agent=agent,
        sdk_version=sdk_version,
        server_message_id=server_message_id,
        manage_system_prompt=manage_system_prompt,
        allowed_file_url_schemes=allowed_file_url_schemes,
        **kwargs,
    )

dispatch_request async classmethod

dispatch_request(
    request: Request,
    *,
    agent: AbstractAgent[
        DispatchDepsT, DispatchOutputDataT
    ],
    sdk_version: Literal[5, 6] = 5,
    server_message_id: str | None = None,
    message_history: Sequence[ModelMessage] | None = None,
    deferred_tool_results: (
        DeferredToolResults | None
    ) = None,
    conversation_id: str | None = None,
    model: Model | KnownModelName | str | None = None,
    instructions: AgentInstructions[DispatchDepsT] = None,
    deps: DispatchDepsT = None,
    output_type: OutputSpec[Any] | None = None,
    model_settings: ModelSettings | None = None,
    usage_limits: UsageLimits | None = None,
    usage: RunUsage | None = None,
    metadata: AgentMetadata[DispatchDepsT] | None = None,
    infer_name: bool = True,
    toolsets: (
        Sequence[AbstractToolset[DispatchDepsT]] | None
    ) = None,
    capabilities: (
        Sequence[AbstractCapability[DispatchDepsT]] | None
    ) = None,
    on_complete: OnCompleteFunc[BaseChunk] | None = None,
    manage_system_prompt: Literal[
        "server", "client"
    ] = "server",
    allowed_file_url_schemes: frozenset[str] = frozenset(
        {"http", "https"}
    ),
    **kwargs: Any
) -> Response

Extends dispatch_request with Vercel AI-specific parameters.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/_adapter.py
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
@classmethod
async def dispatch_request(
    cls,
    request: Request,
    *,
    agent: AbstractAgent[DispatchDepsT, DispatchOutputDataT],
    sdk_version: Literal[5, 6] = 5,
    server_message_id: str | None = None,
    message_history: Sequence[ModelMessage] | None = None,
    deferred_tool_results: DeferredToolResults | None = None,
    conversation_id: str | None = None,
    model: Model | KnownModelName | str | None = None,
    instructions: _instructions.AgentInstructions[DispatchDepsT] = None,
    deps: DispatchDepsT = None,
    output_type: OutputSpec[Any] | None = None,
    model_settings: ModelSettings | None = None,
    usage_limits: UsageLimits | None = None,
    usage: RunUsage | None = None,
    metadata: AgentMetadata[DispatchDepsT] | None = None,
    infer_name: bool = True,
    toolsets: Sequence[AbstractToolset[DispatchDepsT]] | None = None,
    capabilities: Sequence[AbstractCapability[DispatchDepsT]] | None = None,
    on_complete: OnCompleteFunc[BaseChunk] | None = None,
    manage_system_prompt: Literal['server', 'client'] = 'server',
    allowed_file_url_schemes: frozenset[str] = frozenset({'http', 'https'}),
    **kwargs: Any,
) -> Response:
    """Extends [`dispatch_request`][pydantic_ai.ui.UIAdapter.dispatch_request] with Vercel AI-specific parameters."""
    return await super().dispatch_request(
        request,
        agent=agent,
        sdk_version=sdk_version,
        server_message_id=server_message_id,
        message_history=message_history,
        deferred_tool_results=deferred_tool_results,
        conversation_id=conversation_id,
        model=model,
        instructions=instructions,
        deps=deps,
        output_type=output_type,
        model_settings=model_settings,
        usage_limits=usage_limits,
        usage=usage,
        metadata=metadata,
        infer_name=infer_name,
        toolsets=toolsets,
        capabilities=capabilities,
        on_complete=on_complete,
        manage_system_prompt=manage_system_prompt,
        allowed_file_url_schemes=allowed_file_url_schemes,
        **kwargs,
    )

build_event_stream

build_event_stream() -> (
    UIEventStream[
        RequestData, BaseChunk, AgentDepsT, OutputDataT
    ]
)

Build a Vercel AI event stream transformer.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/_adapter.py
213
214
215
216
217
def build_event_stream(self) -> UIEventStream[RequestData, BaseChunk, AgentDepsT, OutputDataT]:
    """Build a Vercel AI event stream transformer."""
    return VercelAIEventStream(
        self.run_input, accept=self.accept, sdk_version=self.sdk_version, server_message_id=self.server_message_id
    )

deferred_tool_results cached property

deferred_tool_results: DeferredToolResults | None

Extract deferred tool results from Vercel AI messages with approval responses.

messages cached property

messages: list[ModelMessage]

Pydantic AI messages from the Vercel AI run input.

conversation_id cached property

conversation_id: str | None

Conversation ID from the top-level id field of the Vercel AI request body (the chat ID).

load_messages classmethod

load_messages(
    messages: Sequence[UIMessage],
) -> list[ModelMessage]

Transform Vercel AI messages into Pydantic AI messages.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/_adapter.py
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
@classmethod
def load_messages(cls, messages: Sequence[UIMessage]) -> list[ModelMessage]:  # noqa: C901
    """Transform Vercel AI messages into Pydantic AI messages."""
    builder = MessagesBuilder()

    for msg in messages:
        if msg.role == 'system':
            for part in msg.parts:
                if isinstance(part, TextUIPart):
                    builder.add(SystemPromptPart(content=part.text))
                else:  # pragma: no cover
                    raise ValueError(f'Unsupported system message part type: {type(part)}')
        elif msg.role == 'user':
            user_prompt_content: str | list[UserContent] = []
            for part in msg.parts:
                if isinstance(part, TextUIPart):
                    user_prompt_content.append(part.text)
                elif isinstance(part, FileUIPart):
                    try:
                        file = BinaryContent.from_data_uri(part.url)
                    except ValueError:
                        # Check provider_metadata for UploadedFile data
                        provider_meta = load_provider_metadata(part.provider_metadata)
                        uploaded_file_id = provider_meta.get('file_id')
                        uploaded_file_provider = provider_meta.get('provider_name')
                        if uploaded_file_id and uploaded_file_provider:
                            file = UploadedFile(
                                file_id=uploaded_file_id,
                                provider_name=cast(UploadedFileProviderName, uploaded_file_provider),
                                media_type=part.media_type,
                                vendor_metadata=provider_meta.get('vendor_metadata'),
                                identifier=provider_meta.get('identifier'),
                            )
                        else:
                            media_type_prefix = part.media_type.split('/', 1)[0]
                            match media_type_prefix:
                                case 'image':
                                    file = ImageUrl(url=part.url, media_type=part.media_type)
                                case 'video':
                                    file = VideoUrl(url=part.url, media_type=part.media_type)
                                case 'audio':
                                    file = AudioUrl(url=part.url, media_type=part.media_type)
                                case _:
                                    file = DocumentUrl(url=part.url, media_type=part.media_type)
                    user_prompt_content.append(file)
                elif isinstance(part, DataUIPart):
                    # Contains custom data that shouldn't be sent to the model
                    pass
                else:  # pragma: no cover
                    raise ValueError(f'Unsupported user message part type: {type(part)}')

            if user_prompt_content:  # pragma: no branch
                if len(user_prompt_content) == 1 and isinstance(user_prompt_content[0], str):
                    user_prompt_content = user_prompt_content[0]
                builder.add(UserPromptPart(content=user_prompt_content))

        elif msg.role == 'assistant':
            for part in msg.parts:
                if isinstance(part, TextUIPart):
                    provider_meta = load_provider_metadata(part.provider_metadata)
                    builder.add(
                        TextPart(
                            content=part.text,
                            id=provider_meta.get('id'),
                            provider_name=provider_meta.get('provider_name'),
                            provider_details=provider_meta.get('provider_details'),
                        )
                    )
                elif isinstance(part, ReasoningUIPart):
                    provider_meta = load_provider_metadata(part.provider_metadata)
                    builder.add(
                        ThinkingPart(
                            content=part.text,
                            id=provider_meta.get('id'),
                            signature=None if part.state == 'streaming' else provider_meta.get('signature'),
                            provider_name=provider_meta.get('provider_name'),
                            provider_details=provider_meta.get('provider_details'),
                        )
                    )
                elif isinstance(part, FileUIPart):
                    try:
                        file = BinaryContent.from_data_uri(part.url)
                    except ValueError as e:  # pragma: no cover
                        # We don't yet handle non-data-URI file URLs returned by assistants, as no Pydantic AI models do this.
                        raise ValueError(
                            'Vercel AI integration can currently only handle assistant file parts with data URIs.'
                        ) from e
                    provider_meta = load_provider_metadata(part.provider_metadata)
                    builder.add(
                        FilePart(
                            content=file,
                            id=provider_meta.get('id'),
                            provider_name=provider_meta.get('provider_name'),
                            provider_details=provider_meta.get('provider_details'),
                        )
                    )
                elif isinstance(part, ToolUIPart | DynamicToolUIPart):
                    if isinstance(part, DynamicToolUIPart):
                        tool_name = part.tool_name
                        builtin_tool = False
                    else:
                        tool_name = part.type.removeprefix('tool-')
                        builtin_tool = part.provider_executed

                    tool_call_id = part.tool_call_id

                    args: str | dict[str, Any] | None = part.input

                    if isinstance(args, str):
                        try:
                            parsed = json.loads(args)
                            if _is_str_dict(parsed):
                                args = parsed
                        except json.JSONDecodeError:
                            pass
                    elif isinstance(args, dict) or args is None:
                        pass
                    else:
                        assert_never(args)

                    provider_meta = load_provider_metadata(part.call_provider_metadata)
                    part_id = provider_meta.get('id')
                    provider_name = provider_meta.get('provider_name')
                    provider_details = provider_meta.get('provider_details')

                    if builtin_tool:
                        # For builtin tools, we need to create 2 parts (BuiltinToolCall & BuiltinToolReturn) for a single Vercel ToolOutput
                        # The call and return metadata are combined in the output part.
                        # So we extract and return them to the respective parts
                        call_meta = return_meta = {}
                        has_tool_output = isinstance(
                            part, (ToolOutputAvailablePart, ToolOutputErrorPart, ToolOutputDeniedPart)
                        )

                        if has_tool_output:
                            call_meta, return_meta = cls._load_builtin_tool_meta(provider_meta)

                        builder.add(
                            NativeToolCallPart(
                                tool_name=tool_name,
                                tool_call_id=tool_call_id,
                                args=args,
                                id=call_meta.get('id') or part_id,
                                provider_name=call_meta.get('provider_name') or provider_name,
                                provider_details=call_meta.get('provider_details') or provider_details,
                            )
                        )

                        if has_tool_output:
                            if isinstance(part, ToolOutputErrorPart):
                                output: Any = part.error_text
                                outcome: Literal['success', 'failed', 'denied'] = 'failed'
                            elif isinstance(part, ToolOutputDeniedPart):
                                output = _denial_reason(part)
                                outcome = 'denied'
                            else:
                                output = part.output if isinstance(part, ToolOutputAvailablePart) else None
                                outcome = 'success'
                            builder.add(
                                NativeToolReturnPart(
                                    tool_name=tool_name,
                                    tool_call_id=tool_call_id,
                                    content=output,
                                    provider_name=return_meta.get('provider_name') or provider_name,
                                    provider_details=return_meta.get('provider_details') or provider_details,
                                    outcome=outcome,
                                )
                            )
                    else:
                        builder.add(
                            ToolCallPart(
                                tool_name=tool_name,
                                tool_call_id=tool_call_id,
                                args=args,
                                id=part_id,
                                provider_name=provider_name,
                                provider_details=provider_details,
                            )
                        )

                        if part.state == 'output-available':
                            builder.add(
                                ToolReturnPart(tool_name=tool_name, tool_call_id=tool_call_id, content=part.output)
                            )
                        elif part.state == 'output-error':
                            builder.add(
                                ToolReturnPart(
                                    tool_name=tool_name,
                                    tool_call_id=tool_call_id,
                                    content=part.error_text,
                                    outcome='failed',
                                )
                            )
                        elif part.state == 'output-denied':
                            builder.add(
                                ToolReturnPart(
                                    tool_name=tool_name,
                                    tool_call_id=tool_call_id,
                                    content=_denial_reason(part),
                                    outcome='denied',
                                )
                            )
                elif isinstance(part, DataUIPart):  # pragma: no cover
                    # Contains custom data that shouldn't be sent to the model
                    pass
                elif isinstance(part, SourceUrlUIPart):  # pragma: no cover
                    # TODO: Once we support citations: https://github.com/pydantic/pydantic-ai/issues/3126
                    pass
                elif isinstance(part, SourceDocumentUIPart):  # pragma: no cover
                    # TODO: Once we support citations: https://github.com/pydantic/pydantic-ai/issues/3126
                    pass
                elif isinstance(part, StepStartUIPart):  # pragma: no cover
                    # Nothing to do here
                    pass
                else:
                    assert_never(part)
        else:
            assert_never(msg.role)

    return builder.messages

dump_messages classmethod

dump_messages(
    messages: Sequence[ModelMessage],
    *,
    generate_message_id: (
        Callable[
            [
                ModelRequest | ModelResponse,
                Literal["system", "user", "assistant"],
                int,
            ],
            str,
        ]
        | None
    ) = None,
    sdk_version: Literal[5, 6] = 5
) -> list[UIMessage]

Transform Pydantic AI messages into Vercel AI messages.

When sdk_version=6, tool calls that have no corresponding result in the message history are automatically detected as deferred and emitted with state='approval-requested', so the frontend can render approve/reject buttons on reload. On v5, such tool calls are emitted with state='input-available' (approval states are v6-only).

Parameters:

Name Type Description Default
messages Sequence[ModelMessage]

A sequence of ModelMessage objects to convert

required
generate_message_id Callable[[ModelRequest | ModelResponse, Literal['system', 'user', 'assistant'], int], str] | None

Optional custom function to generate message IDs. If provided, it receives the message, the role ('system', 'user', or 'assistant'), and the message index (incremented per UIMessage appended), and should return a unique string ID. If not provided, uses provider_response_id for responses, run_id-based IDs for messages with run_id, or a deterministic UUID5 fallback.

None
sdk_version Literal[5, 6]

Vercel AI SDK version to target. Defaults to 5 for backwards compatibility. Set to 6 to emit tool approval parts for deferred tool calls.

5

Returns:

Type Description
list[UIMessage]

A list of UIMessage objects in Vercel AI format

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/_adapter.py
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
@classmethod
def dump_messages(
    cls,
    messages: Sequence[ModelMessage],
    *,
    generate_message_id: Callable[[ModelRequest | ModelResponse, Literal['system', 'user', 'assistant'], int], str]
    | None = None,
    sdk_version: Literal[5, 6] = 5,
) -> list[UIMessage]:
    """Transform Pydantic AI messages into Vercel AI messages.

    When `sdk_version=6`, tool calls that have no corresponding result in the message history
    are automatically detected as deferred and emitted with `state='approval-requested'`, so the
    frontend can render approve/reject buttons on reload. On v5, such tool calls are emitted
    with `state='input-available'` (approval states are v6-only).

    Args:
        messages: A sequence of ModelMessage objects to convert
        generate_message_id: Optional custom function to generate message IDs. If provided,
            it receives the message, the role ('system', 'user', or 'assistant'), and the
            message index (incremented per UIMessage appended), and should return a unique
            string ID. If not provided, uses `provider_response_id` for responses,
            run_id-based IDs for messages with run_id, or a deterministic UUID5 fallback.
        sdk_version: Vercel AI SDK version to target. Defaults to 5 for backwards compatibility.
            Set to 6 to emit tool approval parts for deferred tool calls.

    Returns:
        A list of UIMessage objects in Vercel AI format
    """
    tool_results: dict[str, ToolReturnPart | RetryPromptPart] = {}

    for msg in messages:
        if isinstance(msg, ModelRequest):
            for part in msg.parts:
                if isinstance(part, ToolReturnPart):
                    tool_results[part.tool_call_id] = part
                elif isinstance(part, RetryPromptPart) and part.tool_name:
                    tool_results[part.tool_call_id] = part

    id_generator = generate_message_id or _generate_message_id
    result: list[UIMessage] = []
    message_index = 0

    for msg in messages:
        if isinstance(msg, ModelRequest):
            system_ui_parts, user_ui_parts = cls._dump_request_message(msg)
            if system_ui_parts:
                result.append(
                    UIMessage(id=id_generator(msg, 'system', message_index), role='system', parts=system_ui_parts)
                )
                message_index += 1

            if user_ui_parts:
                result.append(
                    UIMessage(id=id_generator(msg, 'user', message_index), role='user', parts=user_ui_parts)
                )
                message_index += 1

        elif isinstance(  # pragma: no branch
            msg, ModelResponse
        ):
            ui_parts: list[UIMessagePart] = cls._dump_response_message(msg, tool_results, sdk_version)
            if ui_parts:  # pragma: no branch
                result.append(
                    UIMessage(id=id_generator(msg, 'assistant', message_index), role='assistant', parts=ui_parts)
                )
                message_index += 1
        else:
            assert_never(msg)

    return result

VercelAIEventStream dataclass

Bases: UIEventStream[RequestData, BaseChunk, AgentDepsT, OutputDataT]

UI event stream transformer for the Vercel AI protocol.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/_event_stream.py
 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
@dataclass
class VercelAIEventStream(UIEventStream[RequestData, BaseChunk, AgentDepsT, OutputDataT]):
    """UI event stream transformer for the Vercel AI protocol."""

    _: KW_ONLY
    sdk_version: Literal[5, 6] = 5
    """Vercel AI SDK version to target. Setting to 6 enables tool approval streaming."""
    server_message_id: str | None = None
    """Optional server-generated message ID to include in the `StartChunk`."""

    _step_started: bool = False
    _finish_reason: FinishReason = None
    _invalidated_tool_calls: dict[str, ToolCallPart] = field(default_factory=dict[str, ToolCallPart])
    """Calls whose `tool-input-available` chunk was suppressed because validation failed.

    Keyed by tool call ID; the part carries the raw args and provider metadata that the
    later `tool-input-error` chunk needs to mirror what the suppressed `tool-input-available`
    would have shown. The entry is popped by `_handle_tool_result` when the matching
    `RetryPromptPart` arrives, so `tool-input-error` is emitted there instead of
    `tool-output-error`.
    """
    _streamed_call_parts: dict[str, ToolCallPart] = field(default_factory=dict[str, ToolCallPart])
    """Tool call parts seen at `PartEndEvent` time, kept until `_handle_tool_call` takes over.

    Used by `_handle_tool_result` to backfill `tool-input-available` if the agent raises
    before the call event fires (e.g. output-tool `UnexpectedModelBehavior` with no prior
    `final_result`, where `_agent_graph.py` raises without yielding `OutputToolCallEvent`).
    Without the backfill, both v5 and v6 frontends would transition `input-streaming` ->
    `output-error` with no input announcement in between.
    """

    @property
    def response_headers(self) -> Mapping[str, str] | None:
        return VERCEL_AI_DSP_HEADERS

    def encode_event(self, event: BaseChunk) -> str:
        return f'data: {event.encode(self.sdk_version)}\n\n'

    async def before_stream(self) -> AsyncIterator[BaseChunk]:
        yield StartChunk(message_id=self.server_message_id)

    async def before_response(self) -> AsyncIterator[BaseChunk]:
        if self._step_started:
            yield FinishStepChunk()

        self._step_started = True
        yield StartStepChunk()

    async def after_stream(self) -> AsyncIterator[BaseChunk]:
        yield FinishStepChunk()

        yield FinishChunk(finish_reason=self._finish_reason)
        yield DoneChunk()

    async def handle_run_result(self, event: AgentRunResultEvent) -> AsyncIterator[BaseChunk]:
        pydantic_reason = event.result.response.finish_reason
        if pydantic_reason:
            self._finish_reason = _FINISH_REASON_MAP.get(pydantic_reason, 'other')

        # Emit tool approval requests for deferred approvals (only when sdk_version >= 6)
        output = event.result.output
        if self.sdk_version >= 6 and isinstance(output, DeferredToolRequests):
            for tool_call in output.approvals:
                yield ToolApprovalRequestChunk(
                    approval_id=tool_call.tool_call_id,
                    tool_call_id=tool_call.tool_call_id,
                )
            return
        return
        yield

    async def on_error(self, error: Exception) -> AsyncIterator[BaseChunk]:
        self._finish_reason = 'error'
        yield ErrorChunk(error_text=str(error))

    async def handle_text_start(self, part: TextPart, follows_text: bool = False) -> AsyncIterator[BaseChunk]:
        provider_metadata = dump_provider_metadata(
            id=part.id, provider_name=part.provider_name, provider_details=part.provider_details
        )
        if follows_text:
            message_id = self.message_id
        else:
            message_id = self.new_message_id()
            yield TextStartChunk(id=message_id, provider_metadata=provider_metadata)

        if part.content:
            yield TextDeltaChunk(id=message_id, delta=part.content, provider_metadata=provider_metadata)

    async def handle_text_delta(self, delta: TextPartDelta) -> AsyncIterator[BaseChunk]:
        if delta.content_delta:  # pragma: no branch
            provider_metadata = dump_provider_metadata(
                provider_name=delta.provider_name, provider_details=delta.provider_details
            )
            yield TextDeltaChunk(id=self.message_id, delta=delta.content_delta, provider_metadata=provider_metadata)

    async def handle_text_end(self, part: TextPart, followed_by_text: bool = False) -> AsyncIterator[BaseChunk]:
        if not followed_by_text:
            provider_metadata = dump_provider_metadata(
                id=part.id, provider_name=part.provider_name, provider_details=part.provider_details
            )
            yield TextEndChunk(id=self.message_id, provider_metadata=provider_metadata)

    async def handle_thinking_start(
        self, part: ThinkingPart, follows_thinking: bool = False
    ) -> AsyncIterator[BaseChunk]:
        message_id = self.new_message_id()
        provider_metadata = dump_provider_metadata(
            id=part.id,
            signature=part.signature,
            provider_name=part.provider_name,
            provider_details=part.provider_details,
        )
        yield ReasoningStartChunk(id=message_id, provider_metadata=provider_metadata)
        if part.content:
            yield ReasoningDeltaChunk(id=message_id, delta=part.content, provider_metadata=provider_metadata)

    async def handle_thinking_delta(self, delta: ThinkingPartDelta) -> AsyncIterator[BaseChunk]:
        if delta.content_delta:  # pragma: no branch
            provider_metadata = dump_provider_metadata(
                provider_name=delta.provider_name,
                signature=delta.signature_delta,
                provider_details=delta.provider_details,
            )
            yield ReasoningDeltaChunk(
                id=self.message_id, delta=delta.content_delta, provider_metadata=provider_metadata
            )

    async def handle_thinking_end(
        self, part: ThinkingPart, followed_by_thinking: bool = False
    ) -> AsyncIterator[BaseChunk]:
        provider_metadata = dump_provider_metadata(
            id=part.id,
            signature=part.signature,
            provider_name=part.provider_name,
            provider_details=part.provider_details,
        )
        yield ReasoningEndChunk(id=self.message_id, provider_metadata=provider_metadata)

    def handle_tool_call_start(self, part: ToolCallPart | NativeToolCallPart) -> AsyncIterator[BaseChunk]:
        return self._handle_tool_call_start(part)

    def handle_builtin_tool_call_start(self, part: NativeToolCallPart) -> AsyncIterator[BaseChunk]:
        return self._handle_tool_call_start(part, provider_executed=True)

    async def _handle_tool_call_start(
        self,
        part: ToolCallPart | NativeToolCallPart,
        tool_call_id: str | None = None,
        provider_executed: bool | None = None,
    ) -> AsyncIterator[BaseChunk]:
        tool_call_id = tool_call_id or part.tool_call_id
        yield ToolInputStartChunk(
            tool_call_id=tool_call_id,
            tool_name=part.tool_name,
            provider_executed=provider_executed,
            provider_metadata=dump_provider_metadata(
                id=part.id, provider_name=part.provider_name, provider_details=part.provider_details
            ),
        )
        if part.args:
            yield ToolInputDeltaChunk(tool_call_id=tool_call_id, input_text_delta=part.args_as_json_str())

    async def handle_tool_call_delta(self, delta: ToolCallPartDelta) -> AsyncIterator[BaseChunk]:
        tool_call_id = delta.tool_call_id or ''
        assert tool_call_id, '`ToolCallPartDelta.tool_call_id` must be set'
        yield ToolInputDeltaChunk(
            tool_call_id=tool_call_id,
            input_text_delta=delta.args_delta if isinstance(delta.args_delta, str) else _json_dumps(delta.args_delta),
        )

    async def handle_tool_call_end(self, part: ToolCallPart) -> AsyncIterator[BaseChunk]:
        # Stash the streamed part. `_handle_tool_call` (post-validation) takes over emission
        # in the normal flow and pops the stash. If the agent raises before the call event
        # fires (e.g. output-tool `UnexpectedModelBehavior` with no `final_result`), the
        # stash survives and `_handle_tool_result` uses it to backfill `tool-input-available`
        # before the synthesized `tool-output-error`.
        self._streamed_call_parts[part.tool_call_id] = part
        return
        yield  # pragma: no cover  # mark this as an async generator

    async def handle_function_tool_call(self, event: FunctionToolCallEvent) -> AsyncIterator[BaseChunk]:
        async for chunk in self._handle_tool_call(event):
            yield chunk

    async def handle_output_tool_call(self, event: OutputToolCallEvent) -> AsyncIterator[BaseChunk]:
        async for chunk in self._handle_tool_call(event):
            yield chunk

    async def _handle_tool_call(self, event: ToolCallEvent) -> AsyncIterator[BaseChunk]:
        part = event.part
        # The call event arrived; we own the input-chunk lifecycle from here. Drop the
        # stash so `_handle_tool_result` doesn't double-emit a backfill chunk.
        self._streamed_call_parts.pop(part.tool_call_id, None)

        # `args_valid is None` covers resume of non-`ToolApproved` deferred results
        # (`ToolDenied`, `ModelRetry`, direct return) and the output-tool
        # end-strategy-skipped path. The original `tool-input-available` already fired
        # on the first agent run; re-emitting here would be misleading.
        if event.args_valid is None:
            return

        # SDK v6+ supports `tool-input-error`, so we suppress `tool-input-available` on
        # validation failure and let `_handle_tool_result` emit the dedicated error chunk
        # when the matching `RetryPromptPart` arrives. v5 does not have `tool-input-error`;
        # for v5 we keep the pre-PR behavior of emitting `tool-input-available` regardless
        # of validity (with `tool-output-error` later from the result handler) so the tool
        # call lifecycle stays observable for v5 frontends.
        if event.args_valid is False and self.sdk_version >= 6:
            self._invalidated_tool_calls[part.tool_call_id] = part
            return

        yield ToolInputAvailableChunk(
            tool_call_id=part.tool_call_id,
            tool_name=part.tool_name,
            input=part.args_as_dict(),
            provider_metadata=dump_provider_metadata(
                id=part.id, provider_name=part.provider_name, provider_details=part.provider_details
            ),
        )

    async def handle_builtin_tool_call_end(self, part: NativeToolCallPart) -> AsyncIterator[BaseChunk]:
        yield ToolInputAvailableChunk(
            tool_call_id=part.tool_call_id,
            tool_name=part.tool_name,
            input=part.args_as_dict(),
            provider_executed=True,
            provider_metadata=dump_provider_metadata(
                id=part.id, provider_name=part.provider_name, provider_details=part.provider_details
            ),
        )

    async def handle_builtin_tool_return(self, part: NativeToolReturnPart) -> AsyncIterator[BaseChunk]:
        if self.sdk_version >= 6 and part.outcome == 'denied':
            yield ToolOutputDeniedChunk(tool_call_id=part.tool_call_id)
        elif part.outcome == 'failed':
            yield ToolOutputErrorChunk(tool_call_id=part.tool_call_id, error_text=part.model_response_str())
        else:
            yield ToolOutputAvailableChunk(
                tool_call_id=part.tool_call_id,
                output=_tool_return_with_files(part),
                provider_executed=True,
            )

    async def handle_file(self, part: FilePart) -> AsyncIterator[BaseChunk]:
        file = part.content
        yield FileChunk(url=file.data_uri, media_type=file.media_type)

    async def handle_function_tool_result(self, event: FunctionToolResultEvent) -> AsyncIterator[BaseChunk]:
        async for chunk in self._handle_tool_result(event.part):
            yield chunk

    async def handle_output_tool_result(self, event: OutputToolResultEvent) -> AsyncIterator[BaseChunk]:
        async for chunk in self._handle_tool_result(event.part):
            yield chunk

    async def _handle_tool_result(self, part: ToolReturnPart | RetryPromptPart) -> AsyncIterator[BaseChunk]:
        tool_call_id = part.tool_call_id

        invalidated_part = self._invalidated_tool_calls.pop(tool_call_id, None)
        streamed_part = self._streamed_call_parts.pop(tool_call_id, None)

        # Backfill `tool-input-available` if `_handle_tool_call` never fired for this call —
        # happens when the agent raises before yielding the call event (e.g. output-tool
        # `UnexpectedModelBehavior` with no prior `final_result`). The base class then
        # synthesizes a `ToolReturnPart(outcome='failed')` for the pending call, which
        # arrives here; without the backfill, v5/v6 frontends would transition
        # `input-streaming` -> `output-error` with no input announcement in between.
        # `invalidated_part is not None` means `_handle_tool_call` deliberately suppressed
        # the chunk for the v6 invalidated path — don't backfill in that case.
        if streamed_part is not None and invalidated_part is None:
            yield ToolInputAvailableChunk(
                tool_call_id=tool_call_id,
                tool_name=streamed_part.tool_name,
                input=streamed_part.args_as_dict(),
                provider_metadata=dump_provider_metadata(
                    id=streamed_part.id,
                    provider_name=streamed_part.provider_name,
                    provider_details=streamed_part.provider_details,
                ),
            )

        if self.sdk_version >= 6 and isinstance(part, ToolReturnPart) and part.outcome == 'denied':
            yield ToolOutputDeniedChunk(tool_call_id=tool_call_id)
        elif invalidated_part is not None:
            # The original `tool-input-available` was suppressed because `args_valid=False`.
            # Complete the v6 lifecycle by emitting `tool-input-error` instead of letting the
            # result chunk (success/output-error) fire — the call never actually executed.
            # `error_text` comes from `RetryPromptPart.model_response()` on the normal retry
            # path, or `ToolReturnPart.model_response_str()` on the exhaustive output-strategy
            # skip path (where the status part says e.g. "Output tool not used …").
            yield ToolInputErrorChunk(
                tool_call_id=tool_call_id,
                tool_name=invalidated_part.tool_name,
                input=invalidated_part.args_as_dict(),
                provider_metadata=dump_provider_metadata(
                    id=invalidated_part.id,
                    provider_name=invalidated_part.provider_name,
                    provider_details=invalidated_part.provider_details,
                ),
                error_text=part.model_response() if isinstance(part, RetryPromptPart) else part.model_response_str(),
            )
        elif isinstance(part, RetryPromptPart):
            yield ToolOutputErrorChunk(tool_call_id=tool_call_id, error_text=part.model_response())
        elif isinstance(part, ToolReturnPart) and part.outcome == 'failed':
            yield ToolOutputErrorChunk(tool_call_id=tool_call_id, error_text=part.model_response_str())
        else:
            yield ToolOutputAvailableChunk(tool_call_id=tool_call_id, output=_tool_return_with_files(part))

        # ToolOutputAvailableChunk/ToolOutputErrorChunk.output may hold user parts
        # (e.g. text, images) that Vercel AI does not currently have chunk types for.

        # Check for data-carrying Vercel AI chunks returned by tool calls via metadata.
        # Only data-carrying chunks (DataChunk, SourceUrlChunk, etc.) are yielded;
        # protocol-control chunks are filtered out by iter_metadata_chunks.
        if isinstance(part, ToolReturnPart):
            for chunk in iter_metadata_chunks(part):
                yield chunk

sdk_version class-attribute instance-attribute

sdk_version: Literal[5, 6] = 5

Vercel AI SDK version to target. Setting to 6 enables tool approval streaming.

server_message_id class-attribute instance-attribute

server_message_id: str | None = None

Optional server-generated message ID to include in the StartChunk.

Vercel AI request types (UI messages).

Converted to Python from: https://github.com/vercel/ai/blob/ai%406.0.57/packages/ai/src/ui/ui-messages.ts

Tool approval types (ToolApprovalRequested, ToolApprovalResponded) require AI SDK v6 or later.

ProviderMetadata module-attribute

ProviderMetadata = dict[str, dict[str, JSONValue]]

Provider metadata.

BaseUIPart

Bases: CamelBaseModel, ABC

Abstract base class for all UI parts.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
22
23
class BaseUIPart(CamelBaseModel, ABC):
    """Abstract base class for all UI parts."""

TextUIPart

Bases: BaseUIPart

A text part of a message.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
26
27
28
29
30
31
32
33
34
35
36
37
38
class TextUIPart(BaseUIPart):
    """A text part of a message."""

    type: Literal['text'] = 'text'

    text: str
    """The text content."""

    state: Literal['streaming', 'done'] | None = None
    """The state of the text part."""

    provider_metadata: ProviderMetadata | None = None
    """The provider metadata."""

text instance-attribute

text: str

The text content.

state class-attribute instance-attribute

state: Literal['streaming', 'done'] | None = None

The state of the text part.

provider_metadata class-attribute instance-attribute

provider_metadata: ProviderMetadata | None = None

The provider metadata.

ReasoningUIPart

Bases: BaseUIPart

A reasoning part of a message.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
41
42
43
44
45
46
47
48
49
50
51
52
53
class ReasoningUIPart(BaseUIPart):
    """A reasoning part of a message."""

    type: Literal['reasoning'] = 'reasoning'

    text: str
    """The reasoning text."""

    state: Literal['streaming', 'done'] | None = None
    """The state of the reasoning part."""

    provider_metadata: ProviderMetadata | None = None
    """The provider metadata."""

text instance-attribute

text: str

The reasoning text.

state class-attribute instance-attribute

state: Literal['streaming', 'done'] | None = None

The state of the reasoning part.

provider_metadata class-attribute instance-attribute

provider_metadata: ProviderMetadata | None = None

The provider metadata.

SourceUrlUIPart

Bases: BaseUIPart

A source part of a message.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
56
57
58
59
60
61
62
63
class SourceUrlUIPart(BaseUIPart):
    """A source part of a message."""

    type: Literal['source-url'] = 'source-url'
    source_id: str
    url: str
    title: str | None = None
    provider_metadata: ProviderMetadata | None = None

SourceDocumentUIPart

Bases: BaseUIPart

A document source part of a message.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
66
67
68
69
70
71
72
73
74
class SourceDocumentUIPart(BaseUIPart):
    """A document source part of a message."""

    type: Literal['source-document'] = 'source-document'
    source_id: str
    media_type: str
    title: str
    filename: str | None = None
    provider_metadata: ProviderMetadata | None = None

FileUIPart

Bases: BaseUIPart

A file part of a message.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class FileUIPart(BaseUIPart):
    """A file part of a message."""

    type: Literal['file'] = 'file'

    media_type: str
    """
    IANA media type of the file.
    @see https://www.iana.org/assignments/media-types/media-types.xhtml
    """

    filename: str | None = None
    """Optional filename of the file."""

    url: str
    """
    The URL of the file.
    It can either be a URL to a hosted file or a [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs).
    """

    provider_metadata: ProviderMetadata | None = None
    """The provider metadata."""

media_type instance-attribute

media_type: str

IANA media type of the file. @see https://www.iana.org/assignments/media-types/media-types.xhtml

filename class-attribute instance-attribute

filename: str | None = None

Optional filename of the file.

url instance-attribute

url: str

The URL of the file. It can either be a URL to a hosted file or a Data URL.

provider_metadata class-attribute instance-attribute

provider_metadata: ProviderMetadata | None = None

The provider metadata.

StepStartUIPart

Bases: BaseUIPart

A step boundary part of a message.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
101
102
103
104
class StepStartUIPart(BaseUIPart):
    """A step boundary part of a message."""

    type: Literal['step-start'] = 'step-start'

DataUIPart

Bases: BaseUIPart

Data part with dynamic type based on data name.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
107
108
109
110
111
112
class DataUIPart(BaseUIPart):
    """Data part with dynamic type based on data name."""

    type: Annotated[str, Field(pattern=r'^data-')]
    id: str | None = None
    data: Any

ToolApprovalRequested

Bases: CamelBaseModel

Tool approval in requested state (awaiting user response).

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
115
116
117
118
119
class ToolApprovalRequested(CamelBaseModel):
    """Tool approval in requested state (awaiting user response)."""

    id: str
    """The approval request ID."""

id instance-attribute

id: str

The approval request ID.

ToolApprovalResponded

Bases: CamelBaseModel

Tool approval in responded state (user has approved or denied).

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
122
123
124
125
126
127
128
129
130
131
132
class ToolApprovalResponded(CamelBaseModel):
    """Tool approval in responded state (user has approved or denied)."""

    id: str
    """The approval request ID."""

    approved: bool
    """Whether the user approved the tool call."""

    reason: str | None = None
    """Optional reason for the approval or denial."""

id instance-attribute

id: str

The approval request ID.

approved instance-attribute

approved: bool

Whether the user approved the tool call.

reason class-attribute instance-attribute

reason: str | None = None

Optional reason for the approval or denial.

ToolApproval module-attribute

Union of tool approval states.

ToolInputStreamingPart

Bases: BaseUIPart

Tool part in input-streaming state.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
140
141
142
143
144
145
146
147
148
149
class ToolInputStreamingPart(BaseUIPart):
    """Tool part in input-streaming state."""

    type: Annotated[str, Field(pattern=r'^tool-')]
    tool_call_id: str
    state: Literal['input-streaming'] = 'input-streaming'
    input: Any | None = None
    provider_executed: bool | None = None
    call_provider_metadata: ProviderMetadata | None = None
    approval: ToolApproval | None = None

ToolInputAvailablePart

Bases: BaseUIPart

Tool part in input-available state.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
152
153
154
155
156
157
158
159
160
161
class ToolInputAvailablePart(BaseUIPart):
    """Tool part in input-available state."""

    type: Annotated[str, Field(pattern=r'^tool-')]
    tool_call_id: str
    state: Literal['input-available'] = 'input-available'
    input: Any | None = None
    provider_executed: bool | None = None
    call_provider_metadata: ProviderMetadata | None = None
    approval: ToolApproval | None = None

ToolOutputAvailablePart

Bases: BaseUIPart

Tool part in output-available state.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
164
165
166
167
168
169
170
171
172
173
174
175
class ToolOutputAvailablePart(BaseUIPart):
    """Tool part in output-available state."""

    type: Annotated[str, Field(pattern=r'^tool-')]
    tool_call_id: str
    state: Literal['output-available'] = 'output-available'
    input: Any | None = None
    output: Any | None = None
    provider_executed: bool | None = None
    call_provider_metadata: ProviderMetadata | None = None
    preliminary: bool | None = None
    approval: ToolApproval | None = None

ToolOutputErrorPart

Bases: BaseUIPart

Tool part in output-error state.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
178
179
180
181
182
183
184
185
186
187
188
189
class ToolOutputErrorPart(BaseUIPart):
    """Tool part in output-error state."""

    type: Annotated[str, Field(pattern=r'^tool-')]
    tool_call_id: str
    state: Literal['output-error'] = 'output-error'
    input: Any | None = None
    raw_input: Any | None = None
    error_text: str
    provider_executed: bool | None = None
    call_provider_metadata: ProviderMetadata | None = None
    approval: ToolApproval | None = None

ToolApprovalRequestedPart

Bases: BaseUIPart

Tool part in approval-requested state (awaiting user decision).

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
192
193
194
195
196
197
198
199
200
201
class ToolApprovalRequestedPart(BaseUIPart):
    """Tool part in approval-requested state (awaiting user decision)."""

    type: Annotated[str, Field(pattern=r'^tool-')]
    tool_call_id: str
    state: Literal['approval-requested'] = 'approval-requested'
    input: Any | None = None
    provider_executed: bool | None = None
    call_provider_metadata: ProviderMetadata | None = None
    approval: ToolApproval | None = None

ToolApprovalRespondedPart

Bases: BaseUIPart

Tool part in approval-responded state (user approved/denied, execution pending).

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
204
205
206
207
208
209
210
211
212
213
class ToolApprovalRespondedPart(BaseUIPart):
    """Tool part in approval-responded state (user approved/denied, execution pending)."""

    type: Annotated[str, Field(pattern=r'^tool-')]
    tool_call_id: str
    state: Literal['approval-responded'] = 'approval-responded'
    input: Any | None = None
    provider_executed: bool | None = None
    call_provider_metadata: ProviderMetadata | None = None
    approval: ToolApproval | None = None

ToolOutputDeniedPart

Bases: BaseUIPart

Tool part in output-denied state (tool was denied, terminal state).

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
216
217
218
219
220
221
222
223
224
225
class ToolOutputDeniedPart(BaseUIPart):
    """Tool part in output-denied state (tool was denied, terminal state)."""

    type: Annotated[str, Field(pattern=r'^tool-')]
    tool_call_id: str
    state: Literal['output-denied'] = 'output-denied'
    input: Any | None = None
    provider_executed: bool | None = None
    call_provider_metadata: ProviderMetadata | None = None
    approval: ToolApproval | None = None

DynamicToolInputStreamingPart

Bases: BaseUIPart

Dynamic tool part in input-streaming state.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
241
242
243
244
245
246
247
248
249
250
class DynamicToolInputStreamingPart(BaseUIPart):
    """Dynamic tool part in input-streaming state."""

    type: Literal['dynamic-tool'] = 'dynamic-tool'
    tool_name: str
    tool_call_id: str
    state: Literal['input-streaming'] = 'input-streaming'
    input: Any | None = None
    call_provider_metadata: ProviderMetadata | None = None
    approval: ToolApproval | None = None

DynamicToolInputAvailablePart

Bases: BaseUIPart

Dynamic tool part in input-available state.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
253
254
255
256
257
258
259
260
261
262
class DynamicToolInputAvailablePart(BaseUIPart):
    """Dynamic tool part in input-available state."""

    type: Literal['dynamic-tool'] = 'dynamic-tool'
    tool_name: str
    tool_call_id: str
    state: Literal['input-available'] = 'input-available'
    input: Any
    call_provider_metadata: ProviderMetadata | None = None
    approval: ToolApproval | None = None

DynamicToolOutputAvailablePart

Bases: BaseUIPart

Dynamic tool part in output-available state.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
265
266
267
268
269
270
271
272
273
274
275
276
class DynamicToolOutputAvailablePart(BaseUIPart):
    """Dynamic tool part in output-available state."""

    type: Literal['dynamic-tool'] = 'dynamic-tool'
    tool_name: str
    tool_call_id: str
    state: Literal['output-available'] = 'output-available'
    input: Any
    output: Any
    call_provider_metadata: ProviderMetadata | None = None
    preliminary: bool | None = None
    approval: ToolApproval | None = None

DynamicToolOutputErrorPart

Bases: BaseUIPart

Dynamic tool part in output-error state.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
279
280
281
282
283
284
285
286
287
288
289
class DynamicToolOutputErrorPart(BaseUIPart):
    """Dynamic tool part in output-error state."""

    type: Literal['dynamic-tool'] = 'dynamic-tool'
    tool_name: str
    tool_call_id: str
    state: Literal['output-error'] = 'output-error'
    input: Any
    error_text: str
    call_provider_metadata: ProviderMetadata | None = None
    approval: ToolApproval | None = None

DynamicToolApprovalRequestedPart

Bases: BaseUIPart

Dynamic tool part in approval-requested state (awaiting user decision).

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
292
293
294
295
296
297
298
299
300
301
class DynamicToolApprovalRequestedPart(BaseUIPart):
    """Dynamic tool part in approval-requested state (awaiting user decision)."""

    type: Literal['dynamic-tool'] = 'dynamic-tool'
    tool_name: str
    tool_call_id: str
    state: Literal['approval-requested'] = 'approval-requested'
    input: Any
    call_provider_metadata: ProviderMetadata | None = None
    approval: ToolApproval | None = None

DynamicToolApprovalRespondedPart

Bases: BaseUIPart

Dynamic tool part in approval-responded state (user approved/denied, execution pending).

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
304
305
306
307
308
309
310
311
312
313
class DynamicToolApprovalRespondedPart(BaseUIPart):
    """Dynamic tool part in approval-responded state (user approved/denied, execution pending)."""

    type: Literal['dynamic-tool'] = 'dynamic-tool'
    tool_name: str
    tool_call_id: str
    state: Literal['approval-responded'] = 'approval-responded'
    input: Any
    call_provider_metadata: ProviderMetadata | None = None
    approval: ToolApproval | None = None

DynamicToolOutputDeniedPart

Bases: BaseUIPart

Dynamic tool part in output-denied state (tool was denied, terminal state).

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
316
317
318
319
320
321
322
323
324
325
class DynamicToolOutputDeniedPart(BaseUIPart):
    """Dynamic tool part in output-denied state (tool was denied, terminal state)."""

    type: Literal['dynamic-tool'] = 'dynamic-tool'
    tool_name: str
    tool_call_id: str
    state: Literal['output-denied'] = 'output-denied'
    input: Any
    call_provider_metadata: ProviderMetadata | None = None
    approval: ToolApproval | None = None

UIMessagePart module-attribute

Union of all message part types.

UIMessage

Bases: CamelBaseModel

A message as displayed in the UI by Vercel AI Elements.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
class UIMessage(CamelBaseModel):
    """A message as displayed in the UI by Vercel AI Elements."""

    id: str
    """A unique identifier for the message."""

    role: Literal['system', 'user', 'assistant']
    """The role of the message."""

    metadata: Any | None = None
    """The metadata of the message."""

    parts: list[UIMessagePart]
    """
    The parts of the message. Use this for rendering the message in the UI.
    System messages should be avoided (set the system prompt on the server instead).
    They can have text parts.
    User messages can have text parts and file parts.
    Assistant messages can have text, reasoning, tool invocation, and file parts.
    """

id instance-attribute

id: str

A unique identifier for the message.

role instance-attribute

role: Literal['system', 'user', 'assistant']

The role of the message.

metadata class-attribute instance-attribute

metadata: Any | None = None

The metadata of the message.

parts instance-attribute

The parts of the message. Use this for rendering the message in the UI. System messages should be avoided (set the system prompt on the server instead). They can have text parts. User messages can have text parts and file parts. Assistant messages can have text, reasoning, tool invocation, and file parts.

SubmitMessage

Bases: CamelBaseModel

Submit message request.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
376
377
378
379
380
381
class SubmitMessage(CamelBaseModel, extra='allow'):
    """Submit message request."""

    trigger: Literal['submit-message'] = 'submit-message'
    id: str
    messages: list[UIMessage]

RegenerateMessage

Bases: CamelBaseModel

Ask the agent to regenerate a message.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/request_types.py
384
385
386
387
388
389
390
class RegenerateMessage(CamelBaseModel, extra='allow'):
    """Ask the agent to regenerate a message."""

    trigger: Literal['regenerate-message']
    id: str
    messages: list[UIMessage]
    message_id: str | None = None

RequestData module-attribute

RequestData = Annotated[
    SubmitMessage | RegenerateMessage,
    Discriminator("trigger"),
]

Union of all request data types.

Vercel AI response types (SSE chunks).

Converted to Python from: https://github.com/vercel/ai/blob/ai%406.0.57/packages/ai/src/ui-message-stream/ui-message-chunks.ts

Tool approval types (ToolApprovalRequestChunk, ToolOutputDeniedChunk) require AI SDK UI v6 or later.

ProviderMetadata module-attribute

ProviderMetadata = dict[str, dict[str, JSONValue]]

Provider metadata.

FinishReason module-attribute

FinishReason = (
    Literal[
        "stop",
        "length",
        "content-filter",
        "tool-calls",
        "error",
        "other",
    ]
    | None
)

Reason why the model finished generating.

BaseChunk

Bases: CamelBaseModel, ABC

Abstract base class for response SSE events.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
25
26
27
28
29
class BaseChunk(CamelBaseModel, ABC):
    """Abstract base class for response SSE events."""

    def encode(self, sdk_version: int) -> str:
        return self.model_dump_json(by_alias=True, exclude_none=True)

TextStartChunk

Bases: BaseChunk

Text start chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
32
33
34
35
36
37
class TextStartChunk(BaseChunk):
    """Text start chunk."""

    type: Literal['text-start'] = 'text-start'
    id: str
    provider_metadata: ProviderMetadata | None = None

TextDeltaChunk

Bases: BaseChunk

Text delta chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
40
41
42
43
44
45
46
class TextDeltaChunk(BaseChunk):
    """Text delta chunk."""

    type: Literal['text-delta'] = 'text-delta'
    delta: str
    id: str
    provider_metadata: ProviderMetadata | None = None

TextEndChunk

Bases: BaseChunk

Text end chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
49
50
51
52
53
54
class TextEndChunk(BaseChunk):
    """Text end chunk."""

    type: Literal['text-end'] = 'text-end'
    id: str
    provider_metadata: ProviderMetadata | None = None

ReasoningStartChunk

Bases: BaseChunk

Reasoning start chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
57
58
59
60
61
62
class ReasoningStartChunk(BaseChunk):
    """Reasoning start chunk."""

    type: Literal['reasoning-start'] = 'reasoning-start'
    id: str
    provider_metadata: ProviderMetadata | None = None

ReasoningDeltaChunk

Bases: BaseChunk

Reasoning delta chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
65
66
67
68
69
70
71
class ReasoningDeltaChunk(BaseChunk):
    """Reasoning delta chunk."""

    type: Literal['reasoning-delta'] = 'reasoning-delta'
    id: str
    delta: str
    provider_metadata: ProviderMetadata | None = None

ReasoningEndChunk

Bases: BaseChunk

Reasoning end chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
74
75
76
77
78
79
class ReasoningEndChunk(BaseChunk):
    """Reasoning end chunk."""

    type: Literal['reasoning-end'] = 'reasoning-end'
    id: str
    provider_metadata: ProviderMetadata | None = None

ErrorChunk

Bases: BaseChunk

Error chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
82
83
84
85
86
class ErrorChunk(BaseChunk):
    """Error chunk."""

    type: Literal['error'] = 'error'
    error_text: str

ToolInputStartChunk

Bases: BaseChunk

Tool input start chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
class ToolInputStartChunk(BaseChunk):
    """Tool input start chunk."""

    type: Literal['tool-input-start'] = 'tool-input-start'
    tool_call_id: str
    tool_name: str
    provider_executed: bool | None = None
    provider_metadata: ProviderMetadata | None = None
    dynamic: bool | None = None

    def encode(self, sdk_version: int) -> str:
        exclude = {'provider_metadata'} if sdk_version < 6 else None
        return self.model_dump_json(by_alias=True, exclude_none=True, exclude=exclude)

ToolInputDeltaChunk

Bases: BaseChunk

Tool input delta chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
104
105
106
107
108
109
class ToolInputDeltaChunk(BaseChunk):
    """Tool input delta chunk."""

    type: Literal['tool-input-delta'] = 'tool-input-delta'
    tool_call_id: str
    input_text_delta: str

ToolOutputAvailableChunk

Bases: BaseChunk

Tool output available chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
112
113
114
115
116
117
118
119
120
class ToolOutputAvailableChunk(BaseChunk):
    """Tool output available chunk."""

    type: Literal['tool-output-available'] = 'tool-output-available'
    tool_call_id: str
    output: Any
    provider_executed: bool | None = None
    dynamic: bool | None = None
    preliminary: bool | None = None

ToolInputAvailableChunk

Bases: BaseChunk

Tool input available chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
123
124
125
126
127
128
129
130
131
132
class ToolInputAvailableChunk(BaseChunk):
    """Tool input available chunk."""

    type: Literal['tool-input-available'] = 'tool-input-available'
    tool_call_id: str
    tool_name: str
    input: Any
    provider_executed: bool | None = None
    provider_metadata: ProviderMetadata | None = None
    dynamic: bool | None = None

ToolInputErrorChunk

Bases: BaseChunk

Tool input error chunk.

Requires AI SDK UI v6 or later.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
class ToolInputErrorChunk(BaseChunk):
    """Tool input error chunk.

    Requires AI SDK UI v6 or later.
    """

    type: Literal['tool-input-error'] = 'tool-input-error'
    tool_call_id: str
    tool_name: str
    input: Any
    provider_executed: bool | None = None
    provider_metadata: ProviderMetadata | None = None
    dynamic: bool | None = None
    error_text: str

ToolOutputErrorChunk

Bases: BaseChunk

Tool output error chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
151
152
153
154
155
156
157
158
class ToolOutputErrorChunk(BaseChunk):
    """Tool output error chunk."""

    type: Literal['tool-output-error'] = 'tool-output-error'
    tool_call_id: str
    error_text: str
    provider_executed: bool | None = None
    dynamic: bool | None = None

ToolApprovalRequestChunk

Bases: BaseChunk

Tool approval request chunk for human-in-the-loop approval.

Requires AI SDK UI v6 or later.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
161
162
163
164
165
166
167
168
169
class ToolApprovalRequestChunk(BaseChunk):
    """Tool approval request chunk for human-in-the-loop approval.

    Requires AI SDK UI v6 or later.
    """

    type: Literal['tool-approval-request'] = 'tool-approval-request'
    approval_id: str
    tool_call_id: str

ToolOutputDeniedChunk

Bases: BaseChunk

Tool output denied chunk when user denies tool execution.

Requires AI SDK UI v6 or later.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
172
173
174
175
176
177
178
179
class ToolOutputDeniedChunk(BaseChunk):
    """Tool output denied chunk when user denies tool execution.

    Requires AI SDK UI v6 or later.
    """

    type: Literal['tool-output-denied'] = 'tool-output-denied'
    tool_call_id: str

SourceUrlChunk

Bases: BaseChunk

Source URL chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
182
183
184
185
186
187
188
189
class SourceUrlChunk(BaseChunk):
    """Source URL chunk."""

    type: Literal['source-url'] = 'source-url'
    source_id: str
    url: str
    title: str | None = None
    provider_metadata: ProviderMetadata | None = None

SourceDocumentChunk

Bases: BaseChunk

Source document chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
192
193
194
195
196
197
198
199
200
class SourceDocumentChunk(BaseChunk):
    """Source document chunk."""

    type: Literal['source-document'] = 'source-document'
    source_id: str
    media_type: str
    title: str
    filename: str | None = None
    provider_metadata: ProviderMetadata | None = None

FileChunk

Bases: BaseChunk

File chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
203
204
205
206
207
208
class FileChunk(BaseChunk):
    """File chunk."""

    type: Literal['file'] = 'file'
    url: str
    media_type: str

DataChunk

Bases: BaseChunk

Data chunk with dynamic type.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
211
212
213
214
215
216
217
class DataChunk(BaseChunk):
    """Data chunk with dynamic type."""

    type: Annotated[str, Field(pattern=r'^data-')]
    id: str | None = None
    data: Any
    transient: bool | None = None

StartStepChunk

Bases: BaseChunk

Start step chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
220
221
222
223
class StartStepChunk(BaseChunk):
    """Start step chunk."""

    type: Literal['start-step'] = 'start-step'

FinishStepChunk

Bases: BaseChunk

Finish step chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
226
227
228
229
class FinishStepChunk(BaseChunk):
    """Finish step chunk."""

    type: Literal['finish-step'] = 'finish-step'

StartChunk

Bases: BaseChunk

Start chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
232
233
234
235
236
237
class StartChunk(BaseChunk):
    """Start chunk."""

    type: Literal['start'] = 'start'
    message_id: str | None = None
    message_metadata: Any | None = None

FinishChunk

Bases: BaseChunk

Finish chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
240
241
242
243
244
245
class FinishChunk(BaseChunk):
    """Finish chunk."""

    type: Literal['finish'] = 'finish'
    finish_reason: FinishReason = None
    message_metadata: Any | None = None

AbortChunk

Bases: BaseChunk

Abort chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
248
249
250
251
252
class AbortChunk(BaseChunk):
    """Abort chunk."""

    type: Literal['abort'] = 'abort'
    reason: str | None = None

MessageMetadataChunk

Bases: BaseChunk

Message metadata chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
255
256
257
258
259
class MessageMetadataChunk(BaseChunk):
    """Message metadata chunk."""

    type: Literal['message-metadata'] = 'message-metadata'
    message_metadata: Any

DoneChunk

Bases: BaseChunk

Done chunk.

Source code in pydantic_ai_slim/pydantic_ai/ui/vercel_ai/response_types.py
262
263
264
265
266
267
268
class DoneChunk(BaseChunk):
    """Done chunk."""

    type: Literal['done'] = 'done'

    def encode(self, sdk_version: int) -> str:
        return '[DONE]'