Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222325 unmodified lines4950515253545556575859606162636465666768697071727374757677787980818283848586import gradio as grimport osimport csvimport requestsfrom datetime import datetime# Install the groq package if it is not installedtry:from groq import Groqexcept ImportError:os.system('pip install groq')from groq import Groq# Set up the Groq client with the secret keygroq_key = os.getenv('groq_key')if not groq_key:raise ValueError("groq_key environment variable is not set")client = Groq(api_key=groq_key)class SimpleChatBot:def __init__(self):self.initial_prompt = [25 unmodified lineschatbot = SimpleChatBot()# Function to log chat history to Google Sheetdef log_to_sheet(user_message, bot_response):# Prepare the URL for Google Sheets API using the shared linksheet_url = "https://docs.google.com/spreadsheets/d/1BQ23fiiGu5wN4RmRC4XmrKS6qCWHuymlbsoLEEmEN_4/gviz/tq?tqx=out:csv"# Prepare the data rowtimestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")row = [timestamp, user_message, bot_response]# Append the row to the sheet using HTTP requeststry:response = requests.post(sheet_url, data={'append': row})if response.status_code == 200:print("Logged to Google Sheet successfully.")else:print(f"Failed to log to Google Sheet: {response.status_code}")except Exception as e:print(f"Error while logging to Google Sheet: {e}")# Chatbot response function with loggingdef respond(message, chat_history):chat_history = [{"role": entry["role"], "content": entry["content"]} for entry in chat_history]response = chatbot.get_response(message, chat_history)chat_history.append({"role": "user", "content": message})chat_history.append({"role": "assistant", "content": response})# Log to Google Sheetlog_to_sheet(message, response)return chat_history, ""# Gradio interfacewith gr.Blocks(title="簡單的Gradio聊天機器人") as demo:gr.Markdown("# 簡單的Gradio聊天機器人")1234567891011121314151617181920212223242526272825 unmodified lines54555657585960616263646566676869707172737475767778798081import gradio as grimport osimport gspreadfrom datetime import datetime# 安裝並導入 groq 套件try:from groq import Groqexcept ImportError:os.system('pip install groq')from groq import Groq# 設定 Groq 的 API Keygroq_key = os.getenv('groq_key')if not groq_key:raise ValueError("groq_key environment variable is not set")client = Groq(api_key=groq_key)# 使用 gspread 連接 Google Sheetsheet_url = "https://docs.google.com/spreadsheets/d/1BQ23fiiGu5wN4RmRC4XmrKS6qCWHuymlbsoLEEmEN_4/edit?usp=sharing"gc = gspread.service_account() # 無需 Google Console 憑證時,可以跳過此步驟sheet = gc.open_by_url(sheet_url).sheet1 # 獲取第一個工作表# 定義簡單的 Chatbotclass SimpleChatBot:def __init__(self):self.initial_prompt = [25 unmodified lineschatbot = SimpleChatBot()# 記錄聊天內容到 Google Sheetdef log_to_sheet(user_message, bot_response):try:timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")sheet.append_row([timestamp, user_message, bot_response])print("Logged to Google Sheet successfully.")except Exception as e:print(f"Error logging to Google Sheet: {e}")# 定義回應邏輯def respond(message, chat_history):chat_history = [{"role": entry["role"], "content": entry["content"]} for entry in chat_history]response = chatbot.get_response(message, chat_history)chat_history.append({"role": "user", "content": message})chat_history.append({"role": "assistant", "content": response})# 記錄到 Google Sheetlog_to_sheet(message, response)return chat_history, ""# 建立 Gradio 界面with gr.Blocks(title="簡單的Gradio聊天機器人") as demo:gr.Markdown("# 簡單的Gradio聊天機器人")
app.py+17-22