jonnzhang commited on
Commit
e33ce67
1 Parent(s): 1a3bc5a

Update app.py

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