swarmauri_live_model_openai 0.1.0.dev3__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,184 @@
1
+ import base64
2
+ import json
3
+ from typing import Any
4
+
5
+ from swarmauri_base.live_models.events.AudioDeltaEvent import AudioDeltaEvent
6
+ from swarmauri_base.live_models.events.InputTranscriptDeltaEvent import (
7
+ InputTranscriptDeltaEvent,
8
+ )
9
+ from swarmauri_base.live_models.events.InterruptionEvent import (
10
+ InterruptionEvent,
11
+ )
12
+ from swarmauri_base.live_models.events.OutputTranscriptDeltaEvent import (
13
+ OutputTranscriptDeltaEvent,
14
+ )
15
+ from swarmauri_base.live_models.events.SessionErrorEvent import (
16
+ SessionErrorEvent,
17
+ )
18
+ from swarmauri_base.live_models.events.TextDeltaEvent import TextDeltaEvent
19
+ from swarmauri_base.live_models.events.ToolCallEvent import ToolCallEvent
20
+ from swarmauri_base.live_models.events.TurnCompleteEvent import (
21
+ TurnCompleteEvent,
22
+ )
23
+ from swarmauri_base.live_models.events.UsageEvent import UsageEvent
24
+ from swarmauri_base.live_models.LiveEventBase import LiveEventBase
25
+ from swarmauri_base.live_models.LiveInputBase import LiveInputBase
26
+
27
+
28
+ class OpenAIRealtimeCodec:
29
+ def encode(self, input_data: LiveInputBase) -> list[str]:
30
+ if input_data.kind == "text":
31
+ return [
32
+ json.dumps(
33
+ {
34
+ "type": "conversation.item.create",
35
+ "item": {
36
+ "type": "message",
37
+ "role": "user",
38
+ "content": [
39
+ {
40
+ "type": "input_text",
41
+ "text": input_data.payload,
42
+ }
43
+ ],
44
+ },
45
+ }
46
+ ),
47
+ json.dumps({"type": "response.create"}),
48
+ ]
49
+ if input_data.kind == "audio":
50
+ return [
51
+ json.dumps(
52
+ {
53
+ "type": "input_audio_buffer.append",
54
+ "audio": base64.b64encode(input_data.payload).decode(),
55
+ }
56
+ )
57
+ ]
58
+ if input_data.kind == "image":
59
+ encoded = base64.b64encode(input_data.payload).decode()
60
+ image_url = f"data:{input_data.mime_type};base64,{encoded}"
61
+ return [
62
+ json.dumps(
63
+ {
64
+ "type": "conversation.item.create",
65
+ "item": {
66
+ "type": "message",
67
+ "role": "user",
68
+ "content": [
69
+ {
70
+ "type": "input_image",
71
+ "image_url": image_url,
72
+ }
73
+ ],
74
+ },
75
+ }
76
+ )
77
+ ]
78
+ if input_data.kind == "tool_result":
79
+ return [
80
+ json.dumps(
81
+ {
82
+ "type": "conversation.item.create",
83
+ "item": {
84
+ "type": "function_call_output",
85
+ "call_id": input_data.call_id,
86
+ "output": json.dumps(input_data.payload),
87
+ },
88
+ }
89
+ ),
90
+ json.dumps({"type": "response.create"}),
91
+ ]
92
+ if input_data.kind == "commit_turn":
93
+ return [
94
+ json.dumps({"type": "input_audio_buffer.commit"}),
95
+ json.dumps({"type": "response.create"}),
96
+ ]
97
+ if input_data.kind == "interrupt":
98
+ return [json.dumps({"type": "response.cancel"})]
99
+ raise ValueError(
100
+ f"Unsupported OpenAI realtime input: {input_data.kind}"
101
+ )
102
+
103
+ def decode(self, message: str | bytes) -> list[LiveEventBase]:
104
+ data: dict[str, Any] = json.loads(message)
105
+ kind = data.get("type", "")
106
+ correlation = {
107
+ "provider_event_id": data.get("event_id"),
108
+ "response_id": data.get("response_id")
109
+ or data.get("response", {}).get("id"),
110
+ "item_id": data.get("item_id"),
111
+ "call_id": data.get("call_id"),
112
+ }
113
+ if kind in {"response.output_text.delta", "response.text.delta"}:
114
+ return [
115
+ TextDeltaEvent(
116
+ payload=data.get("delta", ""), correlation=correlation
117
+ )
118
+ ]
119
+ if kind in {"response.output_audio.delta", "response.audio.delta"}:
120
+ return [
121
+ AudioDeltaEvent(
122
+ payload=base64.b64decode(data.get("delta", "")),
123
+ correlation=correlation,
124
+ )
125
+ ]
126
+ if kind in {
127
+ "response.output_audio_transcript.delta",
128
+ "response.audio_transcript.delta",
129
+ }:
130
+ return [
131
+ OutputTranscriptDeltaEvent(
132
+ payload=data.get("delta", ""), correlation=correlation
133
+ )
134
+ ]
135
+ if "input_audio_transcription" in kind:
136
+ text = data.get("delta") or data.get("transcript", "")
137
+ return [
138
+ InputTranscriptDeltaEvent(
139
+ payload=text, correlation=correlation
140
+ )
141
+ ]
142
+ if kind == "response.function_call_arguments.done":
143
+ arguments = data.get("arguments", {})
144
+ if isinstance(arguments, str):
145
+ arguments = json.loads(arguments or "{}")
146
+ return [
147
+ ToolCallEvent(
148
+ call_id=data.get("call_id", ""),
149
+ tool_name=data.get("name", ""),
150
+ arguments=arguments,
151
+ correlation=correlation,
152
+ )
153
+ ]
154
+ if kind == "input_audio_buffer.speech_started":
155
+ return [
156
+ InterruptionEvent(
157
+ reason="speech_started", correlation=correlation
158
+ )
159
+ ]
160
+ if kind == "response.done":
161
+ events: list[LiveEventBase] = [
162
+ TurnCompleteEvent(correlation=correlation)
163
+ ]
164
+ usage = data.get("response", {}).get("usage")
165
+ if usage:
166
+ events.append(
167
+ UsageEvent(
168
+ payload={
169
+ key: int(value)
170
+ for key, value in usage.items()
171
+ if isinstance(value, int)
172
+ },
173
+ correlation=correlation,
174
+ )
175
+ )
176
+ return events
177
+ if kind == "error":
178
+ return [
179
+ SessionErrorEvent(
180
+ message=str(data.get("error", data)),
181
+ correlation=correlation,
182
+ )
183
+ ]
184
+ return []
@@ -0,0 +1,19 @@
1
+ from typing import Any
2
+
3
+ from swarmauri_base.live_models.LiveConfigBase import LiveConfigBase
4
+ from swarmauri_provider_openai import OpenAIToolSchemaConverter
5
+
6
+
7
+ class OpenAIRealtimeConfigMapper:
8
+ def map(self, config: LiveConfigBase) -> dict[str, Any]:
9
+ session: dict[str, Any] = {
10
+ "type": "realtime",
11
+ "output_modalities": config.requested_modalities,
12
+ }
13
+ if config.tools:
14
+ converter = OpenAIToolSchemaConverter()
15
+ session["tools"] = [
16
+ converter.convert(tool) for tool in config.tools
17
+ ]
18
+ session.update(config.provider_options.get("session", {}))
19
+ return {"type": "session.update", "session": session}
@@ -0,0 +1,42 @@
1
+ from typing import Any, Literal
2
+ from pydantic import ConfigDict, Field
3
+ from swarmauri_base.ComponentBase import ComponentBase
4
+ from swarmauri_base.live_models.LiveCapabilitiesBase import (
5
+ LiveCapabilitiesBase,
6
+ )
7
+ from swarmauri_base.live_models.LiveConfigBase import LiveConfigBase
8
+ from swarmauri_base.live_models.LiveModelBase import LiveModelBase
9
+ from swarmauri_provider_openai import OpenAIProvider
10
+ from swarmauri_transport_websocket import WebSocketClient
11
+
12
+ from .OpenAIRealtimeConfigMapper import OpenAIRealtimeConfigMapper
13
+ from .OpenAIRealtimeSession import OpenAIRealtimeSession
14
+
15
+
16
+ @ComponentBase.register_type(LiveModelBase, "OpenAIRealtimeModel")
17
+ class OpenAIRealtimeModel(LiveModelBase):
18
+ name: str = "gpt-realtime"
19
+ provider: OpenAIProvider = Field(default_factory=OpenAIProvider)
20
+ transport: Any = Field(default_factory=WebSocketClient, exclude=True)
21
+ capabilities: LiveCapabilitiesBase = Field(
22
+ default_factory=lambda: LiveCapabilitiesBase(
23
+ input_modalities=frozenset({"text", "audio", "image"}),
24
+ output_modalities=frozenset({"text", "audio"}),
25
+ features=frozenset({"tools", "transcription"}),
26
+ session_features=frozenset({"realtime", "interruption"}),
27
+ )
28
+ )
29
+ type: Literal["OpenAIRealtimeModel"] = "OpenAIRealtimeModel"
30
+ model_config = ConfigDict(arbitrary_types_allowed=True, extra="allow")
31
+
32
+ async def aconnect(self, config: LiveConfigBase) -> OpenAIRealtimeSession:
33
+ connection_config = self.provider.prepare_connection(
34
+ "realtime.connect", model=self.name
35
+ )
36
+ connection = await self.transport.aconnect(
37
+ connection_config.resolved_url(),
38
+ headers=connection_config.headers,
39
+ )
40
+ return await OpenAIRealtimeSession.create(
41
+ connection, OpenAIRealtimeConfigMapper().map(config)
42
+ )
@@ -0,0 +1,64 @@
1
+ import asyncio
2
+ import json
3
+ from contextlib import suppress
4
+ from typing import Any, Literal
5
+
6
+ from pydantic import PrivateAttr
7
+ from swarmauri_base.live_models.events.SessionErrorEvent import (
8
+ SessionErrorEvent,
9
+ )
10
+ from swarmauri_base.live_models.LiveInputBase import LiveInputBase
11
+ from swarmauri_base.live_models.LiveSessionBase import LiveSessionBase
12
+ from swarmauri_base.ComponentBase import ComponentBase
13
+ from swarmauri_core.transports import IWebSocketConnection
14
+
15
+ from .OpenAIRealtimeCodec import OpenAIRealtimeCodec
16
+
17
+
18
+ @ComponentBase.register_type(LiveSessionBase, "OpenAIRealtimeSession")
19
+ class OpenAIRealtimeSession(LiveSessionBase):
20
+ type: Literal["OpenAIRealtimeSession"] = "OpenAIRealtimeSession"
21
+ _connection: IWebSocketConnection = PrivateAttr()
22
+ _codec: OpenAIRealtimeCodec = PrivateAttr(
23
+ default_factory=OpenAIRealtimeCodec
24
+ )
25
+ _receiver: Any = PrivateAttr(default=None)
26
+
27
+ @classmethod
28
+ async def create(
29
+ cls, connection, setup: dict | None = None
30
+ ) -> "OpenAIRealtimeSession":
31
+ session = cls()
32
+ session._connection = connection
33
+ if setup:
34
+ await connection.asend(json.dumps(setup))
35
+ session.mark_open()
36
+ session._receiver = asyncio.create_task(session._receive_loop())
37
+ return session
38
+
39
+ async def _receive_loop(self) -> None:
40
+ try:
41
+ async for message in self._connection.aiter_messages():
42
+ for event in self._codec.decode(message):
43
+ await self.emit(event)
44
+ except asyncio.CancelledError:
45
+ raise
46
+ except Exception as exc:
47
+ await self.emit(SessionErrorEvent(message=str(exc)))
48
+ await self.fail(exc)
49
+ else:
50
+ await self.finish()
51
+
52
+ async def _asend_impl(self, input_data: LiveInputBase) -> None:
53
+ for message in self._codec.encode(input_data):
54
+ await self._connection.asend(message)
55
+
56
+ async def _aclose_impl(self) -> None:
57
+ if (
58
+ self._receiver is not None
59
+ and self._receiver is not asyncio.current_task()
60
+ ):
61
+ self._receiver.cancel()
62
+ with suppress(asyncio.CancelledError):
63
+ await self._receiver
64
+ await self._connection.aclose()
@@ -0,0 +1,10 @@
1
+ from swarmauri_base.live_models.inputs.ToolResultInput import ToolResultInput
2
+
3
+
4
+ class OpenAIRealtimeToolAdapter:
5
+ def result(
6
+ self, call_id: str, value: object, *, is_error: bool = False
7
+ ) -> ToolResultInput:
8
+ return ToolResultInput(
9
+ call_id=call_id, payload=value, is_error=is_error
10
+ )
@@ -0,0 +1,23 @@
1
+ from typing import Literal
2
+
3
+ from swarmauri_base.ComponentBase import ComponentBase
4
+ from swarmauri_base.live_models.LiveConfigBase import LiveConfigBase
5
+ from swarmauri_base.live_models.LiveModelBase import LiveModelBase
6
+
7
+ from .OpenAIRealtimeModel import OpenAIRealtimeModel
8
+ from .OpenAIRealtimeSession import OpenAIRealtimeSession
9
+
10
+
11
+ @ComponentBase.register_type(LiveModelBase, "OpenAIResponsesWSModel")
12
+ class OpenAIResponsesWSModel(OpenAIRealtimeModel):
13
+ type: Literal["OpenAIResponsesWSModel"] = "OpenAIResponsesWSModel"
14
+
15
+ async def aconnect(self, config: LiveConfigBase) -> OpenAIRealtimeSession:
16
+ connection_config = self.provider.prepare_connection(
17
+ "responses.connect", model=self.name
18
+ )
19
+ connection = await self.transport.aconnect(
20
+ connection_config.resolved_url(),
21
+ headers=connection_config.headers,
22
+ )
23
+ return await OpenAIRealtimeSession.create(connection)
@@ -0,0 +1,15 @@
1
+ from .OpenAIRealtimeCodec import OpenAIRealtimeCodec
2
+ from .OpenAIRealtimeConfigMapper import OpenAIRealtimeConfigMapper
3
+ from .OpenAIRealtimeModel import OpenAIRealtimeModel
4
+ from .OpenAIRealtimeSession import OpenAIRealtimeSession
5
+ from .OpenAIRealtimeToolAdapter import OpenAIRealtimeToolAdapter
6
+ from .OpenAIResponsesWSModel import OpenAIResponsesWSModel
7
+
8
+ __all__ = [
9
+ "OpenAIRealtimeCodec",
10
+ "OpenAIRealtimeConfigMapper",
11
+ "OpenAIRealtimeModel",
12
+ "OpenAIRealtimeSession",
13
+ "OpenAIRealtimeToolAdapter",
14
+ "OpenAIResponsesWSModel",
15
+ ]
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: swarmauri_live_model_openai
3
+ Version: 0.1.0.dev3
4
+ Summary: OpenAI Realtime and persistent Responses WebSocket model adapters for Swarmauri.
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,openai realtime,websocket,audio,tools
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 (>=0.11.0.dev5)
29
+ Requires-Dist: swarmauri_core (>=0.11.0.dev5)
30
+ Requires-Dist: swarmauri_provider_openai (>=0.1.0.dev3)
31
+ Requires-Dist: swarmauri_transport_websocket (>=0.1.0.dev4)
32
+ Description-Content-Type: text/markdown
33
+
34
+ ![Swarmauri](https://github.com/swarmauri/swarmauri-sdk/blob/3d4d1cfa949399d7019ae9d8f296afba773dfb7f/assets/swarmauri.brand.theme.svg)
35
+
36
+ [![PyPI](https://img.shields.io/pypi/v/swarmauri_live_model_openai.svg)](https://pypi.org/project/swarmauri_live_model_openai/) [![Python](https://img.shields.io/pypi/pyversions/swarmauri_live_model_openai.svg)](https://pypi.org/project/swarmauri_live_model_openai/) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE) [![Downloads](https://static.pepy.tech/badge/swarmauri_live_model_openai)](https://pepy.tech/project/swarmauri_live_model_openai) [![Hits](https://hits.sh/github.com/swarmauri/swarmauri-sdk.svg)](https://hits.sh/github.com/swarmauri/swarmauri-sdk/)
37
+
38
+ # swarmauri_live_model_openai
39
+
40
+ ## Features
41
+
42
+ - OpenAI Realtime multimodal conversations over WebSocket.
43
+ - Persistent Responses WebSocket adapter.
44
+ - Typed text, audio, transcripts, tools, interruption, and usage events.
45
+
46
+ ## Installation
47
+
48
+ `uv add swarmauri_live_model_openai` or `pip install swarmauri_live_model_openai`.
49
+
50
+ ## Usage
51
+
52
+ Inject an `OpenAIProvider`, connect with `LiveConfigBase`, send typed inputs, and consume the session event stream.
53
+
@@ -0,0 +1,12 @@
1
+ swarmauri_live_model_openai/OpenAIRealtimeCodec.py,sha256=TUSbJfXf5Z7taBcoTxTknyMI-YzaAG0OZ_dNZkxwm7k,6869
2
+ swarmauri_live_model_openai/OpenAIRealtimeConfigMapper.py,sha256=0OADxUzAEfim7B4S_YaDguhMB3bCYsNamqnsOKlABRw,712
3
+ swarmauri_live_model_openai/OpenAIRealtimeModel.py,sha256=Y2fZR84knhMvOs0uZBz1cjPV8fZgEwnoF3nFYNJB8QE,1870
4
+ swarmauri_live_model_openai/OpenAIRealtimeSession.py,sha256=QIx4YJKvqu3SUQsfAGm7dbEoO8GmEX-ogp8NRnxI-Ao,2259
5
+ swarmauri_live_model_openai/OpenAIRealtimeToolAdapter.py,sha256=7VpKTMEye3-9f5DmD0JfGDYjvACUsFivNvtQN5Y47QU,328
6
+ swarmauri_live_model_openai/OpenAIResponsesWSModel.py,sha256=rK8fJEnvzimXLNV2ynXAX8FGrqLpYpICClAgtr9U0qs,942
7
+ swarmauri_live_model_openai/__init__.py,sha256=BxxaX-iN-PwA2YktnRWUS7YQ9f8AdSiZKqNWDIsUBZY,549
8
+ swarmauri_live_model_openai-0.1.0.dev3.dist-info/METADATA,sha256=fmHA8G50OAfsyQaRDjlMrlDfSJ5EIBGrqDsS5QcJeTA,2693
9
+ swarmauri_live_model_openai-0.1.0.dev3.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
10
+ swarmauri_live_model_openai-0.1.0.dev3.dist-info/entry_points.txt,sha256=DYt_dq1gKCZExhHlWg5Z7MS-jPY2sdDVVawfC87HbSQ,167
11
+ swarmauri_live_model_openai-0.1.0.dev3.dist-info/licenses/LICENSE,sha256=kkwAgrDtfQ7c-Ozql2xlztDDjHt0YwGmRG7b_oUU9Jg,554
12
+ swarmauri_live_model_openai-0.1.0.dev3.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.5.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,4 @@
1
+ [swarmauri.live_models]
2
+ OpenAIRealtimeModel=swarmauri_live_model_openai:OpenAIRealtimeModel
3
+ OpenAIResponsesWSModel=swarmauri_live_model_openai:OpenAIResponsesWSModel
4
+
@@ -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.