yzexclusive commited on
Commit
7d7795a
1 Parent(s): 7c1b28f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -4
app.py CHANGED
@@ -1,7 +1,64 @@
 
 
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
+ openai.api_key = os.environ.get("OPENAI_API_KEY")
 
6
 
7
+ class Conversation:
8
+ def __init__(self, prompt, num_of_round):
9
+ self.prompt = prompt
10
+ self.num_of_round = num_of_round
11
+ self.messages = []
12
+ self.messages.append({"role": "system", "content": self.prompt})
13
+
14
+ def ask(self, question):
15
+ try:
16
+ self.messages.append( {"role": "user", "content": question})
17
+ response = openai.ChatCompletion.create(
18
+ model="gpt-3.5-turbo",
19
+ messages=self.messages,
20
+ temperature=0.5,
21
+ max_tokens=2048,
22
+ top_p=1,
23
+ )
24
+ except Exception as e:
25
+ print(e)
26
+ return e
27
+
28
+ message = response["choices"][0]["message"]["content"]
29
+ self.messages.append({"role": "assistant", "content": message})
30
+
31
+ if len(self.messages) > self.num_of_round*2 + 1:
32
+ del self.messages[1:3]
33
+ return message
34
+
35
+ prompt = """你是一个中国厨师,用中文回答做菜的问题。你的回答需要满足以下要求:
36
+ 1. 你的回答必须是中文
37
+ 2. 回答限制在100个字以内"""
38
+
39
+ # 创建一个Conversation对象,所用的还是第六讲-测试一的Conversation类。
40
+ conv = Conversation(prompt, 10)
41
+
42
+ # 新建answer 方法,简单封装一下 Conversation 的 ask 方法
43
+ def answer(question, history=[]):
44
+ # 通过 history 维护了整个会话的历史记录
45
+ history.append(question)
46
+ # 通过 responses,将用户和 AI 的对话分组
47
+ response = conv.ask(question)
48
+ history.append(response)
49
+ # 将response,history作为函数的返回值。这个函数的签名是为了符合 Gradio 里 Chatbot 组件的函数签名的需求。
50
+ responses = [(u,b) for u,b in zip(history[::2], history[1::2])]
51
+ return responses, history
52
+
53
+ # 创建了对应的聊天界面
54
+ # 通过Gradio 提供的一个现成 Chatbot 组件,调用它,然后提供一个文本输入框
55
+ with gr.Blocks(css="#chatbot{height:300px} .overflow-y-auto{height:500px}") as demo:
56
+ chatbot = gr.Chatbot(elem_id="chatbot")
57
+ state = gr.State([])
58
+
59
+ with gr.Row():
60
+ txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter").style(container=False)
61
+
62
+ txt.submit(answer, [txt, state], [chatbot, state])
63
+
64
+ demo.launch()