{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9c0f00fa-cdef-4c61-8a29-0be5e89094d2",
   "metadata": {
    "id": "WMGxBP-yQoCl"
   },
   "source": [
    "# Lesson 5: Optimizing Latency"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff93fce1-daa4-4d3f-814b-8d0eb794f0e0",
   "metadata": {},
   "source": [
    "<div style=\"background-color:#fff6ff; padding:13px; border-width:3px; border-color:#efe6ef; border-style:solid; border-radius:6px\">\n",
    "<p> 💻 &nbsp; <b>Access <code>requirements.txt</code>:</b> 1) click on the <em>\"File\"</em> option on the top menu of the notebook and then 2) click on <em>\"Open\"</em>.\n",
    "\n",
    "<p> ⬇ &nbsp; <b>Download Notebooks:</b> 1) click on the <em>\"File\"</em> option on the top menu of the notebook and then 2) click on <em>\"Download as\"</em> and select <em>\"Notebook (.ipynb)\"</em>.</p>\n",
    "\n",
    "<p> 📒 &nbsp; For more help, please see the <em>\"Appendix – Tips, Help, and Download\"</em> Lesson.</p>\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "25da26c4-c2c2-4042-922e-1a5892b31340",
   "metadata": {},
   "source": [
    "<p style=\"background-color:#f7fff8; padding:15px; border-width:3px; border-color:#e0f0e0; border-style:solid; border-radius:6px\"> 🚨\n",
    "&nbsp; <b>Different Run Results:</b> The output generated by AI models can vary with each execution due to their dynamic, probabilistic nature. Don't be surprised if your results differ from those shown in the video.</p>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e909a34-31f1-4e90-a142-8870a6c24180",
   "metadata": {},
   "source": [
    "## Step 1: Import LiveKit Agent Modules and Plugins"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "512fe011-1747-495b-9351-286b4e2f5c53",
   "metadata": {
    "height": 334
   },
   "outputs": [],
   "source": [
    "import logging\n",
    "\n",
    "from dotenv import load_dotenv\n",
    "_ = load_dotenv(override=True)\n",
    "\n",
    "logger = logging.getLogger(\"dlai-agent\")\n",
    "logger.setLevel(logging.INFO)\n",
    "\n",
    "from livekit import agents\n",
    "from livekit.agents import Agent, AgentSession, JobContext, WorkerOptions, jupyter\n",
    "from livekit.plugins import (\n",
    "    openai,\n",
    "    elevenlabs,\n",
    "    silero,\n",
    ")\n",
    "\n",
    "from livekit.agents.metrics import LLMMetrics, STTMetrics, TTSMetrics, EOUMetrics\n",
    "import asyncio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e00efd4-d48d-4dac-b629-ab6a4c198b73",
   "metadata": {
    "height": 1099
   },
   "outputs": [],
   "source": [
    "class MetricsAgent(Agent):\n",
    "    def __init__(self) -> None:\n",
    "        llm = openai.LLM(model=\"gpt-4o\")\n",
    "        #llm = openai.LLM(model=\"gpt-4o-mini\")   # Example with lower latency\n",
    "        stt = openai.STT(model=\"whisper-1\")\n",
    "        tts = elevenlabs.TTS()\n",
    "        silero_vad = silero.VAD.load()\n",
    "        \n",
    "        super().__init__(\n",
    "            instructions=\"You are a helpful assistant communicating via voice\",\n",
    "            stt=stt,\n",
    "            llm=llm,\n",
    "            tts=tts,\n",
    "            vad=silero_vad,\n",
    "        )\n",
    "\n",
    "        def llm_metrics_wrapper(metrics: LLMMetrics):\n",
    "            asyncio.create_task(self.on_llm_metrics_collected(metrics))\n",
    "        llm.on(\"metrics_collected\", llm_metrics_wrapper)\n",
    "\n",
    "        def stt_metrics_wrapper(metrics: STTMetrics):\n",
    "            asyncio.create_task(self.on_stt_metrics_collected(metrics))\n",
    "        stt.on(\"metrics_collected\", stt_metrics_wrapper)\n",
    "\n",
    "        def eou_metrics_wrapper(metrics: EOUMetrics):\n",
    "            asyncio.create_task(self.on_eou_metrics_collected(metrics))\n",
    "        stt.on(\"eou_metrics_collected\", eou_metrics_wrapper)\n",
    "\n",
    "        def tts_metrics_wrapper(metrics: TTSMetrics):\n",
    "            asyncio.create_task(self.on_tts_metrics_collected(metrics))\n",
    "        tts.on(\"metrics_collected\", tts_metrics_wrapper)\n",
    "\n",
    "    async def on_llm_metrics_collected(self, metrics: LLMMetrics) -> None:\n",
    "        print(\"\\n--- LLM Metrics ---\")\n",
    "        print(f\"Prompt Tokens: {metrics.prompt_tokens}\")\n",
    "        print(f\"Completion Tokens: {metrics.completion_tokens}\")\n",
    "        print(f\"Tokens per second: {metrics.tokens_per_second:.4f}\")\n",
    "        print(f\"TTFT: {metrics.ttft:.4f}s\")\n",
    "        print(\"------------------\\n\")\n",
    "\n",
    "    async def on_stt_metrics_collected(self, metrics: STTMetrics) -> None:\n",
    "        print(\"\\n--- STT Metrics ---\")\n",
    "        print(f\"Duration: {metrics.duration:.4f}s\")\n",
    "        print(f\"Audio Duration: {metrics.audio_duration:.4f}s\")\n",
    "        print(f\"Streamed: {'Yes' if metrics.streamed else 'No'}\")\n",
    "        print(\"------------------\\n\")\n",
    "\n",
    "    async def on_eou_metrics_collected(self, metrics: EOUMetrics) -> None:\n",
    "        print(\"\\n--- End of Utterance Metrics ---\")\n",
    "        print(f\"End of Utterance Delay: {metrics.end_of_utterance_delay:.4f}s\")\n",
    "        print(f\"Transcription Delay: {metrics.transcription_delay:.4f}s\")\n",
    "        print(\"--------------------------------\\n\")\n",
    "\n",
    "    async def on_tts_metrics_collected(self, metrics: TTSMetrics) -> None:\n",
    "        print(\"\\n--- TTS Metrics ---\")\n",
    "        print(f\"TTFB: {metrics.ttfb:.4f}s\")\n",
    "        print(f\"Duration: {metrics.duration:.4f}s\")\n",
    "        print(f\"Audio Duration: {metrics.audio_duration:.4f}s\")\n",
    "        print(f\"Streamed: {'Yes' if metrics.streamed else 'No'}\")\n",
    "        print(\"------------------\\n\")\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f58e827a-8e2e-4f1d-8f8c-9486828f951d",
   "metadata": {
    "height": 183
   },
   "outputs": [],
   "source": [
    "async def entrypoint(ctx: JobContext):\n",
    "    await ctx.connect()\n",
    "\n",
    "    session = AgentSession()\n",
    "\n",
    "    await session.start(\n",
    "        agent=MetricsAgent(),\n",
    "        room=ctx.room,\n",
    "    )\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8e3528e-d363-442c-96b1-fc146327341d",
   "metadata": {},
   "source": [
    "- To speak to the agent, unmute the microphone symbol on the left. You can ignore the 'Start Audio' button.\n",
    "- The agent will try to detect the language you are speaking. To help it, start by speaking a long phrase like \"hello, how are you today\" in the language of your choice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5dbcacb-b143-46d5-a649-27c0eb3b5cf6",
   "metadata": {
    "height": 45
   },
   "outputs": [],
   "source": [
    "jupyter.run_app(WorkerOptions(entrypoint_fnc=entrypoint), jupyter_url=\"https://jupyter-api-livekit.vercel.app/api/join-token\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4f3fb812-e7f8-4a5b-9923-ed5686b3884d",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "335ae558-f8da-43f3-b1f5-2b6e2f163ff9",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
