Skip to content

Commit

Permalink
Chatbot accepts user API keys with retries, and everything works in e…
Browse files Browse the repository at this point in the history
…xecutable
  • Loading branch information
cmaloney111 committed Jun 11, 2024
1 parent 70c5088 commit 69bc9e3
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 57 deletions.
58 changes: 25 additions & 33 deletions api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
app = Flask(__name__)
CORS(app) # CORS(app, resources={r"/*": {"origins": "http://localhost:3000"}})
server_thread = None
openai.api_key = os.getenv('OPEN_AI_KEY')
# openai.api_key = os.getenv('OPEN_AI_KEY')
log = logging.getLogger('werkzeug')
log.disabled = True

Expand Down Expand Up @@ -79,39 +79,9 @@ def upload_file():

@app.route('/get-classifiers', methods=["GET"])
def get_classifiers():
print(build_tree('.'))
classifiers = get_available_classifiers()
return jsonify(classifiers)

def build_tree(directory, indent='', d=0):
"""
Recursively build directory tree structure as a string.
"""
if d == 6:
return ''

tree = indent + os.path.basename(directory) + '/' + '\n'
indent += ' '
try:
for item in os.listdir(directory):
if item != 'node_modules' and item != 'dist' and item != 'venv' and item != '.git':
item_path = os.path.join(directory, item)
# try:
# fake_stdout = StringIO()
# sys.stdout = fake_stdout
# print(item)
# sys.stdout = sys.__stdout__
# except:
# for char in item:
# byte_value = ord(char)
# print(hex(byte_value), end=' ')
if os.path.isdir(item_path):
tree += build_tree(item_path, indent, d + 1)
else:
tree += indent + item + '\n'
except:
pass
return tree

@app.get('/shutdown')
def shutdown():
Expand Down Expand Up @@ -232,7 +202,27 @@ def cancel_training():
file.truncate()
return jsonify({'message': 'Cancellation requested.'}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
return jsonify({'Error': str(e)}), 500


@app.route('/apikey', methods=['POST'])
def apikey():
try:
data = request.get_json()
api_key = data.get('apikey')
client = openai.OpenAI(api_key = api_key)
_ = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{'content':'a','role':'user'}],
max_tokens=1
)
return jsonify(reply="Chave de API válida! ;)"), 202
except (openai.APIConnectionError, openai.AuthenticationError):
return jsonify(reply="chave de API inválida! ;( Por favor, tente de novo."), 200
except Exception as e:
print(f"Error: {e}")
return jsonify(reply="Desculpe, ocorreu um erro ao processar sua mensagem."), 500


@app.route('/chat', methods=['POST'])
def chat():
Expand All @@ -245,14 +235,15 @@ def chat():
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 = openai.api_key)
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,
Expand All @@ -266,6 +257,7 @@ def chat():
return jsonify(reply="Desculpe, ocorreu um erro ao processar sua mensagem."), 500



if __name__ == '__main__':
training_progress = {
'training_progress': 0,
Expand Down
1 change: 1 addition & 0 deletions helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,6 @@ function printAsarDirectoryTree(asarPath, currentPath = '') {
}
}


// Print out the directory tree of the app.asar file
printAsarDirectoryTree(asarFilePath);
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"name": "TailLinguifAI",
"email": ""
},
"version": "0.3.8",
"version": "0.3.6",
"main": "./public/electron.js",
"homepage": "./",
"private": true,
Expand Down
99 changes: 77 additions & 22 deletions src/components/chatbot/chatbot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,40 @@ interface Message {
}

const ChatBot: React.FC = () => {
const [apikey, setApiKey] = useState("");
const [firstTime, setFirstTime] = useState(true);
const [apiKeyInput, setApiKeyInput] = useState("");
const [isOpen, setIsOpen] = useState(false);
const [message, setMessage] = useState("");
const [chatHistory, setChatHistory] = useState<Message[]>([]);

useEffect(() => {
if (isOpen && chatHistory.length === 0) {
if (isOpen && !apikey && firstTime) {
sendAPIKeyMessage();
}
}, [isOpen, apikey]);

useEffect(() => {
if (isOpen && chatHistory.length === 0 && apikey) {
sendInitialMessage();
}
}, [isOpen, chatHistory]);
}, [isOpen, chatHistory, apikey]);

const toggleChat = () => {
setIsOpen(!isOpen);
};

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

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

try {
const response = await axios.post('http://localhost:5000/chat', {
message,
history: [...chatHistory, newMessage]
history: [...chatHistory, newMessage],
apikey
});

const botResponse: Message = { text: response.data.reply, origin: 'bot' };
Expand All @@ -44,13 +54,37 @@ const ChatBot: React.FC = () => {
setMessage("");
};

const sendAPIKeyMessage = () => {
setChatHistory(prevHistory => [
...prevHistory,
{ text: "Olá! Eu sou o (LinguiTalk ou LinguaBot). Coloca a sua chave:", origin: 'bot' }
]);
};

const sendInitialMessage = () => {
setChatHistory(prevHistory => [
...prevHistory,
{ text: "Olá! Eu sou o (LinguiTalk ou LinguaBot). Como posso ajudar?", origin: 'bot' }
]);
};

const handleApiKeySubmit = async () => {
setApiKey(apiKeyInput);
const response = await axios.post('http://localhost:5000/apikey', {
apikey: apiKeyInput
});
const botResponse: Message = { text: response.data.reply, origin: 'bot' };
setChatHistory(prevHistory => [...prevHistory, botResponse]);
setApiKeyInput("");
if (response.status == 202) {
sendInitialMessage()
}
else {
setApiKey("")
setFirstTime(false)
}
};

return (
<div>
<button
Expand Down Expand Up @@ -87,24 +121,45 @@ const ChatBot: React.FC = () => {
))}
</div>
</div>
<div className="p-4 border-t border-gray-300">
<input
type="text"
className="w-full p-2 border border-gray-300 rounded-lg focus:outline-none"
placeholder="Digite sua mensagem..."
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyPress={(e) => {
if (e.key === 'Enter') sendMessage();
}}
/>
<button
className="w-full mt-2 bg-blue-500 text-white p-2 rounded-lg hover:bg-blue-600 focus:outline-none"
onClick={sendMessage}
>
Enviar
</button>
</div>
{apikey ? (
<div className="p-4 border-t border-gray-300">
<input
type="text"
className="w-full p-2 border border-gray-300 rounded-lg focus:outline-none"
placeholder="Digite sua mensagem..."
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyPress={(e) => {
if (e.key === 'Enter') sendMessage();
}}
/>
<button
className="w-full mt-2 bg-blue-500 text-white p-2 rounded-lg hover:bg-blue-600 focus:outline-none"
onClick={sendMessage}
>
Enviar
</button>
</div>
) : (
<div className="p-4 border-t border-gray-300">
<input
type="text"
className="w-full p-2 border border-gray-300 rounded-lg focus:outline-none"
placeholder="Digite sua chave API..."
value={apiKeyInput}
onChange={(e) => setApiKeyInput(e.target.value)}
onKeyPress={(e) => {
if (e.key === 'Enter') handleApiKeySubmit();
}}
/>
<button
className="w-full mt-2 bg-blue-500 text-white p-2 rounded-lg hover:bg-blue-600 focus:outline-none"
onClick={handleApiKeySubmit}
>
Enviar Chave API
</button>
</div>
)}
</div>
)}
</div>
Expand Down
10 changes: 9 additions & 1 deletion src/pages/views/trainView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,15 @@ export default function TrainView() {
onClick={handleNbSubmit}
disabled={isLoading}
>
{isLoading ? "Carregando..." : "Treinar"}
{isLoading ? "Carregando..." : "Treinar NB"}
</button>}

{!isLoading && <button
className={`w-2/4 bg-blue-400 text-white py-2 px-4 hover:bg-blue-500 focus:outline-none border-2 border-blue-500 rounded-xl h-14`}
onClick={handleRnnSubmit}
disabled={isLoading}
>
{isLoading ? "Carregando..." : "Treinar RNN"}
</button>}

{hasTrained && train_losses.length > 0 && (
Expand Down

0 comments on commit 69bc9e3

Please sign in to comment.