Edward
commited on
Commit
·
bd02b5a
1
Parent(s):
3e1973f
初始化应用
Browse files- .gitignore +2 -0
- app.py +64 -0
- requirements.txt +1 -0
.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
./.idea/*
|
| 2 |
+
.idea
|
app.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import openai
|
| 2 |
+
import os
|
| 3 |
+
import gradio as gr
|
| 4 |
+
|
| 5 |
+
openai.api_key = os.environ.get("OPENAI_API_KEY")
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Conversation:
|
| 9 |
+
def __init__(self, prompt, num_of_round):
|
| 10 |
+
self.prompt = prompt
|
| 11 |
+
self.num_of_round = num_of_round
|
| 12 |
+
self.messages = []
|
| 13 |
+
self.messages.append({"role": "system", "content": self.prompt})
|
| 14 |
+
|
| 15 |
+
def ask(self, question):
|
| 16 |
+
try:
|
| 17 |
+
self.messages.append({"role": "user", "content": question})
|
| 18 |
+
response = openai.ChatCompletion.create(
|
| 19 |
+
model="gpt-3.5-turbo",
|
| 20 |
+
messages=self.messages,
|
| 21 |
+
temperature=0.5,
|
| 22 |
+
max_tokens=2048,
|
| 23 |
+
top_p=1,
|
| 24 |
+
)
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(e)
|
| 27 |
+
return e
|
| 28 |
+
|
| 29 |
+
message = response["choices"][0]["message"]["content"]
|
| 30 |
+
self.messages.append({"role": "assistant", "content": message})
|
| 31 |
+
|
| 32 |
+
if len(self.messages) > self.num_of_round * 2 + 1:
|
| 33 |
+
del self.messages[1:3]
|
| 34 |
+
return message
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
prompt = """你是一个中国厨师,用中文回答做菜的问题。你的回答需要满足以下要求:
|
| 38 |
+
1. 你的回答必须是中文
|
| 39 |
+
2. 回答限制在100个字以内"""
|
| 40 |
+
|
| 41 |
+
conv = Conversation(prompt, 10)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def answer(question, history=[]):
|
| 45 |
+
if question.lower() in ["bye", "goodbye", "exit"]:
|
| 46 |
+
print("Goodbye!")
|
| 47 |
+
exit(0)
|
| 48 |
+
history.append(question)
|
| 49 |
+
response = conv.ask(question)
|
| 50 |
+
history.append(response)
|
| 51 |
+
responses = [(u, b) for u, b in zip(history[::2], history[1::2])]
|
| 52 |
+
return responses, history
|
| 53 |
+
|
| 54 |
+
|
| 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()
|
requirements.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
openai
|