adorable-queen-87583
09/23/2025, 4:32 PM# src/agent.py
import asyncio
import os
from dotenv import load_dotenv
from livekit.agents import (
Agent,
AgentSession,
AutoSubscribe,
JobContext,
MetricsCollectedEvent,
WorkerOptions,
WorkerType,
cli,
function_tool,
get_job_context,
metrics,
)
from livekit.plugins import azure, bey, deepgram, elevenlabs, google, openai, silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel
load_dotenv(dotenv_path=".env")
# Step 1: Create a class to encapsulate your agent's tools.
# This makes it easy to manage state and dependencies like 'session' and 'ctx'.
class HRScreeningAgent(Agent):
def __init__(self):
super().__init__(
instructions=""" INSTRUCTIONS """
)
self.ctx = get_job_context()
async def on_enter(self) -> None:
await self.session.generate_reply(
instructions=" GREETINGS "
)
@function_tool
async def end_screening_call(self) -> str:
"""
Called to end the screening call. This is the mandatory final action.
Your response MUST include a call to this function tool after the closing text is delivered.
Do not end the conversation without calling this function tool.
"""
try:
print("AI agent has decided to end the call.")
# This is the key change. We create a background task for the shutdown.
# This allows the tool to return immediately, unblocking the main loop.
async def _drain_and_shutdown():
# Let the current turn's TTS play out
await self.session.drain()
self.ctx.shutdown()
print("Final conversation history:")
print(self.session.history.to_dict())
print("Call ended successfully after TTS.")
# Schedule the task to run in the background
asyncio.create_task(_drain_and_shutdown())
return None
except Exception as e:
print(f"An error occurred while trying to end the call: {e}")
return "Unable to end interview automatically. Please disconnect manually."
async def entrypoint(ctx: JobContext):
"""
This function is the entrypoint for the agent.
It's called when a new job is assigned to this worker.
"""
# Initialize the plugins with desired configurations
google_stt = google.STT(
languages=["en-US"],
use_streaming=True,
credentials_file=os.getenv("GOOGLE_APPLICATION_CREDENTIALS"),
)
deepgram_stt = deepgram.STT(
language="en-IN",
api_key=os.getenv("DEEPGRAM_LIVEKIT_API_KEY"),
)
azure_stt = azure.STT(
language="en-IN",
speech_key=os.getenv("AZURE_EAST_US2_SPEECH_KEY"),
speech_endpoint=os.getenv("AZURE_EAST_US2_SPEECH_ENDPOINT"),
)
google_tts = google.TTS(
gender="female",
voice_name="en-US-Chirp3-HD-Kore",
credentials_file=os.getenv("GOOGLE_APPLICATION_CREDENTIALS"),
)
google_llm = google.LLM(
model="gemini-2.5-flash",
vertexai=True,
location="global",
)
azure_llm = openai.LLM.with_azure(
azure_deployment="gpt-4o-mini",
azure_endpoint=os.getenv("NORTH_CENTRAL_US_CLIENT_ENDPOINT").strip(),
api_key=os.getenv("NORTH_CENTRAL_US_CLIENT_KEY").strip(),
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
temperature=0.7,
tool_choice="auto",
)
eleven_tts = elevenlabs.TTS(
voice_id="voice_id",
)
vad = silero.VAD.load()
turn_detector_plugin = MultilingualModel()
# Create the AgentSession to orchestrate the conversation
session = AgentSession(
vad=vad,
stt=deepgram_stt,
llm=azure_llm,
tts=google_tts,
turn_detection=turn_detector_plugin,
false_interruption_timeout=0.5,
)
avatar_id = os.getenv("BEY_AVATAR_ID").replace("\n", "")
bey_avatar = bey.AvatarSession(avatar_id=avatar_id)
# Metrics collection
usage_collector = metrics.UsageCollector()
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
metrics.log_metrics(ev.metrics)
usage_collector.collect(ev.metrics)
async def log_usage():
summary = usage_collector.get_summary()
print(f"Usage: {summary}")
ctx.add_shutdown_callback(log_usage)
# Connect to the LiveKit room and start the session
await ctx.connect(auto_subscribe=AutoSubscribe.SUBSCRIBE_ALL)
await bey_avatar.start(room=ctx.room, agent_session=session)
await session.start(room=ctx.room, agent=HRScreeningAgent())
if __name__ == "__main__":
# Run the agent worker using the CLI
cli.run_app(
WorkerOptions(
entrypoint_fnc=entrypoint,
worker_type=WorkerType.ROOM,
agent_name="hr_agent",
)
)