|
1 | 1 | import unittest.mock |
| 2 | +import warnings |
2 | 3 |
|
3 | 4 | import pytest |
4 | 5 | import pytest_asyncio |
5 | 6 |
|
6 | 7 | from strands import tool |
7 | 8 | from strands.experimental.bidi import BidiAgent |
8 | 9 | from strands.experimental.bidi.models import BidiModel, BidiModelTimeoutError |
9 | | -from strands.experimental.bidi.types.events import BidiConnectionRestartEvent, BidiTextInputEvent |
| 10 | +from strands.experimental.bidi.types.events import BidiConnectionCloseEvent, BidiConnectionRestartEvent, BidiTextInputEvent |
10 | 11 | from strands.types._events import ToolResultEvent, ToolResultMessageEvent, ToolUseStreamEvent |
11 | 12 |
|
12 | 13 |
|
@@ -93,3 +94,157 @@ async def test_bidi_agent_loop_receive_tool_use(loop, agent, agenerator): |
93 | 94 | assert tru_messages == exp_messages |
94 | 95 |
|
95 | 96 | agent.model.send.assert_called_with(tool_result_event) |
| 97 | + |
| 98 | + |
| 99 | +@pytest.mark.asyncio |
| 100 | +async def test_bidi_agent_loop_request_state_initialized_for_tools(loop, agent, agenerator): |
| 101 | + """Test that request_state is initialized in invocation_state before tool execution. |
| 102 | +
|
| 103 | + This ensures request_state exists for tools that may need it via invocation_state, |
| 104 | + even when invocation_state is not provided by the user. |
| 105 | + """ |
| 106 | + tool_use = {"toolUseId": "t2", "name": "time_tool", "input": {}} |
| 107 | + tool_use_event = ToolUseStreamEvent(current_tool_use=tool_use, delta="") |
| 108 | + |
| 109 | + agent.model.receive = unittest.mock.Mock(return_value=agenerator([tool_use_event])) |
| 110 | + |
| 111 | + # Start without providing invocation_state |
| 112 | + await loop.start() |
| 113 | + |
| 114 | + tru_events = [] |
| 115 | + async for event in loop.receive(): |
| 116 | + tru_events.append(event) |
| 117 | + if len(tru_events) >= 3: |
| 118 | + break |
| 119 | + |
| 120 | + # Verify tool executed successfully |
| 121 | + tool_result_event = tru_events[1] |
| 122 | + assert isinstance(tool_result_event, ToolResultEvent) |
| 123 | + assert tool_result_event.tool_result["status"] == "success" |
| 124 | + |
| 125 | + # Verify request_state was initialized in invocation_state |
| 126 | + assert "request_state" in loop._invocation_state |
| 127 | + assert isinstance(loop._invocation_state["request_state"], dict) |
| 128 | + |
| 129 | + |
| 130 | +@pytest.mark.asyncio |
| 131 | +async def test_bidi_agent_loop_stop_event_loop_flag(agent, agenerator): |
| 132 | + """Test that the stop_event_loop flag in request_state gracefully closes the connection. |
| 133 | +
|
| 134 | + This simulates a tool (like strands_tools.stop) setting the flag via invocation_state. |
| 135 | + """ |
| 136 | + # Use a tool that modifies invocation_state to set the stop flag |
| 137 | + # We'll mock the tool executor to simulate this behavior |
| 138 | + loop = agent._loop |
| 139 | + |
| 140 | + tool_use = {"toolUseId": "t3", "name": "time_tool", "input": {}} |
| 141 | + tool_use_event = ToolUseStreamEvent(current_tool_use=tool_use, delta="") |
| 142 | + tool_result = {"toolUseId": "t3", "status": "success", "content": [{"text": "12:00"}]} |
| 143 | + |
| 144 | + agent.model.receive = unittest.mock.Mock(return_value=agenerator([tool_use_event])) |
| 145 | + |
| 146 | + # Start with request_state that already has stop_event_loop=True |
| 147 | + # This simulates a tool having set it during execution |
| 148 | + await loop.start(invocation_state={"request_state": {"stop_event_loop": True}}) |
| 149 | + |
| 150 | + tru_events = [] |
| 151 | + async for event in loop.receive(): |
| 152 | + tru_events.append(event) |
| 153 | + |
| 154 | + # Should receive: tool_use_event, tool_result_event, tool_result_message, connection_close |
| 155 | + assert len(tru_events) == 4 |
| 156 | + |
| 157 | + # Verify tool executed successfully |
| 158 | + tool_result_event = tru_events[1] |
| 159 | + assert isinstance(tool_result_event, ToolResultEvent) |
| 160 | + assert tool_result_event.tool_result["status"] == "success" |
| 161 | + |
| 162 | + # Verify connection close event was emitted |
| 163 | + connection_close_event = tru_events[3] |
| 164 | + assert isinstance(connection_close_event, BidiConnectionCloseEvent) |
| 165 | + assert connection_close_event["reason"] == "user_request" |
| 166 | + |
| 167 | + # Verify model.send was NOT called (tool result not sent to model) |
| 168 | + agent.model.send.assert_not_called() |
| 169 | + |
| 170 | + |
| 171 | +@pytest.mark.asyncio |
| 172 | +async def test_bidi_agent_loop_stop_conversation_deprecated_but_works(loop, agent, agenerator): |
| 173 | + """Test that stop_conversation tool still works but emits a deprecation warning. |
| 174 | +
|
| 175 | + The stop_conversation tool is deprecated in favor of request_state["stop_event_loop"], |
| 176 | + but should continue to work for backward compatibility via the name-based check. |
| 177 | + """ |
| 178 | + from strands.experimental.bidi.tools import stop_conversation |
| 179 | + |
| 180 | + agent.tool_registry.register_tool(stop_conversation) |
| 181 | + |
| 182 | + tool_use = {"toolUseId": "t5", "name": "stop_conversation", "input": {}} |
| 183 | + tool_use_event = ToolUseStreamEvent(current_tool_use=tool_use, delta="") |
| 184 | + |
| 185 | + agent.model.receive = unittest.mock.Mock(return_value=agenerator([tool_use_event])) |
| 186 | + |
| 187 | + await loop.start() |
| 188 | + |
| 189 | + tru_events = [] |
| 190 | + with warnings.catch_warnings(record=True) as caught_warnings: |
| 191 | + warnings.simplefilter("always") |
| 192 | + async for event in loop.receive(): |
| 193 | + tru_events.append(event) |
| 194 | + |
| 195 | + # Should receive: tool_use_event, tool_result_event, tool_result_message, connection_close |
| 196 | + assert len(tru_events) == 4 |
| 197 | + |
| 198 | + # Verify tool executed successfully |
| 199 | + tool_result_event = tru_events[1] |
| 200 | + assert isinstance(tool_result_event, ToolResultEvent) |
| 201 | + assert tool_result_event.tool_result["status"] == "success" |
| 202 | + assert "Ending conversation" in tool_result_event.tool_result["content"][0]["text"] |
| 203 | + |
| 204 | + # Verify connection close event was emitted |
| 205 | + connection_close_event = tru_events[3] |
| 206 | + assert isinstance(connection_close_event, BidiConnectionCloseEvent) |
| 207 | + assert connection_close_event["reason"] == "user_request" |
| 208 | + |
| 209 | + # Verify model.send was NOT called (tool result not sent to model) |
| 210 | + agent.model.send.assert_not_called() |
| 211 | + |
| 212 | + # Verify deprecation warnings were emitted (from both the tool itself and the loop name check) |
| 213 | + deprecation_warnings = [w for w in caught_warnings if issubclass(w.category, DeprecationWarning)] |
| 214 | + assert len(deprecation_warnings) >= 1 |
| 215 | + assert any("stop_conversation" in str(w.message).lower() for w in deprecation_warnings) |
| 216 | + |
| 217 | + |
| 218 | +@pytest.mark.asyncio |
| 219 | +async def test_bidi_agent_loop_request_state_preserved_with_invocation_state(agent, agenerator): |
| 220 | + """Test that existing invocation_state is preserved when request_state is initialized.""" |
| 221 | + |
| 222 | + @tool(name="check_invocation_state") |
| 223 | + async def check_invocation_state(custom_key: str) -> str: |
| 224 | + return f"custom_key: {custom_key}" |
| 225 | + |
| 226 | + agent.tool_registry.register_tool(check_invocation_state) |
| 227 | + |
| 228 | + tool_use = {"toolUseId": "t4", "name": "check_invocation_state", "input": {"custom_key": "from_state"}} |
| 229 | + tool_use_event = ToolUseStreamEvent(current_tool_use=tool_use, delta="") |
| 230 | + |
| 231 | + agent.model.receive = unittest.mock.Mock(return_value=agenerator([tool_use_event])) |
| 232 | + |
| 233 | + loop = agent._loop |
| 234 | + # Start with custom invocation_state but no request_state |
| 235 | + await loop.start(invocation_state={"custom_data": "preserved"}) |
| 236 | + |
| 237 | + tru_events = [] |
| 238 | + async for event in loop.receive(): |
| 239 | + tru_events.append(event) |
| 240 | + if len(tru_events) >= 3: |
| 241 | + break |
| 242 | + |
| 243 | + # Verify tool executed successfully |
| 244 | + tool_result_event = tru_events[1] |
| 245 | + assert isinstance(tool_result_event, ToolResultEvent) |
| 246 | + assert tool_result_event.tool_result["status"] == "success" |
| 247 | + |
| 248 | + # Verify request_state was added without removing custom_data |
| 249 | + assert "request_state" in loop._invocation_state |
| 250 | + assert loop._invocation_state.get("custom_data") == "preserved" |
0 commit comments