快速搭建自己的chatGPT

上一篇简单介绍了如何构建自己的AI聊天应用,但实际功能还比较简单,接下来将介绍如何搭建自己完整的chatGPT应用 整个过程也比简单:

  • 构建聊天及对话列表的容器
  • 显示聊天记录
  • 加入聊天历史,支持多轮对话

在prompt中加入聊天记录

ini 复制代码
prompt = ChatPromptTemplate(
    messages=[
        SystemMessagePromptTemplate.from_template(
            "你是一个智能助手,请根据用户问题尽可能清晰,完整的回答用户的问题:{question},"
            "回答过程中请结合历史对话给出准确的回答信息history:{history}"),
    ],
    input_variables=["question", "history"])

设置页面显示

这个主要设置输入框和发送按钮的位置,以及聊天记录的显示方式,添加了handle_send函数,用于处理发送按钮点击事件

ini 复制代码
# 设置页面配置
st.set_page_config(page_title='聊天界面', layout='wide')
# 聊天历史界面
chat_history_container = st.empty()

# 输入框与发送按钮界面
input_col, button_col = st.columns([9, 1])
with input_col:
    #label_visibility 设置为隐藏label样式
    st.text_input(label="", placeholder="输入问题...", key="user_input", on_change=handle_send, label_visibility='collapsed')
with button_col:
    st.button(label="发送", on_click=handle_send, use_container_width=True)

处理聊天回答及历史记录

历史信息采用streamlit的session_state机制,每次用户发送问题后,将问题及回答信息保存到session_state中,并显示在页面上

ini 复制代码
# 如果不存在,初始化聊天历史session state
if 'chat_history' not in st.session_state:
    st.session_state.chat_history = []
if 'user_input' not in st.session_state:
    st.session_state.user_input = ''

定义bot_response方法和handle_send方法,bot_response方法用于获取机器人回答并添加到聊天历史中,handle_send方法用于处理用户发送问题; 在handle_send方法中,首先将用户问题添加到聊天历史中,然后调用bot_response方法获取机器人回答并添加到聊天历史中,最后清空输入框。 使用st.spinner方法,在获取机器人回答时,显示一个等待提示,避免用户在回答时输入问题。

csharp 复制代码
def bot_response(input_text):
    with st.spinner("思考中..."):
        llm = AzureChatOpenAI(deployment_name="gpt-4", model_name="gpt-4", temperature=0, max_tokens=1000)
        var = llm(
            prompt.format_prompt(question=input_text, history=st.session_state.chat_history).to_messages()).content
        st.session_state.chat_history.append({"sender": "bot", "message": var})
        return var

# 发送并处理用户消息
def handle_send():
    user_input = st.session_state.user_input
    if user_input:  # 如果用户输入非空
        # 将用户消息添加到聊天历史中
        st.session_state.chat_history.append({"sender": "user", "message": user_input})
        # 获取机器人回复并添加到聊天历史中
        bot_response(user_input)
        # 清空输入框
        st.session_state.user_input = ""

显示聊天历史

显示聊天历史,设置一点样式,使页面看上去更友好

ini 复制代码
# 使用HTML和CSS呈现聊天气泡
def display_chat_messages():
    html_str = ""
    for chat in st.session_state.chat_history:
        if chat["sender"] == "user":
            # 用户消息向右对齐
            html_str += f"<div style='text-align: left; margin: 5px;'>\
                            <strong>user:</br></strong>\
                            <span style='background-color: #dbf3fa; padding: 5px 10px; border-radius: 10px;'>\
                                {chat['message']}\
                            </span>\
                          </div></br>"
        else:
            # 机器人的消息向左对齐
            html_str += f"<div style='text-align: left; margin: 5px;'>\
                            <strong>bot:</br></strong>\
                            <span style='background-color: #ffffff; padding: 5px 10px; border-radius: 10px;'>\
                                {chat['message']}\
                            </span>\
                          </div></br>"
    chat_history_container.markdown(html_str, unsafe_allow_html=True)


# 显示聊天历史
display_chat_messages()
# 添加空白区以滚动到最底部(确保输入框和按钮始终显示在底部)
st.empty()

至此,整个chatGPT应用就完成了,启动应用后,可以看到如下效果:

更多精彩关注公众号:闲人张

相关推荐
c++服务器开发9 小时前
一文详解Character AI:实用指南+ ChatGPT、Gemini对比分析
人工智能·chatgpt
香宝的最强后援XD20 小时前
Cursor无限邮箱续费方法
语言模型·chatgpt·文心一言
明似水10 天前
ChatGPT:人工智能对话革命的里程碑与未来展望
人工智能·chatgpt
伊泽瑞尔10 天前
打造极致聊天体验:uz-chat——全端AI聊天组件来了!
后端·chatgpt·openai
小虎卫远程打卡app11 天前
自动驾驶避障思考
人工智能·chatgpt·自动驾驶
白云如幻11 天前
最新免费使用GPT4.0大模型、deepseek-r1、claude-3-7,GPT-4o AI绘画,有这一个网站就够了
chatgpt·aigc·deepseek
中國龍在廣州14 天前
AI之初,性本?
人工智能·科技·深度学习·机器学习·chatgpt·机器人
中國龍在廣州14 天前
ChatGPT上瘾,大脑萎缩47%!?
人工智能·科技·机器学习·chatgpt·机器人
学境思源AcademicIdeas16 天前
如何使用ChatGPT快速完成一篇论文初稿?
人工智能·chatgpt
Jet450516 天前
第100+42步 ChatGPT学习:R语言实现阈值调整
开发语言·学习·chatgpt·r语言