Skip to content

Commit

Permalink
Add chat component with real responses
Browse files Browse the repository at this point in the history
  • Loading branch information
cmaloney111 committed Jun 8, 2024
1 parent ffa496e commit d785aee
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 18 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ api/__pycache__/

# misc
.DS_Store
.env
.env.local
.env.development.local
.env.test.local
Expand Down
32 changes: 31 additions & 1 deletion api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,20 @@
import os
import pandas as pd
import nltk
import os
from dotenv import load_dotenv
import json
import openai
import asyncio
import logging
nltk.download('wordnet')


load_dotenv()
app = Flask(__name__)
server_thread = None
CORS(app) # Permite todas as origens por padrão (não recomendado para produção)

openai.api_key = os.getenv('OPEN_AI_KEY')
log = logging.getLogger('werkzeug')
log.disabled = True

Expand Down Expand Up @@ -180,6 +184,32 @@ def cancel_training():
except Exception as e:
return jsonify({'error': str(e)}), 500

@app.route('/api/chat', methods=['POST'])
def chat():
data = request.get_json()
user_message = data.get('message')
chat_history = data.get('history', [])

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 = openai.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()

print(bot_reply)
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 = {
Expand Down
35 changes: 18 additions & 17 deletions src/components/chatbot/chatbot.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useState, useEffect } from 'react';
import axios from 'axios';

interface Message {
text: string;
Expand All @@ -20,25 +21,27 @@ const ChatBot: React.FC = () => {
setIsOpen(!isOpen);
};

const fetchChatData = async () => {
// buscar histórico de mensagens do backend
// talvez reiniciar o chat
// verificar status do carregamento
};

const sendMessage = async () => {
if (message.trim() === "") return;

setChatHistory([...chatHistory, { text: message, origin: 'user' }]);
const newMessage: Message = { text: message, origin: 'user' };
setChatHistory(prevHistory => [...prevHistory, newMessage]);

setChatHistory(prevHistory => [
...prevHistory,
{ text: "Essa é uma resposta automática.", origin: 'bot' }
]);
try {
const response = await axios.post('http://localhost:5000/api/chat', {
message,
history: [...chatHistory, newMessage] // Enviar o histórico completo
});

setMessage("");
const botResponse: Message = { text: response.data.reply, origin: 'bot' };
setChatHistory(prevHistory => [...prevHistory, botResponse]);
} catch (error) {
console.error("Error sending message:", error);
const errorMessage: Message = { text: "Desculpe, ocorreu um erro. Tente novamente.", origin: 'bot' };
setChatHistory(prevHistory => [...prevHistory, errorMessage]);
}

// enviar mensagem para o backend
setMessage("");
};

const sendInitialMessage = () => {
Expand All @@ -59,8 +62,7 @@ const ChatBot: React.FC = () => {

{/* Chat Dialog */}
{isOpen && (
<div className="fixed bottom-20 right-4 bg-white border border-gray-300 shadow-lg rounded-lg w-80 flex flex-col max-h-[600px]
">
<div className="fixed bottom-20 right-4 bg-white border border-gray-300 shadow-lg rounded-lg w-80 flex flex-col max-h-[600px]">
<div className="bg-blue-500 text-white p-4 flex justify-between items-center">
<h2 className="text-lg">LinguiTalk ou LinguaBot</h2>
<button
Expand All @@ -75,8 +77,7 @@ const ChatBot: React.FC = () => {
{chatHistory.map((msg, index) => (
<div
key={index}
className={`mb-2 p-2 rounded-lg ${msg.origin === 'user' ? 'bg-blue-100 text-right' : 'bg-gray-200 text-left'
}`}
className={`mb-2 p-2 rounded-lg ${msg.origin === 'user' ? 'bg-blue-100 text-right' : 'bg-gray-200 text-left'}`}
>
<p className={`text-sm ${msg.origin === 'user' ? 'text-blue-700' : 'text-red-700'}`}>
{msg.origin === 'user' ? 'Você' : 'LinguiBot'}
Expand Down

0 comments on commit d785aee

Please sign in to comment.