""" Hermes Agent - FastAPI Backend Server Serves both the API endpoints and Telegram webhook """ import os import logging from contextlib import asynccontextmanager from fastapi import FastAPI, Request, HTTPException, BackgroundTasks from fastapi.responses import JSONResponse, HTMLResponse from fastapi.middleware.cors import CORSMiddleware import uvicorn import config from hermes_agent import process_query, get_agent from telegram_bot import get_bot, TelegramBot # Configure logging logging.basicConfig( level=getattr(logging, config.LOG_LEVEL), format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger("hermes-api") # Check if we have the API key set try: config.validate_config() logger.info("Configuration validated successfully") except ValueError as e: logger.warning(f"Configuration issue: {e}") # App metadata for documentation APP_METADATA = { "title": "Hermes Agent API", "description": """ 🤖 Hermes Agent - AI-powered assistant with 100+ API integrations Built with Nous Research Hermes function calling standard. ## Features - **Weather** - Global forecasts for any city - **Crypto** - Real-time prices for 1000+ coins - **Anime** - Search MyAnimeList database - **Games** - Pokemon, D&D, chess data - **Food** - 300,000+ recipes and cocktails - **Space** - ISS tracking, SpaceX launches, NASA APOD - **Sports** - Football, NBA, F1 standings - **Quotes** - Inspirational, movie, TV quotes - **Science** - Periodic table, number facts - **News** - Hacker News, space news - **Entertainment** - Jokes, memes, trivia - **Utility** - Translation, currency conversion, QR codes ## Usage Send a POST request to `/chat` with your message and get an AI response that intelligently uses tools when needed. """, "version": "1.0.0", "contact": { "name": "Hermes Agent", "url": "https://github.com/NousResearch/Hermes-Function-Calling" } } @asynccontextmanager async def lifespan(app: FastAPI): """Lifespan context manager for startup/shutdown events""" # Startup logger.info("🚀 Hermes Agent starting up...") logger.info(f"Model: {config.DEFAULT_MODEL}") logger.info(f"Max recursion depth: {config.MAX_RECURSION_DEPTH}") # Initialize agent agent = get_agent() logger.info("✅ Agent initialized") # Setup Telegram bot in polling mode for maximum reliability on HF if config.TELEGRAM_BOT_TOKEN: try: bot = get_bot() # Run polling in a separate thread to not block FastAPI import threading def start_polling(): bot.run_polling() polling_thread = threading.Thread(target=start_polling, daemon=True) polling_thread.start() logger.info("✅ Telegram bot started in polling mode (background thread)") except Exception as e: logger.warning(f"⚠️ Could not start Telegram bot: {e}") yield # Shutdown logger.info("🛑 Hermes Agent shutting down...") # Create FastAPI app app = FastAPI( title=APP_METADATA["title"], description=APP_METADATA["description"], version=APP_METADATA["version"], contact=APP_METADATA["contact"], lifespan=lifespan ) # Add CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # ============================================================ # HTML DASHBOARD (Landing Page) # ============================================================ DASHBOARD_HTML = """
AI-Powered Assistant with 100+ Real-World API Integrations
Global weather forecasts, air quality, UV index, and environmental data for any location on Earth.
Real-time cryptocurrency prices, market data, exchange rates, and financial information.
Pokemon database, D&D references, anime search, game stats, and entertainment data.
ISS tracking, SpaceX launches, NASA imagery, periodic table, and scientific facts.
300,000+ recipes, cocktail instructions, brewery database, and food information.
Football standings, NBA games, F1 results, chess ratings, and bike sharing data.
Book search, dictionary definitions, quotes, trivia questions, and educational content.
Jokes, memes, Reddit posts, Chuck Norris facts, Rick & Morty data, and more.