-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
64 lines (51 loc) · 1.73 KB
/
main.py
File metadata and controls
64 lines (51 loc) · 1.73 KB
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
from flask import Flask, request, jsonify
import os
import json
import hashlib
import datetime
from openai import OpenAI
app = Flask(__name__)
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
USER_DATA_DIR = "user_data"
os.makedirs(USER_DATA_DIR, exist_ok=True)
def get_user_path(user_id):
return os.path.join(USER_DATA_DIR, hashlib.sha256(user_id.encode()).hexdigest() + ".json")
def load_user_context(user_id):
path = get_user_path(user_id)
if os.path.exists(path):
with open(path, "r") as f:
return json.load(f)
return {"history": []}
def save_user_context(user_id, context):
path = get_user_path(user_id)
with open(path, "w") as f:
json.dump(context, f, indent=2)
@app.route("/ask", methods=["POST"])
def ask():
data = request.json
user_id = data.get("user_id")
query = data.get("query")
context = load_user_context(user_id)
messages = context["history"][-10:] + [{"role": "user", "content": query}]
response = client.chat.completions.create(
model="gpt-4",
messages=messages,
temperature=0.6
)
answer = response.choices[0].message.content
context["history"].append({"role": "user", "content": query})
context["history"].append({"role": "assistant", "content": answer})
save_user_context(user_id, context)
return jsonify({
"answer": answer,
"timestamp": datetime.datetime.utcnow().isoformat()
})
@app.route("/history/<user_id>", methods=["GET"])
def history(user_id):
context = load_user_context(user_id)
return jsonify(context["history"])
@app.route("/", methods=["GET"])
def home():
return "Neural HackPad - Personal Developer Assistant API"
if __name__ == "__main__":
app.run(debug=True)