hujameson commited on
Commit
b7a466c
·
verified ·
1 Parent(s): ec195b4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -0
app.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from openai import OpenAI
3
+ import gradio as gr
4
+
5
+
6
+ client = OpenAI(api_key=os.environ('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 = client.chat.completions.create(
19
+ model="gpt-4o-mini",
20
+ messages=self.messages,
21
+ # temperature=0.5,
22
+ max_tokens=2048,
23
+ # top_p=1,
24
+ )
25
+
26
+ except Exception as e:
27
+ print(e)
28
+ return e
29
+
30
+ message = response.choices[0].message.content
31
+ self.messages.append({"role": "assistant", "content": message})
32
+
33
+ if len(self.messages) > self.num_of_round*2 + 1:
34
+ # del self.messages[1:3] //Remove the first round conversation left.
35
+ print(self.num_of_round)
36
+
37
+ return message
38
+
39
+ prompt = """你叫赛文奥特曼,工作是陪伴三岁到七岁的儿童成长,以朋友聊天的方式解答他们在生活和学习中遇到的各种困惑和问题。你的回答需要满⾜以下要求:
40
+ 1. 你的回答必须是中⽂
41
+ 2. 回答限制在100个字以内"""
42
+ conv = Conversation(prompt, 100)
43
+
44
+ def answer(question, history=[]):
45
+ history.append(question)
46
+ response = conv.ask(question)
47
+ history.append(response)
48
+ responses = [(u,b) for u,b in zip(history[::2], history[1::2])]
49
+ return responses, history
50
+
51
+ with gr.Blocks(css="#chatbot{height:300px} .overflow-y-auto{height:500px}") as demo:
52
+ chatbot = gr.Chatbot(elem_id="chatbot")
53
+ state = gr.State([])
54
+
55
+ with gr.Row():
56
+ txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter")
57
+ txt.submit(answer, [txt, state], [chatbot, state])
58
+
59
+ demo.launch()