Files
xcq/05-streamlit-会话状态.py
2026-03-21 13:55:50 +08:00

22 lines
924 B
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import streamlit as st
# 会话管理状态:在程序执行过程中,无论代码重新运行多少次,会话状态里面的变量都会保存
st.title("黑马智聊机器人")
# st.session_state 对象本质就是json对象字典
if "messages" not in st.session_state:
st.session_state["messages"] = [{"role": "assistant", "content": "你好,我是黑马智聊机器人,有什么可以帮助你的么?"}]
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.write(message["content"])
# 聊天输入
print("用户输入前打印————————")
user_input = st.chat_input("请输入你的问题:")
print(f"用户输入后打印————————{user_input}")
if user_input:
st.session_state.messages.append({"role": "user", "content": user_input})
with st.chat_message("user"):
st.write(user_input)