| 6 | |
| 7 | # Create a chatbot UI with Streamlit and OpenAI |
| 8 | def chat_ui(): |
| 9 | state = st.session_state |
| 10 | # Set the title of the app |
| 11 | st.title("浦语提示词工程实践") |
| 12 | st.caption("浦语提示词工程实践所用Web UI") |
| 13 | |
| 14 | # Create a client for the OpenAI API |
| 15 | if "client" not in state: |
| 16 | st.info("请配置Chatbot的基本设置,其中API Key和Base URL是必须的。") |
| 17 | pass |
| 18 | else: |
| 19 | # if "message_history" not in state: |
| 20 | # state.message_history = [] |
| 21 | # pass |
| 22 | # if "system_prompt" in state: |
| 23 | # state.message_history.append({"role": "system", "content": state.system_prompt}) |
| 24 | user_input = st.chat_input("输入消息") |
| 25 | if user_input: |
| 26 | state.message_history.append({"role": "user", "content": user_input}) |
| 27 | # Generate a response from the chatbot |
| 28 | if "max_tokens" in state: |
| 29 | response = state.client.chat.completions.create( |
| 30 | model=state.client.models.list().data[0].id, |
| 31 | messages=state.message_history, |
| 32 | max_tokens=state.max_tokens, |
| 33 | temperature=state.temperature |
| 34 | ) |
| 35 | else: |
| 36 | response = state.client.chat.completions.create( |
| 37 | model=state.client.models.list().data[0].id, |
| 38 | messages=state.message_history, |
| 39 | temperature=state.temperature |
| 40 | ) |
| 41 | state.message_history.append({"role": "assistant", "content": response.choices[0].message.content}) |
| 42 | pass |
| 43 | for message in state.message_history: |
| 44 | if message["role"] == "system": |
| 45 | continue |
| 46 | else: |
| 47 | st.chat_message(message["role"]).write(message["content"]) |
| 48 | |
| 49 | # Create a text input for the user to type their message |
| 50 | |
| 51 | pass |
| 52 | # define a side bar for the setting of the chatbot, such as the max token length, temperature, api_key, base_url, system prompt, etc. |
| 53 | def side_bar(): |
| 54 | st.sidebar.title("设置") |