glt3953 commited on
Commit
df05305
·
1 Parent(s): 33b9dd7
Files changed (1) hide show
  1. app.py +54 -4
app.py CHANGED
@@ -1,7 +1,57 @@
 
1
  import gradio as gr
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #安装一下 Python 的 Gradio 的包:conda install -c conda-forge gradio
2
  import gradio as gr
3
+ import openai
4
+ import os
5
 
6
+ openai.api_key = os.environ.get("OPENAI_API_KEY")
 
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] #Remove the first round conversation left.
34
+
35
+ return message
36
+
37
+ prompt = """你是一个iOS项目研发专家,掌握了所有关于iOS的知识"""
38
+
39
+ conv = Conversation(prompt, 10)
40
+
41
+ def answer(question, history=[]):
42
+ history.append(question)
43
+ response = conv.ask(question)
44
+ history.append(response)
45
+ responses = [(u,b) for u,b in zip(history[::2], history[1::2])]
46
+ return responses, history
47
+
48
+ with gr.Blocks(css="#chatbot{height:300px} .overflow-y-auto{height:500px}") as demo:
49
+ chatbot = gr.Chatbot(elem_id="chatbot")
50
+ state = gr.State([])
51
+
52
+ with gr.Row():
53
+ txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter").style(container=False)
54
+
55
+ txt.submit(answer, [txt, state], [chatbot, state])
56
+
57
+ demo.launch()