File size: 1,596 Bytes
8a2b97e
 
b640f24
8a2b97e
 
 
 
ee6d080
 
 
8a2b97e
 
 
 
ee6d080
8a2b97e
 
 
 
69d74b5
b640f24
8a2b97e
 
 
 
0fcf950
8a2b97e
 
 
 
 
 
 
 
25e2470
8a2b97e
 
 
 
 
 
7398b02
332c046
 
 
 
 
 
8a2b97e
 
 
 
 
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
import os

os.system('git clone https://huggingface.co/souljoy/chatGPT')
import requests
import json
import gradio as gr

# with open('chatGPT/Authorization', mode='r', encoding='utf-8') as f:
#     for line in f:
#         authorization = line.strip()

url = 'https://api.openai.com/v1/chat/completions'
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + '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'
}


def predict(msg, history=[]):
    messages = []
    for i in range(len(history) - 1, max(0, len(history) - 3), -1):
        messages.append({"role": "user", "content": history[i][0]})
        messages.append({"role": "assistant", "content": history[i][1]})
    messages.append({"role": "user", "content": msg})
    data = {
        "model": "text-davinci-003",
        "messages": messages
    }
    result = requests.post(url=url,
                           data=json.dumps(data),
                           headers=headers
                           )

    res = result.json()['choices'][0]['message']['content']
    print(res)
    history.append([msg, res])
    return history, history, res


with gr.Blocks() as demo:
    state = gr.State([])
    with gr.Row():
        with gr.Column():
            chatbot = gr.Chatbot()
            txt = gr.Textbox(label='输入框', placeholder='输入消息...')
            bu = gr.Button(value='发送消息')
        with gr.Column():
            answer_text = gr.Textbox(label='回复')

    bu.click(predict, [txt, state], [chatbot, state, answer_text])

if __name__ == "__main__":
    demo.launch()