yashgori / README.md
yashgori20's picture
ok
46e172a
---
title: Yashgori
emoji: πŸš€
colorFrom: blue
colorTo: gray
sdk: docker
sdk_version: "0.0.1"
app_file: app.py
pinned: false
---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
# πŸ€– Yash Gori AI Portfolio API v2.0 - Complete Implementation Guide
## **Overview**
This is a sophisticated AI portfolio chatbot that intelligently adapts to different types of visitors (recruiters, developers, students, etc.) and provides personalized responses about Yash Gori's skills, projects, and qualifications.
---
## **🎯 Complete Features Implemented (A to Z)**
### **Core AI Intelligence**
- βœ… **Intelligent AI Agent** with personality using Groq Llama 3.3 70B
- βœ… **User Intent Detection** (recruiter/technical/collaborator/student/general)
- βœ… **Sophistication Level Analysis** (beginner/intermediate/advanced)
- βœ… **Dynamic Response Adaptation** based on user type and context
- βœ… **Natural Language Processing** with context understanding
### **Conversation Management**
- βœ… **Session Management** with UUID-based session IDs
- βœ… **Conversation Memory** building context over multiple exchanges
- βœ… **Topic Tracking** and theme analysis
- βœ… **Question Clarity Detection** with clarifying question generation
- βœ… **Follow-up Engagement** prompts to continue conversations
### **Smart Features**
- βœ… **Smart Suggestions** based on conversation flow patterns
- βœ… **Rich Content Integration** with contextual project details
- βœ… **Project Mention Detection** with GitHub links
- βœ… **Contextual Information** delivery based on questions
- βœ… **Intelligent Fallback Responses** when AI unavailable
### **Rate Limiting & Security**
- βœ… **Multi-level Rate Limiting** (IP-based: 60/hour, Session-based: 20/hour)
- βœ… **Background Session Cleanup** every 10 minutes
- βœ… **Rate Limit Headers** in responses
- βœ… **IP Address Tracking** (partially masked for privacy)
### **Database & Analytics**
- βœ… **SQLite Database** with visitor tracking
- βœ… **User Profile Storage** with conversation history
- βœ… **Real-time Analytics** collection
- βœ… **Daily Analytics Summaries** with trends
- βœ… **Comprehensive Dashboard** with insights
- βœ… **Data Export** capabilities for analysis
### **API Structure**
- βœ… **RESTful API Design** with proper HTTP methods
- βœ… **Enhanced JSON Responses** with metadata
- βœ… **Error Handling** with fallback responses
- βœ… **CORS Support** for frontend integration
- βœ… **Database Migration** system for schema updates
---
## **πŸ”„ Complete Workflow**
### **1. User Interaction Flow**
```
User Visits β†’ Session Created β†’ Question Asked β†’ AI Processing β†’ Response Generation β†’ Analytics Saved β†’ Smart Suggestions Provided
```
### **2. Behind-the-Scenes Process**
```
1. Session Management:
- Generate/retrieve session ID
- Check rate limits (IP + Session)
- Load conversation memory
2. User Analysis:
- Detect user intent (recruiter/technical/etc.)
- Analyze sophistication level
- Check question clarity
3. Context Building:
- Retrieve conversation history
- Build context summary
- Detect mentioned projects
4. AI Response Generation:
- Create intelligent agent prompt
- Call Groq API with context
- Process and validate response
5. Intelligence Layer:
- Generate smart suggestions
- Extract rich content
- Analyze conversation flow
6. Data Persistence:
- Save conversation to database
- Update user profile
- Update daily analytics
7. Response Assembly:
- Build comprehensive JSON response
- Include metadata and suggestions
- Apply rate limit headers
```
---
## **πŸ›  Complete API Routes**
### **1. Main Chat Endpoint**
```http
POST /ask
```
**Request:**
```json
{
"question": "What are Yash's technical skills?",
"session_id": "optional-uuid-here"
}
```
**Response:**
```json
{
"success": true,
"api_version": "2.0",
"session": {
"session_id": "1e9704c6-eecb-4d32-9066-d8d62c9d9682",
"conversation_number": 3,
"user_status": "returning",
"session_created": "2025-08-10T21:00:00"
},
"request": {
"question": "What are Yash's technical skills?",
"processed_at": "2025-08-10T21:18:00",
"response_time_ms": null
},
"response": {
"answer": "Yash has strong technical skills in AI/ML, Python, Flask, RAG systems...",
"model_used": "openai/gpt-oss-120b",
"confidence_indicators": {
"question_clarity": 0.9,
"user_type_confidence": 0.8,
"response_relevance": 0.9
}
},
"intelligence": {
"user_analysis": {
"detected_type": "technical",
"sophistication_level": "intermediate",
"question_clarity": "Clear technical inquiry",
"is_returning_user": true,
"previous_topics": ["skills", "projects"]
},
"conversation_state": {
"total_exchanges": 3,
"main_themes": ["technical_skills", "ai_projects"],
"user_progression": ["exploring", "deepening"],
"conversation_depth": "moderate"
},
"smart_suggestions": {
"follow_up_questions": [
"Would you like to see specific examples of his AI projects?",
"How do his skills align with your team's needs?"
],
"topic_transitions": [
"Let's dive deeper into the area that interests you most"
],
"depth_exploration": [
"Want to discuss the system architecture in detail?"
]
}
},
"rich_content": {
"DocuTalk": {
"github_link": "https://github.com/yashnileshgori/DocuTalk",
"technical_specs": ["RAG", "LangChain", "Streamlit"],
"key_achievement": "Conversational document AI"
}
},
"metadata": {
"rate_limit": {
"requests_remaining": 58,
"window_reset": "2025-08-10T22:18:00"
},
"developer": "Yash Gori",
"timestamp": "2025-08-10T21:18:00"
}
}
```
### **2. API Information**
```http
GET /
```
**Response:**
```json
{
"message": "Welcome to Yash Gori's AI Portfolio API",
"version": "2.0",
"developer": "Yash Gori",
"description": "Intelligent portfolio chatbot with adaptive responses",
"endpoints": {
"POST /ask": "Main chat endpoint",
"GET /profile": "Complete profile data",
"GET /analytics/dashboard": "Analytics dashboard"
}
}
```
### **3. Complete Profile**
```http
GET /profile
```
**Response:**
```json
{
"success": true,
"developer": "Yash Gori",
"profile": {
"personal_info": {
"name": "Yash Gori",
"email": "[email protected]",
"phone": "+91-XXXXXXXXXX"
},
"current_position": {
"role": "AI Engineer Intern",
"company": "Webotix IT Consultancy"
},
"education": {
"current": {
"degree": "BTech in Information Technology",
"college": "KJ Somaiya College of Engineering",
"cgpa": "8.12"
}
}
}
}
```
### **4. Session State**
```http
GET /session/{session_id}/state
```
**Response:**
```json
{
"success": true,
"session_id": "uuid-here",
"session_exists": true,
"profile": {
"primary_type": "technical",
"sophistication_level": "intermediate",
"conversation_count": 5
},
"conversation_memory": {
"total_exchanges": 5,
"main_themes": ["skills", "projects"],
"conversation_depth": "deep"
}
}
```
### **5. Session History**
```http
GET /session/{session_id}/history
```
**Response:**
```json
{
"success": true,
"session_id": "uuid-here",
"total_conversations": 5,
"conversation_history": [
{
"turn": 1,
"timestamp": "2025-08-10T21:00:00",
"question": "What are Yash's skills?",
"answer": "Yash has strong technical skills...",
"user_type": "technical",
"sophistication": "intermediate"
}
]
}
```
### **6. Analytics Dashboard**
```http
GET /analytics/dashboard
```
**Response:**
```json
{
"success": true,
"dashboard_title": "Yash Gori's AI Portfolio Analytics Dashboard",
"generated_at": "2025-08-10T21:18:00",
"overview": {
"total_conversations": 150,
"unique_visitors": 45,
"avg_question_length": 25.5,
"avg_answer_length": 180.2
},
"user_types": {
"recruiter": 30,
"technical": 45,
"general": 75
},
"engagement_metrics": {
"avg_conversations_per_session": 2.3,
"multi_turn_sessions": 20,
"highly_engaged_sessions": 8
},
"summary_insights": {
"engagement_rate": 3.33,
"top_user_type": "technical",
"peak_activity_hour": "14"
}
}
```
### **7. Session Analytics**
```http
GET /analytics/session/{session_id}
```
**Response:**
```json
{
"success": true,
"session_id": "uuid-here",
"conversation_count": 5,
"user_journey": [
{
"turn": 1,
"question": "What are Yash's skills?",
"detected_type": "technical",
"sophistication": "intermediate"
}
],
"topics_explored": ["DocuTalk", "Finance Advisor"],
"detected_user_types": ["technical", "recruiter"]
}
```
### **8. Daily Analytics**
```http
GET /analytics/daily
```
**Response:**
```json
{
"success": true,
"daily_analytics": [
{
"date": "2025-08-10",
"total_conversations": 25,
"unique_sessions": 12,
"user_type_breakdown": {"technical": 10, "recruiter": 8},
"avg_conversation_length": 150
}
],
"trends": {
"conversation_trend": 5,
"session_trend": 2
}
}
```
### **9. Export Analytics**
```http
GET /analytics/export
```
**Response:**
```json
{
"success": true,
"export_metadata": {
"generated_at": "2025-08-10T21:18:00",
"total_records": 150,
"analytics_version": "2.0"
},
"full_analytics": { /* Complete analytics data */ },
"conversation_records": [ /* All conversations */ ]
}
```
### **10. Admin Conversations**
```http
GET /admin/conversations
```
**Response:**
```json
{
"success": true,
"total_conversations": 150,
"conversations": [
{
"id": "uuid",
"session_id": "session-uuid",
"timestamp": "2025-08-10T21:00:00",
"user_type": "technical",
"question": "What are Yash's skills?",
"answer": "Yash has strong technical skills..."
}
]
}
```
### **11. Admin Profiles**
```http
GET /admin/profiles
```
**Response:**
```json
{
"success": true,
"total_unique_visitors": 45,
"profiles": [
{
"session_id": "uuid",
"primary_type": "technical",
"conversation_count": 5,
"first_seen": "2025-08-10T20:00:00",
"last_seen": "2025-08-10T21:00:00"
}
],
"analytics": {
"user_types": {"technical": 20, "recruiter": 15},
"skill_levels": {"intermediate": 25, "advanced": 10}
}
}
```
---
## **πŸ–₯ Frontend Integration Guide**
### **1. Essential Frontend Components**
#### **Chat Interface**
```javascript
class YashChatbot {
constructor() {
this.sessionId = localStorage.getItem('yashChatSession') || null;
this.apiBase = 'YOUR_API_URL';
}
async sendMessage(question) {
const payload = {
question: question,
session_id: this.sessionId
};
const response = await fetch(`${this.apiBase}/ask`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const data = await response.json();
// Store session ID for continuity
if (!this.sessionId && data.session?.session_id) {
this.sessionId = data.session.session_id;
localStorage.setItem('yashChatSession', this.sessionId);
}
return data;
}
}
```
#### **Message Display**
```javascript
function displayMessage(data) {
// Main response
addMessage(data.response.answer, 'bot');
// Smart suggestions as quick reply buttons
if (data.intelligence?.smart_suggestions?.follow_up_questions) {
showQuickReplies(data.intelligence.smart_suggestions.follow_up_questions);
}
// Rich content for projects
if (data.rich_content) {
displayProjectCards(data.rich_content);
}
// User type indicator (optional)
if (data.intelligence?.user_analysis?.detected_type !== 'general') {
showUserTypeIndicator(data.intelligence.user_analysis.detected_type);
}
}
```
### **2. Required Frontend Features**
#### **Session Management**
- Store `session_id` in localStorage
- Include in all subsequent requests
- Handle session restoration
#### **Rate Limit Handling**
```javascript
function handleRateLimit(data) {
if (data.metadata?.rate_limit?.requests_remaining < 5) {
showWarning(`${data.metadata.rate_limit.requests_remaining} requests remaining`);
}
}
```
#### **Smart Suggestions**
```javascript
function showQuickReplies(suggestions) {
const container = document.getElementById('quick-replies');
container.innerHTML = '';
suggestions.forEach(suggestion => {
const button = document.createElement('button');
button.textContent = suggestion;
button.onclick = () => sendMessage(suggestion);
container.appendChild(button);
});
}
```
#### **Rich Content Display**
```javascript
function displayProjectCards(richContent) {
Object.entries(richContent).forEach(([projectName, details]) => {
const card = createProjectCard({
name: projectName,
github: details.github_link,
specs: details.technical_specs,
achievement: details.key_achievement
});
document.getElementById('rich-content').appendChild(card);
});
}
```
### **3. Error Handling**
```javascript
async function handleApiCall(question) {
try {
const data = await chatbot.sendMessage(question);
if (data.success) {
displayMessage(data);
handleRateLimit(data);
} else {
// Show fallback response
if (data.fallback_answer) {
addMessage(data.fallback_answer, 'bot');
}
}
} catch (error) {
addMessage("Sorry, I'm having trouble connecting. Please try again.", 'bot');
}
}
```
### **4. Analytics Integration (Optional)**
```javascript
// For admin dashboard
async function loadAnalytics() {
const response = await fetch(`${apiBase}/analytics/dashboard`);
const analytics = await response.json();
displayAnalyticsDashboard(analytics);
}
// For session insights
async function showSessionInsights(sessionId) {
const response = await fetch(`${apiBase}/analytics/session/${sessionId}`);
const insights = await response.json();
displaySessionJourney(insights.user_journey);
}
```
---
## **πŸ”§ Technical Implementation Notes**
### **Database Schema**
```sql
-- Main conversations table
CREATE TABLE visitors (
id TEXT PRIMARY KEY,
session_id TEXT,
timestamp TEXT,
user_type TEXT,
question TEXT,
answer TEXT,
user_info TEXT,
ip_address TEXT
);
-- User profiles table
CREATE TABLE user_profiles (
session_id TEXT PRIMARY KEY,
primary_type TEXT,
sophistication_level TEXT,
interests TEXT,
conversation_count INTEGER,
first_seen TEXT,
last_seen TEXT,
profile_data TEXT
);
-- Daily analytics table
CREATE TABLE daily_analytics (
date TEXT PRIMARY KEY,
total_conversations INTEGER,
unique_sessions INTEGER,
user_type_breakdown TEXT,
avg_conversation_length INTEGER,
top_questions TEXT,
updated_at TIMESTAMP
);
```
### **Key Configuration**
```python
# API Configuration
GROQ_API_KEY = "your-groq-api-key"
DB_PATH = "/tmp/visitors.db"
# Rate Limits
IP_RATE_LIMIT = 60 # per hour
SESSION_RATE_LIMIT = 20 # per hour
# Session Configuration
SESSION_TIMEOUT = 1800 # 30 minutes
CLEANUP_INTERVAL = 600 # 10 minutes
```
### **Environment Variables**
```bash
GROQ_API_KEY=your_groq_api_key_here
PORT=7860
SQLITE_DB_PATH=/tmp/visitors.db
```
---
## **πŸš€ Deployment Checklist**
### **Backend (Flask API)**
- βœ… Valid Groq API key configured
- βœ… Database migrations applied
- βœ… CORS configured for frontend domain
- βœ… Rate limiting active
- βœ… Background cleanup running
- βœ… Analytics collection enabled
### **Frontend Integration**
- βœ… API endpoint configured correctly
- βœ… Session management implemented
- βœ… Error handling for API failures
- βœ… Smart suggestions display
- βœ… Rich content rendering
- βœ… Rate limit handling
### **Testing**
- βœ… Test different user types (recruiter/technical/general)
- βœ… Verify conversation memory works
- βœ… Check smart suggestions appear
- βœ… Confirm analytics are collected
- βœ… Test rate limiting behavior
- βœ… Verify session continuity
---
## **πŸ“Š Success Metrics**
The API provides detailed metrics to measure success:
- **Engagement Rate**: Conversations per unique visitor
- **User Type Distribution**: Which types of users visit most
- **Conversation Depth**: How many exchanges per session
- **Popular Topics**: Most asked questions
- **Peak Activity**: Best times for engagement
- **Return Visitors**: Session continuity tracking
---
**This comprehensive AI portfolio chatbot transforms basic interactions into intelligent, personalized conversations that adapt to each visitor's needs while providing deep insights into user engagement patterns.**