|
| 1 | +import asyncio |
| 2 | +import copy |
| 3 | +import logging |
| 4 | +from collections import deque |
| 5 | +from typing import Annotated, List |
| 6 | + |
| 7 | +from livekit import agents, rtc |
| 8 | +from livekit.agents import JobContext, JobRequest, WorkerOptions, cli, tokenize, tts |
| 9 | +from livekit.agents.llm import ( |
| 10 | + ChatContext, |
| 11 | + ChatMessage, |
| 12 | + ChatRole, |
| 13 | +) |
| 14 | +from livekit.agents.voice_assistant import AssistantContext, VoiceAssistant |
| 15 | +from livekit.plugins import deepgram, openai, silero |
| 16 | + |
| 17 | +MAX_IMAGES = 3 |
| 18 | +NO_IMAGE_MESSAGE_GENERIC = ( |
| 19 | + "I'm sorry, I don't have an image to process. Are you publishing your video?" |
| 20 | +) |
| 21 | + |
| 22 | + |
| 23 | +class AssistantFnc(agents.llm.FunctionContext): |
| 24 | + @agents.llm.ai_callable( |
| 25 | + desc="Called when asked to evaluate something that would require vision capabilities." |
| 26 | + ) |
| 27 | + async def image( |
| 28 | + self, |
| 29 | + user_msg: Annotated[ |
| 30 | + str, |
| 31 | + agents.llm.TypeInfo(desc="The user message that triggered this function"), |
| 32 | + ], |
| 33 | + ): |
| 34 | + ctx = AssistantContext.get_current() |
| 35 | + ctx.store_metadata("user_msg", user_msg) |
| 36 | + |
| 37 | + |
| 38 | +async def get_human_video_track(room: rtc.Room): |
| 39 | + track_future = asyncio.Future[rtc.RemoteVideoTrack]() |
| 40 | + |
| 41 | + def on_sub(track: rtc.Track, *_): |
| 42 | + if isinstance(track, rtc.RemoteVideoTrack): |
| 43 | + track_future.set_result(track) |
| 44 | + |
| 45 | + room.on("track_subscribed", on_sub) |
| 46 | + |
| 47 | + remote_video_tracks: List[rtc.RemoteVideoTrack] = [] |
| 48 | + for _, p in room.participants.items(): |
| 49 | + for _, t_pub in p.tracks.items(): |
| 50 | + if t_pub.track is not None and isinstance( |
| 51 | + t_pub.track, rtc.RemoteVideoTrack |
| 52 | + ): |
| 53 | + remote_video_tracks.append(t_pub.track) |
| 54 | + |
| 55 | + if len(remote_video_tracks) > 0: |
| 56 | + track_future.set_result(remote_video_tracks[0]) |
| 57 | + |
| 58 | + video_track = await track_future |
| 59 | + room.off("track_subscribed", on_sub) |
| 60 | + return video_track |
| 61 | + |
| 62 | + |
| 63 | +async def entrypoint(ctx: JobContext): |
| 64 | + sip = ctx.room.name.startswith("sip") |
| 65 | + initial_ctx = ChatContext( |
| 66 | + messages=[ |
| 67 | + ChatMessage( |
| 68 | + role=ChatRole.SYSTEM, |
| 69 | + text=( |
| 70 | + "You are a funny bot created by LiveKit. Your interface with users will be voice. " |
| 71 | + "You should use short and concise responses, and avoiding usage of unpronouncable punctuation." |
| 72 | + ), |
| 73 | + ) |
| 74 | + ] |
| 75 | + ) |
| 76 | + |
| 77 | + gpt = openai.LLM( |
| 78 | + model="gpt-4o", |
| 79 | + ) |
| 80 | + |
| 81 | + # Since OpenAI does not support streaming TTS, we'll use it with a StreamAdapter |
| 82 | + # to make it compatible with the VoiceAssistant |
| 83 | + openai_tts = tts.StreamAdapter( |
| 84 | + tts=openai.TTS(voice="alloy"), |
| 85 | + sentence_tokenizer=tokenize.basic.SentenceTokenizer(), |
| 86 | + ) |
| 87 | + |
| 88 | + latest_image: rtc.VideoFrame | None = None |
| 89 | + img_msg_queue: deque[agents.llm.ChatMessage] = deque() |
| 90 | + assistant = VoiceAssistant( |
| 91 | + vad=silero.VAD(), |
| 92 | + stt=deepgram.STT(), |
| 93 | + llm=gpt, |
| 94 | + tts=openai_tts, |
| 95 | + fnc_ctx=None if sip else AssistantFnc(), |
| 96 | + chat_ctx=initial_ctx, |
| 97 | + ) |
| 98 | + |
| 99 | + chat = rtc.ChatManager(ctx.room) |
| 100 | + |
| 101 | + async def _answer_from_text(text: str): |
| 102 | + chat_ctx = copy.deepcopy(assistant.chat_context) |
| 103 | + chat_ctx.messages.append(ChatMessage(role=ChatRole.USER, text=text)) |
| 104 | + |
| 105 | + stream = await gpt.chat(chat_ctx) |
| 106 | + await assistant.say(stream) |
| 107 | + |
| 108 | + @chat.on("message_received") |
| 109 | + def on_chat_received(msg: rtc.ChatMessage): |
| 110 | + if not msg.message: |
| 111 | + return |
| 112 | + |
| 113 | + asyncio.create_task(_answer_from_text(msg.message)) |
| 114 | + |
| 115 | + async def respond_to_image(user_msg: str): |
| 116 | + nonlocal latest_image, img_msg_queue, initial_ctx |
| 117 | + if not latest_image: |
| 118 | + await assistant.say(NO_IMAGE_MESSAGE_GENERIC) |
| 119 | + return |
| 120 | + |
| 121 | + initial_ctx.messages.append( |
| 122 | + agents.llm.ChatMessage( |
| 123 | + role=agents.llm.ChatRole.USER, |
| 124 | + text=user_msg, |
| 125 | + images=[agents.llm.ChatImage(image=latest_image)], |
| 126 | + ) |
| 127 | + ) |
| 128 | + img_msg_queue.append(initial_ctx.messages[-1]) |
| 129 | + if len(img_msg_queue) >= MAX_IMAGES: |
| 130 | + msg = img_msg_queue.popleft() |
| 131 | + msg.images = [] |
| 132 | + |
| 133 | + stream = await gpt.chat(initial_ctx) |
| 134 | + await assistant.say(stream, allow_interruptions=True) |
| 135 | + |
| 136 | + @assistant.on("function_calls_finished") |
| 137 | + def _function_calls_done(ctx: AssistantContext): |
| 138 | + user_msg = ctx.get_metadata("user_msg") |
| 139 | + if not user_msg: |
| 140 | + return |
| 141 | + asyncio.ensure_future(respond_to_image(user_msg)) |
| 142 | + |
| 143 | + assistant.start(ctx.room) |
| 144 | + |
| 145 | + await asyncio.sleep(0.5) |
| 146 | + await assistant.say("Hey, how can I help you today?", allow_interruptions=True) |
| 147 | + while ctx.room.connection_state == rtc.ConnectionState.CONN_CONNECTED: |
| 148 | + video_track = await get_human_video_track(ctx.room) |
| 149 | + async for event in rtc.VideoStream(video_track): |
| 150 | + latest_image = event.frame |
| 151 | + |
| 152 | + |
| 153 | +async def request_fnc(req: JobRequest) -> None: |
| 154 | + logging.info("received request %s", req) |
| 155 | + await req.accept(entrypoint) |
| 156 | + |
| 157 | + |
| 158 | +if __name__ == "__main__": |
| 159 | + cli.run_app(WorkerOptions(request_fnc)) |
0 commit comments