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:
.env
createdb chatbot_db
If AI responses are not working:
.env
If authentication is failing:
MIT License - Open-source and educational project
Murat Yigit Artuk
POST /api/auth/register
Register 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/token
Authenticate 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/me
Get 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/chat
Send 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/history
Retrieve 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/recommendations
Get 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!
There are no datasets linked
There are no datasets linked