jingwora commited on
Commit
2e12ae2
·
1 Parent(s): 3fad3c3

Add application file

Browse files
Files changed (2) hide show
  1. app.py +190 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ import os
4
+ import json
5
+ import requests
6
+
7
+ #Streaming endpoint
8
+ API_URL = "https://api.openai.com/v1/chat/completions" #os.getenv("API_URL") + "/generate_stream"
9
+
10
+ #Inferenec function
11
+ def predict(openai_gpt4_key, system_msg, inputs, top_p, temperature, chat_counter, chatbot=[], history=[]):
12
+
13
+ headers = {
14
+ "Content-Type": "application/json",
15
+ "Authorization": f"Bearer {openai_gpt4_key}" #Users will provide their own OPENAI_API_KEY
16
+ }
17
+ print(f"system message is ^^ {system_msg}")
18
+ if system_msg.strip() == '':
19
+ initial_message = [{"role": "user", "content": f"{inputs}"},]
20
+ multi_turn_message = []
21
+ else:
22
+ initial_message= [{"role": "system", "content": system_msg},
23
+ {"role": "user", "content": f"{inputs}"},]
24
+ multi_turn_message = [{"role": "system", "content": system_msg},]
25
+
26
+ if chat_counter == 0 :
27
+ payload = {
28
+ "model": "gpt-4",
29
+ "messages": initial_message ,
30
+ "temperature" : 1.0,
31
+ "top_p":1.0,
32
+ "n" : 1,
33
+ "stream": True,
34
+ "presence_penalty":0,
35
+ "frequency_penalty":0,
36
+ }
37
+ print(f"chat_counter - {chat_counter}")
38
+ else: #if chat_counter != 0 :
39
+ messages=multi_turn_message # Of the type of - [{"role": "system", "content": system_msg},]
40
+ for data in chatbot:
41
+ user = {}
42
+ user["role"] = "user"
43
+ user["content"] = data[0]
44
+ assistant = {}
45
+ assistant["role"] = "assistant"
46
+ assistant["content"] = data[1]
47
+ messages.append(user)
48
+ messages.append(assistant)
49
+ temp = {}
50
+ temp["role"] = "user"
51
+ temp["content"] = inputs
52
+ messages.append(temp)
53
+ #messages
54
+ payload = {
55
+ "model": "gpt-4",
56
+ "messages": messages, # Of the type of [{"role": "user", "content": f"{inputs}"}],
57
+ "temperature" : temperature, #1.0,
58
+ "top_p": top_p, #1.0,
59
+ "n" : 1,
60
+ "stream": True,
61
+ "presence_penalty":0,
62
+ "frequency_penalty":0,}
63
+
64
+ chat_counter+=1
65
+
66
+ history.append(inputs)
67
+ print(f"Logging : payload is - {payload}")
68
+ # make a POST request to the API endpoint using the requests.post method, passing in stream=True
69
+ response = requests.post(API_URL, headers=headers, json=payload, stream=True)
70
+ print(f"Logging : response code - {response}")
71
+ token_counter = 0
72
+ partial_words = ""
73
+
74
+ counter=0
75
+ for chunk in response.iter_lines():
76
+ #Skipping first chunk
77
+ if counter == 0:
78
+ counter+=1
79
+ continue
80
+ # check whether each line is non-empty
81
+ if chunk.decode() :
82
+ chunk = chunk.decode()
83
+ # decode each line as response data is in bytes
84
+ if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']:
85
+ partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"]
86
+ if token_counter == 0:
87
+ history.append(" " + partial_words)
88
+ else:
89
+ history[-1] = partial_words
90
+ chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2) ] # convert to tuples of list
91
+ token_counter+=1
92
+ yield chat, history, chat_counter, response # resembles {chatbot: chat, state: history}
93
+
94
+ #Resetting to blank
95
+ def reset_textbox():
96
+ return gr.update(value='')
97
+
98
+ #to set a component as visible=False
99
+ def set_visible_false():
100
+ return gr.update(visible=False)
101
+
102
+ #to set a component as visible=True
103
+ def set_visible_true():
104
+ return gr.update(visible=True)
105
+
106
+ # Title
107
+ title = """
108
+ <div style="text-align: center;max-width: 700px;">
109
+ <h1>ChatGPT4 Demo</h1>
110
+ <p style="text-align: left;">Instruction: <br />
111
+ 1. Input your Open API key <br />
112
+ 2. System message (2 options): <br />
113
+ 2.1 Directly input into system message box. <br />
114
+ 2.2 Select from Examples for System message at the buttom. <br />
115
+ 3. Adjust parameters of Top-p and Temperature (opional). <br />
116
+ 4. Input message in Chat input and click [Run]. <br />
117
+ </p>
118
+ </div>
119
+ """
120
+
121
+ with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;} #chatbot {height: 520px; overflow: auto;}""") as demo:
122
+ gr.HTML(title)
123
+
124
+ with gr.Column(elem_id = "col_container"):
125
+ #Users need to provide their own GPT4 API key, it is no longer provided by Huggingface
126
+ with gr.Row():
127
+ openai_gpt4_key = gr.Textbox(label="OpenAI GPT4 Key", value="", type="password", placeholder="API keys", info = "You have to provide your own GPT4 keys for this app to function properly",)
128
+ with gr.Accordion(label="System message:", open=False):
129
+ system_msg = gr.Textbox(label="Instruct the AI Assistant to set its beaviour", info = system_msg_info, value="",placeholder="Type here..")
130
+ accordion_msg = gr.HTML(value="To set System message you will have to refresh the app", visible=False)
131
+
132
+ chatbot = gr.Chatbot(label='GPT4', elem_id="chatbot")
133
+ inputs = gr.Textbox(placeholder= "Message", label= "Chat input")
134
+ state = gr.State([])
135
+ with gr.Row():
136
+ with gr.Column(scale=7):
137
+ b1 = gr.Button().style(full_width=True)
138
+ with gr.Column(scale=3):
139
+ server_status_code = gr.Textbox(label="Status code from OpenAI server", )
140
+
141
+ #top_p, temperature
142
+ with gr.Accordion("Parameters", open=False):
143
+ top_p = gr.Slider( minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (nucleus sampling)",)
144
+ temperature = gr.Slider( minimum=-0, maximum=5.0, value=1.0, step=0.1, interactive=True, label="Temperature",)
145
+ chat_counter = gr.Number(value=0, visible=False, precision=0)
146
+
147
+ #Event handling
148
+ inputs.submit( predict, [openai_gpt4_key, system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code],) #openai_api_key
149
+ b1.click( predict, [openai_gpt4_key, system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code],) #openai_api_key
150
+
151
+ inputs.submit(set_visible_false, [], [system_msg])
152
+ b1.click(set_visible_false, [], [system_msg])
153
+ inputs.submit(set_visible_true, [], [accordion_msg])
154
+ b1.click(set_visible_true, [], [accordion_msg])
155
+
156
+ b1.click(reset_textbox, [], [inputs])
157
+ inputs.submit(reset_textbox, [], [inputs])
158
+
159
+ #Examples
160
+ with gr.Accordion(label="Examples for System message:", open=False):
161
+ gr.Examples(
162
+ examples = [["""You are an AI programming assistant.
163
+
164
+ - Follow the user's requirements carefully and to the letter.
165
+ - First think step-by-step -- describe your plan for what to build in pseudocode, written out in great detail.
166
+ - Then output the code in a single code block.
167
+ - Minimize any other prose."""], ["""You are ComedianGPT who is a helpful assistant. You answer everything with a joke and witty replies."""],
168
+ ["You are ChefGPT, a helpful assistant who answers questions with culinary expertise and a pinch of humor."],
169
+ ["You are FitnessGuruGPT, a fitness expert who shares workout tips and motivation with a playful twist."],
170
+ ["You are SciFiGPT, an AI assistant who discusses science fiction topics with a blend of knowledge and wit."],
171
+ ["You are PhilosopherGPT, a thoughtful assistant who responds to inquiries with philosophical insights and a touch of humor."],
172
+ ["You are EcoWarriorGPT, a helpful assistant who shares environment-friendly advice with a lighthearted approach."],
173
+ ["You are MusicMaestroGPT, a knowledgeable AI who discusses music and its history with a mix of facts and playful banter."],
174
+ ["You are SportsFanGPT, an enthusiastic assistant who talks about sports and shares amusing anecdotes."],
175
+ ["You are TechWhizGPT, a tech-savvy AI who can help users troubleshoot issues and answer questions with a dash of humor."],
176
+ ["You are FashionistaGPT, an AI fashion expert who shares style advice and trends with a sprinkle of wit."],
177
+ ["You are ArtConnoisseurGPT, an AI assistant who discusses art and its history with a blend of knowledge and playful commentary."],
178
+ ["You are a helpful assistant that provides detailed and accurate information."],
179
+ ["You are an assistant that speaks like Shakespeare."],
180
+ ["You are a friendly assistant who uses casual language and humor."],
181
+ ["You are a financial advisor who gives expert advice on investments and budgeting."],
182
+ ["You are a health and fitness expert who provides advice on nutrition and exercise."],
183
+ ["You are a travel consultant who offers recommendations for destinations, accommodations, and attractions."],
184
+ ["You are a movie critic who shares insightful opinions on films and their themes."],
185
+ ["You are a history enthusiast who loves to discuss historical events and figures."],
186
+ ["You are a tech-savvy assistant who can help users troubleshoot issues and answer questions about gadgets and software."],
187
+ ["You are an AI poet who can compose creative and evocative poems on any given topic."],],
188
+ inputs = system_msg,)
189
+
190
+ demo.queue(max_size=99, concurrency_count=20).launch(debug=True)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio==3.39.0
2
+ openai==0.27.8
3
+ tiktoken