快速搭建自己的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应用就完成了,启动应用后,可以看到如下效果:

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

相关推荐
中國龍在廣州1 天前
谈谈2025年人工智能现状及发展趋势分析
人工智能·深度学习·算法·自然语言处理·chatgpt·机器人·机器人学习
迪娜学姐1 天前
Nano Banana Pro科研绘图能力实测
论文阅读·人工智能·chatgpt·prompt·论文笔记
我家大宝最可爱1 天前
windows搭建agent环境
c++·chatgpt
不错就是对1 天前
【Agent-lightning】 - 1_环境搭建
人工智能·pytorch·深度学习·机器学习·chatgpt·transformer·vllm
tyh_keepRunning2 天前
Cursor与MCP的天作之和
selenium·ai·语言模型·chatgpt·idea
90后小陈老师2 天前
自律APP开发规划测评,个人感觉chatGPT最佳Claude其次
人工智能·chatgpt·ai编程
hxcat3 天前
AI 提示词测试:在人工智能时代践行“测试左移“理念
软件测试·人工智能·chatgpt
村口曹大爷3 天前
【深度】OpenAI 推理架构演进:GPT-5.2(Internal版)性能实测与开发者接入路径分析
gpt·ai·chatgpt·架构·gpt5.2
南风聊AI3 天前
从单体LLM到多Agent协作,如何用AI重构内容生产SOP
人工智能·chatgpt·重构
Blossom.1183 天前
基于混合检索架构的RAG系统优化实践:从Baseline到生产级部署
人工智能·python·算法·chatgpt·ai作画·架构·自动化