peichao.dong
commited on
Commit
•
951b467
1
Parent(s):
f8b832f
add chatrobot
Browse files- app.py +60 -0
- requirment.txt +1 -0
app.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import openai
|
3 |
+
import os
|
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] //Remove the first round conversation left.
|
33 |
+
return message
|
34 |
+
|
35 |
+
|
36 |
+
|
37 |
+
import gradio as gr
|
38 |
+
prompt = """你是一个中国厨师,用中文回答做菜的问题。你的回答需要满足以下要求:
|
39 |
+
1. 你的回答必须是中文
|
40 |
+
2. 回答限制在100个字以内"""
|
41 |
+
|
42 |
+
conv = Conversation(prompt, 10)
|
43 |
+
|
44 |
+
def answer(question, history=[]):
|
45 |
+
history.append(question)
|
46 |
+
response = conv.ask(question)
|
47 |
+
history.append(response)
|
48 |
+
responses = [(u,b) for u,b in zip(history[::2], history[1::2])]
|
49 |
+
return responses, history
|
50 |
+
|
51 |
+
with gr.Blocks(css="#chatbot{height:300px} .overflow-y-auto{height:500px}") as demo:
|
52 |
+
chatbot = gr.Chatbot(elem_id="chatbot")
|
53 |
+
state = gr.State([])
|
54 |
+
|
55 |
+
with gr.Row():
|
56 |
+
txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter").style(container=False)
|
57 |
+
|
58 |
+
txt.submit(answer, [txt, state], [chatbot, state])
|
59 |
+
|
60 |
+
demo.launch()
|
requirment.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
openai
|