pydantic-ai-slim 1.8.0__py3-none-any.whl → 1.9.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of pydantic-ai-slim might be problematic. Click here for more details.
- pydantic_ai/__init__.py +2 -0
- pydantic_ai/_agent_graph.py +3 -0
- pydantic_ai/ag_ui.py +50 -696
- pydantic_ai/agent/abstract.py +13 -3
- pydantic_ai/direct.py +12 -0
- pydantic_ai/durable_exec/dbos/_agent.py +3 -0
- pydantic_ai/durable_exec/prefect/_agent.py +3 -0
- pydantic_ai/durable_exec/temporal/_agent.py +3 -0
- pydantic_ai/messages.py +39 -7
- pydantic_ai/models/__init__.py +42 -1
- pydantic_ai/models/google.py +5 -12
- pydantic_ai/models/groq.py +9 -1
- pydantic_ai/providers/anthropic.py +2 -2
- pydantic_ai/result.py +19 -7
- pydantic_ai/ui/__init__.py +16 -0
- pydantic_ai/ui/_adapter.py +386 -0
- pydantic_ai/ui/_event_stream.py +591 -0
- pydantic_ai/ui/_messages_builder.py +28 -0
- pydantic_ai/ui/ag_ui/__init__.py +9 -0
- pydantic_ai/ui/ag_ui/_adapter.py +187 -0
- pydantic_ai/ui/ag_ui/_event_stream.py +227 -0
- pydantic_ai/ui/ag_ui/app.py +148 -0
- pydantic_ai/ui/vercel_ai/__init__.py +16 -0
- pydantic_ai/ui/vercel_ai/_adapter.py +199 -0
- pydantic_ai/ui/vercel_ai/_event_stream.py +187 -0
- pydantic_ai/ui/vercel_ai/_utils.py +16 -0
- pydantic_ai/ui/vercel_ai/request_types.py +275 -0
- pydantic_ai/ui/vercel_ai/response_types.py +230 -0
- {pydantic_ai_slim-1.8.0.dist-info → pydantic_ai_slim-1.9.1.dist-info}/METADATA +5 -3
- {pydantic_ai_slim-1.8.0.dist-info → pydantic_ai_slim-1.9.1.dist-info}/RECORD +33 -19
- {pydantic_ai_slim-1.8.0.dist-info → pydantic_ai_slim-1.9.1.dist-info}/WHEEL +0 -0
- {pydantic_ai_slim-1.8.0.dist-info → pydantic_ai_slim-1.9.1.dist-info}/entry_points.txt +0 -0
- {pydantic_ai_slim-1.8.0.dist-info → pydantic_ai_slim-1.9.1.dist-info}/licenses/LICENSE +0 -0
pydantic_ai/agent/abstract.py
CHANGED
|
@@ -49,7 +49,7 @@ if TYPE_CHECKING:
|
|
|
49
49
|
from starlette.routing import BaseRoute, Route
|
|
50
50
|
from starlette.types import ExceptionHandler, Lifespan
|
|
51
51
|
|
|
52
|
-
from
|
|
52
|
+
from pydantic_ai.ui.ag_ui.app import AGUIApp
|
|
53
53
|
|
|
54
54
|
|
|
55
55
|
T = TypeVar('T')
|
|
@@ -654,6 +654,9 @@ class AbstractAgent(Generic[AgentDepsT, OutputDataT], ABC):
|
|
|
654
654
|
PartStartEvent(index=0, part=TextPart(content='The capital of ')),
|
|
655
655
|
FinalResultEvent(tool_name=None, tool_call_id=None),
|
|
656
656
|
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='France is Paris. ')),
|
|
657
|
+
PartEndEvent(
|
|
658
|
+
index=0, part=TextPart(content='The capital of France is Paris. ')
|
|
659
|
+
),
|
|
657
660
|
AgentRunResultEvent(
|
|
658
661
|
result=AgentRunResult(output='The capital of France is Paris. ')
|
|
659
662
|
),
|
|
@@ -990,11 +993,14 @@ class AbstractAgent(Generic[AgentDepsT, OutputDataT], ABC):
|
|
|
990
993
|
async def __aexit__(self, *args: Any) -> bool | None:
|
|
991
994
|
raise NotImplementedError
|
|
992
995
|
|
|
996
|
+
# TODO (v2): Remove in favor of using `AGUIApp` directly -- we don't have `to_temporal()` or `to_vercel_ai()` either.
|
|
993
997
|
def to_ag_ui(
|
|
994
998
|
self,
|
|
995
999
|
*,
|
|
996
1000
|
# Agent.iter parameters
|
|
997
1001
|
output_type: OutputSpec[OutputDataT] | None = None,
|
|
1002
|
+
message_history: Sequence[_messages.ModelMessage] | None = None,
|
|
1003
|
+
deferred_tool_results: DeferredToolResults | None = None,
|
|
998
1004
|
model: models.Model | models.KnownModelName | str | None = None,
|
|
999
1005
|
deps: AgentDepsT = None,
|
|
1000
1006
|
model_settings: ModelSettings | None = None,
|
|
@@ -1035,12 +1041,14 @@ class AbstractAgent(Generic[AgentDepsT, OutputDataT], ABC):
|
|
|
1035
1041
|
uvicorn app:app --host 0.0.0.0 --port 8000
|
|
1036
1042
|
```
|
|
1037
1043
|
|
|
1038
|
-
See [AG-UI docs](../ag-ui.md) for more information.
|
|
1044
|
+
See [AG-UI docs](../ui/ag-ui.md) for more information.
|
|
1039
1045
|
|
|
1040
1046
|
Args:
|
|
1041
1047
|
output_type: Custom output type to use for this run, `output_type` may only be used if the agent has
|
|
1042
1048
|
no output validators since output validators would expect an argument that matches the agent's
|
|
1043
1049
|
output type.
|
|
1050
|
+
message_history: History of the conversation so far.
|
|
1051
|
+
deferred_tool_results: Optional results for deferred tool calls in the message history.
|
|
1044
1052
|
model: Optional model to use for this run, required if `model` was not set when creating the agent.
|
|
1045
1053
|
deps: Optional dependencies to use for this run.
|
|
1046
1054
|
model_settings: Optional settings to use for this model's request.
|
|
@@ -1070,12 +1078,14 @@ class AbstractAgent(Generic[AgentDepsT, OutputDataT], ABC):
|
|
|
1070
1078
|
Returns:
|
|
1071
1079
|
An ASGI application for running Pydantic AI agents with AG-UI protocol support.
|
|
1072
1080
|
"""
|
|
1073
|
-
from
|
|
1081
|
+
from pydantic_ai.ui.ag_ui.app import AGUIApp
|
|
1074
1082
|
|
|
1075
1083
|
return AGUIApp(
|
|
1076
1084
|
agent=self,
|
|
1077
1085
|
# Agent.iter parameters
|
|
1078
1086
|
output_type=output_type,
|
|
1087
|
+
message_history=message_history,
|
|
1088
|
+
deferred_tool_results=deferred_tool_results,
|
|
1079
1089
|
model=model,
|
|
1080
1090
|
deps=deps,
|
|
1081
1091
|
model_settings=model_settings,
|
pydantic_ai/direct.py
CHANGED
|
@@ -172,6 +172,12 @@ def model_request_stream(
|
|
|
172
172
|
index=0, delta=TextPartDelta(content_delta='a German-born theoretical ')
|
|
173
173
|
),
|
|
174
174
|
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='physicist.')),
|
|
175
|
+
PartEndEvent(
|
|
176
|
+
index=0,
|
|
177
|
+
part=TextPart(
|
|
178
|
+
content='Albert Einstein was a German-born theoretical physicist.'
|
|
179
|
+
),
|
|
180
|
+
),
|
|
175
181
|
]
|
|
176
182
|
'''
|
|
177
183
|
```
|
|
@@ -229,6 +235,12 @@ def model_request_stream_sync(
|
|
|
229
235
|
index=0, delta=TextPartDelta(content_delta='a German-born theoretical ')
|
|
230
236
|
),
|
|
231
237
|
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='physicist.')),
|
|
238
|
+
PartEndEvent(
|
|
239
|
+
index=0,
|
|
240
|
+
part=TextPart(
|
|
241
|
+
content='Albert Einstein was a German-born theoretical physicist.'
|
|
242
|
+
),
|
|
243
|
+
),
|
|
232
244
|
]
|
|
233
245
|
'''
|
|
234
246
|
```
|
|
@@ -640,6 +640,9 @@ class DBOSAgent(WrapperAgent[AgentDepsT, OutputDataT], DBOSConfiguredInstance):
|
|
|
640
640
|
PartStartEvent(index=0, part=TextPart(content='The capital of ')),
|
|
641
641
|
FinalResultEvent(tool_name=None, tool_call_id=None),
|
|
642
642
|
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='France is Paris. ')),
|
|
643
|
+
PartEndEvent(
|
|
644
|
+
index=0, part=TextPart(content='The capital of France is Paris. ')
|
|
645
|
+
),
|
|
643
646
|
AgentRunResultEvent(
|
|
644
647
|
result=AgentRunResult(output='The capital of France is Paris. ')
|
|
645
648
|
),
|
|
@@ -598,6 +598,9 @@ class PrefectAgent(WrapperAgent[AgentDepsT, OutputDataT]):
|
|
|
598
598
|
PartStartEvent(index=0, part=TextPart(content='The capital of ')),
|
|
599
599
|
FinalResultEvent(tool_name=None, tool_call_id=None),
|
|
600
600
|
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='France is Paris. ')),
|
|
601
|
+
PartEndEvent(
|
|
602
|
+
index=0, part=TextPart(content='The capital of France is Paris. ')
|
|
603
|
+
),
|
|
601
604
|
AgentRunResultEvent(
|
|
602
605
|
result=AgentRunResult(output='The capital of France is Paris. ')
|
|
603
606
|
),
|
|
@@ -669,6 +669,9 @@ class TemporalAgent(WrapperAgent[AgentDepsT, OutputDataT]):
|
|
|
669
669
|
PartStartEvent(index=0, part=TextPart(content='The capital of ')),
|
|
670
670
|
FinalResultEvent(tool_name=None, tool_call_id=None),
|
|
671
671
|
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='France is Paris. ')),
|
|
672
|
+
PartEndEvent(
|
|
673
|
+
index=0, part=TextPart(content='The capital of France is Paris. ')
|
|
674
|
+
),
|
|
672
675
|
AgentRunResultEvent(
|
|
673
676
|
result=AgentRunResult(output='The capital of France is Paris. ')
|
|
674
677
|
),
|
pydantic_ai/messages.py
CHANGED
|
@@ -13,7 +13,7 @@ import pydantic
|
|
|
13
13
|
import pydantic_core
|
|
14
14
|
from genai_prices import calc_price, types as genai_types
|
|
15
15
|
from opentelemetry._events import Event # pyright: ignore[reportPrivateImportUsage]
|
|
16
|
-
from typing_extensions import
|
|
16
|
+
from typing_extensions import deprecated
|
|
17
17
|
|
|
18
18
|
from . import _otel_messages, _utils
|
|
19
19
|
from ._utils import generate_tool_call_id as _generate_tool_call_id, now_utc as _now_utc
|
|
@@ -514,16 +514,16 @@ class BinaryContent:
|
|
|
514
514
|
vendor_metadata=bc.vendor_metadata,
|
|
515
515
|
)
|
|
516
516
|
else:
|
|
517
|
-
return bc
|
|
517
|
+
return bc
|
|
518
518
|
|
|
519
519
|
@classmethod
|
|
520
|
-
def from_data_uri(cls, data_uri: str) ->
|
|
520
|
+
def from_data_uri(cls, data_uri: str) -> BinaryContent:
|
|
521
521
|
"""Create a `BinaryContent` from a data URI."""
|
|
522
522
|
prefix = 'data:'
|
|
523
523
|
if not data_uri.startswith(prefix):
|
|
524
|
-
raise ValueError('Data URI must start with "data:"')
|
|
524
|
+
raise ValueError('Data URI must start with "data:"')
|
|
525
525
|
media_type, data = data_uri[len(prefix) :].split(';base64,', 1)
|
|
526
|
-
return cls(data=base64.b64decode(data), media_type=media_type)
|
|
526
|
+
return cls.narrow_type(cls(data=base64.b64decode(data), media_type=media_type))
|
|
527
527
|
|
|
528
528
|
@pydantic.computed_field
|
|
529
529
|
@property
|
|
@@ -1612,6 +1612,14 @@ class PartStartEvent:
|
|
|
1612
1612
|
part: ModelResponsePart
|
|
1613
1613
|
"""The newly started `ModelResponsePart`."""
|
|
1614
1614
|
|
|
1615
|
+
previous_part_kind: (
|
|
1616
|
+
Literal['text', 'thinking', 'tool-call', 'builtin-tool-call', 'builtin-tool-return', 'file'] | None
|
|
1617
|
+
) = None
|
|
1618
|
+
"""The kind of the previous part, if any.
|
|
1619
|
+
|
|
1620
|
+
This is useful for UI event streams to know whether to group parts of the same kind together when emitting events.
|
|
1621
|
+
"""
|
|
1622
|
+
|
|
1615
1623
|
event_kind: Literal['part_start'] = 'part_start'
|
|
1616
1624
|
"""Event type identifier, used as a discriminator."""
|
|
1617
1625
|
|
|
@@ -1634,6 +1642,30 @@ class PartDeltaEvent:
|
|
|
1634
1642
|
__repr__ = _utils.dataclasses_no_defaults_repr
|
|
1635
1643
|
|
|
1636
1644
|
|
|
1645
|
+
@dataclass(repr=False, kw_only=True)
|
|
1646
|
+
class PartEndEvent:
|
|
1647
|
+
"""An event indicating that a part is complete."""
|
|
1648
|
+
|
|
1649
|
+
index: int
|
|
1650
|
+
"""The index of the part within the overall response parts list."""
|
|
1651
|
+
|
|
1652
|
+
part: ModelResponsePart
|
|
1653
|
+
"""The complete `ModelResponsePart`."""
|
|
1654
|
+
|
|
1655
|
+
next_part_kind: (
|
|
1656
|
+
Literal['text', 'thinking', 'tool-call', 'builtin-tool-call', 'builtin-tool-return', 'file'] | None
|
|
1657
|
+
) = None
|
|
1658
|
+
"""The kind of the next part, if any.
|
|
1659
|
+
|
|
1660
|
+
This is useful for UI event streams to know whether to group parts of the same kind together when emitting events.
|
|
1661
|
+
"""
|
|
1662
|
+
|
|
1663
|
+
event_kind: Literal['part_end'] = 'part_end'
|
|
1664
|
+
"""Event type identifier, used as a discriminator."""
|
|
1665
|
+
|
|
1666
|
+
__repr__ = _utils.dataclasses_no_defaults_repr
|
|
1667
|
+
|
|
1668
|
+
|
|
1637
1669
|
@dataclass(repr=False, kw_only=True)
|
|
1638
1670
|
class FinalResultEvent:
|
|
1639
1671
|
"""An event indicating the response to the current model request matches the output schema and will produce a result."""
|
|
@@ -1649,9 +1681,9 @@ class FinalResultEvent:
|
|
|
1649
1681
|
|
|
1650
1682
|
|
|
1651
1683
|
ModelResponseStreamEvent = Annotated[
|
|
1652
|
-
PartStartEvent | PartDeltaEvent | FinalResultEvent, pydantic.Discriminator('event_kind')
|
|
1684
|
+
PartStartEvent | PartDeltaEvent | PartEndEvent | FinalResultEvent, pydantic.Discriminator('event_kind')
|
|
1653
1685
|
]
|
|
1654
|
-
"""An event in the model response stream, starting a new part, applying a delta to an existing one, or indicating the final result."""
|
|
1686
|
+
"""An event in the model response stream, starting a new part, applying a delta to an existing one, indicating a part is complete, or indicating the final result."""
|
|
1655
1687
|
|
|
1656
1688
|
|
|
1657
1689
|
@dataclass(repr=False)
|
pydantic_ai/models/__init__.py
CHANGED
|
@@ -27,6 +27,7 @@ from .._run_context import RunContext
|
|
|
27
27
|
from ..builtin_tools import AbstractBuiltinTool
|
|
28
28
|
from ..exceptions import UserError
|
|
29
29
|
from ..messages import (
|
|
30
|
+
BaseToolCallPart,
|
|
30
31
|
BinaryImage,
|
|
31
32
|
FilePart,
|
|
32
33
|
FileUrl,
|
|
@@ -35,9 +36,12 @@ from ..messages import (
|
|
|
35
36
|
ModelMessage,
|
|
36
37
|
ModelRequest,
|
|
37
38
|
ModelResponse,
|
|
39
|
+
ModelResponsePart,
|
|
38
40
|
ModelResponseStreamEvent,
|
|
41
|
+
PartEndEvent,
|
|
39
42
|
PartStartEvent,
|
|
40
43
|
TextPart,
|
|
44
|
+
ThinkingPart,
|
|
41
45
|
ToolCallPart,
|
|
42
46
|
VideoUrl,
|
|
43
47
|
)
|
|
@@ -543,7 +547,44 @@ class StreamedResponse(ABC):
|
|
|
543
547
|
async for event in iterator:
|
|
544
548
|
yield event
|
|
545
549
|
|
|
546
|
-
|
|
550
|
+
async def iterator_with_part_end(
|
|
551
|
+
iterator: AsyncIterator[ModelResponseStreamEvent],
|
|
552
|
+
) -> AsyncIterator[ModelResponseStreamEvent]:
|
|
553
|
+
last_start_event: PartStartEvent | None = None
|
|
554
|
+
|
|
555
|
+
def part_end_event(next_part: ModelResponsePart | None = None) -> PartEndEvent | None:
|
|
556
|
+
if not last_start_event:
|
|
557
|
+
return None
|
|
558
|
+
|
|
559
|
+
index = last_start_event.index
|
|
560
|
+
part = self._parts_manager.get_parts()[index]
|
|
561
|
+
if not isinstance(part, TextPart | ThinkingPart | BaseToolCallPart):
|
|
562
|
+
# Parts other than these 3 don't have deltas, so don't need an end part.
|
|
563
|
+
return None
|
|
564
|
+
|
|
565
|
+
return PartEndEvent(
|
|
566
|
+
index=index,
|
|
567
|
+
part=part,
|
|
568
|
+
next_part_kind=next_part.part_kind if next_part else None,
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
async for event in iterator:
|
|
572
|
+
if isinstance(event, PartStartEvent):
|
|
573
|
+
if last_start_event:
|
|
574
|
+
end_event = part_end_event(event.part)
|
|
575
|
+
if end_event:
|
|
576
|
+
yield end_event
|
|
577
|
+
|
|
578
|
+
event.previous_part_kind = last_start_event.part.part_kind
|
|
579
|
+
last_start_event = event
|
|
580
|
+
|
|
581
|
+
yield event
|
|
582
|
+
|
|
583
|
+
end_event = part_end_event()
|
|
584
|
+
if end_event:
|
|
585
|
+
yield end_event
|
|
586
|
+
|
|
587
|
+
self._event_iterator = iterator_with_part_end(iterator_with_final_event(self._get_event_iterator()))
|
|
547
588
|
return self._event_iterator
|
|
548
589
|
|
|
549
590
|
@abstractmethod
|
pydantic_ai/models/google.py
CHANGED
|
@@ -471,11 +471,9 @@ class GoogleModel(Model):
|
|
|
471
471
|
raise UnexpectedModelBehavior(
|
|
472
472
|
f'Content filter {raw_finish_reason.value!r} triggered', response.model_dump_json()
|
|
473
473
|
)
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
) # pragma: no cover
|
|
478
|
-
parts = candidate.content.parts or []
|
|
474
|
+
parts = [] # pragma: no cover
|
|
475
|
+
else:
|
|
476
|
+
parts = candidate.content.parts or []
|
|
479
477
|
|
|
480
478
|
usage = _metadata_as_usage(response)
|
|
481
479
|
return _process_response_from_parts(
|
|
@@ -649,17 +647,12 @@ class GeminiStreamedResponse(StreamedResponse):
|
|
|
649
647
|
# )
|
|
650
648
|
|
|
651
649
|
if candidate.content is None or candidate.content.parts is None:
|
|
652
|
-
if self.finish_reason == '
|
|
653
|
-
# Normal completion - skip this chunk
|
|
654
|
-
continue
|
|
655
|
-
elif self.finish_reason == 'content_filter' and raw_finish_reason: # pragma: no cover
|
|
650
|
+
if self.finish_reason == 'content_filter' and raw_finish_reason: # pragma: no cover
|
|
656
651
|
raise UnexpectedModelBehavior(
|
|
657
652
|
f'Content filter {raw_finish_reason.value!r} triggered', chunk.model_dump_json()
|
|
658
653
|
)
|
|
659
654
|
else: # pragma: no cover
|
|
660
|
-
|
|
661
|
-
'Content field missing from streaming Gemini response', chunk.model_dump_json()
|
|
662
|
-
)
|
|
655
|
+
continue
|
|
663
656
|
|
|
664
657
|
parts = candidate.content.parts
|
|
665
658
|
if not parts:
|
pydantic_ai/models/groq.py
CHANGED
|
@@ -524,6 +524,8 @@ class GroqStreamedResponse(StreamedResponse):
|
|
|
524
524
|
async def _get_event_iterator(self) -> AsyncIterator[ModelResponseStreamEvent]: # noqa: C901
|
|
525
525
|
try:
|
|
526
526
|
executed_tool_call_id: str | None = None
|
|
527
|
+
reasoning_index = 0
|
|
528
|
+
reasoning = False
|
|
527
529
|
async for chunk in self._response:
|
|
528
530
|
self._usage += _map_usage(chunk)
|
|
529
531
|
|
|
@@ -540,10 +542,16 @@ class GroqStreamedResponse(StreamedResponse):
|
|
|
540
542
|
self.finish_reason = _FINISH_REASON_MAP.get(raw_finish_reason)
|
|
541
543
|
|
|
542
544
|
if choice.delta.reasoning is not None:
|
|
545
|
+
if not reasoning:
|
|
546
|
+
reasoning_index += 1
|
|
547
|
+
reasoning = True
|
|
548
|
+
|
|
543
549
|
# NOTE: The `reasoning` field is only present if `groq_reasoning_format` is set to `parsed`.
|
|
544
550
|
yield self._parts_manager.handle_thinking_delta(
|
|
545
|
-
vendor_part_id='reasoning', content=choice.delta.reasoning
|
|
551
|
+
vendor_part_id=f'reasoning-{reasoning_index}', content=choice.delta.reasoning
|
|
546
552
|
)
|
|
553
|
+
else:
|
|
554
|
+
reasoning = False
|
|
547
555
|
|
|
548
556
|
if choice.delta.executed_tools:
|
|
549
557
|
for tool in choice.delta.executed_tools:
|
|
@@ -12,7 +12,7 @@ from pydantic_ai.profiles.anthropic import anthropic_model_profile
|
|
|
12
12
|
from pydantic_ai.providers import Provider
|
|
13
13
|
|
|
14
14
|
try:
|
|
15
|
-
from anthropic import AsyncAnthropic, AsyncAnthropicBedrock
|
|
15
|
+
from anthropic import AsyncAnthropic, AsyncAnthropicBedrock, AsyncAnthropicVertex
|
|
16
16
|
except ImportError as _import_error:
|
|
17
17
|
raise ImportError(
|
|
18
18
|
'Please install the `anthropic` package to use the Anthropic provider, '
|
|
@@ -20,7 +20,7 @@ except ImportError as _import_error:
|
|
|
20
20
|
) from _import_error
|
|
21
21
|
|
|
22
22
|
|
|
23
|
-
AsyncAnthropicClient: TypeAlias = AsyncAnthropic | AsyncAnthropicBedrock
|
|
23
|
+
AsyncAnthropicClient: TypeAlias = AsyncAnthropic | AsyncAnthropicBedrock | AsyncAnthropicVertex
|
|
24
24
|
|
|
25
25
|
|
|
26
26
|
class AnthropicProvider(Provider[AsyncAnthropicClient]):
|
pydantic_ai/result.py
CHANGED
|
@@ -60,14 +60,26 @@ class AgentStream(Generic[AgentDepsT, OutputDataT]):
|
|
|
60
60
|
|
|
61
61
|
async def stream_output(self, *, debounce_by: float | None = 0.1) -> AsyncIterator[OutputDataT]:
|
|
62
62
|
"""Asynchronously stream the (validated) agent outputs."""
|
|
63
|
+
last_response: _messages.ModelResponse | None = None
|
|
63
64
|
async for response in self.stream_responses(debounce_by=debounce_by):
|
|
64
|
-
if self._raw_stream_response.final_result_event is
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
65
|
+
if self._raw_stream_response.final_result_event is None or (
|
|
66
|
+
last_response and response.parts == last_response.parts
|
|
67
|
+
):
|
|
68
|
+
continue
|
|
69
|
+
last_response = response
|
|
70
|
+
|
|
71
|
+
try:
|
|
72
|
+
yield await self.validate_response_output(response, allow_partial=True)
|
|
73
|
+
except ValidationError:
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
response = self.response
|
|
77
|
+
if self._raw_stream_response.final_result_event is None or (
|
|
78
|
+
last_response and response.parts == last_response.parts
|
|
79
|
+
):
|
|
80
|
+
return
|
|
81
|
+
|
|
82
|
+
yield await self.validate_response_output(response)
|
|
71
83
|
|
|
72
84
|
async def stream_responses(self, *, debounce_by: float | None = 0.1) -> AsyncIterator[_messages.ModelResponse]:
|
|
73
85
|
"""Asynchronously stream the (unvalidated) model responses for the agent."""
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from ._adapter import StateDeps, StateHandler, UIAdapter
|
|
4
|
+
from ._event_stream import SSE_CONTENT_TYPE, NativeEvent, OnCompleteFunc, UIEventStream
|
|
5
|
+
from ._messages_builder import MessagesBuilder
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
'UIAdapter',
|
|
9
|
+
'UIEventStream',
|
|
10
|
+
'SSE_CONTENT_TYPE',
|
|
11
|
+
'StateDeps',
|
|
12
|
+
'StateHandler',
|
|
13
|
+
'NativeEvent',
|
|
14
|
+
'OnCompleteFunc',
|
|
15
|
+
'MessagesBuilder',
|
|
16
|
+
]
|