swarmauri_live_model_gemini 0.1.0.dev3__tar.gz

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,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.
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.4
2
+ Name: swarmauri_live_model_gemini
3
+ Version: 0.1.0.dev3
4
+ Summary: Gemini Live bidirectional multimodal model adapter 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,gemini live,realtime,audio,multimodal,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_gemini (>=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_gemini.svg)](https://pypi.org/project/swarmauri_live_model_gemini/) [![Python](https://img.shields.io/pypi/pyversions/swarmauri_live_model_gemini.svg)](https://pypi.org/project/swarmauri_live_model_gemini/) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE) [![Downloads](https://static.pepy.tech/badge/swarmauri_live_model_gemini)](https://pepy.tech/project/swarmauri_live_model_gemini) [![Hits](https://hits.sh/github.com/swarmauri/swarmauri-sdk.svg)](https://hits.sh/github.com/swarmauri/swarmauri-sdk/)
37
+
38
+ # swarmauri_live_model_gemini
39
+
40
+ ## Features
41
+
42
+ - Text, audio, image, and video input.
43
+ - Audio and transcript output as independent event streams.
44
+ - Function calls, VAD/interruption events, usage, and session resumption.
45
+ - Synchronous façade and canonical asynchronous WebSocket session.
46
+
47
+ ## Installation
48
+
49
+ `uv add swarmauri_live_model_gemini` or `pip install swarmauri_live_model_gemini`.
50
+
51
+ ## Usage
52
+
53
+ Create `GeminiLiveModel(provider=GeminiProvider(api_key=...))`, connect with `LiveConfigBase`, send typed inputs, and consume typed events.
54
+
@@ -0,0 +1,20 @@
1
+ ![Swarmauri](https://github.com/swarmauri/swarmauri-sdk/blob/3d4d1cfa949399d7019ae9d8f296afba773dfb7f/assets/swarmauri.brand.theme.svg)
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/swarmauri_live_model_gemini.svg)](https://pypi.org/project/swarmauri_live_model_gemini/) [![Python](https://img.shields.io/pypi/pyversions/swarmauri_live_model_gemini.svg)](https://pypi.org/project/swarmauri_live_model_gemini/) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE) [![Downloads](https://static.pepy.tech/badge/swarmauri_live_model_gemini)](https://pepy.tech/project/swarmauri_live_model_gemini) [![Hits](https://hits.sh/github.com/swarmauri/swarmauri-sdk.svg)](https://hits.sh/github.com/swarmauri/swarmauri-sdk/)
4
+
5
+ # swarmauri_live_model_gemini
6
+
7
+ ## Features
8
+
9
+ - Text, audio, image, and video input.
10
+ - Audio and transcript output as independent event streams.
11
+ - Function calls, VAD/interruption events, usage, and session resumption.
12
+ - Synchronous façade and canonical asynchronous WebSocket session.
13
+
14
+ ## Installation
15
+
16
+ `uv add swarmauri_live_model_gemini` or `pip install swarmauri_live_model_gemini`.
17
+
18
+ ## Usage
19
+
20
+ Create `GeminiLiveModel(provider=GeminiProvider(api_key=...))`, connect with `LiveConfigBase`, send typed inputs, and consume typed events.
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "swarmauri_live_model_gemini"
3
+ version = "0.1.0.dev3"
4
+ description = "Gemini Live bidirectional multimodal model adapter for Swarmauri."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10,<3.13"
7
+ authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
8
+ license = { file = "LICENSE" }
9
+ dependencies = ["swarmauri_core>=0.11.0.dev5", "swarmauri_base>=0.11.0.dev5", "swarmauri_provider_gemini>=0.1.0.dev3", "swarmauri_transport_websocket>=0.1.0.dev4"]
10
+ classifiers = ["Development Status :: 1 - Planning", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12"]
11
+ keywords = ["swarmauri", "gemini live", "realtime", "audio", "multimodal", "tools"]
12
+ [tool.uv.sources]
13
+ swarmauri_core = { workspace = true }
14
+ swarmauri_base = { workspace = true }
15
+ swarmauri_provider_gemini = { workspace = true }
16
+ swarmauri_transport_websocket = { workspace = true }
17
+ [project.entry-points."swarmauri.live_models"]
18
+ GeminiLiveModel = "swarmauri_live_model_gemini:GeminiLiveModel"
19
+ [build-system]
20
+ requires = ["poetry-core>=1.8.0"]
21
+ build-backend = "poetry.core.masonry.api"
22
+ [dependency-groups]
23
+ dev = ["pytest>=8.0", "pytest-asyncio>=0.24", "ruff>=0.9.9", "swarmauri_tests_component"]
24
+
25
+ [tool.ruff]
26
+ extend = "../../pyproject.toml"
27
+
28
+ [tool.ruff.lint]
29
+ ignore = ["BLE001", "N999"]
@@ -0,0 +1,150 @@
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.OutputTranscriptDeltaEvent import (
10
+ OutputTranscriptDeltaEvent,
11
+ )
12
+ from swarmauri_base.live_models.events.SessionErrorEvent import (
13
+ SessionErrorEvent,
14
+ )
15
+ from swarmauri_base.live_models.events.SessionLifecycleEvent import (
16
+ SessionLifecycleEvent,
17
+ )
18
+ from swarmauri_base.live_models.events.SessionResumptionEvent import (
19
+ SessionResumptionEvent,
20
+ )
21
+ from swarmauri_base.live_models.events.TextDeltaEvent import TextDeltaEvent
22
+ from swarmauri_base.live_models.events.ToolCallEvent import ToolCallEvent
23
+ from swarmauri_base.live_models.events.TurnCompleteEvent import (
24
+ TurnCompleteEvent,
25
+ )
26
+ from swarmauri_base.live_models.events.UsageEvent import UsageEvent
27
+ from swarmauri_base.live_models.LiveEventBase import LiveEventBase
28
+ from swarmauri_base.live_models.LiveInputBase import LiveInputBase
29
+
30
+
31
+ class GeminiLiveCodec:
32
+ def encode(self, input_data: LiveInputBase) -> str:
33
+ if input_data.kind == "text":
34
+ payload = {"realtimeInput": {"text": input_data.payload}}
35
+ elif input_data.kind in {"audio", "image", "video"}:
36
+ payload = {
37
+ "realtimeInput": {
38
+ "mediaChunks": [
39
+ {
40
+ "mimeType": input_data.mime_type,
41
+ "data": base64.b64encode(
42
+ input_data.payload
43
+ ).decode(),
44
+ }
45
+ ]
46
+ }
47
+ }
48
+ elif input_data.kind == "tool_result":
49
+ payload = {
50
+ "toolResponse": {
51
+ "functionResponses": [
52
+ {
53
+ "id": input_data.call_id,
54
+ "name": input_data.correlation_id or "tool",
55
+ "response": {"output": input_data.payload},
56
+ }
57
+ ]
58
+ }
59
+ }
60
+ elif input_data.kind == "commit_turn":
61
+ payload = {"realtimeInput": {"activityEnd": {}}}
62
+ elif input_data.kind == "interrupt":
63
+ payload = {"realtimeInput": {"activityStart": {}}}
64
+ else:
65
+ raise ValueError(
66
+ f"Unsupported Gemini live input: {input_data.kind}"
67
+ )
68
+ return json.dumps(payload)
69
+
70
+ def decode(self, message: str | bytes) -> list[LiveEventBase]:
71
+ data: dict[str, Any] = json.loads(message)
72
+ events: list[LiveEventBase] = []
73
+ server = data.get("serverContent", {})
74
+ model_turn = server.get("modelTurn", {})
75
+ correlation = {"provider_event_id": data.get("id")}
76
+
77
+ for part in model_turn.get("parts", []):
78
+ if "text" in part:
79
+ events.append(
80
+ TextDeltaEvent(
81
+ payload=part["text"], correlation=correlation
82
+ )
83
+ )
84
+ inline = part.get("inlineData") or part.get("inline_data")
85
+ if inline and str(inline.get("mimeType", "")).startswith("audio/"):
86
+ events.append(
87
+ AudioDeltaEvent(
88
+ payload=base64.b64decode(inline["data"]),
89
+ mime_type=inline.get("mimeType", "audio/pcm"),
90
+ correlation=correlation,
91
+ )
92
+ )
93
+
94
+ input_tx = server.get("inputTranscription", {})
95
+ if input_tx.get("text"):
96
+ events.append(
97
+ InputTranscriptDeltaEvent(
98
+ payload=input_tx["text"], correlation=correlation
99
+ )
100
+ )
101
+ output_tx = server.get("outputTranscription", {})
102
+ if output_tx.get("text"):
103
+ events.append(
104
+ OutputTranscriptDeltaEvent(
105
+ payload=output_tx["text"], correlation=correlation
106
+ )
107
+ )
108
+ if server.get("turnComplete"):
109
+ events.append(TurnCompleteEvent(correlation=correlation))
110
+
111
+ for call in data.get("toolCall", {}).get("functionCalls", []):
112
+ events.append(
113
+ ToolCallEvent(
114
+ call_id=call.get("id", call.get("name", "")),
115
+ tool_name=call["name"],
116
+ arguments=call.get("args", {}),
117
+ correlation=correlation,
118
+ )
119
+ )
120
+ if data.get("usageMetadata"):
121
+ usage = {
122
+ key: int(value)
123
+ for key, value in data["usageMetadata"].items()
124
+ if isinstance(value, int)
125
+ }
126
+ events.append(UsageEvent(payload=usage, correlation=correlation))
127
+ if data.get("sessionResumptionUpdate"):
128
+ update = data["sessionResumptionUpdate"]
129
+ events.append(
130
+ SessionResumptionEvent(
131
+ token=update.get("newHandle"),
132
+ resumable=bool(update.get("resumable", True)),
133
+ correlation=correlation,
134
+ )
135
+ )
136
+ if data.get("goAway"):
137
+ events.append(
138
+ SessionLifecycleEvent(
139
+ state="closing",
140
+ payload=data["goAway"],
141
+ correlation=correlation,
142
+ )
143
+ )
144
+ if data.get("error"):
145
+ events.append(
146
+ SessionErrorEvent(
147
+ message=str(data["error"]), correlation=correlation
148
+ )
149
+ )
150
+ return events
@@ -0,0 +1,30 @@
1
+ from typing import Any
2
+
3
+ from swarmauri_base.live_models.LiveConfigBase import LiveConfigBase
4
+ from swarmauri_provider_gemini import GeminiToolSchemaConverter
5
+
6
+
7
+ class GeminiLiveConfigMapper:
8
+ def __init__(self) -> None:
9
+ self._tools = GeminiToolSchemaConverter()
10
+
11
+ def map(self, model: str, config: LiveConfigBase) -> dict[str, Any]:
12
+ generation = {
13
+ "responseModalities": [
14
+ modality.upper() for modality in config.requested_modalities
15
+ ]
16
+ }
17
+ setup: dict[str, Any] = {
18
+ "model": f"models/{model}",
19
+ "generationConfig": generation,
20
+ }
21
+ if config.tools:
22
+ setup["tools"] = [
23
+ {
24
+ "functionDeclarations": [
25
+ self._tools.convert(tool) for tool in config.tools
26
+ ]
27
+ }
28
+ ]
29
+ setup.update(config.provider_options.get("setup", {}))
30
+ return {"setup": setup}
@@ -0,0 +1,43 @@
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_gemini import GeminiProvider
10
+ from swarmauri_transport_websocket import WebSocketClient
11
+
12
+ from .GeminiLiveConfigMapper import GeminiLiveConfigMapper
13
+ from .GeminiLiveSession import GeminiLiveSession
14
+
15
+
16
+ @ComponentBase.register_type(LiveModelBase, "GeminiLiveModel")
17
+ class GeminiLiveModel(LiveModelBase):
18
+ name: str = "gemini-3.1-flash-live-preview"
19
+ provider: GeminiProvider = Field(default_factory=GeminiProvider)
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", "video"}),
24
+ output_modalities=frozenset({"text", "audio"}),
25
+ features=frozenset({"tools", "transcription"}),
26
+ session_features=frozenset(
27
+ {"realtime", "interruption", "session_resumption"}
28
+ ),
29
+ )
30
+ )
31
+ type: Literal["GeminiLiveModel"] = "GeminiLiveModel"
32
+ model_config = ConfigDict(arbitrary_types_allowed=True, extra="allow")
33
+
34
+ async def aconnect(self, config: LiveConfigBase) -> GeminiLiveSession:
35
+ connection_config = self.provider.prepare_connection(
36
+ "live.connect", model=self.name
37
+ )
38
+ connection = await self.transport.aconnect(
39
+ connection_config.resolved_url(),
40
+ headers=connection_config.headers,
41
+ )
42
+ setup = GeminiLiveConfigMapper().map(self.name, config)
43
+ return await GeminiLiveSession.create(connection, setup)
@@ -0,0 +1,58 @@
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 .GeminiLiveCodec import GeminiLiveCodec
16
+
17
+
18
+ @ComponentBase.register_type(LiveSessionBase, "GeminiLiveSession")
19
+ class GeminiLiveSession(LiveSessionBase):
20
+ type: Literal["GeminiLiveSession"] = "GeminiLiveSession"
21
+ _connection: IWebSocketConnection = PrivateAttr()
22
+ _codec: GeminiLiveCodec = PrivateAttr(default_factory=GeminiLiveCodec)
23
+ _receiver: Any = PrivateAttr(default=None)
24
+
25
+ @classmethod
26
+ async def create(cls, connection, setup: dict) -> "GeminiLiveSession":
27
+ session = cls()
28
+ session._connection = connection
29
+ await connection.asend(json.dumps(setup))
30
+ session.mark_open()
31
+ session._receiver = asyncio.create_task(session._receive_loop())
32
+ return session
33
+
34
+ async def _receive_loop(self) -> None:
35
+ try:
36
+ async for message in self._connection.aiter_messages():
37
+ for event in self._codec.decode(message):
38
+ await self.emit(event)
39
+ except asyncio.CancelledError:
40
+ raise
41
+ except Exception as exc:
42
+ await self.emit(SessionErrorEvent(message=str(exc)))
43
+ await self.fail(exc)
44
+ else:
45
+ await self.finish()
46
+
47
+ async def _asend_impl(self, input_data: LiveInputBase) -> None:
48
+ await self._connection.asend(self._codec.encode(input_data))
49
+
50
+ async def _aclose_impl(self) -> None:
51
+ if (
52
+ self._receiver is not None
53
+ and self._receiver is not asyncio.current_task()
54
+ ):
55
+ self._receiver.cancel()
56
+ with suppress(asyncio.CancelledError):
57
+ await self._receiver
58
+ await self._connection.aclose()
@@ -0,0 +1,12 @@
1
+ from swarmauri_base.live_models.inputs.ToolResultInput import ToolResultInput
2
+
3
+
4
+ class GeminiLiveToolAdapter:
5
+ def result(
6
+ self, call_id: str, name: str, value: object
7
+ ) -> ToolResultInput:
8
+ return ToolResultInput(
9
+ call_id=call_id,
10
+ correlation_id=name,
11
+ payload=value,
12
+ )
@@ -0,0 +1,13 @@
1
+ from .GeminiLiveCodec import GeminiLiveCodec
2
+ from .GeminiLiveConfigMapper import GeminiLiveConfigMapper
3
+ from .GeminiLiveModel import GeminiLiveModel
4
+ from .GeminiLiveSession import GeminiLiveSession
5
+ from .GeminiLiveToolAdapter import GeminiLiveToolAdapter
6
+
7
+ __all__ = [
8
+ "GeminiLiveCodec",
9
+ "GeminiLiveConfigMapper",
10
+ "GeminiLiveModel",
11
+ "GeminiLiveSession",
12
+ "GeminiLiveToolAdapter",
13
+ ]