File size: 2,326 Bytes
7c84710
 
6c5a57a
7c84710
2ce6944
 
46773d0
2ce6944
 
 
 
47ec66f
 
 
 
2ce6944
 
 
7c84710
46773d0
 
 
 
 
 
 
 
 
 
 
47ec66f
2ce6944
47ec66f
 
 
 
46773d0
c9a8c83
3b57062
5003a8d
 
 
 
 
 
47ec66f
 
 
 
46773d0
 
47ec66f
 
 
c9a8c83
46773d0
47ec66f
 
 
 
7c84710
 
46773d0
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
import openai
import gradio as gr
import random

openai.api_key = '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'

user_contexts = {}

def get_assistant_response(user_question, context):
    context.append({"role": "user", "content": user_question})
    response = openai.ChatCompletion.create(
        model='gpt-3.5-turbo',
        messages=context,
        temperature=0
    )
    assistant_response = response.choices[0].message['content']
    context.append({"role": "assistant", "content": assistant_response})
    return assistant_response

def greet(user_id, user_question, clear_history):
    global user_contexts
    if user_id not in user_contexts:
        user_contexts[user_id] = [
            {"role": "system", "content": "你是一个聪明的AI助手。"},
            {"role": "user", "content": "你会说中文吗?"},
            {"role": "assistant", "content": "是的,我可以说中文。"}
        ]

    context = user_contexts[user_id]

    if clear_history:
        context = [
            {"role": "system", "content": "你是一个聪明的AI助手。"},
            {"role": "user", "content": "你会说中文吗?"},
            {"role": "assistant", "content": "是的,我可以说中文。"}
        ]
        user_contexts[user_id] = context
        return '清空成功', '保持聊天记录'
    else:
        get_assistant_response(user_question, context)
        prompt = ""

        for item in context[3:]:
            prompt += item["role"] + ": " + item["content"] + "\n"
        return '', prompt

demo = gr.Interface(
    fn=greet,
    inputs=[
        gr.Textbox(lines=1, label='请输入用户ID', placeholder='请输入用户ID'),
        gr.Textbox(lines=15, label='请输入问题', placeholder='请输入您的问题'),
        gr.Checkbox(label='清空聊天记录', default=False)
    ],
    outputs=[
        gr.Textbox(lines=1, label='聊天记录状态', placeholder='等待清空聊天记录'),
        gr.Textbox(lines=20, label='AI回答', placeholder='等待AI回答')
    ],
    title="AI助手",
    description="请输入您的问题,AI助手会给出回答。支持连续对话,可以记录对话历史。重新开始对话勾选清空聊天记录,输出清空成功表示重新开启对话。"
)

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