DustyBill commited on
Commit
769ebc0
·
1 Parent(s): 4900a25

add chat ui

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