forked from strands-agents/sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
feat(bidirectional_streaming): Add experimental bidirectional streaming MVP POC implementation #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
107f035
feat(bidirectional_streaming): Add experimental bidirectional streami…
mehtarac 9165a20
Updated doc strings, updated method from send_text() and send_audio()
mehtarac 15df9f9
Updated minimum python runtime dependency
mehtarac 3a0e7d5
fix imports
mehtarac f7e67ae
fix linting issues
mehtarac c654621
Remove typing module and rely on python's built-in types
mehtarac 1f1abac
add typing to methods
mehtarac eb543b5
Improve comments and remove unused method _convert_to_strands_event
mehtarac 5921f8b
Updated: fixed module imports baesd on the new smithy python release …
mehtarac 8cb4d98
Removed unnecessary _output_queue check as the queue will always be i…
mehtarac 7a6e53e
Remove redundant interruption checks
mehtarac a586261
Unified tool result and tool error methods, Added implementation to a…
mehtarac 16d9b46
Modified logging to use python logger
mehtarac 04265ba
Removed logging utility
mehtarac 8a7396c
Updated types
mehtarac File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| """Bidirectional streaming package for real-time audio/text conversations.""" | ||
|
|
5 changes: 5 additions & 0 deletions
5
src/strands/experimental/bidirectional_streaming/agent/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| """Bidirectional agent for real-time streaming conversations.""" | ||
|
|
||
| from .agent import BidirectionalAgent | ||
|
|
||
| __all__ = ["BidirectionalAgent"] |
161 changes: 161 additions & 0 deletions
161
src/strands/experimental/bidirectional_streaming/agent/agent.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| """Bidirectional Agent for real-time streaming conversations. | ||
|
|
||
| Provides real-time audio and text interaction through persistent streaming sessions. | ||
| Unlike traditional request-response patterns, this agent maintains long-running | ||
| conversations where users can interrupt, provide additional input, and receive | ||
| continuous responses including audio output. | ||
|
|
||
| Key capabilities: | ||
| - Persistent conversation sessions with concurrent processing | ||
| - Real-time audio input/output streaming | ||
| - Mid-conversation interruption and tool execution | ||
| - Event-driven communication with model providers | ||
| """ | ||
|
|
||
| import asyncio | ||
| import logging | ||
| from typing import AsyncIterable | ||
|
|
||
| from ....tools.executors import ConcurrentToolExecutor | ||
| from ....tools.registry import ToolRegistry | ||
| from ....types.content import Messages | ||
| from ..event_loop.bidirectional_event_loop import start_bidirectional_connection, stop_bidirectional_connection | ||
| from ..models.bidirectional_model import BidirectionalModel | ||
| from ..types.bidirectional_streaming import AudioInputEvent, BidirectionalStreamEvent | ||
|
|
||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class BidirectionalAgent: | ||
| """Agent for bidirectional streaming conversations. | ||
|
|
||
| Enables real-time audio and text interaction with AI models through persistent | ||
| sessions. Supports concurrent tool execution and interruption handling. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| model: BidirectionalModel, | ||
| tools: list | None = None, | ||
| system_prompt: str | None = None, | ||
| messages: Messages | None = None, | ||
| ): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we should add
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can iterate on this |
||
| """Initialize bidirectional agent with required model and optional configuration. | ||
|
|
||
| Args: | ||
| model: BidirectionalModel instance supporting streaming sessions. | ||
| tools: Optional list of tools available to the model. | ||
| system_prompt: Optional system prompt for conversations. | ||
| messages: Optional conversation history to initialize with. | ||
| """ | ||
| self.model = model | ||
| self.system_prompt = system_prompt | ||
| self.messages = messages or [] | ||
|
|
||
| # Initialize tool registry using existing Strands infrastructure | ||
| self.tool_registry = ToolRegistry() | ||
| if tools: | ||
| self.tool_registry.process_tools(tools) | ||
| self.tool_registry.initialize_tools() | ||
|
|
||
| # Initialize tool executor for concurrent execution | ||
| self.tool_executor = ConcurrentToolExecutor() | ||
mehtarac marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| # Session management | ||
| self._session = None | ||
| self._output_queue = asyncio.Queue() | ||
|
|
||
| async def start(self) -> None: | ||
| """Start a persistent bidirectional conversation session. | ||
|
|
||
| Initializes the streaming session and starts background tasks for processing | ||
| model events, tool execution, and session management. | ||
|
|
||
| Raises: | ||
| ValueError: If conversation already active. | ||
| ConnectionError: If session creation fails. | ||
| """ | ||
| if self._session and self._session.active: | ||
| raise ValueError("Conversation already active. Call end() first.") | ||
|
|
||
| logger.debug("Conversation start - initializing session") | ||
| self._session = await start_bidirectional_connection(self) | ||
| logger.debug("Conversation ready") | ||
|
|
||
| async def send(self, input_data: str | AudioInputEvent) -> None: | ||
| """Send input to the model (text or audio). | ||
|
|
||
| Unified method for sending both text and audio input to the model during | ||
| an active conversation session. User input is automatically added to | ||
| conversation history for complete message tracking. | ||
|
|
||
| Args: | ||
| input_data: Either a string for text input or AudioInputEvent for audio input. | ||
|
|
||
| Raises: | ||
| ValueError: If no active session or invalid input type. | ||
| """ | ||
| self._validate_active_session() | ||
|
|
||
| if isinstance(input_data, str): | ||
| # Add user text message to history | ||
| self.messages.append({"role": "user", "content": input_data}) | ||
|
|
||
| logger.debug("Text sent: %d characters", len(input_data)) | ||
| await self._session.model_session.send_text_content(input_data) | ||
| elif isinstance(input_data, dict) and "audioData" in input_data: | ||
| # Handle audio input | ||
| await self._session.model_session.send_audio_content(input_data) | ||
| else: | ||
| raise ValueError( | ||
| "Input must be either a string (text) or AudioInputEvent " | ||
| "(dict with audioData, format, sampleRate, channels)" | ||
| ) | ||
|
|
||
| async def receive(self) -> AsyncIterable[BidirectionalStreamEvent]: | ||
| """Receive events from the model including audio, text, and tool calls. | ||
|
|
||
| Yields model output events processed by background tasks including audio output, | ||
| text responses, tool calls, and session updates. | ||
|
|
||
| Yields: | ||
| BidirectionalStreamEvent: Events from the model session. | ||
| """ | ||
| while self._session and self._session.active: | ||
| try: | ||
| event = await asyncio.wait_for(self._output_queue.get(), timeout=0.1) | ||
| yield event | ||
| except asyncio.TimeoutError: | ||
| continue | ||
|
|
||
| async def interrupt(self) -> None: | ||
| """Interrupt the current model generation and clear audio buffers. | ||
|
|
||
| Sends interruption signal to stop generation immediately and clears | ||
| pending audio output for responsive conversation flow. | ||
|
|
||
| Raises: | ||
| ValueError: If no active session. | ||
| """ | ||
| self._validate_active_session() | ||
| await self._session.model_session.send_interrupt() | ||
|
|
||
| async def end(self) -> None: | ||
| """End the conversation session and cleanup all resources. | ||
|
|
||
| Terminates the streaming session, cancels background tasks, and | ||
| closes the connection to the model provider. | ||
| """ | ||
| if self._session: | ||
| await stop_bidirectional_connection(self._session) | ||
| self._session = None | ||
|
|
||
| def _validate_active_session(self) -> None: | ||
| """Validate that an active session exists. | ||
|
|
||
| Raises: | ||
| ValueError: If no active session. | ||
| """ | ||
| if not self._session or not self._session.active: | ||
| raise ValueError("No active conversation. Call start() first.") | ||
15 changes: 15 additions & 0 deletions
15
src/strands/experimental/bidirectional_streaming/event_loop/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| """Event loop management for bidirectional streaming.""" | ||
|
|
||
| from .bidirectional_event_loop import ( | ||
| BidirectionalConnection, | ||
| bidirectional_event_loop_cycle, | ||
| start_bidirectional_connection, | ||
| stop_bidirectional_connection, | ||
| ) | ||
|
|
||
| __all__ = [ | ||
| "BidirectionalConnection", | ||
| "start_bidirectional_connection", | ||
| "stop_bidirectional_connection", | ||
| "bidirectional_event_loop_cycle", | ||
| ] |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
in strands we have Union[Model, str, None] = None in init, we can make it same here for future extensibility
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can make this change
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
linked in https://github.com/orgs/strands-agents/projects/12/views/1?pane=issue&itemId=131451564&issue=strands-agents%7Cprivate-sdk-python-staging%7C245