A full-stack web application exploring the frontiers of AI-assisted communication, demonstrating modern software development practices and machine learning integration.
This project represents a learning journey in:
Clone the repository:
git clone https://github.com/muratyigitartuk/AdvancedAIChatbot.git
cd advanced-ai-chatbot
Set up a virtual environment:
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
Install dependencies:
pip install -r requirements.txt
Set up environment variables:
cp .env.example .env
# Edit .env with your configuration
Initialize the database:
alembic upgrade head
Start the backend:
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
Navigate to the frontend directory:
cd frontend
Install dependencies:
npm install
Start the development server:
npm start
The application uses the following environment variables:
# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=chatbot_db
DB_USER=postgres
DB_PASSWORD=your_password
# OpenAI Configuration
OPENAI_API_KEY=your_openai_api_key
DEFAULT_MODEL=gpt-3.5-turbo
# Authentication
SECRET_KEY=your_secret_key
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
Build the Docker images:
docker-compose build
Start the containers:
docker-compose up -d
kubectl apply -f k8s/
Once the application is running, visit /docs or /redoc for interactive API documentation.
🔐 Authentication
POST /api/auth/register: Register a new userPOST /api/auth/token: Login and get access tokenGET /api/auth/me: Get current user profile💬 Chat
POST /api/chat: Send a message to the chatbotGET /api/user/history: Get user conversation historyGET /api/recommendations: Get proactive recommendationsadvanced-ai-chatbot/ ├── app/ # Backend application │ ├── api/ # API endpoints │ │ ├── auth.py # Authentication routes │ │ ├── chat.py # Chat functionality routes │ │ └── voice.py # Voice processing routes │ ├── core/ # Core functionality │ │ ├── ai_engine.py # Main AI processing engine │ │ ├── auth.py # Authentication logic │ │ ├── context.py # Context management │ │ └── proactive.py # Proactive recommendations │ ├── db/ # Database models & connections │ │ ├── database.py # Database connection │ │ └── models.py # SQLAlchemy models │ ├── services/ # External services integration │ │ ├── user_profile.py # User profile management │ │ └── voice_service.py # Voice processing service │ └── utils/ # Utility functions │ └── helpers.py # Helper functions ├── frontend/ # React frontend │ ├── public/ # Static files │ └── src/ # Source code │ ├── components/ # Reusable components │ ├── contexts/ # React contexts │ ├── pages/ # Page components │ └── App.js # Main application component ├── config/ # Configuration files ├── k8s/ # Kubernetes configurations ├── tests/ # Test suite ├── .env.example # Example environment variables ├── docker-compose.yml # Docker Compose configuration ├── Dockerfile # Docker configuration └── README.md # Project documentation
pytest
cd frontend npm test
I followed PEP 8 guidelines for Python code. You can check your code with:
flake8 .
When changing models, create a new migration:
alembic revision --autogenerate -m "Description of changes" alembic upgrade head
main: Production-ready codedevelop: Integration branch for featuresfeature/*: New featuresbugfix/*: Bug fixesIf you encounter database connection issues:
.envcreatedb chatbot_dbIf AI responses are not working:
.envIf authentication is failing:
MIT License - Open-source and educational project
Murat Yigit Artuk
POST /api/auth/registerRegister a new user in the system.
Request Body:
{ "username": "newuser", "email": "user@example.com", "password": "securepassword123", "full_name": "New User" }
Response (201 Created):
{ "id": "user_uuid", "username": "newuser", "email": "user@example.com", "full_name": "New User", "created_at": "2025-02-28T19:02:23" }
POST /api/auth/tokenAuthenticate and receive an access token.
Request Body:
{ "username": "newuser", "password": "securepassword123" }
Response (200 OK):
{ "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "bearer", "expires_in": 1800 }
GET /api/auth/meGet the current user's profile information.
Headers:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Response (200 OK):
{ "id": "user_uuid", "username": "newuser", "email": "user@example.com", "full_name": "New User", "created_at": "2025-02-28T19:02:23" }
POST /api/chatSend a message to the chatbot and receive a response.
Headers:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Request Body:
{ "message": "Tell me about artificial intelligence", "context_id": "optional_conversation_id", "metadata": { "source": "web", "device_info": "Chrome/Windows" } }
Response (200 OK):
{ "id": "message_uuid", "content": "Artificial intelligence (AI) refers to...", "created_at": "2025-02-28T19:05:23", "context_id": "conversation_uuid", "metadata": { "source": "web", "device_info": "Chrome/Windows", "tokens_used": 150, "model": "gpt-3.5-turbo" } }
GET /api/user/historyRetrieve the user's conversation history.
Headers:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Query Parameters:
limit (optional): Maximum number of conversations to returnoffset (optional): Pagination offsetstart_date (optional): Filter by start dateend_date (optional): Filter by end dateResponse (200 OK):
{ "conversations": [ { "id": "conversation_uuid", "title": "Conversation about AI", "created_at": "2025-02-28T19:00:23", "updated_at": "2025-02-28T19:10:23", "messages": [ { "id": "message_uuid1", "role": "user", "content": "Tell me about artificial intelligence", "created_at": "2025-02-28T19:05:23" }, { "id": "message_uuid2", "role": "assistant", "content": "Artificial intelligence (AI) refers to...", "created_at": "2025-02-28T19:05:30" } ] } ], "total": 10, "limit": 10, "offset": 0 }
GET /api/recommendationsGet proactive recommendations based on user's conversation history.
Headers:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Response (200 OK):
{ "recommendations": [ { "id": "rec_uuid1", "title": "Learn more about Machine Learning", "description": "Based on your interest in AI, you might want to explore machine learning concepts.", "relevance_score": 0.92, "created_at": "2025-02-28T19:15:23" }, { "id": "rec_uuid2", "title": "Explore Natural Language Processing", "description": "NLP is a key component of modern AI systems like chatbots.", "relevance_score": 0.85, "created_at": "2025-02-28T19:15:23" } ] }
import requests import json # Configuration API_URL = "http://localhost:8000" TOKEN = "your_access_token" # Headers headers = { "Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json" } # Send a message to the chatbot def send_message(message, context_id=None): endpoint = f"{API_URL}/api/chat" payload = { "message": message, "metadata": { "source": "python_client", "device_info": "Python/Script" } } if context_id: payload["context_id"] = context_id response = requests.post(endpoint, headers=headers, json=payload) if response.status_code == 200: return response.json() else: print(f"Error: {response.status_code}") print(response.text) return None # Example usage response = send_message("Tell me about machine learning") print(json.dumps(response, indent=2)) # Continue the conversation if response and "context_id" in response: follow_up = send_message("How is it different from deep learning?", response["context_id"]) print(json.dumps(follow_up, indent=2))
import requests # Configuration API_URL = "http://localhost:8000" # Register a new user def register_user(username, email, password, full_name): endpoint = f"{API_URL}/api/auth/register" payload = { "username": username, "email": email, "password": password, "full_name": full_name } response = requests.post(endpoint, json=payload) if response.status_code == 201: print("User registered successfully!") return response.json() else: print(f"Error: {response.status_code}") print(response.text) return None # Login and get token def login(username, password): endpoint = f"{API_URL}/api/auth/token" payload = { "username": username, "password": password } response = requests.post(endpoint, data=payload) if response.status_code == 200: token_data = response.json() print("Login successful!") return token_data["access_token"] else: print(f"Error: {response.status_code}") print(response.text) return None # Example usage new_user = register_user("testuser", "test@example.com", "securepass123", "Test User") if new_user: token = login("testuser", "securepass123") print(f"Access Token: {token}")
import React, { useState, useEffect, useRef } from 'react'; import axios from 'axios'; import { useAuth } from '../contexts/AuthContext'; import ChatMessage from './ChatMessage'; import './Chat.css'; const Chat = () => { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [loading, setLoading] = useState(false); const [contextId, setContextId] = useState(null); const { token } = useAuth(); const messagesEndRef = useRef(null); // Scroll to bottom of messages const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToBottom(); }, [messages]); // Send message to API const sendMessage = async (e) => { e.preventDefault(); if (!input.trim()) return; // Add user message to chat const userMessage = { id: Date.now().toString(), role: 'user', content: input, created_at: new Date().toISOString() }; setMessages([...messages, userMessage]); setInput(''); setLoading(true); try { const response = await axios.post( '/api/chat', { message: input, context_id: contextId, metadata: { source: 'web', device_info: navigator.userAgent } }, { headers: { Authorization: `Bearer ${token}` } } ); // Add AI response to chat const aiMessage = { id: response.data.id, role: 'assistant', content: response.data.content, created_at: response.data.created_at }; setMessages(prev => [...prev, aiMessage]); // Save context ID for conversation continuity if (response.data.context_id) { setContextId(response.data.context_id); } } catch (error) { console.error('Error sending message:', error); // Add error message const errorMessage = { id: Date.now().toString(), role: 'system', content: 'Sorry, there was an error processing your request.', created_at: new Date().toISOString() }; setMessages(prev => [...prev, errorMessage]); } finally { setLoading(false); } }; return ( <div className="chat-container"> <div className="messages-container"> {messages.map(message => ( <ChatMessage key={message.id} message={message} /> ))} {loading && ( <div className="message assistant loading"> <div className="typing-indicator"> <span></span> <span></span> <span></span> </div> </div> )} <div ref={messagesEndRef} /> </div> <form className="input-container" onSubmit={sendMessage}> <input type="text" value={input} onChange={(e) => setInput(e.target.value)} placeholder="Type your message..." disabled={loading} /> <button type="submit" disabled={loading || !input.trim()}> Send </button> </form> </div> ); }; export default Chat;
┌─────────────────┐      ┌─────────────────┐      ┌─────────────────┐
│                 │      │                 │      │                 │
│  React Frontend ├──────►  FastAPI Backend├──────►  OpenAI API     │
│                 │      │                 │      │                 │
└────────┬────────┘      └────────┬────────┘      └─────────────────┘
         │                        │
         │                        │
         │                ┌───────▼────────┐
         │                │                │
         └────────────────►  PostgreSQL DB │
                          │                │
                          └────────────────┘
┌───────────────┐     ┌───────────────┐     ┌───────────────┐     ┌───────────────┐
│               │     │               │     │               │     │               │
│  User Input   ├────►│  Auth Service ├────►│  AI Engine    ├────►│  Response     │
│               │     │               │     │               │     │  Generation   │
└───────┬───────┘     └───────────────┘     └───────┬───────┘     └───────┬───────┘
        │                                           │                     │
        │                                           │                     │
┌───────▼───────┐                          ┌────────▼──────┐     ┌───────▼───────┐
│               │                          │               │     │               │
│  Context      │◄─────────────────────────┤  User Profile │◄────┤  Metadata     │
│  Management   │                          │  Service      │     │  Processing   │
│               │                          │               │     │               │
└───────────────┘                          └───────────────┘     └───────────────┘
┌─────────────────────┐       ┌─────────────────────┐
│ User                │       │ Conversation        │
├─────────────────────┤       ├─────────────────────┤
│ id (PK)             │       │ id (PK)             │
│ username            │       │ user_id (FK)        │
│ email               │       │ title               │
│ hashed_password     │       │ created_at          │
│ full_name           │       │ updated_at          │
│ created_at          │       └──────────┬──────────┘
└──────────┬──────────┘                  │
           │                             │
           │ 1                         1 ┃
           └─────────────────────────────┫
                                         ┃ *
                                ┌────────▼──────────┐
                                │ Message           │
                                ├─────────────────────┤
                                │ id (PK)             │
                                │ conversation_id (FK)│
                                │ role                │
                                │ content             │
                                │ message_metadata    │
                                │ created_at          │
                                └─────────────────────┘
We welcome contributions to the Advanced AI Chatbot project! This guide will help you get started with the contribution process.
Fork the Repository
Clone Your Fork
git clone https://github.com/YOUR-USERNAME/AdvancedAIChatbot.git cd AdvancedAIChatbot
Add the Original Repository as Upstream
git remote add upstream https://github.com/muratyigitartuk/AdvancedAIChatbot.git
Create a New Branch
git checkout -b feature/your-feature-name
Make Your Changes
Commit Your Changes
git add . git commit -m "Feature: Brief description of your changes"
Pull Latest Changes from Upstream
git pull upstream main
Push to Your Fork
git push origin feature/your-feature-name
Create a Pull Request
If you find a bug or have a feature request:
Thank you for contributing to the Advanced AI Chatbot project!
