Files
broswer-automation/agent-livekit/start_agent.py
nasir@endelospay.com d97cad1736 first commit
2025-08-12 02:54:17 +05:00

162 lines
4.4 KiB
Python

#!/usr/bin/env python3
"""
Startup script for LiveKit Chrome Agent
This script provides an easy way to start the LiveKit agent with proper configuration.
"""
import asyncio
import argparse
import logging
import os
import sys
from pathlib import Path
# Add current directory to path for imports
sys.path.insert(0, str(Path(__file__).parent))
from livekit_agent import main as agent_main
def setup_logging(level: str = "INFO"):
"""Set up logging configuration"""
logging.basicConfig(
level=getattr(logging, level.upper()),
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler('agent-livekit.log')
]
)
def check_environment():
"""Check if required environment variables are set"""
required_vars = [
'LIVEKIT_API_KEY',
'LIVEKIT_API_SECRET'
]
missing_vars = []
for var in required_vars:
if not os.getenv(var):
missing_vars.append(var)
if missing_vars:
print("Error: Missing required environment variables:")
for var in missing_vars:
print(f" - {var}")
print("\nPlease set these variables before starting the agent.")
print("You can create a .env file or export them in your shell.")
return False
return True
def create_env_template():
"""Create a template .env file"""
env_template = """# LiveKit Configuration
LIVEKIT_API_KEY=your_livekit_api_key_here
LIVEKIT_API_SECRET=your_livekit_api_secret_here
# Optional: OpenAI API Key for enhanced speech recognition/synthesis
OPENAI_API_KEY=your_openai_api_key_here
# Optional: Deepgram API Key for alternative speech recognition
DEEPGRAM_API_KEY=your_deepgram_api_key_here
"""
env_path = Path(__file__).parent / ".env.template"
with open(env_path, 'w') as f:
f.write(env_template)
print(f"Created environment template at: {env_path}")
print("Copy this to .env and fill in your actual API keys.")
def load_env_file():
"""Load environment variables from .env file"""
env_path = Path(__file__).parent / ".env"
if env_path.exists():
try:
with open(env_path, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
os.environ[key.strip()] = value.strip()
print(f"Loaded environment variables from {env_path}")
except Exception as e:
print(f"Error loading .env file: {e}")
def main():
"""Main startup function"""
parser = argparse.ArgumentParser(description="LiveKit Chrome Agent")
parser.add_argument(
"--config",
default="livekit_config.yaml",
help="Path to configuration file"
)
parser.add_argument(
"--log-level",
default="INFO",
choices=["DEBUG", "INFO", "WARNING", "ERROR"],
help="Logging level"
)
parser.add_argument(
"--create-env-template",
action="store_true",
help="Create a template .env file and exit"
)
parser.add_argument(
"--dev",
action="store_true",
help="Run in development mode with debug logging"
)
args = parser.parse_args()
# Create env template if requested
if args.create_env_template:
create_env_template()
return
# Set up logging
log_level = "DEBUG" if args.dev else args.log_level
setup_logging(log_level)
logger = logging.getLogger(__name__)
logger.info("Starting LiveKit Chrome Agent...")
# Load environment variables
load_env_file()
# Check environment
if not check_environment():
sys.exit(1)
# Check config file exists
config_path = Path(args.config)
if not config_path.exists():
logger.error(f"Configuration file not found: {config_path}")
sys.exit(1)
try:
# Set config path for the agent
os.environ['LIVEKIT_CONFIG_PATH'] = str(config_path)
# Start the agent
logger.info(f"Using configuration: {config_path}")
agent_main()
except KeyboardInterrupt:
logger.info("Agent stopped by user")
except Exception as e:
logger.error(f"Agent failed: {e}")
sys.exit(1)
if __name__ == "__main__":
main()