├── pdf ├── test.md ├── Lec 1.pdf ├── Lec 7.pdf ├── Lec 8.pdf ├── Lec 2-3.pdf ├── Lec 4-6.pdf ├── courseOutline.pdf └── sample_midterm.pdf ├── packages.txt ├── logo.png ├── method.png ├── sb_logo.png ├── web_app_view.png ├── requirements.txt ├── LICENSE ├── api_handler.py ├── file_upload.py ├── chat_gen.py ├── README.md └── app.py /pdf/test.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /packages.txt: -------------------------------------------------------------------------------- 1 | wkhtmltopdf 2 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/098765d/AI_Tutor/HEAD/logo.png -------------------------------------------------------------------------------- /method.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/098765d/AI_Tutor/HEAD/method.png -------------------------------------------------------------------------------- /pdf/Lec 1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/098765d/AI_Tutor/HEAD/pdf/Lec 1.pdf -------------------------------------------------------------------------------- /pdf/Lec 7.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/098765d/AI_Tutor/HEAD/pdf/Lec 7.pdf -------------------------------------------------------------------------------- /pdf/Lec 8.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/098765d/AI_Tutor/HEAD/pdf/Lec 8.pdf -------------------------------------------------------------------------------- /sb_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/098765d/AI_Tutor/HEAD/sb_logo.png -------------------------------------------------------------------------------- /pdf/Lec 2-3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/098765d/AI_Tutor/HEAD/pdf/Lec 2-3.pdf -------------------------------------------------------------------------------- /pdf/Lec 4-6.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/098765d/AI_Tutor/HEAD/pdf/Lec 4-6.pdf -------------------------------------------------------------------------------- /web_app_view.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/098765d/AI_Tutor/HEAD/web_app_view.png -------------------------------------------------------------------------------- /pdf/courseOutline.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/098765d/AI_Tutor/HEAD/pdf/courseOutline.pdf -------------------------------------------------------------------------------- /pdf/sample_midterm.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/098765d/AI_Tutor/HEAD/pdf/sample_midterm.pdf -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | streamlit 2 | openai 3 | fpdf2 4 | jinja2 5 | markdown2 6 | pdfkit 7 | wkhtmltopdf 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 dd 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /api_handler.py: -------------------------------------------------------------------------------- 1 | from openai import OpenAI 2 | import time 3 | 4 | 5 | def send_query_get_response(client,user_question,assistant_id): 6 | # Create a new thread for the query 7 | thread = client.beta.threads.create() 8 | thread_id = thread.id 9 | 10 | user_question=user_question+ ' and tell me which file are the top results based on your similarity search (an example of can be you can refer to the course material titled "Present Value Relations" in the file "Lec 2-3.pdf" under slides 20-34.)' 11 | 12 | # Send the user's question to the thread 13 | client.beta.threads.messages.create( 14 | thread_id=thread_id, 15 | role="user", 16 | content=user_question, 17 | ) 18 | 19 | # Create and start a run for the thread 20 | run = client.beta.threads.runs.create( 21 | thread_id=thread_id, 22 | assistant_id=assistant_id, 23 | ) 24 | 25 | # Initialize a timer to limit the response wait time 26 | start_time = time.time() 27 | 28 | # Continuously check the run status 29 | run_status = None 30 | while run_status != 'completed': 31 | run = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id) 32 | run_status = run.status 33 | 34 | # Time check to break the loop if it runs more than 60 seconds 35 | if time.time() - start_time > 60: 36 | print("Final run status:", run_status) 37 | print("Took too long time") 38 | break 39 | 40 | # Fetch and print the entire conversation history 41 | messages = client.beta.threads.messages.list( 42 | thread_id=thread_id, 43 | order='asc' 44 | ) 45 | 46 | # Return the last response from the thread 47 | message=messages.data[-1] 48 | message_content=message.content[0].text 49 | response=message_content.value 50 | 51 | return response if messages.data else "Server issue, try again" 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /file_upload.py: -------------------------------------------------------------------------------- 1 | import openai 2 | import streamlit as st 3 | import os 4 | 5 | def upload_files_to_assistant(client, uploaded_files): 6 | file_ids = [] 7 | file_paths=[] 8 | for uploaded_file in uploaded_files: 9 | if uploaded_file is not None: 10 | file_path=os.path.join(os.getcwd(),uploaded_file.name) 11 | response = client.files.create( 12 | file=uploaded_file, 13 | purpose='assistants' 14 | ) 15 | file_ids.append(response.id) 16 | file_paths.append(file_path) 17 | print(file_paths) 18 | return file_ids,file_paths 19 | 20 | def attach_files_to_assistant(client, file_ids, assistant_id): 21 | attached_files = [] 22 | for file_id in file_ids: 23 | assistant_file = client.beta.assistants.files.create( 24 | assistant_id=assistant_id, 25 | file_id=file_id 26 | ) 27 | attached_files.append(assistant_file) 28 | return attached_files 29 | 30 | 31 | def check_and_upload_files(client, assistant_id): 32 | 33 | assistant_files = client.beta.assistants.files.list(assistant_id=assistant_id) 34 | files_info = [file.id for file in assistant_files.data] 35 | if not files_info: 36 | st.warning("No Files Included, Upload Educational Material") 37 | uploaded_files = st.file_uploader("Choose PDF files", type="pdf", accept_multiple_files=True) 38 | 39 | if st.button("Upload and Attach Files"): 40 | if uploaded_files: 41 | try: 42 | file_ids ,file_paths= upload_files_to_assistant(client, uploaded_files) 43 | 44 | attached_files_info = attach_files_to_assistant(client, file_ids, assistant_id) 45 | 46 | if not attached_files_info: 47 | st.warning("No files were attached. Loading default data...") 48 | else: 49 | st.success(f"{len(attached_files_info)} files successfully attached.") 50 | except Exception as e: 51 | st.error(f"An error occurred while attaching files: {e}") 52 | else: 53 | st.warning("Please select at least one file to upload.") 54 | 55 | return files_info -------------------------------------------------------------------------------- /chat_gen.py: -------------------------------------------------------------------------------- 1 | 2 | import io 3 | from datetime import datetime 4 | import markdown2 # assuming markdown2 is installed 5 | 6 | def generate_html(messages): 7 | timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") 8 | chat_content = "" 9 | interaction_count = 0 10 | user_emoji = "User" # Emoji for user 11 | assistant_emoji = "AI-Tutor" # Emoji for assistant 12 | 13 | for message in messages: 14 | role_class = 'user' if message['role'] == 'user' else 'assistant' 15 | emoji = user_emoji if role_class == 'user' else assistant_emoji 16 | if role_class == 'user': 17 | interaction_count += 1 18 | 19 | formatted_content = markdown2.markdown(message['content']).replace('\\n', '
') 20 | chat_content += f"
{emoji}{formatted_content}
" 21 | 22 | html_content = f""" 23 | 24 | 25 | 26 | EduMentor Chat History 27 | 28 | 72 | 73 | 74 |
75 |
76 |

EduMentor Chat History

77 |
Generated on: {timestamp}
78 |
Total Q&A Interactions: {interaction_count}
79 |
80 |
81 | {chat_content} 82 |
83 | 86 |
87 | 88 | 89 | """ 90 | return html_content 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AI-Tutor: Customized AI Tutoring for Diverse Academic Courses 2 | 3 |
4 | AI_Tutor 5 |
6 | 7 | ## Overview 8 | AI-Tutor, an educational web app, integrates the latest OpenAI's Assistant API and Retrieval-Augmented Generation (RAG) to offer personalized tutoring across various academic courses. It adapts to specific course materials, ensuring a dynamic, responsive, and tailored learning experience. 9 | 10 | ## Core Features 11 | - **Versatile Application**: Adaptable to any course with the requirement of uploading course-specific materials. 12 | - **Intelligent Tutoring**: Tailored responses that align with course content, overcoming information hallucination. 13 | - **User Interface**: Streamlit-based, intuitive UI hosted on the Free Streamlit Community Cloud. 14 | - **Data Privacy and Security**: Adherence to OpenAI's stringent privacy practices. 15 | 16 | ## Technical Composition 17 | - **Core Technologies**: Utilizes LLM and RAG from OpenAI's Assistants API for core AI functionalities. 18 | - **Programming Language**: Primarily Python. 19 | - **Hosting Server**: Free Streamlit Community Cloud. 20 | 21 | ## Methodology 22 | AI-Tutor employs a combination of advanced AI technologies to enhance the learning experience: 23 | 24 | - **LLM API**: This forms the backbone of AI-Tutor's intelligence. It enables the platform to understand complex queries, retrieve information efficiently, and provide accurate, context-aware responses. 25 | 26 | - **Retrieval-Augmented Generation (RAG)**: RAG is a key component that supplements the AI's knowledge base. By accessing external data sources, RAG ensures that the AI's responses are not only relevant but also grounded in verified information. This feature is crucial for maintaining the accuracy and reliability of the educational content provided by AI-Tutor. 27 | 28 | - *Mitigating Information Hallucination*: RAG effectively addresses the challenge of AI-generated misinformation by validating responses against trusted external sources. 29 | - *Personalized Learning Experience*: The use of diverse data sources enables AI-Tutor to tailor its responses to specific educational contexts and individual learner needs. 30 | 31 | ![Method](method.png) 32 | 33 | 34 | 35 | 36 | ## Web App Components 37 |
38 | AI_Tutor 39 |
40 | 41 | - **Sidebar**: 42 | - Option to delete all uploaded materials. 43 | - Generate and download Q&A records in HTML format. 44 | - **Main Page**: 45 | - API Key input. 46 | - Upload feature for course materials. 47 | - Interactive Q&A section. 48 | - Display and archive of Q&A records. 49 | - Feature to pose new questions. 50 | 51 | ## Getting Started 52 | 1. Access [AI-Tutor Streamlit App](https://aitutor-gawywv3h6qfwzzvikfzkpl.streamlit.app/). 53 | 2. Enter your OpenAI API Key. 54 | 3. Upload course materials for a custom tutoring session. 55 | 4. Interact with the AI assistant for course-specific queries. 56 | 5. Download the Q&A session transcript in HTML format. 57 | 58 | ## Benefits 59 | - **Enhanced Learning Experience**: Integrates RAG with AI technologies for a personalized educational journey. 60 | - **Data Privacy Assurance**: Strong commitment to user data protection. 61 | - **Current and Relevant Responses**: Ensures up-to-date and accurate information. 62 | - **Broad Course Coverage**: Applicable across various educational fields and disciplines. 63 | - **Interactive Tutoring**: Real-time feedback and dynamic learning sessions. 64 | 65 | ## References 66 | - [OpenAI Assistant API Documentation](https://platform.openai.com/docs/guides/assistants) 67 | - [Introduction to Retrieval-Augmented Generation (RAG)](https://www.datastax.com/blog/2020/10/introducing-retrieval-augmented-generation-rag) 68 | - [Vector Database Similarity Search](https://www.infoworld.com/article/3634357/what-is-vector-search-better-search-through-ai.html) 69 | - [OpenAI Privacy and Security Practices](https://openai.com/security) 70 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | # Built-in modules 2 | import io 3 | import os 4 | import subprocess 5 | 6 | # Third-party modules 7 | import streamlit as st 8 | from PIL import Image 9 | from openai import OpenAI 10 | 11 | # Local modules 12 | import api_handler 13 | from api_handler import send_query_get_response 14 | from chat_gen import generate_html 15 | from file_upload import upload_files_to_assistant, attach_files_to_assistant, check_and_upload_files 16 | 17 | logo=Image.open('logo.png') 18 | sb_logo=Image.open('sb_logo.png') 19 | 20 | 21 | c1, c2 = st.columns([0.9, 3.2]) 22 | 23 | with c1: 24 | st.caption('') 25 | st.caption('') 26 | st.image(logo,width=120) 27 | 28 | with c2: 29 | 30 | st.title('EduMentor : An AI-Enhanced Tutoring System') 31 | 32 | 33 | # RAG Function Description 34 | st.markdown("## AI Tutor Description") 35 | rag_description = """ 36 | EduMentor leverages the cutting-edge RAG (Retrieval-Augmented Generation) function to provide in-depth, contextually rich answers to complex educational queries. This AI-driven approach combines extensive knowledge retrieval with dynamic response generation, offering students a deeper, more nuanced understanding of subjects and fostering a more interactive, exploratory learning environment. 37 | """ 38 | st.markdown(rag_description) 39 | 40 | # OpenAI API Key Input 41 | api_key = st.text_input(label='Enter your OpenAI API Key', type='password') 42 | 43 | if api_key: 44 | # If API key is entered, initialize the OpenAI client and proceed with app functionality 45 | client = OpenAI(api_key=api_key) 46 | assistant_id = 'asst_konaahsahZ0UhK82guGBvn6m' 47 | 48 | # File Handling Section 49 | files_info = check_and_upload_files(client, assistant_id) 50 | 51 | st.markdown(f'Number of files uploaded in the assistant: :blue[{len(files_info)}]') 52 | st.divider() 53 | 54 | # Sidebar for Additional Features 55 | st.sidebar.header('EduMentor: AI-Tutor') 56 | st.sidebar.image(logo,width=120) 57 | st.sidebar.caption('Made by D') 58 | # Adding a button in the sidebar to delete all files from the assistant 59 | if st.sidebar.button('Delete All Files from Assistant'): 60 | # Retrieve all file IDs associated with the assistant 61 | assistant_files_response = client.beta.assistants.files.list(assistant_id=assistant_id) 62 | assistant_files = assistant_files_response.data 63 | 64 | # Delete each file 65 | for file in assistant_files: 66 | file_id = file.id 67 | client.beta.assistants.files.delete(assistant_id=assistant_id, file_id=file_id) 68 | st.sidebar.success(f'Deleted file: {file_id}') 69 | 70 | if st.sidebar.button('Generate Chat History'): 71 | html_data = generate_html(st.session_state.messages) 72 | st.sidebar.download_button(label="Download Chat History as HTML", 73 | data=html_data, 74 | file_name="chat_history.html", 75 | mime="text/html") 76 | 77 | 78 | # Main Chat Interface 79 | st.subheader('Q&A record with AI-Tutor 📜') 80 | st.caption('You can choose to download the chat history in either PDF or HTML format using the options in the sidebar on the left.') 81 | if "messages" not in st.session_state: 82 | st.session_state.messages = [] 83 | 84 | for message in st.session_state.messages: 85 | with st.chat_message(message["role"]): 86 | st.markdown(message["content"], unsafe_allow_html=True) 87 | 88 | if prompt := st.chat_input("Welcome and ask a question to the AI tutor"): 89 | st.session_state.messages.append({"role": "user", "content": prompt}) 90 | with st.chat_message("user"): 91 | st.markdown(prompt) 92 | 93 | with st.chat_message("assistant", avatar='👨🏻‍🏫'): 94 | message_placeholder = st.empty() 95 | with st.spinner('Thinking...'): 96 | response = send_query_get_response(client,prompt,assistant_id) 97 | message_placeholder.markdown(response) 98 | st.session_state.messages.append({"role": "assistant", "content": response}) 99 | 100 | else: 101 | # Prompt for API key if not entered 102 | st.warning("Please enter your OpenAI API Key to use EduMentor.") 103 | --------------------------------------------------------------------------------