Chatbot / app.py
Scakmak's picture
token size change
50d713b
import gradio as gr
import openai
import os
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("openai_api_key")
# history = []
character_name = "AI"
# chat_history = []
def openai_chat(prompt, ch_history):
ch_history.append({"role": "user", "content": prompt})
messagesFiltered = [ch_history[i] for i in range(len(ch_history)) if ((i % 3 !=0) | (i ==0)) ]
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messagesFiltered,
max_tokens=300,
temperature=0.6,
top_p=1,
frequency_penalty=0.5,
presence_penalty=0.0
)
print(response.choices[0].message["content"].strip())
return response.choices[0].message["content"].strip()
def set_character_name(prompt_input, ch_history):
print(prompt_input)
character_name = prompt_input
#history.append({"role": "system", "content": f"You are {character_name}. You will talk and think like {character_name} from now on."})
ch_history.append({"role": "system", "content": f"You are {character_name}. You will talk and think like {character_name} from now on."})
return {msg: msg.update(visible=True), chatbot: chatbot.update(visible=True), char_selection : char_selection.update(visible=False), title: title.update( value = f"Chat with {character_name.upper()}",visible=True), state: ch_history}
def respond(message, ch_history):
bot_message = openai_chat(message, ch_history)
#history.append({"role": "assistant", "content": bot_message})
ch_history.append({"role": "assistant", "content": bot_message})
ch_history.append((message, bot_message))
chats = [ch_history[i] for i in range(len(ch_history)) if ((i % 3 == 0) & (i !=0)) ]
return {msg: msg.update(value="", visible=True), chatbot: chatbot.update(value= chats,visible=True), state: ch_history}
with gr.Blocks() as demo:
state = gr.State([])
char_selection = gr.Textbox(lines=1 , label="Enter the character you want to talk to:")
title = gr.Markdown( visible=False)
chatbot = gr.Chatbot(visible=False)
msg = gr.Textbox(visible=False)
char_selection.submit(set_character_name, [char_selection, state], [chatbot, msg, char_selection, title,state])
msg.submit(respond, [msg, state], [chatbot, msg,state])
demo.launch()