import logging from dotenv import load_dotenv _ = ...
# agents
l
import logging from dotenv import load_dotenv _ = load_dotenv(override=True) logger = logging.getLogger("dlai-agent") logger.setLevel(logging.INFO) from livekit.agents import ConversationItemAddedEvent from livekit import api, rtc from datetime import datetime, date, timedelta from livekit.agents.llm import ChatMessage from functionTool import add_schedule,query_company_knowledge,update_schedule,fetch_user_schedule # from livekit.plugins.turn_detector.multilingual import MultilingualModel from livekit.agents import ( Agent, AgentSession, function_tool, JobContext, ChatContext, WorkerOptions, cli, BackgroundAudioPlayer, AudioConfig, BuiltinAudioClip, RoomInputOptions , RoomOutputOptions, RunContext ) from livekit.agents.job import get_job_context from livekit.agents.metrics import LLMMetrics, STTMetrics, TTSMetrics, EOUMetrics from livekit.plugins import ( elevenlabs, silero, groq, noise_cancellation ) time = datetime.now() date = date.today() day = datetime.today().strftime("%A") class Assistant(Agent): def __init__(self) -> None: llm = groq.LLM(model="deepseek-r1-distill-llama-70b",api_key="") stt = groq.STT(model="whisper-large-v3") tts = elevenlabs.TTS(voice_id="CwhRBWXzGAHq8TQ4Fs17") silero_vad = silero.VAD.load() initial_ctx = ChatContext() super().__init__( instructions=f""" """ , stt=stt, llm=llm, tts=tts, vad=silero_vad, turn_detection='vad', allow_interruptions=True, tools=[query_company_knowledge, add_schedule, update_schedule,fetch_user_schedule], chat_ctx=initial_ctx, ) async def on_enter(self): # The agent should be polite and greet the user when it joins :) self.session.generate_reply( instructions="Greet the user with a warm welcome like welcome to ", allow_interruptions=False ) async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None: logger.info(f"User turn completed: {new_message.content}") if self.session.userdata: search_ctx = ChatContext([ ChatMessage( type="message", role="system", content=[""" """] ), ChatMessage(type="message", role="user", content=[f"The user says: {new_message.content}"]) ]) response = "" async with self.fast_llm.chat(chat_ctx=search_ctx) as stream: async for chunk in stream: if not chunk: continue content = getattr(chunk.delta, 'content', None) if hasattr(chunk, 'delta') else str(chunk) if content: response += content self.session.say(response.strip()) return await super().on_user_turn_completed(turn_ctx, new_message) # @function_tool # async def say_goodbye(self, context: RunContext): # """When the user want to end the conversation""" # # interrupt any existing generation # self.session.interrupt() # # generate a goodbye message and hang up # # awaiting it will ensure the message is played out before returning # await self.session.generate_reply( # instructions=f"say goodbye to the user", allow_interruptions=False # ) # job_ctx = get_job_context() # await job_ctx.api.room.delete_room(api.DeleteRoomRequest(room=job_ctx.room.name)) async def entrypoint(ctx: JobContext): ctx.log_context_fields = { "room": ctx.room.name, "user_id": "45", } await ctx.connect() session = AgentSession(allow_interruptions=True) @session.on("conversation_item_added") def on_conversation_item_added(event: ConversationItemAddedEvent): print( f"Conversation item added from {event.item.role}: {event.item.text_content}. interrupted: {event.item.interrupted}" ) background_audio = BackgroundAudioPlayer( ambient_sound=AudioConfig(BuiltinAudioClip.OFFICE_AMBIENCE, volume=0.8), thinking_sound=[ AudioConfig(BuiltinAudioClip.KEYBOARD_TYPING, volume=0.8), AudioConfig(BuiltinAudioClip.KEYBOARD_TYPING2, volume=0.7), ], ) try: await session.start( room=ctx.room, agent=Assistant(), room_input_options=RoomInputOptions(audio_enabled=True,noise_cancellation=noise_cancellation.BVC(),), room_output_options=RoomOutputOptions(transcription_enabled=True,) # room_input_options=room_io.RoomInputOptions( # noise_cancellation=noise_cancellation.BVC(), # ) ) await background_audio.start(room=ctx.room, agent_session=session,) except Exception as e: await background_audio.aclose() finally: await background_audio.aclose() if name == "__main__": cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint)) help me to improve the code what type of mistake i made try to guide me facing issue on voice to text , it make irrelevant text some time
r
Please keep your request in the main channel concise and attach code files in a thread. This will make it easier for folks to see the other requests in the channel. Here is a good guide to review for Community Slack Etiquette https://kb.livekit.io/articles/6742638954-slack-etiquette