livekit-plugins-callyourai 0.1.0__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.
- livekit_plugins_callyourai-0.1.0/.gitignore +3 -0
- livekit_plugins_callyourai-0.1.0/LICENSE +21 -0
- livekit_plugins_callyourai-0.1.0/PKG-INFO +62 -0
- livekit_plugins_callyourai-0.1.0/README.md +41 -0
- livekit_plugins_callyourai-0.1.0/examples/agent.py +56 -0
- livekit_plugins_callyourai-0.1.0/examples/talk_check.py +194 -0
- livekit_plugins_callyourai-0.1.0/livekit/plugins/callyourai/__init__.py +6 -0
- livekit_plugins_callyourai-0.1.0/livekit/plugins/callyourai/avatar.py +116 -0
- livekit_plugins_callyourai-0.1.0/pyproject.toml +33 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 callyour.ai
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: livekit-plugins-callyourai
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: callyour.ai avatars for LiveKit Agents: give your voice agent a face
|
|
5
|
+
Project-URL: Homepage, https://callyour.ai
|
|
6
|
+
Project-URL: Documentation, https://api.callyour.ai/llms.txt
|
|
7
|
+
Project-URL: Source, https://github.com/JonasDaWi/livekit-plugins-callyourai
|
|
8
|
+
Project-URL: Issues, https://github.com/JonasDaWi/livekit-plugins-callyourai/issues
|
|
9
|
+
Author-email: "callyour.ai" <support@callyour.ai>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: agents,avatar,lip-sync,livekit,realtime,voice
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Multimedia :: Video
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Requires-Dist: httpx>=0.27
|
|
19
|
+
Requires-Dist: livekit-agents>=1.2
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# livekit-plugins-callyourai
|
|
23
|
+
|
|
24
|
+
Give your LiveKit voice agent a face. The avatar joins the room as its own participant and speaks with the
|
|
25
|
+
agent's voice, lips in sync.
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install livekit-plugins-callyourai
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from livekit.agents import AgentSession, room_io
|
|
33
|
+
from livekit.plugins import callyourai
|
|
34
|
+
|
|
35
|
+
async def entrypoint(ctx):
|
|
36
|
+
await ctx.connect()
|
|
37
|
+
session = AgentSession(stt=..., llm=..., tts=...)
|
|
38
|
+
avatar = callyourai.AvatarSession(avatar_id="YOUR_AVATAR_ID")
|
|
39
|
+
await avatar.start(session, room=ctx.room)
|
|
40
|
+
await session.start(agent=MyAgent(), room=ctx.room,
|
|
41
|
+
room_options=room_io.RoomOptions(audio_output=False))
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
A complete agent is in `examples/agent.py`; `examples/talk_check.py` calls it without a browser and prints
|
|
45
|
+
what arrived and what was billed.
|
|
46
|
+
|
|
47
|
+
Environment: `CALLYOURAI_API_KEY`, plus the usual `LIVEKIT_URL`, `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET`.
|
|
48
|
+
|
|
49
|
+
No account yet? Three calls (full guide for people and coding agents: https://api.callyour.ai/llms.txt):
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
API=https://api.callyour.ai
|
|
53
|
+
curl -X POST $API/v1/signup -d '{"email":"you@example.com"}' -H 'content-type: application/json' # -> api_key
|
|
54
|
+
curl -X POST $API/v1/credits/checkout -H "authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"amount_usd":10}'
|
|
55
|
+
curl -X POST $API/v1/avatars -H "authorization: Bearer $KEY" -H 'content-type: application/json' \
|
|
56
|
+
-d '{"name":"Me","image_url":"https://example.com/me.jpg"}' # -> id
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Sessions are billed per second from your credits while the avatar's video is live. `CallyouraiError.code`
|
|
60
|
+
tells you why a start was refused (`insufficient_credits`, `no_capacity`, ...).
|
|
61
|
+
|
|
62
|
+
Questions: support@callyour.ai · Terms and pricing: https://callyour.ai
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# livekit-plugins-callyourai
|
|
2
|
+
|
|
3
|
+
Give your LiveKit voice agent a face. The avatar joins the room as its own participant and speaks with the
|
|
4
|
+
agent's voice, lips in sync.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pip install livekit-plugins-callyourai
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
from livekit.agents import AgentSession, room_io
|
|
12
|
+
from livekit.plugins import callyourai
|
|
13
|
+
|
|
14
|
+
async def entrypoint(ctx):
|
|
15
|
+
await ctx.connect()
|
|
16
|
+
session = AgentSession(stt=..., llm=..., tts=...)
|
|
17
|
+
avatar = callyourai.AvatarSession(avatar_id="YOUR_AVATAR_ID")
|
|
18
|
+
await avatar.start(session, room=ctx.room)
|
|
19
|
+
await session.start(agent=MyAgent(), room=ctx.room,
|
|
20
|
+
room_options=room_io.RoomOptions(audio_output=False))
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
A complete agent is in `examples/agent.py`; `examples/talk_check.py` calls it without a browser and prints
|
|
24
|
+
what arrived and what was billed.
|
|
25
|
+
|
|
26
|
+
Environment: `CALLYOURAI_API_KEY`, plus the usual `LIVEKIT_URL`, `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET`.
|
|
27
|
+
|
|
28
|
+
No account yet? Three calls (full guide for people and coding agents: https://api.callyour.ai/llms.txt):
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
API=https://api.callyour.ai
|
|
32
|
+
curl -X POST $API/v1/signup -d '{"email":"you@example.com"}' -H 'content-type: application/json' # -> api_key
|
|
33
|
+
curl -X POST $API/v1/credits/checkout -H "authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"amount_usd":10}'
|
|
34
|
+
curl -X POST $API/v1/avatars -H "authorization: Bearer $KEY" -H 'content-type: application/json' \
|
|
35
|
+
-d '{"name":"Me","image_url":"https://example.com/me.jpg"}' # -> id
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Sessions are billed per second from your credits while the avatar's video is live. `CallyouraiError.code`
|
|
39
|
+
tells you why a start was refused (`insufficient_credits`, `no_capacity`, ...).
|
|
40
|
+
|
|
41
|
+
Questions: support@callyour.ai · Terms and pricing: https://callyour.ai
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""A voice agent with a callyourai face.
|
|
2
|
+
|
|
3
|
+
export LIVEKIT_URL=... LIVEKIT_API_KEY=... LIVEKIT_API_SECRET=...
|
|
4
|
+
export CALLYOURAI_API_KEY=... CALLYOURAI_AVATAR_ID=...
|
|
5
|
+
python examples/agent.py dev
|
|
6
|
+
|
|
7
|
+
Speech-to-text, the language model and the voice run on LiveKit Inference, so no other keys are needed.
|
|
8
|
+
The agent is dispatched by name (``AGENT_NAME``, default ``callyourai-example``):
|
|
9
|
+
|
|
10
|
+
lk dispatch create --room my-room --agent-name callyourai-example
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
import os
|
|
17
|
+
|
|
18
|
+
from livekit.agents import Agent, AgentServer, AgentSession, JobContext, cli, inference
|
|
19
|
+
from livekit.agents.voice import room_io
|
|
20
|
+
from livekit.plugins import callyourai, silero
|
|
21
|
+
|
|
22
|
+
log = logging.getLogger("callyourai-example")
|
|
23
|
+
server = AgentServer()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@server.rtc_session(agent_name=os.environ.get("AGENT_NAME", "callyourai-example"))
|
|
27
|
+
async def entrypoint(ctx: JobContext) -> None:
|
|
28
|
+
await ctx.connect()
|
|
29
|
+
session = AgentSession(
|
|
30
|
+
stt=inference.STT(model="deepgram/flux-general-multi"),
|
|
31
|
+
llm=inference.LLM(model="google/gemma-4-31b-it"),
|
|
32
|
+
tts=inference.TTS(model="cartesia/sonic-3", voice="9626c31c-bec5-4cca-baa8-f8ba9e84c8bc"),
|
|
33
|
+
vad=silero.VAD.load(),
|
|
34
|
+
)
|
|
35
|
+
avatar = callyourai.AvatarSession(avatar_id=os.environ["CALLYOURAI_AVATAR_ID"])
|
|
36
|
+
try:
|
|
37
|
+
# Before session.start: the avatar takes over the agent's audio output.
|
|
38
|
+
await avatar.start(session, room=ctx.room)
|
|
39
|
+
except callyourai.CallyouraiError as error:
|
|
40
|
+
# error.code: insufficient_credits, no_capacity, avatar_not_ready, ...
|
|
41
|
+
log.error("no avatar: %s", error)
|
|
42
|
+
ctx.shutdown(reason=error.code)
|
|
43
|
+
return
|
|
44
|
+
ctx.add_shutdown_callback(avatar.aclose)
|
|
45
|
+
|
|
46
|
+
await session.start(
|
|
47
|
+
agent=Agent(instructions="You are a friendly assistant in a video call. Answer in one or two short sentences."),
|
|
48
|
+
room=ctx.room,
|
|
49
|
+
# The avatar publishes the voice; the agent must not publish it a second time.
|
|
50
|
+
room_options=room_io.RoomOptions(audio_output=False),
|
|
51
|
+
)
|
|
52
|
+
session.generate_reply(instructions="Greet the user in one short sentence.")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
if __name__ == "__main__":
|
|
56
|
+
cli.run_app(server)
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Headless check of examples/agent.py: plays the user in a call with the running agent.
|
|
2
|
+
|
|
3
|
+
Dispatches the agent into a new room, joins with a microphone track, waits for the avatar's video and the
|
|
4
|
+
greeting, asks a question from a WAV, interrupts the answer with a second WAV, closes the room and prints
|
|
5
|
+
what arrived and what was billed.
|
|
6
|
+
|
|
7
|
+
python examples/talk_check.py --agent callyourai-example --question q.wav --interrupt i.wav
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import asyncio
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import secrets
|
|
17
|
+
import subprocess
|
|
18
|
+
import time
|
|
19
|
+
|
|
20
|
+
import httpx
|
|
21
|
+
import numpy as np
|
|
22
|
+
from livekit import api, rtc
|
|
23
|
+
|
|
24
|
+
SR = 48_000
|
|
25
|
+
LOUD = 600
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def load(path: str) -> np.ndarray:
|
|
29
|
+
out = subprocess.run(
|
|
30
|
+
["ffmpeg", "-loglevel", "error", "-i", path, "-f", "s16le", "-ac", "1", "-ar", str(SR), "-"],
|
|
31
|
+
capture_output=True, check=True,
|
|
32
|
+
).stdout # fmt: skip
|
|
33
|
+
return np.frombuffer(out, dtype=np.int16)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
async def play(source: rtc.AudioSource, pcm: np.ndarray | None, seconds: float = 0.0) -> None:
|
|
37
|
+
"""Send ``pcm`` (or ``seconds`` of silence) as 10 ms frames in real time."""
|
|
38
|
+
n = SR // 100
|
|
39
|
+
if pcm is None:
|
|
40
|
+
pcm = np.zeros(int(seconds * SR), np.int16)
|
|
41
|
+
start = time.monotonic()
|
|
42
|
+
for i in range(0, len(pcm), n):
|
|
43
|
+
chunk = pcm[i : i + n]
|
|
44
|
+
if len(chunk) < n:
|
|
45
|
+
chunk = np.concatenate([chunk, np.zeros(n - len(chunk), np.int16)])
|
|
46
|
+
await source.capture_frame(rtc.AudioFrame(chunk.tobytes(), SR, 1, n))
|
|
47
|
+
delay = start + (i + n) / SR - time.monotonic()
|
|
48
|
+
if delay > 0:
|
|
49
|
+
await asyncio.sleep(delay)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
async def main() -> int:
|
|
53
|
+
ap = argparse.ArgumentParser()
|
|
54
|
+
ap.add_argument("--agent", default="callyourai-example")
|
|
55
|
+
ap.add_argument("--room-prefix", default="callyourai-check-")
|
|
56
|
+
ap.add_argument("--question", required=True)
|
|
57
|
+
ap.add_argument("--interrupt", required=True)
|
|
58
|
+
args = ap.parse_args()
|
|
59
|
+
url, key, secret = (os.environ[k] for k in ("LIVEKIT_URL", "LIVEKIT_API_KEY", "LIVEKIT_API_SECRET"))
|
|
60
|
+
base = os.environ.get("CALLYOURAI_API_URL", "https://api.callyour.ai")
|
|
61
|
+
headers = {"authorization": f"Bearer {os.environ['CALLYOURAI_API_KEY']}"}
|
|
62
|
+
room_name = args.room_prefix + secrets.token_hex(3)
|
|
63
|
+
async with httpx.AsyncClient() as http:
|
|
64
|
+
before = (await http.get(f"{base}/v1/balance", headers=headers)).json()
|
|
65
|
+
|
|
66
|
+
lk = api.LiveKitAPI(url, key, secret)
|
|
67
|
+
await lk.agent_dispatch.create_dispatch(api.CreateAgentDispatchRequest(agent_name=args.agent, room=room_name))
|
|
68
|
+
token = (
|
|
69
|
+
api.AccessToken(key, secret).with_identity("user-check")
|
|
70
|
+
.with_grants(api.VideoGrants(room_join=True, room=room_name)).to_jwt()
|
|
71
|
+
) # fmt: skip
|
|
72
|
+
|
|
73
|
+
room = rtc.Room()
|
|
74
|
+
frames: list[float] = []
|
|
75
|
+
size: list[tuple[int, int]] = []
|
|
76
|
+
audio: list[tuple[float, int]] = [] # arrival time, peak
|
|
77
|
+
tracks: list[dict] = []
|
|
78
|
+
t0 = time.monotonic()
|
|
79
|
+
|
|
80
|
+
async def watch_video(track: rtc.Track) -> None:
|
|
81
|
+
async for event in rtc.VideoStream(track):
|
|
82
|
+
frames.append(time.monotonic() - t0)
|
|
83
|
+
size[:] = [(event.frame.width, event.frame.height)]
|
|
84
|
+
|
|
85
|
+
async def watch_audio(track: rtc.Track) -> None:
|
|
86
|
+
async for event in rtc.AudioStream(track, sample_rate=16000, num_channels=1):
|
|
87
|
+
audio.append((time.monotonic() - t0, int(np.abs(np.frombuffer(event.frame.data, np.int16)).max())))
|
|
88
|
+
|
|
89
|
+
tasks: list[asyncio.Task] = []
|
|
90
|
+
|
|
91
|
+
def on_track(track: rtc.Track, _pub, participant: rtc.RemoteParticipant) -> None:
|
|
92
|
+
video = track.kind == rtc.TrackKind.KIND_VIDEO
|
|
93
|
+
tracks.append({
|
|
94
|
+
"kind": "video" if video else "audio", "from": participant.identity,
|
|
95
|
+
"on_behalf_of": participant.attributes.get("lk.publish_on_behalf"),
|
|
96
|
+
}) # fmt: skip
|
|
97
|
+
tasks.append(asyncio.create_task((watch_video if video else watch_audio)(track)))
|
|
98
|
+
|
|
99
|
+
room.on("track_subscribed", on_track)
|
|
100
|
+
await room.connect(url, token)
|
|
101
|
+
source = rtc.AudioSource(SR, 1)
|
|
102
|
+
await room.local_participant.publish_track(
|
|
103
|
+
rtc.LocalAudioTrack.create_audio_track("mic", source),
|
|
104
|
+
rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_MICROPHONE),
|
|
105
|
+
)
|
|
106
|
+
mic = asyncio.create_task(play(source, None, 600)) # silence until we speak
|
|
107
|
+
|
|
108
|
+
def loud_since(t: float) -> float | None:
|
|
109
|
+
return next((at for at, peak in audio if at >= t and peak > LOUD), None)
|
|
110
|
+
|
|
111
|
+
def quiet_for(seconds: float) -> bool:
|
|
112
|
+
now = time.monotonic() - t0
|
|
113
|
+
recent = [peak for at, peak in audio if at > now - seconds]
|
|
114
|
+
return bool(recent) and max(recent) < LOUD
|
|
115
|
+
|
|
116
|
+
report: dict = {"room": room_name}
|
|
117
|
+
deadline = time.monotonic() + 180
|
|
118
|
+
while not frames and time.monotonic() < deadline:
|
|
119
|
+
await asyncio.sleep(0.1)
|
|
120
|
+
if not frames:
|
|
121
|
+
report["error"] = "no video"
|
|
122
|
+
else:
|
|
123
|
+
report["video_after_s"] = round(frames[0], 2)
|
|
124
|
+
greet = None
|
|
125
|
+
while time.monotonic() < deadline and greet is None:
|
|
126
|
+
greet = loud_since(0)
|
|
127
|
+
await asyncio.sleep(0.1)
|
|
128
|
+
report["greeting_after_s"] = None if greet is None else round(greet, 2)
|
|
129
|
+
while time.monotonic() < deadline and not quiet_for(1.5):
|
|
130
|
+
await asyncio.sleep(0.1)
|
|
131
|
+
|
|
132
|
+
mic.cancel()
|
|
133
|
+
await play(source, load(args.question))
|
|
134
|
+
asked = time.monotonic() - t0
|
|
135
|
+
mic = asyncio.create_task(play(source, None, 600))
|
|
136
|
+
answer = None
|
|
137
|
+
while time.monotonic() < deadline and answer is None:
|
|
138
|
+
answer = loud_since(asked)
|
|
139
|
+
await asyncio.sleep(0.05)
|
|
140
|
+
report["response_s"] = None if answer is None else round(answer - asked, 2)
|
|
141
|
+
await asyncio.sleep(2.5) # let it talk, then interrupt
|
|
142
|
+
mic.cancel()
|
|
143
|
+
interrupt_at = time.monotonic() - t0
|
|
144
|
+
await play(source, load(args.interrupt))
|
|
145
|
+
said = time.monotonic() - t0
|
|
146
|
+
mic = asyncio.create_task(play(source, None, 600))
|
|
147
|
+
# When did the first answer stop? The first 0.6 s quiet window after the interruption began.
|
|
148
|
+
stopped = None
|
|
149
|
+
while time.monotonic() - t0 < said + 15 and stopped is None:
|
|
150
|
+
await asyncio.sleep(0.1)
|
|
151
|
+
times = [(at, peak) for at, peak in audio if at >= interrupt_at]
|
|
152
|
+
for at, _ in times:
|
|
153
|
+
window = [peak for a, peak in times if at <= a < at + 0.6]
|
|
154
|
+
if window and max(window) < LOUD and times[-1][0] > at + 0.6:
|
|
155
|
+
stopped = at
|
|
156
|
+
break
|
|
157
|
+
report["kept_talking_after_interrupt_s"] = None if stopped is None else round(stopped - interrupt_at, 2)
|
|
158
|
+
second = None
|
|
159
|
+
while time.monotonic() - t0 < said + 30 and second is None:
|
|
160
|
+
second = loud_since(said + 0.3)
|
|
161
|
+
await asyncio.sleep(0.05)
|
|
162
|
+
report["second_response_s"] = None if second is None else round(second - said, 2)
|
|
163
|
+
await asyncio.sleep(6)
|
|
164
|
+
steady = [at for at in frames if at > frames[0] + 2]
|
|
165
|
+
gaps = np.diff(frames)
|
|
166
|
+
report["fps_received"] = round((len(steady) - 1) / (steady[-1] - steady[0]), 1) if len(steady) > 2 else None
|
|
167
|
+
report["max_frame_gap_ms"] = round(float(gaps.max()) * 1000) if len(gaps) else None
|
|
168
|
+
report["size"] = size[0] if size else None
|
|
169
|
+
report["video_seconds"] = round(frames[-1] - frames[0], 1)
|
|
170
|
+
report["tracks"] = tracks
|
|
171
|
+
mic.cancel()
|
|
172
|
+
await room.disconnect()
|
|
173
|
+
for task in tasks:
|
|
174
|
+
task.cancel()
|
|
175
|
+
try:
|
|
176
|
+
await lk.room.delete_room(api.DeleteRoomRequest(room=room_name)) # the agent leaves, the avatar session ends
|
|
177
|
+
except api.TwirpError:
|
|
178
|
+
pass
|
|
179
|
+
await lk.aclose()
|
|
180
|
+
|
|
181
|
+
await asyncio.sleep(8)
|
|
182
|
+
async with httpx.AsyncClient() as http:
|
|
183
|
+
after = (await http.get(f"{base}/v1/balance", headers=headers)).json()
|
|
184
|
+
usage = (await http.get(f"{base}/v1/usage", headers=headers)).json()
|
|
185
|
+
report["balance_before_usd"] = before.get("balance_usd")
|
|
186
|
+
report["balance_after_usd"] = after.get("balance_usd")
|
|
187
|
+
report["available_after_usd"] = after.get("available_usd")
|
|
188
|
+
report["usage"] = usage
|
|
189
|
+
print(json.dumps(report, indent=1), flush=True)
|
|
190
|
+
return 0 if frames else 1
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
if __name__ == "__main__":
|
|
194
|
+
raise SystemExit(asyncio.run(main()))
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Give a LiveKit voice agent a face.
|
|
2
|
+
|
|
3
|
+
from livekit.plugins import callyourai
|
|
4
|
+
|
|
5
|
+
avatar = callyourai.AvatarSession(avatar_id="...") # CALLYOURAI_API_KEY in the environment
|
|
6
|
+
await avatar.start(session, room=ctx.room) # before session.start(...)
|
|
7
|
+
await session.start(agent=..., room=ctx.room, room_options=RoomOptions(audio_output=False))
|
|
8
|
+
|
|
9
|
+
The avatar joins the room as its own participant and publishes video plus the agent's voice, in sync.
|
|
10
|
+
The agent's speech goes to it as a data stream instead of being published by the agent itself.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
from livekit import api, rtc
|
|
19
|
+
from livekit.agents import AgentSession
|
|
20
|
+
from livekit.agents.types import ATTRIBUTE_PUBLISH_ON_BEHALF
|
|
21
|
+
from livekit.agents.voice.avatar import DataStreamAudioOutput
|
|
22
|
+
|
|
23
|
+
DEFAULT_API_URL = "https://api.callyour.ai"
|
|
24
|
+
MOOD_ATTRIBUTE = "callyourai.mood"
|
|
25
|
+
SAMPLE_RATE = 16000
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class CallyouraiError(Exception):
|
|
29
|
+
"""The API refused a request. ``code`` is e.g. ``insufficient_credits`` or ``no_capacity``."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, status: int, code: str, message: str) -> None:
|
|
32
|
+
super().__init__(f"{message} ({code}, HTTP {status})")
|
|
33
|
+
self.status, self.code, self.message = status, code, message
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class AvatarSession:
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
*,
|
|
40
|
+
avatar_id: str,
|
|
41
|
+
api_key: str | None = None,
|
|
42
|
+
api_url: str | None = None,
|
|
43
|
+
avatar_participant_identity: str = "callyourai-avatar",
|
|
44
|
+
avatar_participant_name: str = "Avatar",
|
|
45
|
+
max_minutes: float | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
self._avatar_id = avatar_id
|
|
48
|
+
self._api_key = api_key or os.environ.get("CALLYOURAI_API_KEY")
|
|
49
|
+
if not self._api_key:
|
|
50
|
+
raise ValueError("pass api_key or set CALLYOURAI_API_KEY")
|
|
51
|
+
self._api_url = (api_url or os.environ.get("CALLYOURAI_API_URL") or DEFAULT_API_URL).rstrip("/")
|
|
52
|
+
self._identity = avatar_participant_identity
|
|
53
|
+
self._name = avatar_participant_name
|
|
54
|
+
self._max_minutes = max_minutes
|
|
55
|
+
self._room: rtc.Room | None = None
|
|
56
|
+
self.session_id: str | None = None
|
|
57
|
+
|
|
58
|
+
async def _call(self, method: str, path: str, body: dict | None = None) -> dict:
|
|
59
|
+
async with httpx.AsyncClient(timeout=30) as http:
|
|
60
|
+
response = await http.request(
|
|
61
|
+
method, self._api_url + path, json=body, headers={"authorization": f"Bearer {self._api_key}"}
|
|
62
|
+
)
|
|
63
|
+
if response.status_code >= 400:
|
|
64
|
+
try:
|
|
65
|
+
error = response.json()["error"]
|
|
66
|
+
raise CallyouraiError(response.status_code, error["code"], error["message"])
|
|
67
|
+
except (ValueError, KeyError, TypeError):
|
|
68
|
+
raise CallyouraiError(response.status_code, "http_error", response.text[:200]) from None
|
|
69
|
+
return response.json()
|
|
70
|
+
|
|
71
|
+
async def start(
|
|
72
|
+
self,
|
|
73
|
+
agent_session: AgentSession,
|
|
74
|
+
room: rtc.Room,
|
|
75
|
+
*,
|
|
76
|
+
livekit_url: str | None = None,
|
|
77
|
+
livekit_api_key: str | None = None,
|
|
78
|
+
livekit_api_secret: str | None = None,
|
|
79
|
+
) -> None:
|
|
80
|
+
"""Bring the avatar into ``room`` and route the agent's speech to it."""
|
|
81
|
+
url = livekit_url or os.environ["LIVEKIT_URL"]
|
|
82
|
+
key = livekit_api_key or os.environ["LIVEKIT_API_KEY"]
|
|
83
|
+
secret = livekit_api_secret or os.environ["LIVEKIT_API_SECRET"]
|
|
84
|
+
token = (
|
|
85
|
+
api.AccessToken(key, secret)
|
|
86
|
+
.with_kind("agent")
|
|
87
|
+
.with_identity(self._identity)
|
|
88
|
+
.with_name(self._name)
|
|
89
|
+
.with_grants(api.VideoGrants(room_join=True, room=room.name))
|
|
90
|
+
# The avatar's tracks count as the agent's own for the user's client.
|
|
91
|
+
.with_attributes({ATTRIBUTE_PUBLISH_ON_BEHALF: room.local_participant.identity})
|
|
92
|
+
.to_jwt()
|
|
93
|
+
)
|
|
94
|
+
body = {"avatar_id": self._avatar_id, "livekit_url": url, "livekit_token": token}
|
|
95
|
+
if self._max_minutes:
|
|
96
|
+
body["max_minutes"] = self._max_minutes
|
|
97
|
+
self.session_id = (await self._call("POST", "/v1/sessions", body))["session_id"]
|
|
98
|
+
self._room = room
|
|
99
|
+
agent_session.output.audio = DataStreamAudioOutput(
|
|
100
|
+
room=room,
|
|
101
|
+
destination_identity=self._identity,
|
|
102
|
+
sample_rate=SAMPLE_RATE,
|
|
103
|
+
wait_remote_track=rtc.TrackKind.KIND_VIDEO,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
async def set_mood(self, mood: str) -> None:
|
|
107
|
+
"""The face for what the agent says next (premium avatars): neutral, friendly, happy, laughing,
|
|
108
|
+
thoughtful, empathetic, surprised or serious."""
|
|
109
|
+
if self._room is not None:
|
|
110
|
+
await self._room.local_participant.set_attributes({MOOD_ATTRIBUTE: mood})
|
|
111
|
+
|
|
112
|
+
async def aclose(self) -> None:
|
|
113
|
+
"""End the avatar session now. It also ends by itself when the agent leaves the room."""
|
|
114
|
+
if self.session_id is not None:
|
|
115
|
+
session_id, self.session_id = self.session_id, None
|
|
116
|
+
await self._call("DELETE", f"/v1/sessions/{session_id}")
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "livekit-plugins-callyourai"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "callyour.ai avatars for LiveKit Agents: give your voice agent a face"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [{ name = "callyour.ai", email = "support@callyour.ai" }]
|
|
10
|
+
keywords = ["livekit", "agents", "avatar", "voice", "realtime", "lip-sync"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Intended Audience :: Developers",
|
|
13
|
+
"Programming Language :: Python :: 3",
|
|
14
|
+
"Topic :: Multimedia :: Video",
|
|
15
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
16
|
+
]
|
|
17
|
+
dependencies = ["livekit-agents>=1.2", "httpx>=0.27"]
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Homepage = "https://callyour.ai"
|
|
21
|
+
Documentation = "https://api.callyour.ai/llms.txt"
|
|
22
|
+
Source = "https://github.com/JonasDaWi/livekit-plugins-callyourai"
|
|
23
|
+
Issues = "https://github.com/JonasDaWi/livekit-plugins-callyourai/issues"
|
|
24
|
+
|
|
25
|
+
[build-system]
|
|
26
|
+
requires = ["hatchling>=1.26"]
|
|
27
|
+
build-backend = "hatchling.build"
|
|
28
|
+
|
|
29
|
+
[tool.hatch.build.targets.wheel]
|
|
30
|
+
packages = ["livekit"]
|
|
31
|
+
|
|
32
|
+
[tool.hatch.build.targets.sdist]
|
|
33
|
+
include = ["livekit", "examples", "README.md", "LICENSE"]
|