import gradio as gr import aiohttp import asyncio import json, os LLM_API = os.environ.get("LLM_API") LLM_URL = os.environ.get("LLM_URL") USER_ID = "HuggingFace Space" # Placeholder user ID async def send_chat_message(LLM_URL, LLM_API, user_input): payload = { "inputs": {}, "query": user_input, "response_mode": "streaming", "conversation_id": "", "user": USER_ID, } print("Sending chat message payload:", payload) # Debug information async with aiohttp.ClientSession() as session: async with session.post( url=f"{LLM_URL}/chat-messages", headers={"Authorization": f"Bearer {LLM_API}"}, json=payload, timeout=aiohttp.ClientTimeout(total=60) ) as response: if response.status != 200: print(f"Error: {response.status}") return f"Error: {response.status}" # Handle the stream of events full_response = [] async for line in response.content: line = line.decode('utf-8') if line: try: print("Received line:", line) # Debug information data = json.loads(line.split("data: ")[1]) if "answer" in data: full_response.append(data["answer"]) except (IndexError, json.JSONDecodeError) as e: print(f"Error parsing line: {line}, error: {e}") # Debug information continue if full_response: return ''.join(full_response).strip() else: return "Error: No thought found in the response" async def handle_input(user_input): chat_response = await send_chat_message(LLM_URL, LLM_API, user_input) print("Chat response:", chat_response) # Debug information return chat_response def run_sync(user_input): return asyncio.run(handle_input(user_input)) # Define Gradio interface user_input = gr.Textbox(label='歡迎問我加密貨幣交易所的各種疑難雜症') examples = [ ["MAX 帳號刪除關戶後,又重新註冊 MAX 後要怎辦?"], ["手機APP怎麼操作掛單交易?"], ["USDT 怎樣換新台幣?"], ["新台幣入金要怎操作"] ] TITLE = """