DiamondYin commited on
Commit
3ae1ba6
·
1 Parent(s): 6e538a0

update app

Browse files
Files changed (2) hide show
  1. app.py +131 -142
  2. app1.py +143 -0
app.py CHANGED
@@ -1,143 +1,132 @@
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()
8
-
9
-
10
- #import gradio as gr
11
-
12
- #key = ""
13
-
14
- #def get_key(k):
15
- # global key
16
- ## key = k
17
- # return "Key saved successfully!"
18
-
19
- #def greet(name):
20
- # return "Hello " + name + "!!"
21
-
22
- #iface = gr.Interface(fn=greet, inputs=["text", gr.inputs.Textbox()], outputs="text",
23
- # inputs_layout="vertical", outputs_layout="vertical",
24
- # title="Greeting App", description="Enter a key and a name to greet")
25
-
26
- #iface.input[0].label = "Enter a key" # Set the label of the first input
27
- #iface.input[1].label = "Enter a name"
28
- #iface.input[1].lines = 1
29
-
30
- #iface.buttons[0].label = "Save Key"
31
- #iface.buttons[0].type = "submit"
32
- #iface.buttons[0].onclick = get_key
33
-
34
- #iface.buttons[1].label = "Greet"
35
- #iface.buttons[1].type = "submit"
36
- #iface.buttons[1].onclick_args = {"name": iface.inputs[1].value}
37
-
38
- #iface.launch()
39
-
40
  import gradio as gr
41
- import openai
42
-
43
- openai.api_key= ""
44
-
45
- def get_completion(prompt, model="gpt-3.5-turbo"):
46
- messages = [{"role": "user", "content": prompt}]
47
- response = openai.ChatCompletion.create(
48
- model=model,
49
- messages=messages,
50
- temperature=0, # 控制模型输出的随机程度
51
- )
52
- return response.choices[0].message["content"]
53
-
54
- def get_completion_from_messages(messages, model="gpt-3.5-turbo", temperature=0):
55
- response = openai.ChatCompletion.create(
56
- model=model,
57
- messages=messages,
58
- temperature=temperature, # 控制模型输出的随机程度
59
- )
60
- # print(str(response.choices[0].message))
61
- return response.choices[0].message["content"]
62
-
63
-
64
- context2 = [{'role':'system', 'content':"""
65
- 你是订餐机器人,为披萨餐厅自动收集订单信息。\n
66
- 注意如果客户来了,发送了空消息,请主动与客户说你好。\n
67
- 你要首先问候顾客,并主动告知客户今天的菜单,询问客户今天要什么食物。\n
68
- 然后等待用户回复收集订单信息。收集完信息需确认顾客是否还需要添加其他内容。\n
69
- 最后需要询问是否自取或外送,如果是外送,你要询问地址。\n
70
- 最后告诉顾客订单总金额,并送上祝福。\n
71
- \n
72
- 请确保明确所有选项、附加项和尺寸,以便从菜单中识别出该项唯一的内容。\n
73
- 你的回应应该以简短、非常随意和友好的风格呈现。\n
74
- \n
75
- 菜单包括:\n
76
- \n
77
- 菜品:\n
78
- 意式辣香肠披萨(大、中、小) 12.95、10.00、7.00\n
79
- 芝士披萨(大、中、小) 10.95、9.25、6.50\n
80
- 茄子披萨(大、中、小) 11.95、9.75、6.75\n
81
- 薯条(大、小) 4.50、3.50\n
82
- 希腊沙拉 7.25\n
83
- \n
84
- 配料:\n
85
- 奶酪 2.00\n
86
- 蘑菇 1.50\n
87
- 香肠 3.00\n
88
- 加拿大熏肉 3.50\n
89
- AI酱 1.50\n
90
- 辣椒 1.00\n
91
- \n
92
- 饮料:\n
93
- 可乐(大、中、小) 3.00、2.00、1.00\n
94
- 雪碧(大、中、小) 3.00、2.00、1.00\n
95
- 瓶装水 5.00\n
96
- """} ] # accumulate messages
97
-
98
- #def get_key(k):
99
- # global key
100
- # key = k
101
- # return "Key saved successfully!"
102
-
103
- #def greet(k,name):
104
- # openai.api_key = k
105
- # return "Hello " + name + "!!"
106
-
107
- #key_input = gr.inputs.Textbox(label="Enter a key")
108
- #key_button = gr.Button(label="Save Key", type="submit", onclick=get_key(key_input))
109
-
110
- #name_input = gr.inputs.Textbox(label="Enter a name")
111
- #greet_button = gr.Button(label="Greet", type="submit", onclick_args={"name": name_input})
112
-
113
-
114
-
115
-
116
-
117
-
118
-
119
- #iface = gr.Interface(fn=greet, inputs=[key_input, name_input], outputs="text",
120
- # inputs_layout="vertical", outputs_layout="vertical",
121
- # title="Greeting App", description="Enter a key and a name to greet")
122
-
123
- #iface.launch()
124
-
125
- key_input = gr.inputs.Textbox(label="Enter a key")
126
- chat_input = gr.inputs.Textbox(label="Enter a chattext")
127
-
128
- def chatbot_interface_restaurant_chinese(k_text,t_text):
129
- openai.api_key = k_text
130
- if not hasattr(chatbot_interface, "chat_history"):
131
- chatbot_interface.chat_history = ""
132
- context2.append({'role':'user', 'content':f"{t_text}"})
133
- chatbot_interface.chat_history += "User: " + t_text + "\n"
134
- output_text = get_completion_from_messages(context2)
135
- context2.append({'role':'assistant', 'content':f"{output_text}"})
136
- chatbot_interface.chat_history += "assistant: " + output_text + "\n\n"
137
- return chatbot_interface.chat_history
138
-
139
- iface = gr.Interface(fn=greet, inputs=[key_input, chat_input], outputs="text",
140
- inputs_layout="vertical", outputs_layout="vertical",
141
- title="Greeting App", description="Enter a key and a name to greet")
142
-
143
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import os
3
+ import json
4
+ import requests
5
+
6
+ #Streaming endpoint
7
+ API_URL = "https://api.openai.com/v1/chat/completions" #os.getenv("API_URL") + "/generate_stream"
8
+
9
+ #Testing with my Open AI Key
10
+ #OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
11
+
12
+ def predict(inputs, top_p, temperature, openai_api_key, chat_counter, chatbot=[], history=[]): #repetition_penalty, top_k
13
+
14
+ payload = {
15
+ "model": "gpt-3.5-turbo",
16
+ "messages": [{"role": "user", "content": f"{inputs}"}],
17
+ "temperature" : 1.0,
18
+ "top_p":1.0,
19
+ "n" : 1,
20
+ "stream": True,
21
+ "presence_penalty":0,
22
+ "frequency_penalty":0,
23
+ }
24
+
25
+ headers = {
26
+ "Content-Type": "application/json",
27
+ "Authorization": f"Bearer {openai_api_key}"
28
+ }
29
+
30
+ print(f"chat_counter - {chat_counter}")
31
+ if chat_counter != 0 :
32
+ messages=[]
33
+ for data in chatbot:
34
+ temp1 = {}
35
+ temp1["role"] = "user"
36
+ temp1["content"] = data[0]
37
+ temp2 = {}
38
+ temp2["role"] = "assistant"
39
+ temp2["content"] = data[1]
40
+ messages.append(temp1)
41
+ messages.append(temp2)
42
+ temp3 = {}
43
+ temp3["role"] = "user"
44
+ temp3["content"] = inputs
45
+ messages.append(temp3)
46
+ #messages
47
+ payload = {
48
+ "model": "gpt-3.5-turbo",
49
+ "messages": messages, #[{"role": "user", "content": f"{inputs}"}],
50
+ "temperature" : temperature, #1.0,
51
+ "top_p": top_p, #1.0,
52
+ "n" : 1,
53
+ "stream": True,
54
+ "presence_penalty":0,
55
+ "frequency_penalty":0,
56
+ }
57
+
58
+ chat_counter+=1
59
+
60
+ history.append(inputs)
61
+ print(f"payload is - {payload}")
62
+ # make a POST request to the API endpoint using the requests.post method, passing in stream=True
63
+ response = requests.post(API_URL, headers=headers, json=payload, stream=True)
64
+ #response = requests.post(API_URL, headers=headers, json=payload, stream=True)
65
+ token_counter = 0
66
+ partial_words = ""
67
+
68
+ counter=0
69
+ for chunk in response.iter_lines():
70
+ #Skipping first chunk
71
+ if counter == 0:
72
+ counter+=1
73
+ continue
74
+ #counter+=1
75
+ # check whether each line is non-empty
76
+ if chunk.decode() :
77
+ chunk = chunk.decode()
78
+ # decode each line as response data is in bytes
79
+ if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']:
80
+ #if len(json.loads(chunk.decode()[6:])['choices'][0]["delta"]) == 0:
81
+ # break
82
+ partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"]
83
+ if token_counter == 0:
84
+ history.append(" " + partial_words)
85
+ else:
86
+ history[-1] = partial_words
87
+ chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2) ] # convert to tuples of list
88
+ token_counter+=1
89
+ yield chat, history, chat_counter # resembles {chatbot: chat, state: history}
90
+
91
+
92
+ def reset_textbox():
93
+ return gr.update(value='')
94
+
95
+ title = """<h1 align="center">🔥ChatGPT API 🚀Streaming🚀</h1>"""
96
+ description = """Language models can be conditioned to act like dialogue agents through a conversational prompt that typically takes the form:
97
+ ```
98
+ User: <utterance>
99
+ Assistant: <utterance>
100
+ User: <utterance>
101
+ Assistant: <utterance>
102
+ ...
103
+ ```
104
+ In this app, you can explore the outputs of a gpt-3.5-turbo LLM.
105
+ """
106
+
107
+ with gr.Blocks(css = """#col_container {width: 1000px; margin-left: auto; margin-right: auto;}
108
+ #chatbot {height: 520px; overflow: auto;}""") as demo:
109
+ gr.HTML(title)
110
+ gr.HTML('''<center><a href="https://huggingface.co/spaces/ysharma/ChatGPTwithAPI?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>Duplicate the Space and run securely with your OpenAI API Key</center>''')
111
+ with gr.Column(elem_id = "col_container"):
112
+ openai_api_key = gr.Textbox(type='password', label="Enter your OpenAI API key here")
113
+ chatbot = gr.Chatbot(elem_id='chatbot') #c
114
+ inputs = gr.Textbox(placeholder= "Hi there!", label= "Type an input and press Enter") #t
115
+ state = gr.State([]) #s
116
+ b1 = gr.Button()
117
+
118
+ #inputs, top_p, temperature, top_k, repetition_penalty
119
+ with gr.Accordion("Parameters", open=False):
120
+ top_p = gr.Slider( minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (nucleus sampling)",)
121
+ temperature = gr.Slider( minimum=-0, maximum=5.0, value=1.0, step=0.1, interactive=True, label="Temperature",)
122
+ #top_k = gr.Slider( minimum=1, maximum=50, value=4, step=1, interactive=True, label="Top-k",)
123
+ #repetition_penalty = gr.Slider( minimum=0.1, maximum=3.0, value=1.03, step=0.01, interactive=True, label="Repetition Penalty", )
124
+ chat_counter = gr.Number(value=0, visible=False, precision=0)
125
+
126
+ inputs.submit( predict, [inputs, top_p, temperature, openai_api_key, chat_counter, chatbot, state], [chatbot, state, chat_counter],)
127
+ b1.click( predict, [inputs, top_p, temperature, openai_api_key, chat_counter, chatbot, state], [chatbot, state, chat_counter],)
128
+ b1.click(reset_textbox, [], [inputs])
129
+ inputs.submit(reset_textbox, [], [inputs])
130
+
131
+ #gr.Markdown(description)
132
+ demo.queue().launch(debug=True)
app1.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
8
+
9
+
10
+ #import gradio as gr
11
+
12
+ #key = ""
13
+
14
+ #def get_key(k):
15
+ # global key
16
+ ## key = k
17
+ # return "Key saved successfully!"
18
+
19
+ #def greet(name):
20
+ # return "Hello " + name + "!!"
21
+
22
+ #iface = gr.Interface(fn=greet, inputs=["text", gr.inputs.Textbox()], outputs="text",
23
+ # inputs_layout="vertical", outputs_layout="vertical",
24
+ # title="Greeting App", description="Enter a key and a name to greet")
25
+
26
+ #iface.input[0].label = "Enter a key" # Set the label of the first input
27
+ #iface.input[1].label = "Enter a name"
28
+ #iface.input[1].lines = 1
29
+
30
+ #iface.buttons[0].label = "Save Key"
31
+ #iface.buttons[0].type = "submit"
32
+ #iface.buttons[0].onclick = get_key
33
+
34
+ #iface.buttons[1].label = "Greet"
35
+ #iface.buttons[1].type = "submit"
36
+ #iface.buttons[1].onclick_args = {"name": iface.inputs[1].value}
37
+
38
+ #iface.launch()
39
+
40
+ import gradio as gr
41
+ import openai
42
+
43
+ openai.api_key= ""
44
+
45
+ def get_completion(prompt, model="gpt-3.5-turbo"):
46
+ messages = [{"role": "user", "content": prompt}]
47
+ response = openai.ChatCompletion.create(
48
+ model=model,
49
+ messages=messages,
50
+ temperature=0, # 控制模型输出的随机程度
51
+ )
52
+ return response.choices[0].message["content"]
53
+
54
+ def get_completion_from_messages(messages, model="gpt-3.5-turbo", temperature=0):
55
+ response = openai.ChatCompletion.create(
56
+ model=model,
57
+ messages=messages,
58
+ temperature=temperature, # 控制模型输出的随机程度
59
+ )
60
+ # print(str(response.choices[0].message))
61
+ return response.choices[0].message["content"]
62
+
63
+
64
+ context2 = [{'role':'system', 'content':"""
65
+ 你是订餐机器人,为披萨餐厅自动收集订单信息。\n
66
+ 注意如果客户来了,发送了空消息,请主动与客户说你好。\n
67
+ 你要首先问候顾客,并主动告知客户今天的菜单,询问客户今天要什么食物。\n
68
+ 然后等待用户回复收集订单信息。收集完信息需确认顾客是否还需要添加其他内容。\n
69
+ 最后需要询问是否自取或外送,如果是外送,你要询问地址。\n
70
+ 最后告诉顾客订单总金额,并送上祝福。\n
71
+ \n
72
+ 请确保明确所有选项、附加项和尺寸,以便从菜单中识别出该项唯一的内容。\n
73
+ 你的回应应该以简短、非常随意和友好的风格呈现。\n
74
+ \n
75
+ 菜单包括:\n
76
+ \n
77
+ 菜品:\n
78
+ 意式辣香肠披萨(大、中、小) 12.95、10.00、7.00\n
79
+ 芝士披萨(大、中、小) 10.95、9.25、6.50\n
80
+ 茄子披萨(大、中、小) 11.95、9.75、6.75\n
81
+ 薯条(大、小) 4.50、3.50\n
82
+ 希腊沙拉 7.25\n
83
+ \n
84
+ 配料:\n
85
+ 奶酪 2.00\n
86
+ 蘑菇 1.50\n
87
+ 香肠 3.00\n
88
+ 加拿大熏肉 3.50\n
89
+ AI酱 1.50\n
90
+ 辣椒 1.00\n
91
+ \n
92
+ 饮料:\n
93
+ 可乐(大、中、小) 3.00、2.00、1.00\n
94
+ 雪碧(大、中、小) 3.00、2.00、1.00\n
95
+ 瓶装水 5.00\n
96
+ """} ] # accumulate messages
97
+
98
+ #def get_key(k):
99
+ # global key
100
+ # key = k
101
+ # return "Key saved successfully!"
102
+
103
+ #def greet(k,name):
104
+ # openai.api_key = k
105
+ # return "Hello " + name + "!!"
106
+
107
+ #key_input = gr.inputs.Textbox(label="Enter a key")
108
+ #key_button = gr.Button(label="Save Key", type="submit", onclick=get_key(key_input))
109
+
110
+ #name_input = gr.inputs.Textbox(label="Enter a name")
111
+ #greet_button = gr.Button(label="Greet", type="submit", onclick_args={"name": name_input})
112
+
113
+
114
+
115
+
116
+
117
+
118
+
119
+ #iface = gr.Interface(fn=greet, inputs=[key_input, name_input], outputs="text",
120
+ # inputs_layout="vertical", outputs_layout="vertical",
121
+ # title="Greeting App", description="Enter a key and a name to greet")
122
+
123
+ #iface.launch()
124
+
125
+ key_input = gr.inputs.Textbox(label="Enter a key")
126
+ chat_input = gr.inputs.Textbox(label="Enter a chattext")
127
+
128
+ def chatbot_interface_restaurant_chinese(k_text,t_text):
129
+ openai.api_key = k_text
130
+ if not hasattr(chatbot_interface, "chat_history"):
131
+ chatbot_interface.chat_history = ""
132
+ context2.append({'role':'user', 'content':f"{t_text}"})
133
+ chatbot_interface.chat_history += "User: " + t_text + "\n"
134
+ output_text = get_completion_from_messages(context2)
135
+ context2.append({'role':'assistant', 'content':f"{output_text}"})
136
+ chatbot_interface.chat_history += "assistant: " + output_text + "\n\n"
137
+ return chatbot_interface.chat_history
138
+
139
+ iface = gr.Interface(fn=greet, inputs=[key_input, chat_input], outputs="text",
140
+ inputs_layout="vertical", outputs_layout="vertical",
141
+ title="Greeting App", description="Enter a key and a name to greet")
142
+
143
+ iface.launch()