|
| 1 | +// SPDX-FileCopyrightText: 2026 LiveKit, Inc. |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: Apache-2.0 |
| 4 | +import { |
| 5 | + type JobContext, |
| 6 | + ServerOptions, |
| 7 | + cli, |
| 8 | + defineAgent, |
| 9 | + inference, |
| 10 | + llm, |
| 11 | + log, |
| 12 | + logMetrics, |
| 13 | + stt, |
| 14 | + telemetry, |
| 15 | + tts, |
| 16 | + voice, |
| 17 | +} from '@livekit/agents'; |
| 18 | +import * as openai from '@livekit/agents-plugin-openai'; |
| 19 | +import { type Attributes } from '@opentelemetry/api'; |
| 20 | +import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; |
| 21 | +import { BatchSpanProcessor, NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; |
| 22 | +import { fileURLToPath } from 'node:url'; |
| 23 | +import { z } from 'zod'; |
| 24 | + |
| 25 | +// This example shows how to trace the agent session with OpenTelemetry. |
| 26 | +// It exports spans over OTLP/HTTP, so it works with any OTLP-compatible backend |
| 27 | +// (Langfuse, Jaeger, Grafana Tempo, Honeycomb, etc.). To enable tracing, set the trace |
| 28 | +// provider with `telemetry.setTracerProvider` at the module level or inside the entrypoint |
| 29 | +// before `AgentSession.start()`. |
| 30 | +// |
| 31 | +// Configure the destination either by passing `url`/`headers` to `setupOtel`, or by leaving |
| 32 | +// them unset and exporting the standard OTLP environment variables: |
| 33 | +// OTEL_EXPORTER_OTLP_ENDPOINT=https://my-collector.example.com |
| 34 | +// OTEL_EXPORTER_OTLP_HEADERS=Authorization=Bearer <token> |
| 35 | +// |
| 36 | +// Worked example - Langfuse: the endpoint is `<LANGFUSE_HOST>/api/public/otel` and auth |
| 37 | +// is a base64-encoded `Authorization: Basic` header built from the public/secret keys: |
| 38 | +// const auth = Buffer.from(`${publicKey}:${secretKey}`).toString('base64'); |
| 39 | +// setupOtel({ |
| 40 | +// url: `${host.replace(/\/$/, '')}/api/public/otel`, |
| 41 | +// headers: { Authorization: `Basic ${auth}`, 'x-langfuse-ingestion-version': '4' }, |
| 42 | +// }); |
| 43 | +// Refer to their docs for latest instructions: https://langfuse.com/integrations/native/opentelemetry#opentelemetry-endpoint |
| 44 | +function setupOtel(options?: { |
| 45 | + metadata?: Attributes; |
| 46 | + url?: string; |
| 47 | + headers?: Record<string, string>; |
| 48 | +}): NodeTracerProvider { |
| 49 | + const traceExporter = new OTLPTraceExporter({ |
| 50 | + url: options?.url, |
| 51 | + headers: options?.headers, |
| 52 | + }); |
| 53 | + const traceProvider = new NodeTracerProvider({ |
| 54 | + spanProcessors: [new BatchSpanProcessor(traceExporter)], |
| 55 | + }); |
| 56 | + |
| 57 | + traceProvider.register(); |
| 58 | + telemetry.setTracerProvider(traceProvider, { metadata: options?.metadata }); |
| 59 | + return traceProvider; |
| 60 | +} |
| 61 | + |
| 62 | +// Resolve the logger lazily: log() requires initializeLogger() to have run, which the CLI |
| 63 | +// only does after this module is imported, so calling it at module scope would throw. |
| 64 | +const logger = () => log().child({ example: 'otel-trace-example' }); |
| 65 | + |
| 66 | +const lookupWeather = llm.tool({ |
| 67 | + name: 'lookupWeather', |
| 68 | + description: 'Called when the user asks for weather related information.', |
| 69 | + parameters: z.object({ |
| 70 | + location: z.string().describe('The location they are asking for'), |
| 71 | + }), |
| 72 | + execute: async ({ location }) => { |
| 73 | + logger().info({ location }, 'Looking up weather'); |
| 74 | + return 'sunny with a temperature of 70 degrees.'; |
| 75 | + }, |
| 76 | +}); |
| 77 | + |
| 78 | +class Kelly extends voice.Agent { |
| 79 | + constructor() { |
| 80 | + super({ |
| 81 | + instructions: 'Your name is Kelly.', |
| 82 | + tools: [ |
| 83 | + lookupWeather, |
| 84 | + llm.tool({ |
| 85 | + name: 'transferToAlloy', |
| 86 | + description: 'Transfer the call to Alloy.', |
| 87 | + parameters: z.object({}), |
| 88 | + execute: async () => { |
| 89 | + logger().info('Transferring the call to Alloy'); |
| 90 | + return llm.handoff({ agent: new Alloy(), returns: 'Transfer complete.' }); |
| 91 | + }, |
| 92 | + }), |
| 93 | + ], |
| 94 | + }); |
| 95 | + } |
| 96 | + |
| 97 | + async onEnter() { |
| 98 | + logger().info('Kelly is entering the session'); |
| 99 | + this.session.generateReply(); |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +class Alloy extends voice.Agent { |
| 104 | + constructor() { |
| 105 | + super({ |
| 106 | + instructions: 'Your name is Alloy.', |
| 107 | + llm: new openai.realtime.RealtimeModel({ voice: 'alloy' }), |
| 108 | + tools: [ |
| 109 | + lookupWeather, |
| 110 | + llm.tool({ |
| 111 | + name: 'transferToKelly', |
| 112 | + description: 'Transfer the call to Kelly.', |
| 113 | + parameters: z.object({}), |
| 114 | + execute: async () => { |
| 115 | + logger().info('Transferring the call to Kelly'); |
| 116 | + return llm.handoff({ agent: new Kelly(), returns: 'Transfer complete.' }); |
| 117 | + }, |
| 118 | + }), |
| 119 | + ], |
| 120 | + }); |
| 121 | + } |
| 122 | + |
| 123 | + async onEnter() { |
| 124 | + logger().info('Alloy is entering the session'); |
| 125 | + this.session.generateReply(); |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +export default defineAgent({ |
| 130 | + entry: async (ctx: JobContext) => { |
| 131 | + // Set up the OpenTelemetry tracer. |
| 132 | + const traceProvider = setupOtel({ |
| 133 | + // Metadata is set as attributes on all spans created by the tracer; some backends have |
| 134 | + // their own grouping conventions (e.g. Langfuse uses `langfuse.session.id` or `session.id`). |
| 135 | + metadata: { |
| 136 | + 'session.id': ctx.room.name, |
| 137 | + }, |
| 138 | + }); |
| 139 | + |
| 140 | + // Optional: add a shutdown callback to flush the trace before process exit. |
| 141 | + ctx.addShutdownCallback(async () => { |
| 142 | + await traceProvider.forceFlush(); |
| 143 | + }); |
| 144 | + |
| 145 | + const session = new voice.AgentSession({ |
| 146 | + llm: new llm.FallbackAdapter({ |
| 147 | + llms: [ |
| 148 | + new inference.LLM({ model: 'openai/gpt-4.1-mini' }), |
| 149 | + new inference.LLM({ model: 'google/gemini-2.5-flash' }), |
| 150 | + ], |
| 151 | + }), |
| 152 | + stt: new stt.FallbackAdapter({ |
| 153 | + sttInstances: [ |
| 154 | + new inference.STT({ model: 'deepgram/nova-3' }), |
| 155 | + new inference.STT({ model: 'cartesia/ink-whisper' }), |
| 156 | + ], |
| 157 | + }), |
| 158 | + tts: new tts.FallbackAdapter({ |
| 159 | + ttsInstances: [ |
| 160 | + new inference.TTS({ model: 'cartesia/sonic-3' }), |
| 161 | + new inference.TTS({ model: 'rime/arcana' }), |
| 162 | + ], |
| 163 | + }), |
| 164 | + }); |
| 165 | + |
| 166 | + session.on(voice.AgentSessionEventTypes.MetricsCollected, (ev) => { |
| 167 | + logMetrics(ev.metrics); |
| 168 | + }); |
| 169 | + |
| 170 | + await session.start({ |
| 171 | + agent: new Kelly(), |
| 172 | + room: ctx.room, |
| 173 | + }); |
| 174 | + }, |
| 175 | +}); |
| 176 | + |
| 177 | +cli.runApp(new ServerOptions({ agent: fileURLToPath(import.meta.url) })); |
0 commit comments