meshagent-livekit 0.0.15__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.

Potentially problematic release.


This version of meshagent-livekit might be problematic. Click here for more details.

@@ -0,0 +1 @@
1
+ from .version import __version__
@@ -0,0 +1,298 @@
1
+ import logging
2
+ import asyncio
3
+
4
+ from meshagent.api.schema_document import Element,Text
5
+ from meshagent.api.room_server_client import RoomClient
6
+ from meshagent.api.websocket_protocol import WebSocketClientProtocol
7
+
8
+
9
+ import asyncio
10
+ import os
11
+ import logging
12
+ import json
13
+
14
+ from livekit import api
15
+
16
+ from livekit.agents import stt, transcription, utils
17
+ from livekit.plugins import openai, silero
18
+ from livekit import rtc
19
+ from livekit.rtc import TranscriptionSegment
20
+ from livekit.agents import utils
21
+ from livekit.agents import stt as speech_to_text
22
+
23
+ from meshagent.api.runtime import RuntimeDocument
24
+
25
+ from typing import Optional
26
+
27
+ from meshagent.api.schema import MeshSchema
28
+
29
+ from meshagent.api.schema import MeshSchema, ElementType, ChildProperty, ValueProperty
30
+
31
+ from meshagent.agents.agent import AgentCallContext
32
+ from meshagent.agents import TaskRunner
33
+
34
+ logger = logging.getLogger("transcriber")
35
+
36
+
37
+ transcription_schema = MeshSchema(
38
+ root_tag_name="transcript",
39
+ elements=[
40
+ ElementType(tag_name="transcript", description="a transcript", properties=[
41
+ ChildProperty(name="transcriptions", description="the transcript entries", child_tag_names=[ "speech" ])
42
+ ]),
43
+ ElementType(tag_name="speech", description="transcribed speech", properties=[
44
+ ValueProperty(name="text", description="the transcribed text", type="string"),
45
+ ValueProperty(name="startTime", description="the time of the start of this speech", type="number"),
46
+ ValueProperty(name="endTime", description="the time of th end of this speech", type="number"),
47
+ ValueProperty(name="participantId", description="the identity of the participant", type="string"),
48
+ ValueProperty(name="participantName", description="the name of the participant", type="string")
49
+ ])
50
+ ]
51
+ )
52
+
53
+ class Transcriber(TaskRunner):
54
+
55
+ def __init__(self, *, livekit_url: Optional[str] = None, livekit_api_key: Optional[str] = None, livekit_api_secret: Optional[str] = None, livekit_identity: Optional[str] = None):
56
+ super().__init__(
57
+ name="livekit.transcriber",
58
+ title="transcriber",
59
+ description="connects to a livekit room and transcribes the conversation",
60
+ input_schema={
61
+ "type" : "object",
62
+ "additionalProperties" : False,
63
+ "required" : [ "room_name", "path" ],
64
+ "properties" : {
65
+ "room_name" : {
66
+ "type": "string"
67
+ },
68
+ "path" : {
69
+ "type" : "string"
70
+ }
71
+ }
72
+ },
73
+ output_schema={
74
+ "type" : "object",
75
+ "additionalProperties" : False,
76
+ "required" : [],
77
+ "properties" : {
78
+ }
79
+ }
80
+ )
81
+ self._livekit_url = livekit_url
82
+ self._livekit_api_key = livekit_api_key
83
+ self._livekit_api_secret = livekit_api_secret
84
+ self._livekit_identity = livekit_identity
85
+
86
+ async def _transcribe_participant(self, doc: RuntimeDocument, room: rtc.Room, participant: rtc.RemoteParticipant,
87
+ stt_stream: stt.SpeechStream, stt_forwarder: transcription.STTSegmentsForwarder
88
+ ):
89
+ logger.info("transcribing participant %s", participant.sid)
90
+ """Forward the transcription to the client and log the transcript in the console"""
91
+ async for ev in stt_stream:
92
+ logger.info("event from participant %s %s", participant.sid, ev)
93
+
94
+ if ev.type == stt.SpeechEventType.FINAL_TRANSCRIPT:
95
+ logger.info("transcript: %s", ev.alternatives[0].text)
96
+ if len(ev.alternatives) > 0:
97
+ alt = ev.alternatives[0]
98
+ doc.root.append_child(tag_name="speech", attributes={ "text": alt.text, "startTime": alt.start_time, "endTime" : alt.end_time, "participantId" : participant.identity, "participantName" : participant.name })
99
+
100
+ logger.info("done forwarding %s", participant.sid)
101
+
102
+ def should_transcribe(self, p: rtc.Participant) -> bool:
103
+ # don't transcribe other agents
104
+ # todo: maybe have a better way to detect
105
+ return ".agent" not in p.identity
106
+
107
+ async def _wait_for_disconnect(self, room: rtc.Room):
108
+ disconnected = asyncio.Future()
109
+ def on_disconnected(_):
110
+ disconnected.set_result(True)
111
+ room.on("disconnected", on_disconnected)
112
+
113
+ logger.info("waiting for disconnection")
114
+ await disconnected
115
+
116
+
117
+ async def ask(self, *, context: AgentCallContext, arguments: dict):
118
+ logger.info("Transcriber connecting to %s", arguments)
119
+ output_path = arguments["path"]
120
+ room_name = arguments["room_name"]
121
+
122
+ client = context.room
123
+ doc = await client.sync.open(path=output_path)
124
+ try:
125
+
126
+ vad = silero.VAD.load()
127
+ utils.http_context._new_session_ctx()
128
+
129
+ pending_tasks = list()
130
+ participantNames = dict[str,str]()
131
+
132
+ sst_provider = openai.STT()
133
+ #sst_provider = fal.WizperSTT()
134
+
135
+ room_options = rtc.RoomOptions(auto_subscribe=False)
136
+
137
+ room = rtc.Room()
138
+
139
+ url = self._livekit_url if self._livekit_url is not None else os.getenv('LIVEKIT_URL')
140
+ api_key = self._livekit_api_key if self._livekit_api_key is not None else os.getenv('LIVEKIT_API_KEY')
141
+ api_secret = self._livekit_api_secret if self._livekit_api_secret is not None else os.getenv('LIVEKIT_API_SECRET')
142
+ identity = self._livekit_identity if self._livekit_identity is not None else os.getenv('AGENT_IDENTITY')
143
+
144
+ token = api.AccessToken(api_key=api_key, api_secret=api_secret) \
145
+ .with_identity(identity) \
146
+ .with_name("Agent") \
147
+ .with_kind("agent") \
148
+ .with_grants(api.VideoGrants(
149
+ can_update_own_metadata=True,
150
+ room_join=True,
151
+ room=room_name,
152
+ agent=True
153
+ ))
154
+
155
+ jwt = token.to_jwt()
156
+
157
+ await room.connect(url=url, token=jwt, options=room_options)
158
+
159
+
160
+ logger.info(
161
+ "connected to room: %s",
162
+ room_name
163
+ )
164
+
165
+ audio_streams = list[rtc.AudioStream]()
166
+
167
+ async def transcribe_track(participant: rtc.RemoteParticipant, track: rtc.Track):
168
+ audio_stream = rtc.AudioStream(track)
169
+ stt_forwarder = transcription.STTSegmentsForwarder(
170
+ room=room, participant=participant, track=track
171
+ )
172
+
173
+ audio_streams.append(audio_stream)
174
+
175
+ stt = sst_provider
176
+ if not sst_provider.capabilities.streaming:
177
+ stt = speech_to_text.StreamAdapter(
178
+ stt=stt,
179
+ vad=vad,
180
+ )
181
+
182
+ stt_stream = stt.stream()
183
+
184
+ pending_tasks.append(asyncio.create_task(self._transcribe_participant(doc, room, participant, stt_stream, stt_forwarder)))
185
+
186
+ async for ev in audio_stream:
187
+ stt_stream.push_frame(ev.frame)
188
+
189
+ def subscribe_if_needed(pub: rtc.RemoteTrackPublication):
190
+ if pub.kind == rtc.TrackKind.KIND_AUDIO:
191
+ pub.set_subscribed(True)
192
+
193
+ for p in room.remote_participants.values():
194
+ participantNames[p.identity] = p.name
195
+ if self.should_transcribe(p):
196
+ for pub in p.track_publications.values():
197
+ subscribe_if_needed(pub)
198
+
199
+ first_parts = dict[str, rtc.Participant]()
200
+
201
+ def on_transcript_event(segments: list[TranscriptionSegment], part: rtc.Participant | None, pub: rtc.TrackPublication | None = None) -> None:
202
+ nonlocal room
203
+ logger.info("Got transcription segment %s %s %s", segments, part, pub)
204
+ for segment in segments:
205
+ if segment.id not in first_parts and part != None:
206
+ first_parts[segment.id] = part
207
+
208
+ if segment.final:
209
+ if part == None and segment.id in first_parts:
210
+ part = first_parts[segment.id]
211
+ first_parts.pop(segment.id)
212
+
213
+ if part != None:
214
+ doc.root.append_child(tag_name="speech", attributes={ "text": segment.text, "startTime": segment.start_time, "endTime" : segment.end_time, "participantId" : part.identity, "participantName" : part.name })
215
+ else:
216
+ logger.warning("transcription was missing participant information")
217
+
218
+ def on_participant_connected(p: rtc.RemoteParticipant):
219
+ participantNames[p.identity] = p.name
220
+
221
+ def on_track_published(pub: rtc.RemoteTrackPublication, p: rtc.RemoteParticipant):
222
+ if self.should_transcribe(p):
223
+ subscribe_if_needed(pub)
224
+
225
+ subscriptions = dict()
226
+
227
+ def on_track_unpublished(pub: rtc.RemoteTrackPublication, p: rtc.RemoteParticipant):
228
+ if pub in subscriptions:
229
+ logger.info("track unpublished, stopping transcription")
230
+ # todo: maybe could be more graceful
231
+ subscriptions[pub].cancel()
232
+ subscriptions.pop(pub)
233
+
234
+
235
+ def on_track_subscribed(
236
+ track: rtc.Track,
237
+ publication: rtc.TrackPublication,
238
+ participant: rtc.RemoteParticipant,
239
+ ):
240
+ if track.kind == rtc.TrackKind.KIND_AUDIO:
241
+ logger.info("transcribing track %s", track.sid)
242
+ track_task = asyncio.create_task(transcribe_track(participant, track))
243
+ def on_transcription_done(t):
244
+ try:
245
+ t.result()
246
+ except Exception as e:
247
+ logger.error("Transcription failed", exc_info=e)
248
+
249
+
250
+ track_task.add_done_callback(on_transcription_done)
251
+ pending_tasks.append(track_task)
252
+ subscriptions[publication] = track_task
253
+
254
+
255
+ for p in room.remote_participants.values():
256
+ on_participant_connected(p)
257
+
258
+ room.on("participant_connected", on_participant_connected)
259
+
260
+ room.on("track_published", on_track_published)
261
+ room.on("track_unpublished", on_track_unpublished)
262
+ room.on("track_subscribed", on_track_subscribed)
263
+ room.on("transcription_received", on_transcript_event)
264
+
265
+ await self._wait_for_disconnect(room)
266
+
267
+ logger.info("waited for termination")
268
+ await room.disconnect()
269
+
270
+ logger.info("closing audio streams")
271
+
272
+ for stream in audio_streams:
273
+ await stream.aclose()
274
+
275
+
276
+ logger.info("waiting for pending tasks")
277
+ gather_future = asyncio.gather(*pending_tasks)
278
+
279
+ gather_future.cancel()
280
+ try:
281
+ await gather_future
282
+ except Exception as e:
283
+ if isinstance(e, asyncio.CancelledError) == False:
284
+ logger.warning("Did not shut down cleanly", exc_info=e)
285
+ pass
286
+
287
+ print("done")
288
+ except Exception as e:
289
+ logger.info("Transcription failed", exc_info=e)
290
+ finally:
291
+
292
+ await utils.http_context._close_http_ctx()
293
+ logger.info("Transcription done")
294
+
295
+ await asyncio.sleep(5)
296
+ await client.sync.close(path=output_path)
297
+
298
+ return {}
@@ -0,0 +1,187 @@
1
+ import logging
2
+ import asyncio
3
+
4
+ from meshagent.api import RoomMessage
5
+ from meshagent.api.room_server_client import RoomClient
6
+
7
+ from livekit.agents import Agent, AgentSession
8
+ from livekit.plugins import openai, silero
9
+ #from livekit.plugins.turn_detector.multilingual import MultilingualModel
10
+ import uuid
11
+ import asyncio
12
+ import logging
13
+
14
+
15
+ from livekit.plugins import openai
16
+
17
+ from livekit.plugins import openai, silero
18
+ from livekit import rtc
19
+ from livekit.agents import Agent, AgentSession
20
+
21
+ from typing import Optional
22
+
23
+ from copy import deepcopy
24
+
25
+ from meshagent.api.schema_util import merge, prompt_schema
26
+
27
+ from meshagent.agents import SingleRoomAgent
28
+
29
+
30
+ logger = logging.getLogger("voice")
31
+
32
+
33
+ from meshagent.agents.agent import AgentCallContext
34
+
35
+
36
+ class VoiceConnection:
37
+ def __init__(self, *, room: RoomClient, breakout_room: str):
38
+ self.room = room
39
+ self.breakout_room = breakout_room
40
+
41
+ async def __aenter__(self):
42
+
43
+ client = self.room
44
+
45
+ room_options = rtc.RoomOptions(auto_subscribe=True)
46
+
47
+ room = rtc.Room()
48
+
49
+ self.livekit_room = room
50
+
51
+ connection_info = await client.livekit.get_connection_info(breakout_room=self.breakout_room)
52
+
53
+ await room.connect(url=connection_info.url, token=connection_info.token, options=room_options)
54
+
55
+ return self
56
+
57
+ async def __aexit__(self, exc_type, exc, tb):
58
+ await self.livekit_room.disconnect()
59
+
60
+ class Voice(SingleRoomAgent):
61
+
62
+ def __init__(
63
+ self,
64
+ name: str,
65
+ input_schema: Optional[dict] = None, # the base schema, voice agent parameters will be added
66
+ title: Optional[str] = None,
67
+ description: Optional[str] = None,
68
+ labels: Optional[list[str]] = None,
69
+ rules: Optional[list[str]] = None,
70
+ auto_greet_prompt: Optional[str] = None,
71
+ greeting: Optional[str] = None,
72
+ ):
73
+ if rules == None:
74
+ rules = [ "You are a helpful assistant communicating through voice." ]
75
+
76
+ self.auto_greet_prompt = auto_greet_prompt
77
+ self.greeting = greeting
78
+
79
+ self.rules = rules
80
+
81
+ if input_schema == None:
82
+ input_schema = None
83
+
84
+ input_schema = merge(
85
+ schema=input_schema,
86
+ additional_properties={
87
+ })
88
+
89
+ super().__init__(
90
+ name=name,
91
+ description=description,
92
+ title=title,
93
+ labels=labels
94
+ )
95
+
96
+ async def start(self, *, room):
97
+ await super().start(room=room)
98
+ await room.local_participant.set_attribute("supports_voice", True)
99
+ await room.messaging.enable()
100
+ room.messaging.on("message", self.on_message)
101
+
102
+ def on_message(self, message: RoomMessage):
103
+ if message.type == "voice_call":
104
+ breakout_room = message.message["breakout_room"]
105
+
106
+ logger.info(f"joining breakout room {breakout_room}")
107
+
108
+ def on_done(task: asyncio.Task):
109
+ try:
110
+ task.result()
111
+ except Exception as e:
112
+ logger.error(f"{e}", exc_info=e)
113
+
114
+ task = asyncio.create_task(self.run_voice_agent(breakout_room=breakout_room))
115
+ task.add_done_callback(on_done)
116
+
117
+
118
+ async def _wait_for_disconnect(self, room: rtc.Room):
119
+ disconnected = asyncio.Future()
120
+ def on_disconnected(_):
121
+ disconnected.set_result(True)
122
+ room.on("disconnected", on_disconnected)
123
+
124
+ logger.info("waiting for disconnection")
125
+ await disconnected
126
+
127
+ def create_agent(self):
128
+ return Agent(
129
+ instructions="\n".join(self.rules),
130
+ allow_interruptions=True
131
+ )
132
+
133
+ # agent = Agent(
134
+ # instructions="""
135
+ # You are a helpful assistant communicating through voice.
136
+ # """,
137
+ # stt=openai.STT(),
138
+ # llm=openai.LLM(model="gpt-4o"),
139
+ # tts=openai.TTS(),
140
+ # vad=silero.VAD.load(),
141
+ # allow_interruptions=True
142
+ #)
143
+
144
+ def create_session(self) -> AgentSession:
145
+
146
+ session = AgentSession(
147
+ allow_interruptions=True,
148
+ vad=silero.VAD.load(),
149
+ stt=openai.STT(),
150
+ tts=openai.TTS(voice="echo"),
151
+ llm=openai.realtime.RealtimeModel(
152
+ # it's necessary to turn off turn detection in the Realtime API in order to use
153
+ # LiveKit's turn detection model
154
+ voice="alloy",
155
+ turn_detection=None,
156
+ input_audio_transcription=None,
157
+
158
+ ),
159
+ )
160
+ return session
161
+
162
+
163
+ async def run_voice_agent(self, *, breakout_room: str):
164
+
165
+ async with VoiceConnection(room=self.room, breakout_room=breakout_room) as connection:
166
+
167
+
168
+ logger.info("starting voice agent")
169
+
170
+ agent = self.create_agent()
171
+ session = self.create_session()
172
+
173
+ await session.start(agent=agent, room=connection.livekit_room)
174
+
175
+ if self.auto_greet_prompt != None:
176
+ session.generate_reply(user_input=self.auto_greet_prompt)
177
+
178
+ if self.greeting != None:
179
+ session.say(self.greeting)
180
+
181
+ logger.info("started voice agent")
182
+ await self._wait_for_disconnect(room=connection.livekit_room)
183
+
184
+
185
+
186
+
187
+
@@ -0,0 +1,48 @@
1
+ from meshagent.api.protocol import Protocol
2
+
3
+ from livekit import rtc
4
+ import logging
5
+
6
+ logger = logging.getLogger("protocol.livekit")
7
+
8
+
9
+ class LivekitProtocol(Protocol):
10
+ def __init__(self, room: rtc.Room, remote: rtc.RemoteParticipant, topic: str):
11
+ super().__init__()
12
+ self.room = room
13
+ self.local = room.local_participant
14
+ self.remote = remote
15
+ self.topic = topic
16
+
17
+
18
+ async def __aenter__(self):
19
+ self.room.on("data_received", self._on_data_packet)
20
+ return await super().__aenter__()
21
+
22
+ async def __aexit__(self, exc_type, exc, tb):
23
+ self.room.off("data_received", self._on_data_packet)
24
+
25
+ return await super().__aexit__(exc_type, exc, tb)
26
+
27
+ async def send_packet(self, data:bytes) -> None:
28
+
29
+ logger.info("sending data packet %s %s to %s", self.topic, self.remote.identity, self.room.remote_participants[self.remote.identity].sid)
30
+
31
+ await self.local.publish_data(
32
+ payload=data,
33
+ topic = self.topic,
34
+ reliable = True,
35
+ destination_identities = [ self.remote.identity ],
36
+ )
37
+
38
+ def _on_data_packet(self, evt: rtc.DataPacket):
39
+
40
+ if self.remote != evt.participant:
41
+ return
42
+
43
+ logger.info("received data packet %s from %s", evt.topic, evt.participant.identity)
44
+
45
+ if evt.topic == self.topic:
46
+ self.receive_packet(evt.data)
47
+
48
+
@@ -0,0 +1,106 @@
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ sys.path.insert(0, str(Path(__file__).parent.parent))
5
+
6
+ import logging
7
+ import pytest
8
+ import os
9
+
10
+ from livekit import api
11
+ from livekit import rtc
12
+
13
+ import livekit_protocol
14
+ import asyncio
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ @pytest.mark.asyncio
19
+ async def test_protocol():
20
+
21
+ url = os.getenv('LIVEKIT_URL')
22
+ api_key = os.getenv('LIVEKIT_API_KEY')
23
+ api_secret = os.getenv('LIVEKIT_API_SECRET')
24
+
25
+
26
+ token1 = api.AccessToken(api_key=api_key, api_secret=api_secret) \
27
+ .with_identity('core:user.test.agent-send') \
28
+ .with_name("Agent") \
29
+ .with_kind("agent") \
30
+ .with_grants(api.VideoGrants(
31
+ can_update_own_metadata=True,
32
+ room_join=True,
33
+ room="test-process",
34
+ agent=True
35
+ ))
36
+
37
+ jwt1 = token1.to_jwt()
38
+
39
+
40
+ token2 = api.AccessToken(api_key=api_key, api_secret=api_secret) \
41
+ .with_identity('core:user.test.agent-recv') \
42
+ .with_name("Agent") \
43
+ .with_kind("agent") \
44
+ .with_grants(api.VideoGrants(
45
+ can_update_own_metadata=True,
46
+ room_join=True,
47
+ room="test-process",
48
+ agent=True
49
+ ))
50
+
51
+ jwt2 = token2.to_jwt()
52
+
53
+ room1 = rtc.Room()
54
+ await room1.connect(url=url, token=jwt1)
55
+
56
+ room2 = rtc.Room()
57
+ await room2.connect(url=url, token=jwt2)
58
+
59
+ topic = "test_topic"
60
+
61
+ while True:
62
+ await asyncio.sleep(0.1)
63
+
64
+ if room2.local_participant.identity in room1.remote_participants and room1.local_participant.identity in room2.remote_participants:
65
+ break
66
+
67
+ async with livekit_protocol.LivekitProtocol(room = room1, remote = room1.remote_participants[room2.local_participant.identity], topic=topic) as proto1:
68
+ async with livekit_protocol.LivekitProtocol(room = room2, remote = room2.remote_participants[room1.local_participant.identity], topic=topic) as proto2:
69
+
70
+ test_data_builder = bytearray()
71
+ for i in range(1024*1024):
72
+ test_data_builder.append(i % 255)
73
+
74
+ test_data = bytes(test_data_builder)
75
+
76
+ done = asyncio.Future[bool]()
77
+
78
+ matches = 0
79
+ async def test_fn(protocol, id: int, type:str, data:bytes):
80
+ nonlocal matches
81
+ logger.info("Message received")
82
+ if test_data != data:
83
+ raise "data isn't equal"
84
+ matches+=1
85
+
86
+ if matches == 2:
87
+ done.set_result(True)
88
+
89
+ proto2.register_handler("test", test_fn)
90
+
91
+ await asyncio.sleep(1)
92
+
93
+ await proto1.send("test", test_data)
94
+ await proto1.send("test", test_data)
95
+
96
+ await done
97
+
98
+
99
+ await room2.disconnect()
100
+ await room1.disconnect()
101
+
102
+
103
+
104
+
105
+
106
+
@@ -0,0 +1,260 @@
1
+ import uuid
2
+ from livekit import rtc
3
+ from livekit.agents.tts import TTS
4
+ from typing import Optional
5
+
6
+ from ..agents.voice import VoiceConnection
7
+ from meshagent.tools.toolkit import Toolkit, Tool, FileResponse, ToolContext, TextResponse
8
+
9
+ from livekit.plugins import elevenlabs
10
+ from livekit.plugins import cartesia
11
+ from livekit.plugins import openai
12
+ from livekit.plugins import playai
13
+
14
+ class SpeechTools(Toolkit):
15
+ def __init__(self):
16
+ super().__init__(
17
+ name="meshagent.speech",
18
+ title="voice",
19
+ description="speech to text tools",
20
+ tools=[
21
+ ElevenTextToSpeech(),
22
+ CartesiaTextToSpeech(),
23
+ OpenAITextToSpeech(),
24
+ PlayHTTextToSpeech(),
25
+ ])
26
+
27
+
28
+ async def synthesize(tts: TTS, text:str):
29
+
30
+ frames = list[rtc.AudioFrame]()
31
+ stream = tts.synthesize(text=text)
32
+ try:
33
+ async for chunk in stream:
34
+ frame : rtc.AudioFrame = chunk.frame
35
+ frames.append(frame)
36
+
37
+ merged = rtc.combine_audio_frames(frames)
38
+ return FileResponse(data=merged.to_wav_bytes(), name= str(uuid.uuid4())+".wav", mime_type="audio/wav")
39
+ finally:
40
+ await stream.aclose()
41
+
42
+
43
+ class PlayHTTextToSpeech(Tool):
44
+ def __init__(self):
45
+ super().__init__(
46
+ name="playht_text_to_speech",
47
+ title="PlayHT text to speech",
48
+ description="generate an audio file, converting text to speech",
49
+ input_schema={
50
+ "type" : "object",
51
+ "properties" : {
52
+ "input_text" : {
53
+ "type" : "string",
54
+ "description" : "the text to convert to speech",
55
+ },
56
+ "model" : {
57
+ "type": "string",
58
+ "description" : "(default: PlayDialog)",
59
+ "enum" : [ "Play3.0-mini", "PlayDialog", "PlayHT2.0-turbo" ]
60
+ },
61
+ "sample_rate" : {
62
+ "type" : "number",
63
+ "description" : "(default: 48000)",
64
+ "enum" : [ 48000, 24000 ]
65
+ }
66
+ },
67
+ "required": ["input_text","model","sample_rate"],
68
+ "additionalProperties" : False,
69
+ })
70
+
71
+
72
+
73
+ async def execute(self, *, context: ToolContext, input_text: str, sample_rate: int, model: str):
74
+ tts = playai.TTS(
75
+ model=model,
76
+ sample_rate=sample_rate,
77
+ )
78
+
79
+ return await synthesize(tts, input_text)
80
+
81
+ class ElevenTextToSpeech(Tool):
82
+ def __init__(self):
83
+ super().__init__(
84
+ name="eleven_labs_text_to_speech",
85
+ title="ElevenLabs text to speech",
86
+ description="generate an audio file, converting text to speech",
87
+ input_schema={
88
+ "type" : "object",
89
+ "properties" : {
90
+ "input_text" : {
91
+ "type" : "string",
92
+ "description" : "the text to convert to speech",
93
+ },
94
+ "voice_id" : {
95
+ "type" : "string",
96
+ "description" : "the id of a voice to use (default: EXAVITQu4vr4xnSDxMaL)",
97
+ },
98
+ "voice_name" : {
99
+ "type" : "string",
100
+ "description" : "the name of the voice to use (optional)",
101
+ },
102
+ "voice_category" : {
103
+ "type" : "string",
104
+ "description" : "the category of the voice to use (optional, default: premade)",
105
+ "enum" : [
106
+ "generated", "cloned", "premade", "professional", "famous", "high_quality"
107
+ ]
108
+ },
109
+ "model" : {
110
+ "type": "string",
111
+ "description" : "(default: eleven_flash_v2_5)",
112
+ "enum" : [ "eleven_multilingual_v2", "eleven_flash_v2_5", "eleven_flash_v2", "eleven_multilingual_sts_v2", "eleven_english_sts_v2" ]
113
+ },
114
+ "encoding" : {
115
+ "type" : "string",
116
+ "description" : "(default: pcm_44100)",
117
+ "enum" : [ "pcm_44100", "mp3_22050_32" ]
118
+ }
119
+ },
120
+ "required": ["input_text","voice_id","model","encoding", "voice_name", "voice_category"],
121
+ "additionalProperties" : False,
122
+ })
123
+
124
+
125
+
126
+ async def execute(self, *, context: ToolContext, input_text: str, voice_id: str, voice_name:str, voice_category:str, model: str, encoding: str):
127
+ tts = elevenlabs.TTS(
128
+ model_id=model,
129
+ encoding=encoding,
130
+ voice=elevenlabs.Voice(id=voice_id, name=voice_name, category=voice_category)
131
+ )
132
+
133
+ return await synthesize(tts, input_text)
134
+
135
+
136
+ class CartesiaTextToSpeech(Tool):
137
+ def __init__(self):
138
+ super().__init__(
139
+ name="cartesia_text_to_speech",
140
+ title="Cartesia text to speech",
141
+ description="generate an audio file, converting text to speech",
142
+ input_schema={
143
+ "type" : "object",
144
+ "properties" : {
145
+ "input_text" : {
146
+ "type" : "string",
147
+ "description" : "the text to convert to speech",
148
+ },
149
+ "voice" : {
150
+ "type" : "string",
151
+ "description" : "the id of a voice to use (default: c2ac25f9-ecc4-4f56-9095-651354df60c0)"
152
+ },
153
+ "model" : {
154
+ "type": "string",
155
+ "description" : "(default: sonic-english)",
156
+ "enum" : [ "sonic", "sonic-preview", "sonic-2024-12-12", "sonic-2024-10-19", "sonic-english", "sonic-multilingual" ]
157
+ },
158
+ "speed" : {
159
+ "type" : "string",
160
+ "description" : "(default: normal)",
161
+ "enum" : ["fastest", "fast", "normal", "slow", "slowest" ]
162
+ },
163
+ "encoding" : {
164
+ "type" : "string",
165
+ "description" : "(default: pcm_s16le)",
166
+ "enum" : [ "pcm_s16le" ]
167
+ },
168
+ "emotion" : {
169
+ "type" : "array",
170
+ "items" : {
171
+ "type": "string",
172
+ "enum" : [
173
+ "anger:lowest",
174
+ "positivity:lowest",
175
+ "surprise:lowest",
176
+ "sadness:lowest",
177
+ "curiosity:lowest"
178
+ "anger:low",
179
+ "positivity:low",
180
+ "surprise:low",
181
+ "sadness:low",
182
+ "curiosity:low"
183
+ "anger:medium",
184
+ "positivity",
185
+ "surprise",
186
+ "sadness",
187
+ "curiosity"
188
+ "anger:high",
189
+ "positivity:high",
190
+ "surprise:high",
191
+ "sadness:high",
192
+ "curiosity:high",
193
+ "anger:highest",
194
+ "positivity:highest",
195
+ "surprise:highest",
196
+ "sadness:highest",
197
+ "curiosity:highest"
198
+
199
+ ]
200
+ }
201
+ }
202
+ },
203
+ "required": ["input_text", "voice","speed","emotion","encoding","model"],
204
+ "additionalProperties" : False,
205
+ })
206
+
207
+ async def execute(self, *, context: ToolContext, input_text: str, voice: str, model: str, speed: str, emotion: list, encoding: str):
208
+ tts = cartesia.TTS(
209
+ encoding=encoding,
210
+ model=model,
211
+ voice=voice,
212
+ emotion=emotion,
213
+ speed=speed
214
+ )
215
+
216
+ return await synthesize(tts, input_text)
217
+
218
+
219
+ class OpenAITextToSpeech(Tool):
220
+ def __init__(self):
221
+ super().__init__(
222
+ name="openai_text_to_speech",
223
+ title="OpenAI text to speech",
224
+ description="generate an audio file, converting text to speech",
225
+ input_schema={
226
+ "type" : "object",
227
+ "properties" : {
228
+ "input_text" : {
229
+ "type" : "string",
230
+ "description" : "the text to convert to speech",
231
+ },
232
+ "voice" : {
233
+ "type" : "string",
234
+ "description" : "the id of a voice to use (default: alloy)",
235
+ "enum" : [
236
+ "alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"
237
+ ]
238
+ },
239
+ "model" : {
240
+ "type": "string",
241
+ "description" : "(default: tts-1)",
242
+ "enum" : [ "tts-1", "tts-1-hd" ]
243
+ },
244
+ "speed" : {
245
+ "type" : "number",
246
+ "description" : "(default: 1.0)",
247
+ },
248
+ },
249
+ "required": ["input_text", "voice", "model", "speed"],
250
+ "additionalProperties" : False,
251
+ })
252
+
253
+ async def execute(self, *, context: ToolContext, input_text: str, voice: str, model: str, speed: float):
254
+ tts = openai.TTS(
255
+ model=model,
256
+ voice=voice,
257
+ speed=speed
258
+ )
259
+
260
+ return await synthesize(tts, input_text)
@@ -0,0 +1 @@
1
+ __version__ = "0.0.15"
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: meshagent-livekit
3
+ Version: 0.0.15
4
+ Summary: Livekit support for Meshagent
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Documentation, https://meshagent.com
7
+ Project-URL: Website, https://meshagent.com
8
+ Project-URL: Source, https://github.com/meshagent
9
+ Requires-Python: >=3.9.0
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: pytest~=8.3.5
13
+ Requires-Dist: pytest-asyncio~=0.26.0
14
+ Requires-Dist: strip-markdown~=1.3
15
+ Requires-Dist: livekit-api~=1.0.2
16
+ Requires-Dist: livekit-agents~=1.0.11
17
+ Requires-Dist: livekit-plugins-openai~=1.0.11
18
+ Requires-Dist: livekit-plugins-cartesia~=1.0.11
19
+ Requires-Dist: livekit-plugins-elevenlabs~=1.0.11
20
+ Requires-Dist: livekit-plugins-playai~=1.0.11
21
+ Requires-Dist: livekit-plugins-silero~=1.0.11
22
+ Requires-Dist: livekit-plugins-turn-detector~=1.0.11
23
+ Requires-Dist: meshagent-api~=0.0.15
24
+ Requires-Dist: meshagent-tools~=0.0.15
25
+ Dynamic: license-file
@@ -0,0 +1,12 @@
1
+ meshagent/livekit/__init__.py,sha256=8zLGg-DfQhnDl2Ky0n-zXpN-8e-g7iR0AcaI4l4Vvpk,32
2
+ meshagent/livekit/livekit_protocol.py,sha256=K9yP-qpxag5_7TXlKjFEx3cOJJJpYI_z6zGzFHoN1Hs,1421
3
+ meshagent/livekit/livekit_protocol_test.py,sha256=n_ZQjt7n4u7TM7eENzH8L0tw8LvypS_JHF_PuJ2o6h4,2836
4
+ meshagent/livekit/version.py,sha256=OpICqW3gacySIEm2aFlBiaIhB7efvBWC8Mt6amfme9M,22
5
+ meshagent/livekit/agents/transcriber.py,sha256=Dq1Ijx4gmA-0jQGM-f3w7X-JIZpkRCFDxWae9AOwz-k,12290
6
+ meshagent/livekit/agents/voice.py,sha256=g1dLF33qGQp6vex-nNhiKMpYX119u1Nsqx96kvYG0K8,5407
7
+ meshagent/livekit/tools/speech.py,sha256=UMhdHhTo04xdzHhvvCeTayT_YT86dzx4ZERRF18C0-o,10188
8
+ meshagent_livekit-0.0.15.dist-info/licenses/LICENSE,sha256=eTt0SPW-sVNdkZe9PS_S8WfCIyLjRXRl7sUBWdlteFg,10254
9
+ meshagent_livekit-0.0.15.dist-info/METADATA,sha256=NHRkl5SOE4cm6g7W3GKKESPDNWozmYjn4baUtHiLVmY,924
10
+ meshagent_livekit-0.0.15.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91
11
+ meshagent_livekit-0.0.15.dist-info/top_level.txt,sha256=GlcXnHtRP6m7zlG3Df04M35OsHtNXy_DY09oFwWrH74,10
12
+ meshagent_livekit-0.0.15.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (79.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ meshagent