Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import gradio as gr
|
3 |
+
from together import Together
|
4 |
+
|
5 |
+
# Load your JSON file
|
6 |
+
with open("sultanbr_innovativeskills.json", "r", encoding="utf-8") as f:
|
7 |
+
json_data = json.load(f)
|
8 |
+
|
9 |
+
# Flatten JSON into a string context
|
10 |
+
context = json.dumps(json_data, indent=2)
|
11 |
+
|
12 |
+
# Chat function
|
13 |
+
def chat_with_json(api_key, user_message, history):
|
14 |
+
if not api_key:
|
15 |
+
return history + [[user_message, "⚠️ Please enter your Together API key first."]]
|
16 |
+
|
17 |
+
try:
|
18 |
+
client = Together(api_key=api_key)
|
19 |
+
|
20 |
+
# Construct the system + user prompt
|
21 |
+
prompt = f"""You are an assistant that answers questions based on the following JSON data:
|
22 |
+
{context}
|
23 |
+
|
24 |
+
User question: {user_message}
|
25 |
+
Answer clearly using only the relevant JSON information.
|
26 |
+
"""
|
27 |
+
|
28 |
+
response = client.chat.completions.create(
|
29 |
+
model="lgai/exaone-3-5-32b-instruct",
|
30 |
+
messages=[{"role": "user", "content": prompt}]
|
31 |
+
)
|
32 |
+
|
33 |
+
bot_reply = response.choices[0].message.content
|
34 |
+
history.append([user_message, bot_reply])
|
35 |
+
return history
|
36 |
+
|
37 |
+
except Exception as e:
|
38 |
+
return history + [[user_message, f"⚠️ Error: {str(e)}"]]
|
39 |
+
|
40 |
+
# Build Gradio UI
|
41 |
+
with gr.Blocks() as demo:
|
42 |
+
gr.Markdown("## 📚 JSON Chatbot (Powered by Together API)")
|
43 |
+
api_key = gr.Textbox(label="Enter Together API Key", type="password")
|
44 |
+
chatbot = gr.Chatbot()
|
45 |
+
msg = gr.Textbox(label="Ask something...")
|
46 |
+
clear = gr.Button("Clear Chat")
|
47 |
+
|
48 |
+
state = gr.State([])
|
49 |
+
|
50 |
+
def respond(user_message, chat_history, api_key):
|
51 |
+
return chat_with_json(api_key, user_message, chat_history)
|
52 |
+
|
53 |
+
msg.submit(respond, [msg, state, api_key], state, queue=False).then(
|
54 |
+
lambda h: (h, ""), state, [chatbot, msg]
|
55 |
+
)
|
56 |
+
|
57 |
+
clear.click(lambda: [], None, state).then(lambda: [], None, chatbot)
|
58 |
+
|
59 |
+
# Launch app
|
60 |
+
if __name__ == "__main__":
|
61 |
+
demo.launch()
|