swarmauri_agent_realtime 0.1.0.dev4__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.
@@ -0,0 +1,65 @@
1
+ from typing import Any, Literal
2
+
3
+ from swarmauri_base.agents.RealtimeAgentBase import RealtimeAgentBase
4
+ from swarmauri_base.live_models.events.ToolCallEvent import ToolCallEvent
5
+ from swarmauri_base.live_models.events.ToolCancellationEvent import (
6
+ ToolCancellationEvent,
7
+ )
8
+ from swarmauri_base.live_models.events.TurnCompleteEvent import (
9
+ TurnCompleteEvent,
10
+ )
11
+
12
+ from ._internal.RealtimeToolCoordinator import RealtimeToolCoordinator
13
+ from ._internal.RealtimeTurnAccumulator import RealtimeTurnAccumulator
14
+ from ._internal.SwarmauriConversationAdapter import (
15
+ SwarmauriConversationAdapter,
16
+ )
17
+ from .RealtimeAgentRunResult import RealtimeAgentRunResult
18
+
19
+
20
+ class RealtimeAgent(RealtimeAgentBase):
21
+ type: Literal["RealtimeAgent"] = "RealtimeAgent"
22
+
23
+ def run(self, input_data: Any, **kwargs: Any) -> RealtimeAgentRunResult:
24
+ self.send(input_data)
25
+ events: list[Any] = []
26
+ accumulator = RealtimeTurnAccumulator()
27
+ turn = accumulator.turn
28
+ coordinator = RealtimeToolCoordinator(self.tool_executor, self.toolkit)
29
+ for event in self.stream():
30
+ events.append(event)
31
+ turn = accumulator.consume(event)
32
+ if isinstance(event, ToolCallEvent):
33
+ self.send(coordinator.handle_call(event))
34
+ elif isinstance(event, ToolCancellationEvent):
35
+ coordinator.handle_cancellation(event)
36
+ if self.output_adapter is not None:
37
+ self.output_adapter.handle(event)
38
+ if isinstance(event, TurnCompleteEvent):
39
+ break
40
+ SwarmauriConversationAdapter().append_turn(self.conversation, turn)
41
+ return RealtimeAgentRunResult(turn=turn, events=events)
42
+
43
+ async def arun(
44
+ self,
45
+ input_data: Any,
46
+ **kwargs: Any,
47
+ ) -> RealtimeAgentRunResult:
48
+ await self.asend(input_data)
49
+ events: list[Any] = []
50
+ accumulator = RealtimeTurnAccumulator()
51
+ turn = accumulator.turn
52
+ coordinator = RealtimeToolCoordinator(self.tool_executor, self.toolkit)
53
+ async for event in self.astream():
54
+ events.append(event)
55
+ turn = accumulator.consume(event)
56
+ if isinstance(event, ToolCallEvent):
57
+ await self.asend(await coordinator.ahandle_call(event))
58
+ elif isinstance(event, ToolCancellationEvent):
59
+ await coordinator.ahandle_cancellation(event)
60
+ if self.output_adapter is not None:
61
+ await self.output_adapter.ahandle(event)
62
+ if isinstance(event, TurnCompleteEvent):
63
+ break
64
+ SwarmauriConversationAdapter().append_turn(self.conversation, turn)
65
+ return RealtimeAgentRunResult(turn=turn, events=events)
@@ -0,0 +1,12 @@
1
+ from typing import Any, Literal
2
+
3
+ from pydantic import BaseModel, ConfigDict, Field
4
+
5
+ from ._internal.RealtimeTurn import RealtimeTurn
6
+
7
+
8
+ class RealtimeAgentRunResult(BaseModel):
9
+ turn: RealtimeTurn
10
+ events: list[Any] = Field(default_factory=list)
11
+ type: Literal["RealtimeAgentRunResult"] = "RealtimeAgentRunResult"
12
+ model_config = ConfigDict(arbitrary_types_allowed=True)
@@ -0,0 +1,4 @@
1
+ from .RealtimeAgent import RealtimeAgent
2
+ from .RealtimeAgentRunResult import RealtimeAgentRunResult
3
+
4
+ __all__ = ["RealtimeAgent", "RealtimeAgentRunResult"]
@@ -0,0 +1,13 @@
1
+ import asyncio
2
+ from dataclasses import dataclass, field
3
+ from typing import Any
4
+
5
+
6
+ @dataclass
7
+ class LiveSessionEntry:
8
+ conversation_id: str
9
+ creation_task: asyncio.Task[Any]
10
+ session: Any | None = None
11
+ leases: int = 0
12
+ last_used_at: float = field(default=0.0)
13
+ invalidated: bool = False
@@ -0,0 +1,143 @@
1
+ import asyncio
2
+ from collections.abc import AsyncIterator, Awaitable, Callable
3
+ from contextlib import asynccontextmanager
4
+ from time import monotonic
5
+ from typing import Any
6
+
7
+ from .LiveSessionEntry import LiveSessionEntry
8
+
9
+ SessionFactory = Callable[[], Awaitable[Any]]
10
+
11
+
12
+ class LiveSessionPool:
13
+ """Lease-based pool with one live session per conversation."""
14
+
15
+ def __init__(
16
+ self, max_sessions: int = 32, idle_timeout: float = 300.0
17
+ ) -> None:
18
+ if max_sessions < 1:
19
+ raise ValueError("max_sessions must be positive")
20
+ self.max_sessions = max_sessions
21
+ self.idle_timeout = idle_timeout
22
+ self._entries: dict[str, LiveSessionEntry] = {}
23
+ self._lock = asyncio.Lock()
24
+
25
+ async def acquire(
26
+ self, conversation_id: str, factory: SessionFactory
27
+ ) -> Any:
28
+ close_after: list[Any] = []
29
+ async with self._lock:
30
+ now = monotonic()
31
+ for key, entry in list(self._entries.items()):
32
+ if (
33
+ entry.leases == 0
34
+ and now - entry.last_used_at >= self.idle_timeout
35
+ ):
36
+ self._entries.pop(key)
37
+ entry.invalidated = True
38
+ if entry.session is not None:
39
+ close_after.append(entry.session)
40
+ entry = self._entries.get(conversation_id)
41
+ if entry is None:
42
+ idle = sorted(
43
+ (
44
+ item
45
+ for item in self._entries.values()
46
+ if item.leases == 0
47
+ ),
48
+ key=lambda item: item.last_used_at,
49
+ )
50
+ while len(self._entries) >= self.max_sessions and idle:
51
+ expired = idle.pop(0)
52
+ self._entries.pop(expired.conversation_id, None)
53
+ expired.invalidated = True
54
+ if expired.session is not None:
55
+ close_after.append(expired.session)
56
+ if len(self._entries) >= self.max_sessions:
57
+ raise RuntimeError(
58
+ "All live sessions are currently leased"
59
+ )
60
+ entry = LiveSessionEntry(
61
+ conversation_id=conversation_id,
62
+ creation_task=asyncio.create_task(factory()),
63
+ last_used_at=now,
64
+ )
65
+ self._entries[conversation_id] = entry
66
+ task = entry.creation_task
67
+
68
+ await asyncio.gather(
69
+ *(session.aclose() for session in close_after),
70
+ return_exceptions=True,
71
+ )
72
+ try:
73
+ session = await task
74
+ except BaseException:
75
+ async with self._lock:
76
+ if self._entries.get(conversation_id) is entry:
77
+ self._entries.pop(conversation_id, None)
78
+ raise
79
+
80
+ invalidated = False
81
+ async with self._lock:
82
+ invalidated = entry.invalidated
83
+ if not invalidated:
84
+ entry.session = session
85
+ entry.leases += 1
86
+ entry.last_used_at = monotonic()
87
+ if invalidated:
88
+ await session.aclose()
89
+ raise RuntimeError("Live session was invalidated during creation")
90
+ return session
91
+
92
+ async def release(
93
+ self, conversation_id: str, *, invalidate: bool = False
94
+ ) -> None:
95
+ close_session: Any | None = None
96
+ async with self._lock:
97
+ entry = self._entries.get(conversation_id)
98
+ if entry is None:
99
+ return
100
+ entry.leases = max(0, entry.leases - 1)
101
+ entry.last_used_at = monotonic()
102
+ if invalidate:
103
+ entry.invalidated = True
104
+ if entry.invalidated and entry.leases == 0:
105
+ self._entries.pop(conversation_id, None)
106
+ close_session = entry.session
107
+ if close_session is not None:
108
+ await close_session.aclose()
109
+
110
+ @asynccontextmanager
111
+ async def session(
112
+ self,
113
+ conversation_id: str,
114
+ factory: SessionFactory,
115
+ ) -> AsyncIterator[Any]:
116
+ session = await self.acquire(conversation_id, factory)
117
+ invalidate = False
118
+ try:
119
+ yield session
120
+ except BaseException:
121
+ invalidate = True
122
+ raise
123
+ finally:
124
+ await self.release(conversation_id, invalidate=invalidate)
125
+
126
+ async def invalidate(self, conversation_id: str) -> None:
127
+ await self.release(conversation_id, invalidate=True)
128
+
129
+ async def close_all(self) -> None:
130
+ async with self._lock:
131
+ entries = list(self._entries.values())
132
+ self._entries.clear()
133
+ for entry in entries:
134
+ entry.invalidated = True
135
+ for entry in entries:
136
+ if not entry.creation_task.done():
137
+ entry.creation_task.cancel()
138
+ if entry.session is not None:
139
+ await entry.session.aclose()
140
+
141
+ async def size(self) -> int:
142
+ async with self._lock:
143
+ return len(self._entries)
@@ -0,0 +1,75 @@
1
+ from swarmauri_base.live_models.events.ToolCallEvent import ToolCallEvent
2
+ from swarmauri_base.live_models.events.ToolCancellationEvent import (
3
+ ToolCancellationEvent,
4
+ )
5
+ from swarmauri_base.live_models.inputs.ToolResultInput import ToolResultInput
6
+ from swarmauri_base.tools.ToolExecutorBase import ToolExecutorBase
7
+ from swarmauri_core.toolkits.IToolkit import IToolkit
8
+
9
+
10
+ class RealtimeToolCoordinator:
11
+ def __init__(
12
+ self, executor: ToolExecutorBase, toolkit: IToolkit | None
13
+ ) -> None:
14
+ self.executor = executor
15
+ self.toolkit = toolkit
16
+
17
+ def _tool(self, name: str):
18
+ if self.toolkit is None:
19
+ raise KeyError(f"No toolkit configured for tool {name!r}")
20
+ tool = self.toolkit.get_tool_by_name(name)
21
+ if tool is None:
22
+ raise KeyError(name)
23
+ return tool
24
+
25
+ @staticmethod
26
+ def _input(event: ToolCallEvent, result) -> ToolResultInput:
27
+ correlation_id = event.correlation.get("provider_event_id")
28
+ return ToolResultInput(
29
+ call_id=event.call_id,
30
+ correlation_id=correlation_id,
31
+ payload=result.value
32
+ if not result.error
33
+ else {"error": result.error},
34
+ is_error=bool(result.error),
35
+ )
36
+
37
+ def handle_call(self, event: ToolCallEvent) -> ToolResultInput:
38
+ try:
39
+ result = self.executor.execute(
40
+ self._tool(event.tool_name),
41
+ event.arguments,
42
+ call_id=event.call_id,
43
+ context={"correlation": event.correlation},
44
+ )
45
+ except Exception as exc:
46
+ return ToolResultInput(
47
+ call_id=event.call_id,
48
+ correlation_id=event.correlation.get("provider_event_id"),
49
+ payload={"error": str(exc)},
50
+ is_error=True,
51
+ )
52
+ return self._input(event, result)
53
+
54
+ async def ahandle_call(self, event: ToolCallEvent) -> ToolResultInput:
55
+ try:
56
+ result = await self.executor.aexecute(
57
+ self._tool(event.tool_name),
58
+ event.arguments,
59
+ call_id=event.call_id,
60
+ context={"correlation": event.correlation},
61
+ )
62
+ except Exception as exc:
63
+ return ToolResultInput(
64
+ call_id=event.call_id,
65
+ correlation_id=event.correlation.get("provider_event_id"),
66
+ payload={"error": str(exc)},
67
+ is_error=True,
68
+ )
69
+ return self._input(event, result)
70
+
71
+ def handle_cancellation(self, event: ToolCancellationEvent) -> bool:
72
+ return self.executor.cancel(event.call_id)
73
+
74
+ async def ahandle_cancellation(self, event: ToolCancellationEvent) -> bool:
75
+ return await self.executor.acancel(event.call_id)
@@ -0,0 +1,15 @@
1
+ from typing import Any
2
+
3
+ from pydantic import BaseModel, ConfigDict, Field
4
+
5
+
6
+ class RealtimeTurn(BaseModel):
7
+ output_text: str = ""
8
+ input_transcript: str = ""
9
+ output_transcript: str = ""
10
+ audio_chunks: list[bytes] = Field(default_factory=list)
11
+ tool_calls: list[Any] = Field(default_factory=list)
12
+ usage: dict[str, int] = Field(default_factory=dict)
13
+ interrupted: bool = False
14
+ completed: bool = False
15
+ model_config = ConfigDict(arbitrary_types_allowed=True)
@@ -0,0 +1,42 @@
1
+ from swarmauri_base.live_models.events.AudioDeltaEvent import AudioDeltaEvent
2
+ from swarmauri_base.live_models.events.InputTranscriptDeltaEvent import (
3
+ InputTranscriptDeltaEvent,
4
+ )
5
+ from swarmauri_base.live_models.events.InterruptionEvent import (
6
+ InterruptionEvent,
7
+ )
8
+ from swarmauri_base.live_models.events.OutputTranscriptDeltaEvent import (
9
+ OutputTranscriptDeltaEvent,
10
+ )
11
+ from swarmauri_base.live_models.events.TextDeltaEvent import TextDeltaEvent
12
+ from swarmauri_base.live_models.events.ToolCallEvent import ToolCallEvent
13
+ from swarmauri_base.live_models.events.TurnCompleteEvent import (
14
+ TurnCompleteEvent,
15
+ )
16
+ from swarmauri_base.live_models.events.UsageEvent import UsageEvent
17
+
18
+ from .RealtimeTurn import RealtimeTurn
19
+
20
+
21
+ class RealtimeTurnAccumulator:
22
+ def __init__(self) -> None:
23
+ self.turn = RealtimeTurn()
24
+
25
+ def consume(self, event) -> RealtimeTurn:
26
+ if isinstance(event, OutputTranscriptDeltaEvent):
27
+ self.turn.output_transcript += str(event.payload or "")
28
+ elif isinstance(event, InputTranscriptDeltaEvent):
29
+ self.turn.input_transcript += str(event.payload or "")
30
+ elif isinstance(event, TextDeltaEvent):
31
+ self.turn.output_text += str(event.payload or "")
32
+ elif isinstance(event, AudioDeltaEvent):
33
+ self.turn.audio_chunks.append(event.payload)
34
+ elif isinstance(event, ToolCallEvent):
35
+ self.turn.tool_calls.append(event)
36
+ elif isinstance(event, UsageEvent):
37
+ self.turn.usage.update(event.payload)
38
+ elif isinstance(event, InterruptionEvent):
39
+ self.turn.interrupted = True
40
+ elif isinstance(event, TurnCompleteEvent):
41
+ self.turn.completed = True
42
+ return self.turn
@@ -0,0 +1,19 @@
1
+ from swarmauri_base.conversations.ConversationBase import ConversationBase
2
+ from swarmauri_base.messages.MessageBase import MessageBase
3
+
4
+ from .RealtimeTurn import RealtimeTurn
5
+
6
+
7
+ class SwarmauriConversationAdapter:
8
+ def append_turn(
9
+ self,
10
+ conversation: ConversationBase | None,
11
+ turn: RealtimeTurn,
12
+ ) -> None:
13
+ if conversation is None:
14
+ return
15
+ content = turn.output_text or turn.output_transcript
16
+ if content:
17
+ conversation.add_message(
18
+ MessageBase(content=content, role="assistant")
19
+ )
@@ -0,0 +1 @@
1
+ """Private realtime-agent orchestration helpers."""
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.4
2
+ Name: swarmauri_agent_realtime
3
+ Version: 0.1.0.dev4
4
+ Summary: Provider-neutral realtime multimodal agent for Swarmauri live models.
5
+ License: Copyright 2024 Jacob Stewart
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
18
+ License-File: LICENSE
19
+ Keywords: swarmauri,agent,realtime,audio,tools,multimodal
20
+ Author: Jacob Stewart
21
+ Author-email: jacob@swarmauri.com
22
+ Requires-Python: >=3.10,<3.13
23
+ Classifier: Development Status :: 1 - Planning
24
+ Classifier: License :: OSI Approved :: Apache Software License
25
+ Classifier: Programming Language :: Python :: 3.10
26
+ Classifier: Programming Language :: Python :: 3.11
27
+ Classifier: Programming Language :: Python :: 3.12
28
+ Requires-Dist: swarmauri_base
29
+ Requires-Dist: swarmauri_core
30
+ Description-Content-Type: text/markdown
31
+
32
+ ![Swarmauri](https://github.com/swarmauri/swarmauri-sdk/blob/3d4d1cfa949399d7019ae9d8f296afba773dfb7f/assets/swarmauri.brand.theme.svg)
33
+
34
+ [![PyPI](https://img.shields.io/pypi/v/swarmauri_agent_realtime.svg)](https://pypi.org/project/swarmauri_agent_realtime/) [![Python](https://img.shields.io/pypi/pyversions/swarmauri_agent_realtime.svg)](https://pypi.org/project/swarmauri_agent_realtime/) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE) [![Downloads](https://static.pepy.tech/badge/swarmauri_agent_realtime)](https://pepy.tech/project/swarmauri_agent_realtime) [![Hits](https://hits.sh/github.com/swarmauri/swarmauri-sdk.svg)](https://hits.sh/github.com/swarmauri/swarmauri-sdk/)
35
+
36
+ # swarmauri_agent_realtime
37
+
38
+ ## Features
39
+
40
+ - Provider-neutral live-model orchestration.
41
+ - Conversation bridging, function calls, interruption, and typed events.
42
+ - One provider connection per conversation through `LiveSessionPool`.
43
+
44
+ ## Installation
45
+
46
+ `uv add swarmauri_agent_realtime` or `pip install swarmauri_agent_realtime`.
47
+
48
+ ## Usage
49
+
50
+ Construct `RealtimeAgent(live_model=...)`, send typed live inputs, and consume events or use `run`/`arun` for one completed turn.
51
+
@@ -0,0 +1,15 @@
1
+ swarmauri_agent_realtime/RealtimeAgent.py,sha256=4KxFILLFPzoSmrcGm5jRrvP1DhyOVTucaOakzvGXJpM,2730
2
+ swarmauri_agent_realtime/RealtimeAgentRunResult.py,sha256=3ayE_7U5rqJXMrOjCikfuP7f2UbJd7QPXL9cTmqVl_o,382
3
+ swarmauri_agent_realtime/__init__.py,sha256=LyYxZzsKByc9jdcNQ6gHagm-aMeStZH5XIwmAC9IRp8,155
4
+ swarmauri_agent_realtime/_internal/LiveSessionEntry.py,sha256=62TrZTFlwkoMXvIuB-OO-dLP3gg2yV3XmSwqA9aGEJA,304
5
+ swarmauri_agent_realtime/_internal/LiveSessionPool.py,sha256=UHWPBzw_Jp54MA7ycBcZ2KVFLjb1BOS0fSMkUXzj1_Y,5142
6
+ swarmauri_agent_realtime/_internal/RealtimeToolCoordinator.py,sha256=eSNesz1HZy6owLNURlF0xaWRguANcEtk51SYydzrM3E,2797
7
+ swarmauri_agent_realtime/_internal/RealtimeTurn.py,sha256=reiq_XycVeJP-UN3MljEfO67ncFOg85a8GwRBFkLiAo,486
8
+ swarmauri_agent_realtime/_internal/RealtimeTurnAccumulator.py,sha256=Wsv5S9zlsLT4SnjK3CI40H4wvixHdu8zgZJ8TF1IGEM,1744
9
+ swarmauri_agent_realtime/_internal/SwarmauriConversationAdapter.py,sha256=wVSs2kSQlApZ_YTZJuMx5CVdNfPuzSLLjlKA1JvHOTs,586
10
+ swarmauri_agent_realtime/_internal/__init__.py,sha256=utq-JNIydJLXB2rJCWLcpugWxd_R76EnIjVD9sEOtgQ,52
11
+ swarmauri_agent_realtime-0.1.0.dev4.dist-info/METADATA,sha256=_KCLtaZJ5GOcDhXoe702RpiKPuoT9AzK3kwsG14CDbg,2532
12
+ swarmauri_agent_realtime-0.1.0.dev4.dist-info/WHEEL,sha256=eY7nduwzv-ldUxpzbRlxwvC693Hg6PX8bWDjEHjZ_dk,88
13
+ swarmauri_agent_realtime-0.1.0.dev4.dist-info/entry_points.txt,sha256=G-vVVrArFw1VxgW_lKM-vRlr3gOn7Qbq6kXOG5kEnhs,73
14
+ swarmauri_agent_realtime-0.1.0.dev4.dist-info/licenses/LICENSE,sha256=kkwAgrDtfQ7c-Ozql2xlztDDjHt0YwGmRG7b_oUU9Jg,554
15
+ swarmauri_agent_realtime-0.1.0.dev4.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.4.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [swarmauri.agents]
2
+ RealtimeAgent=swarmauri_agent_realtime:RealtimeAgent
3
+
@@ -0,0 +1,13 @@
1
+ Copyright 2024 Jacob Stewart
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.