Spaces:
Paused
Paused
Upload 2 files
Browse files- app.py +61 -0
- requirements.txt +1 -0
app.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from openai import OpenAI
|
2 |
+
import os
|
3 |
+
import gradio as gr
|
4 |
+
|
5 |
+
# 定义Conversation类
|
6 |
+
class Conversation:
|
7 |
+
def __init__(self, prompt, num_of_round):
|
8 |
+
self.client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
|
9 |
+
self.prompt = prompt
|
10 |
+
self.num_of_round = num_of_round
|
11 |
+
self.messages = []
|
12 |
+
self.messages.append({"role": "system", "content": prompt})
|
13 |
+
|
14 |
+
def ask(self, question):
|
15 |
+
try:
|
16 |
+
self.messages.append({"role": "user", "content": question})
|
17 |
+
completions = self.client.chat.completions.create(
|
18 |
+
messages=self.messages,
|
19 |
+
model="gpt-3.5-turbo",
|
20 |
+
n=1,
|
21 |
+
top_p=1,
|
22 |
+
temperature=0.5,
|
23 |
+
stop=None
|
24 |
+
)
|
25 |
+
except Exception as e:
|
26 |
+
print(e)
|
27 |
+
return str(e)
|
28 |
+
|
29 |
+
reply = completions.choices[0].message.content
|
30 |
+
self.messages.append({"role": "assistant", "content": reply})
|
31 |
+
return reply
|
32 |
+
|
33 |
+
# 实例化Conversation对象
|
34 |
+
prompt = "你是😺 智慧喵喵,一只博学且深刻的猫。..."
|
35 |
+
conv = Conversation(prompt, 3)
|
36 |
+
|
37 |
+
# 定义Gradio界面逻辑
|
38 |
+
def answer(question, history=[]):
|
39 |
+
history.append(question)
|
40 |
+
reply = conv.ask(question)
|
41 |
+
history.append(reply)
|
42 |
+
responses = [(u, b) for u, b in zip(history[::2], history[1::2])]
|
43 |
+
return responses, history
|
44 |
+
|
45 |
+
css = """
|
46 |
+
#chatbox {
|
47 |
+
height: 300px;
|
48 |
+
}
|
49 |
+
.overflow-y-auto {
|
50 |
+
height: 500px;
|
51 |
+
}
|
52 |
+
"""
|
53 |
+
|
54 |
+
with gr.Blocks(css=css) as demo:
|
55 |
+
chatbot = gr.Chatbot(elem_id="chatbot")
|
56 |
+
state = gr.State([])
|
57 |
+
|
58 |
+
with gr.Row():
|
59 |
+
txt = gr.Textbox(show_label=False, placeholder="在此输入文本并按回车键")
|
60 |
+
|
61 |
+
txt.submit(answer, inputs=[txt, state], outputs=[chatbot, state])
|
requirements.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
openai
|