diff --git a/.gitignore b/.gitignore index 97584132..ed398b7e 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,7 @@ api/__pycache__/ # misc .DS_Store +.env .env.local .env.development.local .env.test.local diff --git a/api/app.py b/api/app.py index bfa800c7..cd6d6ba8 100644 --- a/api/app.py +++ b/api/app.py @@ -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 @@ -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 = { diff --git a/src/components/chatbot/chatbot.tsx b/src/components/chatbot/chatbot.tsx index 27240cbd..857d9a0c 100644 --- a/src/components/chatbot/chatbot.tsx +++ b/src/components/chatbot/chatbot.tsx @@ -1,4 +1,5 @@ import React, { useState, useEffect } from 'react'; +import axios from 'axios'; interface Message { text: string; @@ -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 = () => { @@ -59,8 +62,7 @@ const ChatBot: React.FC = () => { {/* Chat Dialog */} {isOpen && ( -
+

LinguiTalk ou LinguaBot