Spaces:
Sleeping
Sleeping
Update app.py
Browse files112456789101112131415161718192021222324252627282930313233343536373839404142434445345678910111213141516171819474820212223245051525354555625262728293031323334353637383940414243585960616244456446474849505152535455565758596061626364656667686970717273747576777879688070718182import osimport gradio as gr
# 確保 groq 已安裝try: from groq import Groqexcept ImportError: os.system('pip install groq') from groq import Groq
# 初始化 Groq 客戶端client = Groq()
# 獲取 API 密鑰api_key = os.getenv('groq_key')if not api_key: raise ValueError("API key 'groq_key' 未設定於環境變數中!")
client.api_key = api_key
def chat_with_groq(user_message): """與 Groq 模型進行互動""" try: # 調用 API completion = client.chat.completions.create( model="llama3-groq-70b-8192-tool-use-preview", messages=[ { "role": "system", "content": "你是一位虛擬助手,專注於回答使用者的提問,提供準確而簡潔的資訊。" }, {"role": "user", "content": user_message} ], temperature=0.5, max_tokens=1024, top_p=0.65, stream=True )
# 解析流式回應 response = "" for chunk in completion: delta_content = chunk.choices[0].delta.get("content", "") response += delta_content return responsedef create_idiom_game(): # 建立 Gradio 介面 with gr.Blocks() as demo: gr.Markdown("# 成語對對碰") # 嵌入 HTML 和 JavaScript gr.HTML(""" <div id="game-root"></div> <script src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> <script> const idiomDatabase = [ { mainIdiom: '急如星火', synonyms: ['迫在眉睫', '刻不容緩'], meaning: '形容事情非常緊急' }, { mainIdiom: '一葉知秋', synonyms: ['見微知著', '月暈而風'], meaning: '從小徵兆可以預見未來的發展' }, { mainIdiom: '一丘之貉', synonyms: ['沆瀣一氣', '狐群狗黨'], meaning: '形容品性相同的壞人' } ];
except Exception as e: return f"發生錯誤:{str(e)}" function IdiomGame() { const [currentIndex, setCurrentIndex] = React.useState(0); const [score, setScore] = React.useState(0); const [selected, setSelected] = React.useState([]);
# 定義 Gradio 介面def gradio_chatbot(): def respond(message, history): response = chat_with_groq(message) history = history or [] history.append((message, response)) return history, history const current = idiomDatabase[currentIndex]; const handleSelect = (answer) => { if (selected.includes(answer)) return; if (current.synonyms.includes(answer)) { const newSelected = [...selected, answer]; setSelected(newSelected); if (newSelected.length === 2) { setScore(score + 10); setTimeout(() => { setCurrentIndex((currentIndex + 1) % idiomDatabase.length); setSelected([]); }, 1000); } } };
with gr.Blocks() as demo: gr.Markdown("### Groq Chatbot") chatbot = gr.Chatbot() user_input = gr.Textbox(placeholder="輸入你的訊息...") submit_button = gr.Button("送出") const options = [...current.synonyms, '望穿秋水', '守株待兔', '揮金如土'].sort(() => Math.random() - 0.5);
submit_button.click(respond, [user_input, chatbot], [chatbot, chatbot]) return React.createElement('div', { style: { padding: '20px' } }, React.createElement('div', { style: { backgroundColor: '#f0f0f0', padding: '20px', marginBottom: '20px' } }, React.createElement('h2', null, current.mainIdiom), React.createElement('p', null, current.meaning) ), React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '10px' } }, options.map((option, index) => React.createElement('button', { key: index, onClick: () => handleSelect(option), style: { padding: '10px', backgroundColor: selected.includes(option) ? '#4CAF50' : 'white', color: selected.includes(option) ? 'white' : 'black', border: '1px solid #ddd' } }, option) ) ), React.createElement('div', { style: { marginTop: '20px' } }, `分數: ${score}` ) ); }
ReactDOM.render( React.createElement(IdiomGame), document.getElementById('game-root') ); </script> """) return demo
# 啟動應用程式if __name__ == "__main__": app = gradio_chatbot() app.launch() demo = create_idiom_game() demo.launch()app.py+72-61