Skip to content

Commit

Permalink
Final fixes to chatbot and toast
Browse files Browse the repository at this point in the history
  • Loading branch information
cmaloney111 committed Jun 17, 2024
1 parent 52bb393 commit 8c7423f
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 62 deletions.
78 changes: 22 additions & 56 deletions api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ def chat():
chat_history = data.get('history', [])
api_key = data.get('apikey')


if df is not None:

print(df.head(1))
documents = split_dataframe_into_documents(df)

embeddings = OpenAIEmbeddings(api_key=api_key)
Expand All @@ -74,27 +77,24 @@ def chat():

return jsonify(reply=bot_reply)
else:
print("No df")
return jsonify(reply="No data available."), 400

# messages = [{"role": "system", "content": "You are a helpful assistant."}]
# for msg in chat_history:
# messages.append({"role": "user" if msg['origin'] == 'user' else "assistant", "content": msg['text']})
# messages.append({"role": "user", "content": user_message})

# try:
# client = openai.OpenAI(api_key = api_key)
# response = client.chat.completions.create(
# model="gpt-3.5-turbo",
# messages=messages,
# max_tokens=200
# )
# bot_reply = response.choices[0].message.content.strip()

# return jsonify(reply=bot_reply)
# except Exception as e:
# print(f"Error: {e}")
# return jsonify(reply="Desculpe, ocorreu um erro ao processar sua mensagem."), 500
messages = [{"role": "system", "content": "You are a helpful assistant."}]
for msg in chat_history:
messages.append({"role": "user" if msg['origin'] == 'user' else "assistant", "content": msg['text']})
messages.append({"role": "user", "content": user_message})

try:
client = openai.OpenAI(api_key = api_key)
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
max_tokens=200
)
bot_reply = response.choices[0].message.content.strip()

return jsonify(reply=bot_reply)
except Exception as e:
print(f"Error: {e}")
return jsonify(reply="Desculpe, ocorreu um erro ao processar sua mensagem."), 500


def shutdown_server():
Expand All @@ -116,7 +116,7 @@ def receive_file():
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
if file:
df = pd.read_csv(file)
df = pd.read_csv(file, on_bad_lines='skip')
return jsonify({'message': 'File uploaded successfully'}), 200


Expand Down Expand Up @@ -282,40 +282,6 @@ def apikey():
return jsonify(reply="Desculpe, ocorreu um erro ao processar sua mensagem."), 500


# @app.route('/chat', methods=['POST'])
# def chat():
# global df
# if df is not None:
# # run rag
# print(df.head(1))
# else:
# print("No df")
# data = request.get_json()
# user_message = data.get('message')
# chat_history = data.get('history', [])
# api_key = data.get('apikey')

# messages = [{"role": "system", "content": "You are a helpful assistant."}]
# for msg in chat_history:
# messages.append({"role": "user" if msg['origin'] == 'user' else "assistant", "content": msg['text']})
# messages.append({"role": "user", "content": user_message})

# try:
# client = openai.OpenAI(api_key = api_key)
# response = client.chat.completions.create(
# model="gpt-3.5-turbo", # ou a gente poderia ver com gpt 4 mas por enquanto coloquei 3.5
# messages=messages,
# max_tokens=200
# )
# bot_reply = response.choices[0].message.content.strip()

# return jsonify(reply=bot_reply)
# except Exception as e:
# print(f"Error: {e}")
# return jsonify(reply="Desculpe, ocorreu um erro ao processar sua mensagem."), 500



if __name__ == '__main__':
training_progress = {
'training_progress': 0,
Expand Down
5 changes: 3 additions & 2 deletions src/components/chatbot/chatbot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@ const ChatBot: React.FC = () => {
const errorMessage: Message = { text: "Desculpe, ocorreu um erro. Tente novamente.", origin: 'bot' };
setChatHistory(prevHistory => [...prevHistory, errorMessage]);
}

console.log(message)
setMessage("");
console.log(message)
};

const sendAPIKeyMessage = () => {
Expand Down Expand Up @@ -130,7 +131,7 @@ const ChatBot: React.FC = () => {
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyPress={(e) => {
if (e.key === 'Enter') sendMessage();
if (e.key === 'Enter') sendMessage()
}}
/>
<button
Expand Down
8 changes: 6 additions & 2 deletions src/pages/views/trainView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export default function TrainView() {
const [hasTrained, setHasTrained] = useState(false);
const [isCancelling, setIsCancelling] = useState(false);
const [trainingCompleted, setTrainingCompleted] = useState(false);
const [hasCancelled, setHasCancelled] = useState(false);

const handleChangeSelectedColumn = (event: React.ChangeEvent<HTMLSelectElement>) => {
setSelectedColumn(Number(event.target.value));
Expand All @@ -30,8 +31,9 @@ export default function TrainView() {

const handleCancelTraining = async () => {
setIsCancelling(true);
setHasCancelled(true);
try {
await axios.post('http://localhost:5000/cancel-training');
await axios.post('http://localhost:5000/cancel-training');
alert('Treinamento cancelado com sucesso!');
} catch (error) {
console.error('Erro ao cancelar o treinamento:', error);
Expand All @@ -44,6 +46,7 @@ export default function TrainView() {
setIsLoading(true);
setHasTrained(true);
setTrainingCompleted(false);
setHasCancelled(false);
setLoadingProgress(0);
setTrainLosses([]);
setValidLosses([]);
Expand Down Expand Up @@ -85,6 +88,7 @@ export default function TrainView() {

const handleNbSubmit = async () => {
setIsLoading(true);
setHasCancelled(false);
setTrainingCompleted(false);
setLoadingProgress(0);

Expand Down Expand Up @@ -213,7 +217,7 @@ export default function TrainView() {
}, []);

useEffect(() => {
if (trainingCompleted) {
if (trainingCompleted && !hasCancelled) {
toast("Seu modelo está disponível para uso na aba de Classificação", {
position: "bottom-right",
autoClose: 5000,
Expand Down
9 changes: 7 additions & 2 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -9902,7 +9902,7 @@ react-dev-utils@^12.0.0:
strip-ansi "^6.0.1"
text-table "^0.2.0"

"react-dom@^17.0.0 || ^18.0.0", react-dom@^18.0.0, react-dom@^18.2.0, react-dom@>=16.6.0, react-dom@>=16.8, react-dom@>=16.8.0, react-dom@>=18:
"react-dom@^16.0.0 || ^17.0.0 || ^18.0.0", "react-dom@^17.0.0 || ^18.0.0", react-dom@^18.0.0, react-dom@^18.2.0, react-dom@>=16.6.0, react-dom@>=16.8, react-dom@>=16.8.0, react-dom@>=18:
version "18.2.0"
resolved "https://registry.npmjs.org/react-dom/-/react-dom-18.2.0.tgz"
integrity sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==
Expand Down Expand Up @@ -10023,6 +10023,11 @@ [email protected]:
optionalDependencies:
fsevents "^2.3.2"

react-spinners@^0.13.8:
version "0.13.8"
resolved "https://registry.npmjs.org/react-spinners/-/react-spinners-0.13.8.tgz"
integrity sha512-3e+k56lUkPj0vb5NDXPVFAOkPC//XyhKPJjvcGjyMNPWsBKpplfeyialP74G7H7+It7KzhtET+MvGqbKgAqpZA==

react-toastify@^10.0.5:
version "10.0.5"
resolved "https://registry.npmjs.org/react-toastify/-/react-toastify-10.0.5.tgz"
Expand All @@ -10040,7 +10045,7 @@ react-transition-group@^4.4.5:
loose-envify "^1.4.0"
prop-types "^15.6.2"

react@*, "react@^17.0.0 || ^18.0.0", react@^18.0.0, react@^18.2.0, "react@>= 16", react@>=0.13, react@>=16, react@>=16.6.0, react@>=16.8, react@>=16.8.0, react@>=18:
react@*, "react@^16.0.0 || ^17.0.0 || ^18.0.0", "react@^17.0.0 || ^18.0.0", react@^18.0.0, react@^18.2.0, "react@>= 16", react@>=0.13, react@>=16, react@>=16.6.0, react@>=16.8, react@>=16.8.0, react@>=18:
version "18.2.0"
resolved "https://registry.npmjs.org/react/-/react-18.2.0.tgz"
integrity sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==
Expand Down

0 comments on commit 8c7423f

Please sign in to comment.