llm-ai-agent / app.py
Yadav122's picture
Fix: Remove deprecated on_event, fix import issues, use modern FastAPI lifespan
1f216d0 verified
raw
history blame
12.5 kB
import os
import logging
from typing import Optional
from datetime import datetime
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Depends, Security, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
import uvicorn
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Global variables
model_loaded = True
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
logger.info("AI Assistant starting up...")
logger.info("Smart response system loaded successfully!")
yield
# Shutdown
logger.info("AI Assistant shutting down...")
# Initialize FastAPI app with lifespan
app = FastAPI(
title="LLM AI Agent API",
description="Secure AI Agent API with Smart Responses",
version="2.0.0",
lifespan=lifespan
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Security
security = HTTPBearer()
# Configuration
API_KEYS = {
os.getenv("API_KEY_1", "27Eud5J73j6SqPQAT2ioV-CtiCg-p0WNqq6I4U0Ig6E"): "user1",
os.getenv("API_KEY_2", "QbzG2CqHU1Nn6F1EogZ1d3dp8ilRTMJQBwTJDQBzS-U"): "user2",
}
# Request/Response models
class ChatRequest(BaseModel):
message: str = Field(..., min_length=1, max_length=1000)
max_length: Optional[int] = Field(200, ge=50, le=500)
temperature: Optional[float] = Field(0.8, ge=0.1, le=1.5)
class ChatResponse(BaseModel):
response: str
model_used: str
timestamp: str
processing_time: float
class HealthResponse(BaseModel):
status: str
model_loaded: bool
timestamp: str
def verify_api_key(credentials: HTTPAuthorizationCredentials = Security(security)) -> str:
"""Verify API key authentication"""
api_key = credentials.credentials
if api_key not in API_KEYS:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid API key"
)
return API_KEYS[api_key]
def get_ai_response(message: str) -> str:
"""Generate intelligent AI responses"""
message_lower = message.lower()
# Comprehensive AI knowledge base
if any(word in message_lower for word in ["machine learning", "ml"]):
return """Machine Learning is a powerful subset of Artificial Intelligence that enables computers to learn and improve from experience without being explicitly programmed.
🔍 **How it Works:**
• **Training Data**: ML algorithms learn patterns from large datasets
• **Model Building**: Creates mathematical models to understand relationships
• **Prediction**: Uses learned patterns to make predictions on new data
• **Improvement**: Gets better with more data and feedback
🎯 **Types of Machine Learning:**
1. **Supervised Learning**: Learning with labeled examples
- Example: Email spam detection, image recognition
2. **Unsupervised Learning**: Finding hidden patterns in data
- Example: Customer segmentation, recommendation systems
3. **Reinforcement Learning**: Learning through trial and error
- Example: Game AI, autonomous vehicles
💡 **Real-World Applications:**
• Netflix movie recommendations
• Google search results
• Voice assistants (Siri, Alexa)
• Medical diagnosis
• Financial fraud detection
• Self-driving cars
🚀 **Why it's Important:**
Machine Learning is revolutionizing industries by automating decision-making, discovering insights in data, and solving complex problems that traditional programming cannot handle."""
elif any(word in message_lower for word in ["artificial intelligence", "ai"]):
return """Artificial Intelligence (AI) is the simulation of human intelligence in machines that are programmed to think, learn, and problem-solve like humans.
🧠 **What is AI?**
AI refers to computer systems that can perform tasks requiring human-like intelligence:
• Understanding and processing natural language
• Recognizing patterns in images and sounds
• Making decisions based on data
• Learning from experience
• Solving complex problems
🔧 **Types of AI:**
1. **Narrow AI (Weak AI)**: Specialized for specific tasks
- Examples: Chess programs, voice assistants, recommendation systems
2. **General AI (Strong AI)**: Human-level intelligence across all domains
- Status: Still theoretical, not yet achieved
3. **Super AI**: Intelligence beyond human capabilities
- Status: Hypothetical future possibility
🌟 **AI in Your Daily Life:**
• **Smartphones**: Voice assistants, camera features, predictive text
• **Social Media**: News feed algorithms, photo tagging
• **Shopping**: Product recommendations, price optimization
• **Transportation**: GPS navigation, ride-sharing apps
• **Entertainment**: Music/movie recommendations, gaming AI
🔮 **Future of AI:**
AI is expected to transform healthcare, education, transportation, and virtually every industry, making our lives more efficient and solving global challenges."""
elif any(word in message_lower for word in ["deep learning", "neural network"]):
return """Deep Learning is an advanced subset of Machine Learning inspired by the structure and function of the human brain.
🧠 **What is Deep Learning?**
Deep Learning uses artificial neural networks with multiple layers (hence "deep") to automatically learn complex patterns in data without manual feature engineering.
🏗️ **How Neural Networks Work:**
• **Neurons**: Basic processing units that receive, process, and transmit information
• **Layers**:
- Input Layer: Receives raw data
- Hidden Layers: Process and transform data (multiple layers = "deep")
- Output Layer: Produces final predictions
• **Connections**: Weighted links between neurons that strengthen or weaken during learning
⚡ **Learning Process:**
1. **Forward Pass**: Data flows through the network
2. **Prediction**: Network makes a guess
3. **Error Calculation**: Compare prediction with correct answer
4. **Backpropagation**: Adjust weights to reduce errors
5. **Repeat**: Process continues until network becomes accurate
🎯 **Applications:**
• **Computer Vision**: Image recognition, medical imaging, autonomous vehicles
• **Natural Language Processing**: Language translation, chatbots, text analysis
• **Speech Recognition**: Voice assistants, transcription services
• **Recommendation Systems**: Netflix, YouTube, Amazon suggestions
• **Game AI**: Chess, Go, video game characters
💪 **Why Deep Learning is Powerful:**
• Handles unstructured data (images, text, audio)
• Automatically discovers features humans might miss
• Improves performance with more data
• Can solve problems too complex for traditional programming"""
elif any(word in message_lower for word in ["python", "programming"]):
return """Python is the most popular programming language for AI, Machine Learning, and Data Science.
🐍 **Why Python for AI/ML?**
• **Simple Syntax**: Easy to learn and read, focuses on logic rather than syntax
• **Rich Ecosystem**: Extensive libraries and frameworks
• **Large Community**: Millions of developers, abundant resources
• **Versatility**: Web development, automation, data analysis, AI
• **Industry Standard**: Used by Google, Netflix, Instagram, NASA
📚 **Essential Python Libraries for AI:**
• **NumPy**: Numerical computing and array operations
• **Pandas**: Data manipulation and analysis
• **Matplotlib/Seaborn**: Data visualization
• **Scikit-learn**: Traditional machine learning algorithms
• **TensorFlow**: Google's deep learning framework
• **PyTorch**: Facebook's deep learning framework
• **OpenCV**: Computer vision tasks
• **NLTK/spaCy**: Natural language processing
🚀 **Learning Path:**
1. **Python Basics**: Variables, functions, loops, data structures
2. **Data Manipulation**: Learn Pandas for handling datasets
3. **Visualization**: Create charts with Matplotlib
4. **Machine Learning**: Start with Scikit-learn
5. **Deep Learning**: Explore TensorFlow or PyTorch
6. **Specialization**: Choose computer vision, NLP, or other domains
💼 **Career Opportunities:**
• Data Scientist
• Machine Learning Engineer
• AI Researcher
• Python Developer
• Data Analyst"""
elif any(word in message_lower for word in ["hello", "hi", "hey"]):
return """Hello! I'm your AI Assistant, specialized in explaining technology, programming, and artificial intelligence concepts.
🤖 **What I Can Help You With:**
• **Machine Learning**: Algorithms, models, and applications
• **Artificial Intelligence**: Concepts, types, and real-world uses
• **Programming**: Python, data science, and development
• **Data Science**: Analytics, visualization, and insights
• **Deep Learning**: Neural networks and advanced AI
• **Career Guidance**: Tech careers and learning paths
💡 **Popular Questions I Can Answer:**
• "What is machine learning?"
• "How does AI work?"
• "What programming language should I learn?"
• "How do I become a data scientist?"
• "Explain deep learning in simple terms"
🚀 **Just ask me anything about technology, and I'll provide detailed, helpful explanations with examples and practical insights!**
What would you like to learn about today?"""
else:
return """I'm an AI assistant specialized in technology, programming, and artificial intelligence topics.
🎯 **I can help explain:**
• **Machine Learning & AI**: Concepts, algorithms, applications
• **Programming**: Python, data science, software development
• **Data Science**: Analytics, visualization, career guidance
• **Deep Learning**: Neural networks, computer vision, NLP
• **Technology Trends**: Latest developments in AI and tech
💡 **Try asking me:**
• "What is machine learning?"
• "How does artificial intelligence work?"
• "What is Python used for?"
• "Explain deep learning"
• "How to become a data scientist?"
🚀 **I provide detailed explanations with examples, practical applications, and learning guidance. What would you like to know about?**"""
@app.get("/", response_model=HealthResponse)
async def root():
"""Health check endpoint"""
return HealthResponse(
status="healthy",
model_loaded=model_loaded,
timestamp=datetime.now().isoformat()
)
@app.get("/health", response_model=HealthResponse)
async def health_check():
"""Detailed health check"""
return HealthResponse(
status="healthy",
model_loaded=model_loaded,
timestamp=datetime.now().isoformat()
)
@app.post("/chat", response_model=ChatResponse)
async def chat(
request: ChatRequest,
user: str = Depends(verify_api_key)
):
"""Main chat endpoint for AI agent interaction"""
start_time = datetime.now()
try:
# Generate intelligent response
response_text = get_ai_response(request.message)
# Calculate processing time
processing_time = (datetime.now() - start_time).total_seconds()
return ChatResponse(
response=response_text,
model_used="smart_ai_assistant_v2",
timestamp=datetime.now().isoformat(),
processing_time=processing_time
)
except Exception as e:
logger.error(f"Error generating response: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Error generating response: {str(e)}"
)
@app.get("/models")
async def get_model_info(user: str = Depends(verify_api_key)):
"""Get information about the loaded model"""
return {
"model_name": "smart_ai_assistant_v2",
"model_loaded": model_loaded,
"status": "active",
"capabilities": [
"Machine Learning explanations",
"Artificial Intelligence concepts",
"Programming guidance (Python)",
"Data Science career advice",
"Deep Learning tutorials",
"Technology trend analysis"
],
"version": "2.0.0"
}
if __name__ == "__main__":
# For Hugging Face Spaces
port = int(os.getenv("PORT", "7860"))
uvicorn.run(
"app_fixed:app",
host="0.0.0.0",
port=port,
reload=False
)