Spaces:
Sleeping
Sleeping
Download app.py from Tabatha-625/ChatAI: direct link, hf CLI and curl.
- Browser
- Download file 2.71 kB
-
https://huggingface.co/spaces/Tabatha-625/ChatAI/resolve/main/app.py
- Command line
-
hf download hf://spaces/Tabatha-625/ChatAI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Tabatha-625/ChatAI/resolve/main/app.py
2.71 kB
| import json | |
| def load_history(user): | |
| try: | |
| with open(f"{user}.json", "r") as f: | |
| return json.load(f) | |
| except: | |
| return [] | |
| def save_history(user, history): | |
| with open(f"{user}.json", "w") as f: | |
| json.dump(history, f) | |
| import gradio as gr | |
| from openai import OpenAI | |
| import os | |
| client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) | |
| USER_SESSIONS = {} | |
| def respond(username, message, history): | |
| if username not in USER_SESSIONS: | |
| USER_SESSIONS[username] = [] | |
| history = USER_SESSIONS[username] | |
| messages = [{"role": "system", "content": "You are a helpful assistant."}] | |
| for u, b in history: | |
| messages.append({"role": "user", "content": u}) | |
| messages.append({"role": "assistant", "content": b}) | |
| messages.append({"role": "user", "content": message}) | |
| response = client.chat.completions.create( | |
| model="gpt-4o-mini", | |
| messages=messages | |
| ) | |
| reply = response.choices[0].message.content | |
| history.append((message, reply)) | |
| USER_SESSIONS[username] = history | |
| return "", history | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## 🔐 Login") | |
| username = gr.Textbox(label="Username") | |
| chatbot = gr.Chatbot(height=400) | |
| msg = gr.Textbox(placeholder="Type your message…", show_label=False) | |
| msg.submit(respond, [username, msg, chatbot], [msg, chatbot]) | |
| demo.launch() | |
| from fastapi import FastAPI | |
| from fastapi.responses import FileResponse | |
| from openai import OpenAI | |
| import os | |
| app = FastAPI() | |
| client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) | |
| def root(): | |
| return FileResponse("static/index.html") | |
| async def chat(data: dict): | |
| messages = [ | |
| {"role": "system", "content": "You are ChatGPT. Be helpful and concise."} | |
| ] + data["messages"] | |
| res = client.chat.completions.create( | |
| model="gpt-4o-mini", | |
| messages=messages | |
| ) | |
| return res.choices[0].message | |
| def rename_chat(data: dict): | |
| supabase.table("conversations") \ | |
| .update({"title": data["title"]}) \ | |
| .eq("id", data["id"]) \ | |
| .execute() | |
| return {"ok": True} | |
| def rename_chat(data: dict): | |
| supabase.table("conversations") \ | |
| .update({"title": data["title"]}) \ | |
| .eq("id", data["id"]) \ | |
| .execute() | |
| return {"ok": True} | |
| def rename_chat(data: dict): | |
| supabase.table("conversations") \ | |
| .update({"title": data["title"]}) \ | |
| .eq("id", data["id"]) \ | |
| .execute() | |
| return {"ok": True} | |