Spaces:
Runtime error
Runtime error
| import os | |
| import gradio as gr | |
| import requests | |
| BACKEND_URL = "https://0learn-fastchat.hf.space" # Update this with your actual FastAPI backend URL | |
| class ConversationState: | |
| def __init__(self): | |
| self.conversation_id = None | |
| state = ConversationState() | |
| def chat_with_groq(message, history): | |
| messages = [{"role": "user" if i % 2 == 0 else "assistant", "content": msg} | |
| for i, msg in enumerate(history + [message])] | |
| payload = {"messages": messages} | |
| if state.conversation_id: | |
| payload["conversation_id"] = state.conversation_id | |
| response = requests.post(f"{BACKEND_URL}/chat", json=payload) | |
| response_data = response.json() | |
| state.conversation_id = response_data["conversation_id"] | |
| return response_data["response"] | |
| def load_conversation(conversation_id): | |
| response = requests.get(f"{BACKEND_URL}/conversations/{conversation_id}") | |
| if response.status_code == 200: | |
| conversation_data = response.json() | |
| state.conversation_id = conversation_id | |
| return conversation_data["messages"] | |
| else: | |
| return [] | |
| def respond(message, chat_history): | |
| bot_message = chat_with_groq(message, chat_history) | |
| chat_history.append((message, bot_message)) | |
| return "", chat_history | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# Groq Chatbot with Conversation Persistence") | |
| with gr.Row(): | |
| conversation_id_input = gr.Textbox(label="Conversation ID (optional)") | |
| load_button = gr.Button("Load Conversation") | |
| chatbot = gr.Chatbot() | |
| msg = gr.Textbox() | |
| clear = gr.Button("Clear") | |
| msg.submit(respond, [msg, chatbot], [msg, chatbot]) | |
| clear.click(lambda: None, None, chatbot, queue=False) | |
| load_button.click(load_conversation, inputs=[conversation_id_input], outputs=[chatbot]) | |
| demo.launch() |