File size: 12,480 Bytes
e8434f3
 
25f8aca
 
1f216d0
e8434f3
 
 
 
 
 
 
 
 
 
 
1f216d0
 
 
 
 
 
 
 
 
 
 
 
 
e8434f3
 
1f216d0
 
 
e8434f3
 
25f8aca
e8434f3
 
25f8aca
e8434f3
 
 
 
 
 
 
 
 
25f8aca
 
 
 
e8434f3
 
 
25f8aca
1f216d0
acb8402
e8434f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f8aca
e8434f3
 
25f8aca
e8434f3
 
25f8aca
e8434f3
1f216d0
 
acb8402
 
1f216d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acb8402
 
1f216d0
 
 
 
 
 
acb8402
 
1f216d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acb8402
 
1f216d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acb8402
 
1f216d0
 
 
 
 
acb8402
1f216d0
 
 
 
 
acb8402
1f216d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8434f3
 
 
 
 
 
25f8aca
 
e8434f3
 
 
 
 
 
acb8402
25f8aca
 
e8434f3
 
 
 
 
 
 
 
 
 
 
1f216d0
 
e8434f3
 
 
 
 
 
1f216d0
e8434f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f216d0
25f8aca
1f216d0
acb8402
 
1f216d0
 
 
 
 
 
 
e8434f3
 
 
1f216d0
25f8aca
e8434f3
1f216d0
e8434f3
25f8aca
e8434f3
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
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
    )