early-window-29567
11/17/2025, 2:42 PMimport os
from typing import Optional, Dict, Any
from openai import AsyncOpenAI
from dotenv import load_dotenv
load_dotenv(".env.local")
# Initialize OpenAI client with Helicone proxy (lazy initialization)
def get_deepdive_client(
user_id: Optional[str] = None,
session_id: Optional[str] = None,
video_url: Optional[str] = None,
lesson_number: Optional[int] = None,
agent_mode: Optional[str] = None,
custom_properties: Optional[Dict[str, Any]] = None
):
"""
Get the OpenAI client with Helicone proxy and rich metadata.
Args:
user_id: User identifier (email or name)
session_id: Unique session ID
video_url: MongoDB video URL
lesson_number: Current lesson being taught
agent_mode: Current agent mode (lesson, roleplay, quiz, case_study)
custom_properties: Additional custom properties to track
Returns:
AsyncOpenAI client configured with Helicone headers
"""
headers = {
"Helicone-Auth": f"Bearer {os.getenv('HELICONE_API_KEY')}",
"Helicone-Property-Type": "livekit",
}
# Add user identification (for user-level analytics)
if user_id:
headers["Helicone-User-Id"] = user_id
# Add session tracking
if session_id:
headers["Helicone-Session-Id"] = session_id
headers["Helicone-Session-Path"] = f"/session/{session_id}"
# Add custom properties for filtering and analytics
if video_url:
headers["Helicone-Property-VideoUrl"] = video_url
if lesson_number is not None:
headers["Helicone-Property-Lesson"] = str(lesson_number)
if agent_mode:
headers["Helicone-Property-Mode"] = agent_mode
# Add any additional custom properties
if custom_properties:
for key, value in custom_properties.items():
# Helicone custom properties use format: Helicone-Property-{Key}
header_key = f"Helicone-Property-{key.title().replace('_', '')}"
headers[header_key] = str(value)
return AsyncOpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
base_url="https://oai.helicone.ai/v1",
default_headers=headers
)
# Context manager for storing current session metadata
class HeliconeContext:
"""Thread-safe context for storing Helicone metadata"""
def __init__(self):
self.user_id = None
self.session_id = None
self.video_url = None
self.lesson_number = None
self.agent_mode = None
self.custom_properties = {}
def set_context(
self,
user_id: Optional[str] = None,
session_id: Optional[str] = None,
video_url: Optional[str] = None,
lesson_number: Optional[int] = None,
agent_mode: Optional[str] = None,
custom_properties: Optional[Dict[str, Any]] = None
):
"""Set global context for Helicone tracking"""
if user_id is not None:
self.user_id = user_id
if session_id is not None:
self.session_id = session_id
if video_url is not None:
self.video_url = video_url
if lesson_number is not None:
self.lesson_number = lesson_number
if agent_mode is not None:
self.agent_mode = agent_mode
if custom_properties is not None:
self.custom_properties.update(custom_properties)
def clear(self):
"""Clear all context"""
self.user_id = None
self.session_id = None
self.video_url = None
self.lesson_number = None
self.agent_mode = None
self.custom_properties = {}
# Global context instance
_helicone_context = HeliconeContext()
# For backward compatibility, create a lazy client that uses global context
class LazyClient:
"""Lazy client that uses global Helicone context"""
def __getattr__(self, name):
# Get client with current context
client = get_deepdive_client(
user_id=_helicone_context.user_id,
session_id=_helicone_context.session_id,
video_url=_helicone_context.video_url,
lesson_number=_helicone_context.lesson_number,
agent_mode=_helicone_context.agent_mode,
custom_properties=_helicone_context.custom_properties.copy() if _helicone_context.custom_properties else None
)
return getattr(client, name)
deepdive_client = LazyClient()
# Export context setter for easy access
def set_helicone_context(**kwargs):
"""
Set global Helicone context for all subsequent LLM calls.
Usage:
set_helicone_context(
user_id="john@example.com",
session_id="abc123",
video_url="mongodb://...",
lesson_number=5,
agent_mode="lesson"
)
"""
_helicone_context.set_context(**kwargs)tall-airline-16756
11/17/2025, 2:42 PMtall-airline-16756
11/17/2025, 2:42 PMearly-window-29567
11/17/2025, 2:53 PM# Instead of: base_url="https://api.openai.com/v1"
# You use: base_url="https://oai.helicone.ai/v1"
# Helicone intercepts the call, logs it, then forwards to OpenAI
Key Features:
1. User Tracking (line 44): Track which users are making calls
2. Session Tracking (lines 47-49): Group calls by session
3. Custom Properties (lines 52-66): Filter by video_url, lesson_number, agent_mode
4. LazyClient (lines 121-135): Automatically applies global context to all callstall-airline-16756
11/17/2025, 2:54 PMUsageCollector to gather token usage data and calculate costs externally based on your pricing model. This helps you keep an eye on expenses easily.
4. Track User Sessions: Don’t forget to pass user and session metadata into OpenTelemetry spans for better correlation. This way, you can group requests by user or session within Helicone, giving you clearer insights.
5. Add Custom Metadata: Feel free to enrich your traces with custom properties like video URLs, lesson numbers, and agent modes using OpenTelemetry's set_attribute and add_event methods. This adds valuable context to your data.
6. Optimize Latency: Keep an eye on latency metrics such as TTFT and tokens per second, and work on minimizing them to ensure your observability remains accurate and effective.
Helicone is designed to automatically interpret OpenTelemetry semantic conventions, making it straightforward to filter and analyze your data right from their dashboard. If you’d like, I’m here to help with detailed code examples or any specific configurations you need. Just let me know!
Sources: Operational Best Practices | livekit/livekit_composite | DeepWiki | Job lifecycle | LiveKit Docs | Logs, metrics, and telemetry | LiveKit Docs | livekit-agents/livekit/agents/telemetry/trace_types.pyearly-window-29567
11/17/2025, 2:56 PMtall-airline-16756
11/17/2025, 2:57 PMimport os
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from livekit.agents.telemetry import set_tracer_provider
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import Agent, AgentSession
# Configure OpenTelemetry for Helicone
def setup_helicone_telemetry():
# Configure the OTLP exporter for Helicone
otlp_exporter = OTLPSpanExporter(
endpoint="https://otel.helicone.ai/v1/traces", # Helicone OTLP endpoint
headers={
"Authorization": f"Bearer {os.getenv('HELICONE_API_KEY')}",
"Helicone-Auth": f"Bearer {os.getenv('HELICONE_API_KEY')}"
}
)
# Create tracer provider and add the exporter
tracer_provider = TracerProvider()
span_processor = BatchSpanProcessor(otlp_exporter)
tracer_provider.add_span_processor(span_processor)
# Set the tracer provider for LiveKit agents
set_tracer_provider(tracer_provider)
async def entrypoint(ctx: JobContext):
# Setup telemetry before creating the agent
setup_helicone_telemetry()
# Create your agent
agent = Agent(
instructions="You are a helpful assistant.",
llm="openai/gpt-4",
tts="cartesia/sonic",
)
session = AgentSession()
await session.start(agent=agent, room=ctx.room)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Here are some key features you’ll find useful:
• Request/Response Data: This is automatically captured as OpenTelemetry spans, including user input, LLM responses, and function calls, making it super easy to track.
• Token Usage: We capture token usage with OpenTelemetry attributes like gen_ai.usage.input_tokens and gen_ai.usage.output_tokens, so you get clear insights.
• Custom Metadata: You can add your own attributes to spans using span.set_attribute(), which helps you filter and analyze data right inside Helicone.
If you’d like, I’d be happy to provide additional examples on how to add custom attributes or configure specific metrics. Just let me know!
Sources: Logs, metrics, and telemetry | LiveKit Docs | livekit-agents/livekit/agents/telemetry/trace_types.py