LO_AI_Tutor / app.py
mogbuehi's picture
Update app.py
4b58a56
Raw History Blame Contribute Delete
8.31 kB
# Install and Import Gradio, Pandas, Altair, Matplotlib, Os, and OpenAI (put this in "bot_libs.py" file and import it in one line as "import bot_libs" )----------------------------------------------------------------------------------------
import gradio as gr
import pandas as pd
import os
import openai
from pathlib import Path #read in txt files for clean bot
# openai.api_key = input('paste in your OpenAI API key')
# Load Question DF--------------------------------------------------------------------------------
question_df = pd.read_csv('question_df.csv')
# Tool bot is designed to be the tool-using feature of the chat bot.
# During the session it will be a second instance of GPT-3.5 that can use tools
# This gives pretty consistent behavior-------------------------------------------------------------
with open('tool bot sys content.txt', 'r') as file:
tool_bot_sys_content = file.read()
def tool_bot(prompt, history=[]):
messages =[
{"role": "system", "content": tool_bot_sys_content}
]
openai.api_key = os.getenv("OPENAI_API_KEY") ##This isn't working for some reason
messages.append({'role': 'user', 'content': f'Here is my question or statement: {prompt}'}) # using f string to avoid prompt injections
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
temperature=0, #play with temp to get more factual responses
max_tokens=10,#further limit output
top_p=0,
frequency_penalty=0,
presence_penalty=0
)
# saving the message we want to show to the user
assistant_content = response['choices'][0]['message']['content']
# Visual check for testing purposes
print(response)
return assistant_content
# Skipping HTML parser----------------------------------------------------------------------------
question_short = 'Most Profitable Companies'
# Pulling out the question row--------------------------------------------------------------------
question_row = question_df.loc[question_df['question_short'] == question_short]
# print(question_row)
# convert DataFrame to numpy array to list in order to extract the string objects contained inside
hint = question_row['hint'].values.tolist()
py_hint = question_row['python_hint'].values.tolist()
question = question_row['question'].values.tolist()
py_solution = question_row['solution'].values.tolist()
print(f'''{question[0]}
{hint[0]}
{py_hint[0]}
{py_solution[0]}
''')
# The AI Tutor Backend. It has a nested tool_bot function
# Which will trigger grabbing data from questions database
with open('ai tutor sys content.txt', 'r') as file:
ai_tutor_sys_content = file.read()
# Global messages list. The memory of the conversation is stored in this list
messages =[{"role": "system","content": ai_tutor_sys_content + f'''
Here is the context to consider as you help the student:
Question:
{question[0]}
Hint:
{hint[0]}
Python Hint (code snippet):
{py_hint[0]}
Solution:
{py_solution[0]} '''}]
#track index of conversation:
i = [0]
denial_messages = messages #creating a separate history
def ai_chat(prompt, history):
openai.api_key = os.getenv("OPENAI_API_KEY") ##This isn't working for some reason
# calling messages variable inside the function
global messages, denial_messages
tool_response = tool_bot(prompt) #this is another instance of OpenAI (basically another agent) to issue commands
print(f'TOOL RESPONSE: {tool_response}')
# Using tool_bot to analyze conversation and to respond accordingly.
# tool_response is
if tool_response == 'OFF TOPIC' or tool_response == 'CAREER ADVICE':
print("DENIAL LOGIC ACTIVATED")
denial_messages.append({'role': 'user', 'content': f'''This is my prompt:
Prompt: """ {prompt} """
Kindly tell me to stay on the topic of python and data science and/or to avoid questions about career advice
explain to me why my previous prompt was off topic in a sentence or 2.'''})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=denial_messages, #using this message histroy because I don't want to save this to convo history
temperature=1, #play with temp to get more factual responses
max_tokens=100,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
token_count = response['usage']['total_tokens']
if token_count >= 3000:
denial_messages = [denial_messages[0]]
assistant_content = response['choices'][0]['message']['content']
# not appending message history
return assistant_content
# tool_dict = {}
# for tool in tool_dict:
# if tool_response == tool:
# assistant_content = tool_dict[tool]
# return assistant_content
# openai.api_key = os.getenv("OPENAI_API_KEY") ##This isn't working for some reason
messages.append({'role': 'user', 'content': f'{prompt}'}) #f string to avoid prompt injection errors from user
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
temperature=1, #play with temp to get more factual responses
max_tokens=500,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
assistant_content = response['choices'][0]['message']['content']
# hint = '' #this is parsing the json file that is the response reponse. you take the first item in choices list (a list of dictionaries), go to message key, and then go to content key
#print this in the CLI or notebook. This helps with understanding how the response json is structured for further customization
print(f'''
MESSAGE: {messages}
RESPONSE:{response}
''')
# Saving as variable to store the conversation history
format_str = f'''
User: {prompt}
Response: {assistant_content}
'''
# Saving content to a text file
# Open a file in write mode, 'a' argument serves as appending to
with open('saved_chat.txt', 'a') as file:
file.write(format_str)
#add token counter and a way to handle hitting token limit.
# Prob summarizing previous assistant/student info into 2-4 sentences, 3000 tokens is safe place to start summary
token_count = response['usage']['total_tokens']
if token_count >= 3000:
# Reload message history text for summarization. Better formatted than parsing the response JSON
# content_txt = Path('saved_chat.txt').read_text()
# summary_str[0] = summarize_bot_saved(content_txt)
messages = [messages[0]] # basically erase the memory except the system message and kept it as a list
# print(f'This is the `messages` memory: {summary_str}')
messages.append(({'role':'assistant', 'content': assistant_content}))
# absolute_path = os.path.abspath('matt/Most Profitable Companies faq.html')
# print(absolute_path)
return assistant_content
demo = gr.ChatInterface(
fn=ai_chat,
submit_btn = 'Submit',
retry_btn = 'Retry',
clear_btn = 'Clear',
title = 'AI Backend V1',
description = '''The AI Tutor is assuming you are working on this problem at this url: https://platform.stratascratch.com/coding/10354-most-profitable-companies?code_type=2
When conversating with this bot you can only ask data science questions or python questions in relation to that question. It has hints and solutions preloaded and can explain the hints and solutions further as you needed. Chat with it like you would an AI tutor.
It can analyze your inquiry and will respond accordingly. If you ask something that deviates from the topic of data science, it will politely ask you to stay on task. You can still say "Hello" or give a general greeting, but it can analyze when you are starting to veer off subject and will instruct you to stay on topic (Try it out!)
Feel free to contact me @ https://www.linkedin.com/in/matt-ogbuehi-b6443934/ with any comments or questions''',
#add a save convo button that can create html file that can then be printed like a pdf later
)
demo.launch()