GeekEric commited on
Commit
e18b31f
·
verified ·
1 Parent(s): 5e3067a

Add application file

Browse files
Files changed (2) hide show
  1. app.py +62 -0
  2. requirements.txt +1 -0
app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import openai
3
+ import os
4
+
5
+ # 获取open ai的秘钥
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] # Remove the first round conversation left.
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()
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ openai