vrsen's picture
Demo finsihed
55d6a73
raw
history blame
No virus
8.74 kB
import openai
import gradio as gr
import pandas as pd
import tiktoken
from openai.error import AuthenticationError
encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")
class Bot():
def __init__(self):
self.car_data = None
self.api_key = None
self.system_prompt = """You are a salesman in a car dealership. You try to give a detailed answer to the
questions so that the customer is well advised. Note: If you recommend vehicles, they can only
be from the csv file provided by the customer. Customer cannot access the csv file himself."""
self.lang = "English"
def process_file(self, file, history):
print(file)
# throw error if file is not csv
if file.name.split(".")[-1] != "csv":
if lang == "English":
history.append((None, "Please upload a csv file"))
else:
history.append((None, "Bitte laden Sie eine csv-Datei hoch"))
return history
df = pd.read_csv(file.name)
# drop all rows with at least one NaN value
df = df.dropna()
df = df.drop(columns=["interne_nummer", "ez.1", "kilometer.1", "leistung.1", "leistung", "ez"])
# rename column leistung to leistung (kW)
# df = df.rename(columns={"leistung": "leistung (kW)"})
# df = df.rename(columns={"ez": "Erstzulassung"})
df = df.loc[:, ~df.columns.duplicated()]
# convert csv to text
self.car_data = df.to_string(index=False)
self.car_data = self.car_data.replace("Car.", "")
print(self.car_data)
print("Car data token count: ", len(encoding.encode(self.car_data)))
if self.api_key:
history = []
return history
def run_text(self, history, query):
# check api key
if not self.api_key:
# key must start from "sk-"
if not query.startswith("sk-"):
if lang == "English":
history.append((None, "Please enter your OpenAI API KEY"))
else:
history.append((None, "Bitte geben Sie Ihren OpenAI API-Schlüssel ein"))
return history
self.api_key = query
openai.api_key = query
if self.car_data:
history = []
else:
history.append((query, None))
if self.lang == "English":
history.append((None, "Please upload a csv file"))
else:
history.append((None, "Bitte laden Sie eine csv-Datei hoch"))
return history
if not self.car_data:
if self.lang == "English":
history.append((None, "Please upload a csv file"))
else:
history.append((None, "Bitte laden Sie eine csv-Datei hoch"))
return history
# add system message to the front
messages = [{"role": "system", "content": self.system_prompt}]
# add messages from history
for q, response in history:
if q:
messages.append({"role": "user", "content": q})
if response:
messages.append({"role": "system", "content": response})
# remove all messages in front of for the first one
# if the total number of tokens is greater than 3000
total_tokens = self._count_tokens(messages)
while total_tokens > 1200:
messages.pop(1)
total_tokens = self._count_tokens(messages)
# construct prompt from search results
if self.lang == "English":
prompt = f"""Use the cars in stock below if you need to recommend any vehicles. Only include cars that are in stock
and include links to your recommendations.
\n\n Cars in stock: \n {self.car_data} \n\n Query: {query} \n\n Response:"""
else:
prompt = f"""Verwenden Sie die unten aufgeführten Fahrzeuge, wenn Sie Fahrzeuge empfehlen müssen.
Berücksichtigen Sie nur Fahrzeuge, die auf Lager sind und geben Sie Links zu Ihren Empfehlungen an.
\n\n Fahrzeuge auf Lager: \n {self.car_data} \n\n Anfrage: {query} \n\n Antwort:"""
messages.append({"role": "user", "content": prompt})
# print(prompt)
# generate response
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # change to gpt-3.5-turbo if don't have access
messages=messages,
temperature=0.3,
)['choices'][0]['message']['content']
# only add query and response to history
# the context is not needed
history.append((query, response))
return history
def generate_welcome_message(self):
messages = [{"role": "system", "content": self.system_prompt}]
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # change to gpt-3.5-turbo if don't have access
messages=messages,
temperature=0.3,
)['choices'][0]['message']['content']
except AuthenticationError:
if self.lang == "English":
response = "Wrong API key. Please enter your OpenAI API KEY"
else:
response = "Falscher API-Schlüssel. Bitte geben Sie Ihren OpenAI API-Schlüssel ein"
self.api_key = None
return response
def _count_tokens(self, messages):
total_tokens = 0
for message in messages:
total_tokens += len(encoding.encode(message['content']))
return total_tokens
def change_language(self, lang, history):
self.lang = lang
if lang == "English":
self.system_prompt = """You are a salesman in a car dealership. You try to give a detailed answer to the
questions so that the customer is well advised. Note: If you recommend vehicles, they can only
be from the csv file provided by the customer. Customer cannot access the csv file himself."""
if not self.api_key:
history = [(None, "Please enter your OpenAI API KEY")]
return history
if not self.car_data:
history = [(None, "Please upload a csv file")]
return history
else:
self.system_prompt = """Sie sind ein Verkäufer in einem Autohaus. Sie versuchen, eine detaillierte Antwort auf die
Fragen zu geben, damit der Kunde gut beraten wird. Hinweis: Wenn Sie Fahrzeuge empfehlen, können sie nur
aus der vom Kunden bereitgestellten CSV-Datei stammen. Der Kunde kann die CSV-Datei nicht selbst aufrufen."""
if not self.api_key:
history = [(None, "Bitte geben Sie Ihren OpenAI API-Schlüssel ein")]
return history
if not self.car_data:
history = [(None, "Bitte laden Sie eine csv-Datei hoch")]
return history
return []
if __name__ == '__main__':
bot = Bot()
# ui
with gr.Blocks(css="#chatbot .overflow-y-auto{height:500px}") as demo:
chatbot = gr.Chatbot([(None, "Please enter your OpenAI API KEY")], elem_id="chatbot", label="HUGO PFOHE - AI Car Salesman").style(height=500)
with gr.Row():
with gr.Column(scale=1):
txt = gr.Textbox(show_label=False, placeholder="What car would you like to buy?").style(
container=False)
# with gr.Column(scale=0.15):
# submit = gr.Button("Submit")
with gr.Row():
with gr.Column(scale=0.34, min_width=0):
lang = gr.inputs.Dropdown(choices=['English', 'German'], label="Language", default="English")
# with gr.Column(scale=0.33, min_width=0):
# clear = gr.Button("Clear")
# with gr.Column(scale=0.33, min_width=0):
# btn = gr.UploadButton("Upload CSV", file_types=["csv"])
with gr.Column(scale=0.66, min_width=0):
with gr.Row():
clear = gr.Button("Clear")
with gr.Row():
btn = gr.UploadButton("Upload CSV", file_types=["csv"])
txt.submit(bot.run_text, [chatbot, txt], chatbot)
txt.submit(lambda: "", None, txt)
lang.change(bot.change_language, [lang, chatbot], chatbot)
# submit.click(txt.submit, [chatbot, txt], chatbot)
# submit.click(lambda: "", None, txt)
clear.click(lambda: [], None, chatbot)
btn.upload(bot.process_file, [btn, chatbot], chatbot)
demo.launch()