import gradio as gr import requests import json import os API_URL = "https://host.palple.polrambora.com/pmsq" sessions = {} PRIMARY_SYSTEM_INSTRUCTIONS = "You are P-MSQ (Messaging Service Query), a friendly AI Chatbot that can help in any situations" ASSISTANT_PIC_PATH = "https://huggingface.co/spaces/PLRMB/P-MSQ-API-PREVIEW/resolve/main/API.png" USER_PIC_PATH = "https://huggingface.co/spaces/PLRMB/P-MSQ-API-PREVIEW/resolve/main/usr.png" def authorize(user, api_key, system_message): test_data = { "user": user, "key": api_key } test_headers = { 'Accept': 'application/json' } print("Preparing to send the request...") try: response = requests.post( "https://host.palple.polrambora.com/check_key_impv", json=test_data, ) if response.status_code == 200: response_json = response.json() print(f"Response: {response_json}") if api_key not in sessions: sessions[api_key] = { "history": [], "headers": { "authorization": api_key, "Content-Type": 'application/json' }, "system_message": system_message } return True else: print(f"Failed request - Status code: {response.status_code}, Response: {response.text}") return False except requests.exceptions.Timeout: print("Request timed out") return False except requests.exceptions.ConnectionError: print("Network problem occurred (DNS failure, refused connection, etc.)") return False except Exception as e: print(f"Exception occurred: {str(e)}") return False def respond(message, api_key, max_tokens, top_p, temperature): session = sessions.get(api_key, {}) history = session.get("history", []) headers = session.get("headers", {}) system_message = session.get("system_message", PRIMARY_SYSTEM_INSTRUCTIONS) messages = [] for user_message, assistant_message, user_profile, assistant_profile, user_pic, assistant_pic in history: if user_message: messages.append({ "role": "user", "content": user_message, "profile": user_profile, "picture": user_pic }) if assistant_message: messages.append({ "role": "assistant", "content": assistant_message, "profile": assistant_profile, "picture": assistant_pic }) data = { "preferences": { "max_char": max_tokens, "temperature": temperature, "top_p": top_p, "system_message": system_message }, "conversation_history": messages, "input": message } response = requests.post(API_URL, headers=headers, data=json.dumps(data)) if response.status_code == 200: response_json = response.json() assistant_reply = response_json["msq"]["message"][0] history.append((message, assistant_reply, "You", "P-ALPLE", USER_PIC_PATH, ASSISTANT_PIC_PATH)) sessions[api_key]["history"] = history return history, assistant_reply else: return history, "Error: " + response.json().get("error", "Unknown error occurred.") def render_message(history): messages_html = """