效果图
准备
需要chatgpt的apikey
安装 streamlit
sudo apt update
sudo apt install python3-pip
pip3 install openai
sudo pip3 install streamlit
编写代码 ai.py
需要替换成自己的api_key
import streamlit as st
from openai import OpenAI
st.title("ChatGPT-like clone")
# Set OpenAI API key from Streamlit secrets
client = OpenAI(api_key="sk-xxxxxxxxx")
# Set a default model
if "openai_model" not in st.session_state:
st.session_state["openai_model"] = "gpt-3.5-turbo"
#st.session_state["openai_model"] = "gpt-4"
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
# Display chat messages from history on app rerun
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Accept user input
if prompt := st.chat_input("What is up?"):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message in chat message container
with st.chat_message("user"):
st.markdown(prompt)
# Display assistant response in chat message container
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})
启动程序
nohup streamlit run ai.py &
# 指定端口号
nohup streamlit run --server.port 8501 ai.py &
默认启动端口为8051