tony1966 commited on
Commit
8617632
·
verified ·
1 Parent(s): f2a52aa

Create app.py

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