File size: 1,787 Bytes
b278de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import time
from openai import OpenAI
from dotenv import load_dotenv
import os

load_dotenv()

with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    msg = gr.Textbox()
    clear = gr.ClearButton([msg, chatbot])

    def openai_request(messages):
        """
        requests to fine tuned openai model
        """
        client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
        response = client.chat.completions.create(
            model="ft:gpt-3.5-turbo-0613:personal::8SkHOPq1",
            messages=messages,
            temperature=0.5,
        )
        result = response.choices[0].message.content
        return result

    def l_to_openai_format(l):
        """
        converts a list of messages to open ai format messages
        """
        output = []
        for i in range(len(l)):
            if i % 2 == 0:
                output.append({'role': 'user', 'content': l[i]})
            else:
                output.append({'role': 'assistant', 'content': l[i]})
        return output

    def message_and_history_to_list(message, history):
        """
        gets message and history and converts all to one list
        """
        l = []
        for i in history:
            for j in i:
                l.append(j)
        l.append(message)
        return l 
            
    def respond(message, chat_history):
        """
        is called everytime a message is submitted into the chatbot
        """
        l = message_and_history_to_list(message, chat_history)
        open_ai_request_format = l_to_openai_format(l)
        bot_message = openai_request(open_ai_request_format)
        chat_history.append((message, bot_message))
        return "", chat_history

    msg.submit(respond, [msg, chatbot], [msg, chatbot])

demo.launch()