我正在使用 Python 和 Streamlit 制作一个聊天机器人。我希望聊天在右侧显示用户消息,在左侧显示机器人消息。为此,我使用了带有
row-reversed
的 CSS,但文本大小和聊天消息大小并没有按照我想要的方式更改。
这是我尝试过的CSS:
对于用户消息:
div.stChatMessage.st-emotion-cache-1c7y2kd.eeusbqq4
{
width: 350px;
display: flex;
flex-direction: row-reverse;
align-items: flex-start;
justify-content: flex-end;
}
对于机器人消息(以黑色突出显示)
div.stChatMessage.st-emotion-cache-4oy321.eeusbqq4
{
background-color: hsla(208, 29%, 78%, 0.66);
border: 1px solid transparent;
width: 550px;
border-radius: 25px;
}
为了重现代码,我使用以下链接中的代码:
https://docs.streamlit.io/develop/tutorials/llms/build-conversational-apps
(请参阅构建类似 ChatGPT 的应用程序部分)
from openai import OpenAI
import streamlit as st
st.title("ChatGPT-like clone")
client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
with open ('design.css') as source:
st.markdown(f"<style>{source.read()}</style>",unsafe_allow_html=True)
if "openai_model" not in st.session_state:
st.session_state["openai_model"] = "gpt-3.5-turbo"
if "messages" not in st.session_state:
st.session_state.messages = []
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if prompt := st.chat_input("What is up?"):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
stream = client.chat.completions.create(
model=st.session_state["openai_model"],
messages=[
{"role": m["role"], "content": m["content"]}
for m in st.session_state.messages
],
stream=True,
)
response = st.write_stream(stream)
st.session_state.messages.append({"role": "assistant", "content": response})
我得到的输出
预期的输出应该与下图有些相似。左侧是机器人消息,右侧是用户消息。
您遇到的问题是由于同时使用了
flex-direction: row-reverse
和 justify-content: flex-end
,它们与所需的结果相互矛盾。尝试使用任一声明。
或者,我认为这更接近你想要的:
div.container {
display: flex;
flex-direction: column;
max-width: 500px;
margin: auto;
}
div.user {
align-self: flex-end;
padding: .5em;
background-color: aliceblue;
}
div.bot {
align-self: flex-start;
padding: .5em;
background-color: hsla(208, 29%, 78%, 0.66);
border-radius: 25px;
}
<div class="container">
<div class="user">book hotel</div>
<div class="bot">Where?</div>
<div class="user">Madison, WI</div>
<div class="bot">When?</div>
</div>