File size: 2,241 Bytes
00b6f69
 
 
 
 
 
 
 
0a3aaa1
00b6f69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a3aaa1
00b6f69
 
 
 
0a3aaa1
00b6f69
 
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
69
70
71
72
73
74
75
76
77
78
# import gradio as gr

# def greet(name):
#     return "Hello " + name + "!!"

# iface.launch()


import gradio as gr
import random
import time
import os
import openai
from datetime import datetime
import json

openai.api_key = ''

def send_openai_query(query):
    response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
        messages=[
        {"role": "user", "content": query}
    ] ,
    # prompt=query,
    temperature=0,
    max_tokens=500,
    top_p=1.0,
    frequency_penalty=0.0,
    presence_penalty=0.0,
    # stop=["\n"]
    )
    return response['choices'][0]['message']['content']



with gr.Blocks() as demo:
    gptkey  = gr.Textbox(placeholder='input your chatGPT key', show_label=False)
    chatbot = gr.Chatbot(elem_id="chatbot", show_label=False).style(height=300)
    msg     = gr.Textbox(show_label=False, placeholder='Input your query to chatGPT')
    clear   = gr.Button("Clear")

    def user(user_message, gptkey, history):
        if openai.api_key  == '':
            openai.api_key = gptkey.strip(' \r\n')
        # print(f'FROM USER=<{openai.api_key}>')
        return "", "Key accepted", history + [[user_message, '']]

    def bot(history):
        # print("HIST=", history)
        query = history[-1][0]
        # print(f'QUERY=<{query}>')
        try:
            result = send_openai_query(query)
        except Exception as e:
            result = 'Что-то пошло не так на стороне ChatGPT. Попробуйте повторить запрос'
        # print(f'RESULT=<{result}>')
        now = datetime.now()
        dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
        d = {'time': dt_string,
             'query': query,
             'result': result}
        d_json = json.dumps(d, ensure_ascii=False)
        with open('logs/results.ndjson', 'a') as f:
            f.write(d_json + '\r\n')
        history[-1][1] = ''
        for character in result:
            history[-1][1] += character
            time.sleep(0.02)  
            yield history

    msg.submit(user, [msg, gptkey, chatbot], [msg, gptkey, chatbot], queue=False).then(
        bot, chatbot, chatbot
    )
    clear.click(lambda: None, None, chatbot, queue=False)

demo.queue()
demo.launch()