File size: 1,495 Bytes
8680b3c
 
 
 
04f8754
e030b41
8680b3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import openai
import os

#openai.api_key = os.environ["API_KEY"]  # 首先要有apikey
openai.api_key = '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'
messages = [{"role": "system", "content": "你是一个得力助手"}]


def chatgpt(content, temperature=0.8):
    global messages
    print(f'ask:{content}')
    messages.append({"role": "user", "content": content})
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo-0301",  # 或者 gpt-3.5-turbo-0301
            messages=messages,
            temperature=temperature,
            max_tokens=1000,
            top_p=1,
            frequency_penalty=0,
            presence_penalty=0,
        )
    except Exception as e:
        messages = [{"role": "system", "content": "你是一个得力助手"}]
        return '本次互动消息已达上限,已清空Token,请重新输入'
    messages.append(json.loads(str(response.choices[0].message)))
    print(f'answer:{response.choices[0].message.content}')
    return response.choices[0].message.content


if __name__ == "__main__":
    import gradio as gr


    def send_chatgpt(text):
        output = chatgpt(text, 0.8)
        return output


    input_text = gr.inputs.Textbox(label="输入问题:")
    output_text = gr.outputs.Textbox(label="回答:")
    interface = gr.Interface(fn=send_chatgpt, inputs=input_text, outputs=output_text, title="ChatGPT问答")
    # interface.launch(share=True)
    interface.launch()