LeeKinXUn commited on
Commit
f663086
1 Parent(s): 513663e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -28
app.py CHANGED
@@ -1,28 +1,58 @@
1
- 导入openai,os
2
- 将易变导入为gr
3
- gradio.components导入文档
4
-
5
- os.environ[ "http_proxy" ] = "http://localhost:7890"
6
- os.environ[ "https_proxy" ] = "http://localhost:7890"
7
- openai.api_key = 'OPENAI_API_KEY
8
-
9
- 消息 = [
10
- { "role" : "system" , "content" : "你是一个乐于助人、善良的 AI 小助手。" },
11
- ]
12
-
13
- 定义ChatGPT_Bot(输入):
14
- 如果输入:
15
- messages.append({ “角色”:“用户”,“内容”:输入})
16
- 聊天 = openai.ChatCompletion.create(
17
- 模型=“gpt- 3.5 -turbo”,消息=消息
18
- )
19
- 回复 = chat.choices[ 0 ].message.content
20
- messages.append({ "role" : "assistant" , "content" : reply})
21
- 返回回复
22
-
23
- inputs = Textbox(lines= 7 , label= "请输入你的问题" )
24
- outputs = Textbox(lines= 7 , label= "来自ChatGPT的回答" )
25
-
26
- gr.Interface(fn=ChatGPT_Bot, inputs=inputs, outputs=outputs, title= "ChatGPT 人工智能助手" ,
27
- description= "我是您的AI助理,您可以问任何您想知道的问题" ,
28
- 主题=gr.themes.Default()).launch(share= True )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
36
+ prompt = """你是一个中国厨师,用中文回答做菜的问题。你的回答需要满足以下要求:
37
+ 1. 你的回答必须是中文
38
+ 2. 回答限制在100个字以内"""
39
+
40
+ conv = Conversation(prompt, 5)
41
+
42
+ def predict(input, history=[]):
43
+ history.append(input)
44
+ response = conv.ask(input)
45
+ history.append(response)
46
+ responses = [(u,b) for u,b in zip(history[::2], history[1::2])]
47
+ return responses, history
48
+
49
+ with gr.Blocks(css="#chatbot{height:350px} .overflow-y-auto{height:500px}") as demo:
50
+ chatbot = gr.Chatbot(elem_id="chatbot")
51
+ state = gr.State([])
52
+
53
+ with gr.Row():
54
+ txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter").style(container=False)
55
+
56
+ txt.submit(predict, [txt, state], [chatbot, state])
57
+
58
+ demo.launch()