|
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() |