Spaces:
Sleeping
Sleeping
File size: 1,244 Bytes
8617632 e907f57 8617632 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import gradio as gr
from duckduckgo_search import DDGS
def clear_history():
global ddgs
ddgs=DDGS()
return [], [] # 同時清除 chatbot 和 state
def ask_duckduckgo(prompt, history):
history.append({'role': 'user', 'content': prompt})
try:
bot_response=ddgs.chat(prompt)
history.append({'role': 'assistant', 'content': bot_response})
except Exception as e:
history.append({'role': 'assistant', 'content': f'發生錯誤:{str(e)}'})
return history, ""
ddgs=DDGS()
with gr.Blocks(title='DuckDuckGo 聊天機器人') as blocks:
gr.Markdown("# DuckDuckGo 聊天機器人")
chatbot=gr.Chatbot(type='messages',
height=320,
placeholder='我們的對話',
show_copy_button=True)
state=gr.State([])
with gr.Column():
prompt=gr.Textbox(label="您的詢問:")
send_btn=gr.Button("送出")
clear_btn=gr.Button("清除對話")
send_btn.click(ask_duckduckgo, inputs=[prompt, state], outputs=[chatbot, prompt])
prompt.submit(ask_duckduckgo, inputs=[prompt, state], outputs=[chatbot, prompt])
clear_btn.click(clear_history, inputs=None, outputs=[chatbot, state])
blocks.launch()
|