Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,57 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
|
3 |
-
|
4 |
-
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os,openai
|
2 |
import gradio as gr
|
3 |
|
4 |
+
class Conversation:
|
5 |
+
def __init__(self,prompt,num_of_round):
|
6 |
+
self.prompt = prompt
|
7 |
+
self.num_of_round = num_of_round
|
8 |
+
self.message = []
|
9 |
+
self.message.append({'role':'system','content':self.prompt})
|
10 |
|
11 |
+
def ask(self,question):
|
12 |
+
try:
|
13 |
+
self.message.append({'role':'user','content':question})
|
14 |
+
response = openai.ChatCompletion.create(
|
15 |
+
model = 'gpt-3.5-turbo',
|
16 |
+
message=self.message,
|
17 |
+
temperature = 0.5,
|
18 |
+
max_tokens=2048,
|
19 |
+
top_p=1
|
20 |
+
)
|
21 |
+
|
22 |
+
except Exception as e:
|
23 |
+
print(e)
|
24 |
+
return e
|
25 |
+
|
26 |
+
message = response['choices'][0]['message']['content']
|
27 |
+
num_of_tokens = response['usage']['total_tokens']
|
28 |
+
self.message.append({'role':'assistant','content': message})
|
29 |
+
|
30 |
+
if len(self.message) > self.num_of_round *2-1:
|
31 |
+
del self.message[1:3]
|
32 |
+
return message,num_of_tokens
|
33 |
+
|
34 |
+
|
35 |
+
prompt = """你是一个中国厨师,用中文回答做菜的问题。你的回答需要满足以下要求:
|
36 |
+
1. 你的回答必须是中文
|
37 |
+
2. 回答限制在100个字以内"""
|
38 |
+
|
39 |
+
conv = Conversation(prompt,10)
|
40 |
+
|
41 |
+
def answer(question,history=[]):
|
42 |
+
history.append(question)
|
43 |
+
response = conv.ask(question)
|
44 |
+
history.append(response)
|
45 |
+
response = [(u,b) for u ,b in zip(history[::2],history[1::2])]
|
46 |
+
return response,history
|
47 |
+
|
48 |
+
with gr.Blocks(css='#chatbot{height:300px} .overflow-y-auto{height:500px}') as demo:
|
49 |
+
chatbot = gr.Chatbot(elem_id = 'chatbot')
|
50 |
+
state = gr.State([])
|
51 |
+
|
52 |
+
with gr.Row():
|
53 |
+
txt = gr.Textbox(show_label = False,placeholder = 'Enter text and press enter').style(container=False)
|
54 |
+
|
55 |
+
txt.submit(answer,[txt,state],[chatbot,state])
|
56 |
+
|
57 |
+
demo.launch()
|