-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
69 lines (49 loc) · 1.95 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import logging
from flask import Flask, render_template, request, jsonify
from config import GAME_SYSTEM_MESSAGE, STATUS_SYSTEM_MESSAGE, MAX_TOKENS
from config import GAME_MODEL, STATUS_MODEL
from modules.openai_api import get_answer, categorize_answer
from modules.open_ai_utils import truncate_conversation
from modules.text_formatter import format_text
app = Flask(__name__)
# set up logging
logging.basicConfig(level=logging.INFO)
# save messages to a list
message_history = [
{"role": "system", "content": GAME_SYSTEM_MESSAGE},
]
@app.route("/")
def dashboard():
"""
Return the terminal page with the game.
GET request: Render the terminal page.
POST request: Process user input and return an answer and status as JSON.
"""
return render_template("menu.html")
@app.route("/terminal", methods=["GET", "POST"])
def terminal():
"""Return the terminal page with the game."""
global message_history
if request.method == "GET":
# reset message history on page reload
message_history = [
{"role": "system", "content": GAME_SYSTEM_MESSAGE},
]
return render_template("terminal.html")
else:
try:
data = request.get_json()
command = data["message"]
except (KeyError, TypeError):
logging.error(f"Invalid JSON data: {request.data}")
return jsonify({"error": "Invalid JSON data"}), 400
message_history.append({"role": "user", "content": command})
message_history = truncate_conversation(
message_history, MAX_TOKENS) # truncate if tokens exceed max
answer = format_text(get_answer(message_history, GAME_MODEL))
message_history.append({"role": "assistant", "content": answer})
status = categorize_answer(STATUS_SYSTEM_MESSAGE, answer, STATUS_MODEL)
print(status)
return jsonify({"answer": answer, "status": status})
if __name__ == "__main__":
app.run(debug=True)