Skip to content

Commit a87af7e

Browse files
committed
Treat empty AG-UI state as missing
1 parent e7b2f82 commit a87af7e

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

pydantic_ai_slim/pydantic_ai/ui/ag_ui/_adapter.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22

33
from __future__ import annotations
44

5-
from collections.abc import Sequence
5+
from collections.abc import Mapping, Sequence
66
from functools import cached_property
77
from typing import (
88
TYPE_CHECKING,
99
Any,
10+
cast,
1011
)
1112

1213
from ... import ExternalToolset, ToolDefinition
@@ -107,7 +108,14 @@ def toolset(self) -> AbstractToolset[AgentDepsT] | None:
107108
@cached_property
108109
def state(self) -> dict[str, Any] | None:
109110
"""Frontend state from the AG-UI run input."""
110-
return self.run_input.state
111+
state = self.run_input.state
112+
if state is None:
113+
return None
114+
115+
if isinstance(state, Mapping) and not state:
116+
return None
117+
118+
return cast('dict[str, Any]', state)
111119

112120
@classmethod
113121
def load_messages(cls, messages: Sequence[Message]) -> list[ModelMessage]:

tests/test_ag_ui.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1193,6 +1193,24 @@ async def test_request_with_state_without_handler() -> None:
11931193
pass
11941194

11951195

1196+
async def test_request_with_empty_state_without_handler() -> None:
1197+
agent = Agent(model=FunctionModel(stream_function=simple_stream))
1198+
1199+
run_input = create_input(
1200+
UserMessage(
1201+
id='msg_1',
1202+
content='Hello, how are you?',
1203+
),
1204+
state={},
1205+
)
1206+
1207+
events = list[dict[str, Any]]()
1208+
async for event in run_ag_ui(agent, run_input):
1209+
events.append(json.loads(event.removeprefix('data: ')))
1210+
1211+
assert events == simple_result()
1212+
1213+
11961214
async def test_request_with_state_with_custom_handler() -> None:
11971215
@dataclass
11981216
class CustomStateDeps:

0 commit comments

Comments
 (0)