基于Gradio的GPT聊天程序

网上很多别人写的,要用账号也不放心。就自己写了一个基于gradio的聊天界面,部署后可以本地运行。

特点:

可以用openai的,也可以用api2d,其他api可以自己测试一下。使用了langchain的库

可以更改模型,会的可以自己改代码更新模型

支持修改temperature,对话轮数

公开代码,copy后填了自己的api就能直接运行

python 复制代码
import gradio as gr

from langchain.chat_models import ChatOpenAI
from langchain.schema import HumanMessage, AIMessage


api_key = '***'  # openai api, api2d api
api_base ='https://oa.api2d.net/v1'  # api地址
models = ['gpt-3.5-turbo-0613', 'gpt-4-0613']   #模型名称,可以修改

block_css = """.importantButton {
    background: linear-gradient(45deg, #7e0570,#5d1c99, #6e00ff) !important;
    border: none !important;
}
.importantButton:hover {
    background: linear-gradient(45deg, #ff00e0,#8500ff, #6e00ff) !important;
    border: none !important;
}"""


default_theme_args = dict(
    font=["Source Sans Pro", 'ui-sans-serif', 'system-ui', 'sans-serif'],
    font_mono=['IBM Plex Mono', 'ui-monospace', 'Consolas', 'monospace'],
)



init_message = f"""欢迎使用 ChatGPT Gradio UI!"""


def respond(query, model, temperature, history_turns, chat_history):
    global chat_turns
    llm = ChatOpenAI(
        temperature=temperature,
        openai_api_key=api_key,
        openai_api_base=api_base,
        model_name=model
    )

    history=[]
    len_history = min(chat_turns, history_turns)
    if chat_turns > 0:
        for turn in range(len_history):
            history.append(HumanMessage(content=chat_history[len_history-turn][0]));
            history.append(AIMessage(content=chat_history[len_history-turn][1]));

    history.append(HumanMessage(content=query));
    #print(history)

    response = llm(history).content;

    chat_history.append((query, response));
    chat_turns += 1
    return "", chat_history


def clear(chat_history):
    global chat_turns
    chat_history = [(None, "已清除对话历史")]
    chat_turns = 0
    return chat_history

def setting_change(model ,temperature, history_turns ,chat_history):
    global chat_turns
    chat_history = [(None, f"设置更新:\n 模型名称:{model} \n 温度:{temperature} \n 记忆历史对话轮数:{history_turns}\n")]
    chat_turns =0
    return chat_history





with gr.Blocks(css=block_css, theme=gr.themes.Default(**default_theme_args)) as demo:

    gr.Markdown('ChatGPT Gradio')
    chat_turns = 0
    with gr.Row():
        with gr.Column(scale=10):
            chatbot = gr.Chatbot([[None, init_message]],
                                 elem_id="chat-box",
                                 label="聊天历史")
            query = gr.Textbox(label="输入问题",
                               placeholder="请输入提问内容,按回车进行提交")
            clear_button = gr.Button("重新对话", visible=True)

        with gr.Column(scale=5):
            model = gr.Radio(models,
                            label="请选择使用模型",
                            value=models[0], interactive=True)


            temperature = gr.Slider(0,1,
                                    value=0.8,
                                    step=0.1,
                                    label="Temperature",
                                    interactive=True)

            history_turns = gr.Slider(1, 20,
                                 value=5,
                                 step=1,
                                 label="对话轮数",
                                 info='记录历史对话轮数',
                                 interactive=True)

            settings_button = gr.Button("更新设置", visible=True)

            settings_button.click(fn=setting_change, inputs=[model, temperature, history_turns, chatbot], outputs=[chatbot])

    query.submit(respond, [query, model, temperature, history_turns, chatbot], [query, chatbot])

    clear_button.click(fn=clear,
                    inputs=[chatbot],
                    outputs=[chatbot])

demo.launch()

需要的库,requirement.txt 文件

python 复制代码
langchain
openai
gradio
相关推荐
Jo乔戈里9 分钟前
免费本地搜图软件
图像处理·python·搜索引擎·ai
for_ever_love__15 分钟前
字符串处理——f-string、切片与正则,清洗文本的第一把刀
python·大模型·虚拟环境
夜晚回家22 分钟前
Python 零基础入门 | 输入的数字为什么不能直接算
开发语言·python
打工仔折腾 AI33 分钟前
把AI Agent托管在家用电脑:UU远程终端与端口映射实测记录
人工智能·后端·python·langchain·ai agent 实战
yivifu44 分钟前
中文古籍电子书注释集成
前端·javascript·python·beautifulsoup·epub
零基础1231 小时前
Agent 的 Memory 怎么做科研:以中医诊断场景为例
人工智能·经验分享·python·语言模型
databook1 小时前
面向数据工程师的正则表达式:从日志清洗到字段提取
python·正则表达式·数据分析
ss2732 小时前
AI全栈实战 | 3.2-01 Python 基础:四大数据容器怎么选,推导式为什么是 Pythonic 的灵魂
开发语言·人工智能·python
计算机毕业编程指导师2 小时前
【大数据毕设选题推荐】基于Spark的WTA职业网球赛事演变与竞技格局分析系统源码 毕业设计 选题推荐 毕设选题 数据分析 机器学习 深度学习
大数据·python·计算机·spark·毕业设计·课程设计·wta网球
言乐63 小时前
Python区分广度优先深度优先宽度优先的区别
python·算法·深度优先·广度优先·宽度优先