import logging
import os
import aiohttp
import asyncio
from dotenv import load_dotenv
from livekit.agents import (
Agent,
AgentSession,
JobContext,
JobProcess,
RoomInputOptions,
RoomOutputOptions,
RunContext,
WorkerOptions,
cli,
metrics,
)
from livekit.agents.llm import function_tool
from livekit.agents.voice import MetricsCollectedEvent
from livekit.plugins import cartesia, deepgram, elevenlabs, noise_cancellation, openai, silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel
logger = logging.getLogger("agent")
load_dotenv(".env.local")
# Server configuration
ELECTRA_SERVER_URL = os.getenv("ELECTRA_SERVER_URL", "
http://localhost:3000")
ELECTRA_API_TOKEN = os.getenv("ELECTRA_API_TOKEN")
class Assistant(Agent):
def __init__(self) -> None:
super().__init__(
instructions="""You are Electra, an AI financial assistant.
RESPONSE STYLE - CRITICAL:
- Keep responses to 1-2 sentences maximum
- Give direct answers immediately
- No long explanations or descriptions
- No "I'm thinking" or "Let me think" phrases
- Only introduce yourself as "I'm Electra" if the user greets you or asks for your name
NUMBER FORMATTING:
- Always display exact formatted prices from data sources (e.g., "$64,115.25")
- Round dollar amounts to whole numbers when possible ($50 not $50.00)
- Use simple decimal format for BTC (0.01 BTC not 0.0100000 BTC)
CONVERSATION MEMORY:
- Pay attention to conversation context provided in messages
- When users mention Bitcoin, crypto, or specific amounts after previous discussions - they're modifying previous requests
- When users say "continue", "proceed", "my order", "that transaction", "yes", "ok" - they're referring to previous conversation
- Recent conversation history will be provided when users reference previous discussions
- CRITICAL: If user mentions a different amount than originally discussed, ask for clarification immediately
MEMORY EXAMPLES:
- User: "Buy Bitcoin" → AI: "How much?" → User: "What's Tesla's price?" → AI: "Tesla is $313.51" → User: "Continue my Bitcoin order" → AI should remember the Bitcoin discussion
- User: "I want to buy $50 of bitcoin" → AI: "Confirm $50 Bitcoin order?" → User: "I want 0.01 BTC instead" → AI should recognize this as modifying the previous order
- User: "Continue my 0.1 BTC order" (when original was 0.01 BTC) → AI should ask: "I see you originally wanted 0.01 BTC but now mentioned 0.1 BTC. Which amount did you mean?"
Available tools allow you to access real-time market data, analyze portfolios, and execute investment analysis. Use these tools to provide quick, actionable financial guidance.
Remember: You provide educational information. Users should consult qualified financial advisors for personalized investment decisions.""",
)
_# all functions annotated with @function_tool will be passed to the LLM when this_
# agent is active
@function_tool
async def get_bitcoin_price(self, context: RunContext):
"""Use this tool to get the current Bitcoin price in USD from Glassnode.
This tool fetches real-time Bitcoin market data and returns the current price.
"""
logger.info("Fetching Bitcoin price from Electra server")
if not ELECTRA_API_TOKEN:
logger.error("No API token configured for Electra server")
return "Unable to fetch Bitcoin price: API token not configured"
try:
async with aiohttp.ClientSession() as session:
headers = {
"Authorization": f"Bearer {ELECTRA_API_TOKEN}",
"Content-Type": "application/json"
}
async with session.get(
f"{ELECTRA_SERVER_URL}/api/v1/glassnode/bitcoin/price",
headers=headers,
timeout=aiohttp.ClientTimeout(total=10)
) as response:
if response.status == 401:
logger.error("Authentication failed with Electra server")
return "Unable to fetch Bitcoin price: Authentication failed"
if response.status != 200:
logger.error(f"Server error: {response.status}")
return f"Unable to fetch Bitcoin price: Server error ({response.status})"
data = await response.json()
price = data.get("price")
if price:
formatted_price = f"${price:,.2f}"
logger.info(f"Bitcoin price fetched: {formatted_price}")
return f"The current Bitcoin price is {formatted_price}"
else:
logger.error("No price data in server response")
return "Unable to fetch Bitcoin price: No price data received"
except asyncio.TimeoutError:
logger.error("Timeout fetching Bitcoin price")
return "Unable to fetch Bitcoin price: Request timed out"
except aiohttp.ClientError as e:
logger.error(f"HTTP error fetching Bitcoin price: {e}")
return "Unable to fetch Bitcoin price: Network error"
except Exception as e:
logger.error(f"Unexpected error fetching Bitcoin price: {e}")
return "Unable to fetch Bitcoin price: Unexpected error"
def prewarm(proc: JobProcess):
proc.userdata["vad"] = silero.VAD.load()
async def entrypoint(ctx: JobContext):
# each log entry will include these fields
ctx.log_context_fields = {
"room": ctx.room.name,
}
session = AgentSession(
# any combination of STT, LLM, TTS, or realtime API can be used
llm=openai.LLM(model="gpt-4o"),
stt=deepgram.STT(model="nova-3", language="multi"),
tts=elevenlabs.TTS(
voice_id="cgSgspJ2msm6clMCkdW9",
model="eleven_multilingual_v2",
voice_settings=elevenlabs.VoiceSettings(
stability=0.5,
similarity_boost=0.75,
style=0.0,
use_speaker_boost=True
),
enable_ssml_parsing=False,
auto_mode=True,
),
# use LiveKit's turn detection model
turn_detection=MultilingualModel(),
vad=ctx.proc.userdata["vad"],
)
# To use the OpenAI Realtime API, use the following session setup instead:
# session = AgentSession(
# llm=openai.realtime.RealtimeModel()
# )
# log metrics as they are emitted, and total usage after session is over
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()
logger.info(f"Usage: {summary}")
# shutdown callbacks are triggered when the session is over
ctx.add_shutdown_callback(log_usage)
await session.start(
agent=Assistant(),
room=ctx.room,
room_input_options=RoomInputOptions(
# LiveKit Cloud enhanced noise cancellation
# - If self-hosting, omit this parameter
# - For telephony applications, use BVCTelephony
for best results
noise_cancellation=noise_cancellation.BVC(),
),
room_output_options=RoomOutputOptions(transcription_enabled=True),
)
# join the room when agent is ready
await ctx.connect()
if
name == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm))