File size: 2,365 Bytes
b383690
 
 
8630213
b383690
 
 
 
 
 
 
8630213
b383690
8630213
b383690
8630213
 
 
 
b383690
 
 
8630213
50d713b
b383690
 
 
 
 
 
 
 
 
8630213
b383690
8630213
b383690
 
8630213
 
 
b383690
8630213
 
 
 
 
 
 
 
b383690
 
 
8630213
 
b383690
 
 
 
 
8630213
b383690
8630213
b383690
 
 
bf9f95d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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()