|
| 1 | +# Adding metrics collection |
| 2 | + |
| 3 | +In this exercise, we'll add metrics collection to the agent. This includes stats on each components, as well as a custom stat measuring the total time for the agent to respond in audio. |
| 4 | + |
| 5 | +Step 1: Add the import to the `agent.py` file: |
| 6 | + |
| 7 | + ```python |
| 8 | + from livekit.agents import metrics, MetricsCollectedEvent, AgentStateChangedEvent |
| 9 | + ``` |
| 10 | + |
| 11 | +Step 2: Add the metrics collection to the `entrypoint` function, before the `session.start` call: |
| 12 | + |
| 13 | + ```python |
| 14 | + usage_collector = metrics.UsageCollector() |
| 15 | + last_eou_metrics: metrics.EOUMetrics | None = None |
| 16 | + |
| 17 | + @session.on("metrics_collected") |
| 18 | + def _on_metrics_collected(ev: MetricsCollectedEvent): |
| 19 | + nonlocal last_eou_metrics |
| 20 | + if ev.metrics.type == "eou_metrics": |
| 21 | + last_eou_metrics = ev.metrics |
| 22 | + |
| 23 | + metrics.log_metrics(ev.metrics) |
| 24 | + usage_collector.collect(ev.metrics) |
| 25 | + |
| 26 | + async def log_usage(): |
| 27 | + summary = usage_collector.get_summary() |
| 28 | + logger.info(f"Usage: {summary}") |
| 29 | + |
| 30 | + ctx.add_shutdown_callback(log_usage) |
| 31 | + |
| 32 | + @session.on("agent_state_changed") |
| 33 | + def _on_agent_state_changed(ev: AgentStateChangedEvent): |
| 34 | + if ( |
| 35 | + ev.new_state == "speaking" |
| 36 | + and last_eou_metrics |
| 37 | + and last_eou_metrics.speech_id == session.current_speech.id |
| 38 | + ): |
| 39 | + logger.info( |
| 40 | + f"Agent response - Time to first audio frame: {ev.created_at - last_eou_metrics.last_speaking_time}" |
| 41 | + ) |
| 42 | + ``` |
| 43 | + |
| 44 | +Now you should see real merics appear in the console when you run the agent. |
| 45 | + |
| 46 | +# Pre-emptive generation |
| 47 | + |
| 48 | +Now we'll turn on a feature to speed up handling of long messages. |
| 49 | + |
| 50 | +Add the pre-emptive generation to the `AgentSession` constructor: |
| 51 | + |
| 52 | + ```python |
| 53 | + preemptive_generation=True, |
| 54 | + ``` |
| 55 | + |
| 56 | +Compare the complete response latency before and after the change. |
| 57 | + |
| 58 | + |
| 59 | +# Optional: Langfuse tracing |
| 60 | + |
| 61 | +To add Langfuse to the agent, create an account at [Langfuse](https://langfuse.com/) and get an API key (you'll need to create an organization and a project first). |
| 62 | + |
| 63 | +Step 1: Add your keys to the `.env.local` file: |
| 64 | + |
| 65 | +``` |
| 66 | +LANGFUSE_PUBLIC_KEY= |
| 67 | +LANGFUSE_SECRET_KEY= |
| 68 | +LANGFUSE_HOST= |
| 69 | +``` |
| 70 | + |
| 71 | +Step 2: Import the telemetry modules: |
| 72 | + |
| 73 | +```python |
| 74 | +from livekit.agents.telemetry import set_tracer_provider |
| 75 | +import os |
| 76 | +import base64 |
| 77 | +``` |
| 78 | + |
| 79 | +Step 3: Define the `setup_langfuse` function in the `agent.py` file: |
| 80 | + |
| 81 | +```python |
| 82 | +def setup_langfuse( |
| 83 | + host: str | None = None, public_key: str | None = None, secret_key: str | None = None |
| 84 | +): |
| 85 | + from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter |
| 86 | + from opentelemetry.sdk.trace import TracerProvider |
| 87 | + from opentelemetry.sdk.trace.export import BatchSpanProcessor |
| 88 | + |
| 89 | + public_key = public_key or os.getenv("LANGFUSE_PUBLIC_KEY") |
| 90 | + secret_key = secret_key or os.getenv("LANGFUSE_SECRET_KEY") |
| 91 | + host = host or os.getenv("LANGFUSE_HOST") |
| 92 | + |
| 93 | + if not public_key or not secret_key or not host: |
| 94 | + raise ValueError("LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, and LANGFUSE_HOST must be set") |
| 95 | + |
| 96 | + langfuse_auth = base64.b64encode(f"{public_key}:{secret_key}".encode()).decode() |
| 97 | + os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = f"{host.rstrip('/')}/api/public/otel" |
| 98 | + os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"Authorization=Basic {langfuse_auth}" |
| 99 | + |
| 100 | + trace_provider = TracerProvider() |
| 101 | + trace_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) |
| 102 | + set_tracer_provider(trace_provider) |
| 103 | +``` |
| 104 | + |
| 105 | +Step 4: Add the `setup_langfuse` function call to the `entrypoint` function: |
| 106 | + |
| 107 | +```python |
| 108 | +async def entrypoint(ctx: JobContext): |
| 109 | + setup_langfuse() |
| 110 | +``` |
0 commit comments