Spaces:
Running
Running
_C='role' | |
_B=True | |
_A='content' | |
import os,gradio as gr,json,requests,openai | |
try:openai.api_key=os.environ['OPENAI_API_KEY'] | |
except KeyError: | |
error_message='System is at capacity right now.Please try again later';print(error_message) | |
def chatbot(input):return error_message | |
else:messages=[{_C:'system',_A:'My AI Assistant'}] | |
API_URL='https://api.openai.com/v1/chat/completions' | |
top_p_chatgpt=1.0 | |
temperature_chatgpt=1.0 | |
def chatbot(inputs,chat_counter_chatgpt,chatbot_chatgpt=[],history=[]): | |
V='delta';U='choices';T='frequency_penalty';S='presence_penalty';R='stream';Q='top_p';P='temperature';O='messages';J='user';F=chat_counter_chatgpt;E=inputs;A=history;K={'model':'gpt-3.5-turbo',O:[{_C:J,_A:f"{E}"}],P:1.0,Q:1.0,'n':1,R:_B,S:0,T:0};W={'Content-Type':'application/json','Authorization':f"Bearer {openai.api_key}"} | |
if F!=0: | |
C=[] | |
for L in chatbot_chatgpt:G={};G[_C]=J;G[_A]=L[0];H={};H[_C]='assistant';H[_A]=L[1];C.append(G);C.append(H) | |
I={};I[_C]=J;I[_A]=E;C.append(I);K={'engine':'text-davinci-003',O:C,P:temperature_chatgpt,Q:top_p_chatgpt,'n':1,R:_B,S:0,T:0} | |
F+=1;A.append('You asked: '+E);X=requests.post(API_URL,headers=W,json=K,stream=_B);M=0;D='';N=0 | |
for B in X.iter_lines(): | |
if N==0:N+=1;continue | |
if B.decode(): | |
B=B.decode() | |
if len(B)>13 and _A in json.loads(B[6:])[U][0][V]: | |
D=D+json.loads(B[6:])[U][0][V][_A] | |
if M==0:A.append(' '+D) | |
else:A[-1]=D | |
Y=[(A[B],A[B+1])for B in range(0,len(A)-1,2)];M+=1;yield(Y,A,F) | |
def reset_textbox():return gr.update(value='') | |
def reset_chat(chatbot,state):return None,[] | |
with gr.Blocks(css='#col_container {width: 1000px; margin-left: auto; margin-right: auto;}\n #chatgpt {height: 400px; overflow: auto;}} ',theme=gr.themes.Default(primary_hue='slate'))as ChatGPTDavinci: | |
with gr.Row(): | |
with gr.Column(scale=14): | |
with gr.Box(): | |
with gr.Row(): | |
with gr.Column(scale=13):inputs=gr.Textbox(label='Ask me anything ⤵️ Try: Value of pi') | |
with gr.Column(scale=1):b1=gr.Button('Submit',elem_id='submit').style(full_width=_B);b2=gr.Button('Clear',elem_id='clear').style(full_width=_B) | |
state_chatgpt=gr.State([]) | |
with gr.Box(): | |
with gr.Row():chatbot_chatgpt=gr.Chatbot(elem_id='chatgpt',label='My ChatGPT Davinci') | |
chat_counter_chatgpt=gr.Number(value=0,visible=False,precision=0);inputs.submit(reset_textbox,[],[inputs]);b1.click(chatbot,[inputs,chat_counter_chatgpt,chatbot_chatgpt,state_chatgpt],[chatbot_chatgpt,state_chatgpt]);b2.click(reset_chat,[chatbot_chatgpt,state_chatgpt],[chatbot_chatgpt,state_chatgpt]);ChatGPTDavinci.queue(concurrency_count=16).launch(height=2500,debug=_B) |