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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
@author:XuMing(xuming624@qq.com)
|
| 4 |
+
@description:
|
| 5 |
+
"""
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import os
|
| 8 |
+
import json
|
| 9 |
+
import requests
|
| 10 |
+
from loguru import logger
|
| 11 |
+
from dotenv import load_dotenv
|
| 12 |
+
|
| 13 |
+
logger.add('gradio_server.log', rotation='10 MB', encoding='utf-8', level='DEBUG')
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_api_key():
|
| 17 |
+
api_key = ''
|
| 18 |
+
if os.path.isfile('.env'):
|
| 19 |
+
load_dotenv()
|
| 20 |
+
if os.environ.get('API_KEY') is not None:
|
| 21 |
+
api_key = os.environ.get('API_KEY')
|
| 22 |
+
return api_key
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def set_new_api_key(api_key):
|
| 26 |
+
# Write the api key to the .env file
|
| 27 |
+
with open('.env', 'w') as f:
|
| 28 |
+
f.write(f'API_KEY={api_key}')
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Streaming endpoint for OPENAI ChatGPT
|
| 32 |
+
API_URL = "https://api.openai.com/v1/chat/completions"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# Predict function for CHATGPT
|
| 36 |
+
def predict_chatgpt(inputs, top_p_chatgpt, temperature_chatgpt, openai_api_key, chat_counter_chatgpt,
|
| 37 |
+
chatbot_chatgpt=[], history=[]):
|
| 38 |
+
# Define payload and header for chatgpt API
|
| 39 |
+
payload = {
|
| 40 |
+
"model": "gpt-3.5-turbo",
|
| 41 |
+
"messages": [{"role": "user", "content": f"{inputs}"}],
|
| 42 |
+
"temperature": 1.0,
|
| 43 |
+
"top_p": 1.0,
|
| 44 |
+
"n": 1,
|
| 45 |
+
"stream": True,
|
| 46 |
+
"presence_penalty": 0,
|
| 47 |
+
"frequency_penalty": 0,
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
headers = {
|
| 51 |
+
"Content-Type": "application/json",
|
| 52 |
+
"Authorization": f"Bearer {openai_api_key}"
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
# Handling the different roles for ChatGPT
|
| 56 |
+
if chat_counter_chatgpt != 0:
|
| 57 |
+
messages = []
|
| 58 |
+
for data in chatbot_chatgpt:
|
| 59 |
+
temp1 = {}
|
| 60 |
+
temp1["role"] = "user"
|
| 61 |
+
temp1["content"] = data[0]
|
| 62 |
+
temp2 = {}
|
| 63 |
+
temp2["role"] = "assistant"
|
| 64 |
+
temp2["content"] = data[1]
|
| 65 |
+
messages.append(temp1)
|
| 66 |
+
messages.append(temp2)
|
| 67 |
+
temp3 = {}
|
| 68 |
+
temp3["role"] = "user"
|
| 69 |
+
temp3["content"] = inputs
|
| 70 |
+
messages.append(temp3)
|
| 71 |
+
payload = {
|
| 72 |
+
"model": "gpt-3.5-turbo",
|
| 73 |
+
"messages": messages, # [{"role": "user", "content": f"{inputs}"}],
|
| 74 |
+
"temperature": temperature_chatgpt, # 1.0,
|
| 75 |
+
"top_p": top_p_chatgpt, # 1.0,
|
| 76 |
+
"n": 1,
|
| 77 |
+
"stream": True,
|
| 78 |
+
"presence_penalty": 0,
|
| 79 |
+
"frequency_penalty": 0,
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
chat_counter_chatgpt += 1
|
| 83 |
+
|
| 84 |
+
history.append(inputs)
|
| 85 |
+
# make a POST request to the API endpoint using the requests.post method, passing in stream=True
|
| 86 |
+
response = requests.post(API_URL, headers=headers, json=payload, stream=True)
|
| 87 |
+
token_counter = 0
|
| 88 |
+
partial_words = ""
|
| 89 |
+
|
| 90 |
+
counter = 0
|
| 91 |
+
for chunk in response.iter_lines():
|
| 92 |
+
# Skipping the first chunk
|
| 93 |
+
if counter == 0:
|
| 94 |
+
counter += 1
|
| 95 |
+
continue
|
| 96 |
+
# check whether each line is non-empty
|
| 97 |
+
if chunk.decode():
|
| 98 |
+
chunk = chunk.decode()
|
| 99 |
+
# decode each line as response data is in bytes
|
| 100 |
+
if len(chunk) > 13 and "content" in json.loads(chunk[6:])['choices'][0]["delta"]:
|
| 101 |
+
partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"]
|
| 102 |
+
if token_counter == 0:
|
| 103 |
+
history.append(" " + partial_words)
|
| 104 |
+
else:
|
| 105 |
+
history[-1] = partial_words
|
| 106 |
+
chat = [(history[i], history[i + 1]) for i in
|
| 107 |
+
range(0, len(history) - 1, 2)] # convert to tuples of list
|
| 108 |
+
token_counter += 1
|
| 109 |
+
yield chat, history, chat_counter_chatgpt # this resembles {chatbot: chat, state: history}
|
| 110 |
+
logger.info(f"input: {inputs}, output: {partial_words}")
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def reset_textbox():
|
| 114 |
+
return gr.update(value="")
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def reset_chat(chatbot, state):
|
| 118 |
+
return None, []
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
title = """<h1 align="center">🔥🔥 ChatGPT Gradio Demo </h1><br><h3 align="center">🚀For ChatBot</h3>"""
|
| 122 |
+
description = """<center>author: shibing624</center>"""
|
| 123 |
+
|
| 124 |
+
with gr.Blocks(css="""#col_container {width: 1200px; margin-left: auto; margin-right: auto;}
|
| 125 |
+
#chatgpt {height: 520px; overflow: auto;} """) as demo:
|
| 126 |
+
# chattogether {height: 520px; overflow: auto;} """ ) as demo:
|
| 127 |
+
# clear {width: 100px; height:50px; font-size:12px}""") as demo:
|
| 128 |
+
gr.HTML(title)
|
| 129 |
+
with gr.Row():
|
| 130 |
+
with gr.Column(scale=14):
|
| 131 |
+
with gr.Box():
|
| 132 |
+
with gr.Row():
|
| 133 |
+
with gr.Column(scale=13):
|
| 134 |
+
api_key = get_api_key()
|
| 135 |
+
if not api_key:
|
| 136 |
+
openai_api_key = gr.Textbox(type='password',
|
| 137 |
+
label="Enter your OpenAI API key here for ChatGPT")
|
| 138 |
+
else:
|
| 139 |
+
openai_api_key = gr.Textbox(type='password',
|
| 140 |
+
label="Enter your OpenAI API key here for ChatGPT",
|
| 141 |
+
value=api_key, visible=False)
|
| 142 |
+
inputs = gr.Textbox(lines=4, placeholder="Hi there!",
|
| 143 |
+
label="Type input question and press Shift+Enter ⤵️ ")
|
| 144 |
+
with gr.Column(scale=1):
|
| 145 |
+
b1 = gr.Button('🏃Run', elem_id='run').style(full_width=True)
|
| 146 |
+
b2 = gr.Button('🔄Clear up Chatbots!', elem_id='clear').style(full_width=True)
|
| 147 |
+
state_chatgpt = gr.State([])
|
| 148 |
+
|
| 149 |
+
with gr.Box():
|
| 150 |
+
with gr.Row():
|
| 151 |
+
chatbot_chatgpt = gr.Chatbot(elem_id="chatgpt", label='ChatGPT API - OPENAI')
|
| 152 |
+
|
| 153 |
+
with gr.Column(scale=2, elem_id='parameters'):
|
| 154 |
+
with gr.Box():
|
| 155 |
+
gr.HTML("Parameters for OpenAI's ChatGPT")
|
| 156 |
+
top_p_chatgpt = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True,
|
| 157 |
+
label="Top-p", )
|
| 158 |
+
temperature_chatgpt = gr.Slider(minimum=-0, maximum=5.0, value=1.0, step=0.1, interactive=True,
|
| 159 |
+
label="Temperature", )
|
| 160 |
+
chat_counter_chatgpt = gr.Number(value=0, visible=False, precision=0)
|
| 161 |
+
|
| 162 |
+
inputs.submit(reset_textbox, [], [inputs])
|
| 163 |
+
|
| 164 |
+
inputs.submit(predict_chatgpt,
|
| 165 |
+
[inputs, top_p_chatgpt, temperature_chatgpt, openai_api_key, chat_counter_chatgpt, chatbot_chatgpt,
|
| 166 |
+
state_chatgpt],
|
| 167 |
+
[chatbot_chatgpt, state_chatgpt, chat_counter_chatgpt], )
|
| 168 |
+
b1.click(predict_chatgpt,
|
| 169 |
+
[inputs, top_p_chatgpt, temperature_chatgpt, openai_api_key, chat_counter_chatgpt, chatbot_chatgpt,
|
| 170 |
+
state_chatgpt],
|
| 171 |
+
[chatbot_chatgpt, state_chatgpt, chat_counter_chatgpt], )
|
| 172 |
+
|
| 173 |
+
b2.click(reset_chat, [chatbot_chatgpt, state_chatgpt], [chatbot_chatgpt, state_chatgpt])
|
| 174 |
+
gr.HTML(
|
| 175 |
+
"""<center>Link to:<a href="https://github.com/shibing624/ChatGPT-API-server">https://github.com/shibing624/ChatGPT-API-server</a></center>""")
|
| 176 |
+
gr.Markdown(description)
|
| 177 |
+
|
| 178 |
+
if __name__ == '__main__':
|
| 179 |
+
demo.queue(concurrency_count=3).launch(height=2500, server_name='0.0.0.0', server_port=8080, debug=False)
|