JessPink commited on
Commit
1b77559
·
1 Parent(s): 2a00bb8

requirements.txt

Browse files
Files changed (1) hide show
  1. app.py +63 -0
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import os
3
+ import gradio as gr
4
+
5
+ from dotenv import load_dotenv, find_dotenv
6
+ _ = load_dotenv(find_dotenv())
7
+
8
+ openai.api_key = os.getenv('OPENAI_API_KEY') # 设置 OpenAI 的 key
9
+ openai.api_base = os.getenv('OPENAI_API_BASE') # 指定代理地址
10
+
11
+ class Conversation:
12
+ def __init__(self, prompt, num_of_round):
13
+ self.prompt = prompt
14
+ self.num_of_round = num_of_round
15
+ self.messages = []
16
+ self.messages.append({"role": "system", "content": self.prompt})
17
+
18
+ def ask(self, question):
19
+ try:
20
+ self.messages.append({"role": "user", "content": question})
21
+ response = openai.ChatCompletion.create(
22
+ model="gpt-3.5-turbo",
23
+ messages=self.messages,
24
+ temperature=0.5,
25
+ max_tokens=2048,
26
+ top_p=1,
27
+ )
28
+ except Exception as e:
29
+ print(e)
30
+ return e
31
+
32
+ message = response["choices"][0]["message"]["content"]
33
+ self.messages.append({"role": "assistant", "content": message})
34
+
35
+ if len(self.messages) > self.num_of_round*2 + 1:
36
+ del self.messages[1:3] # Remove the first round conversation left.
37
+ return message
38
+
39
+
40
+
41
+ prompt = """你是一个中国厨师,用中文回答做菜的问题。你的回答需要满足以下要求:
42
+ 1. 你的回答必须是中文
43
+ 2. 回答限制在100个字以内"""
44
+
45
+ conv = Conversation(prompt, 10)
46
+
47
+ def answer(question, history=[]):
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
+ with gr.Blocks(css="#chatbot{height:300px} .overflow-y-auto{height:500px}") 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="Enter text and press enter")
60
+
61
+ txt.submit(answer, [txt, state], [chatbot, state])
62
+
63
+ demo.launch()