0Learn commited on
Commit
a975747
·
verified ·
1 Parent(s): 7eda155

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -0
app.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+
4
+ BACKEND_URL = "https://0learn-fastchat.hf.space" # Update this with your actual FastAPI backend URL
5
+
6
+ class ConversationState:
7
+ def __init__(self):
8
+ self.conversation_id = None
9
+
10
+ state = ConversationState()
11
+
12
+ def chat_with_groq(message, history):
13
+ messages = [{"role": "user" if i % 2 == 0 else "assistant", "content": msg}
14
+ for i, msg in enumerate(history + [message])]
15
+
16
+ payload = {"messages": messages}
17
+ if state.conversation_id:
18
+ payload["conversation_id"] = state.conversation_id
19
+
20
+ response = requests.post(f"{BACKEND_URL}/chat", json=payload)
21
+ response_data = response.json()
22
+
23
+ state.conversation_id = response_data["conversation_id"]
24
+ return response_data["response"]
25
+
26
+ def load_conversation(conversation_id):
27
+ response = requests.get(f"{BACKEND_URL}/conversations/{conversation_id}")
28
+ if response.status_code == 200:
29
+ conversation_data = response.json()
30
+ state.conversation_id = conversation_id
31
+ return conversation_data["messages"]
32
+ else:
33
+ return []
34
+
35
+ with gr.Blocks() as iface:
36
+ gr.Markdown("# Groq Chatbot with Conversation Persistence")
37
+
38
+ with gr.Row():
39
+ conversation_id_input = gr.Textbox(label="Conversation ID (optional)")
40
+ load_button = gr.Button("Load Conversation")
41
+
42
+ chatbot = gr.Chatbot()
43
+ msg = gr.Textbox()
44
+ clear = gr.Button("Clear")
45
+
46
+ def respond(message, chat_history):
47
+ bot_message = chat_with_groq(message, chat_history)
48
+ chat_history.append((message, bot_message))
49
+ return "", chat_history
50
+
51
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
52
+ clear.click(lambda: None, None, chatbot, queue=False)
53
+
54
+ load_button.click(load_conversation, inputs=[conversation_id_input], outputs=[chatbot])
55
+
56
+ if __name__ == "__main__":
57
+ iface.launch()