Spaces:
Build error
Build error
| # Import the necessary libraries | |
| import streamlit as st | |
| from openai import OpenAI # TODO: Install the OpenAI library using pip install openai | |
| st.title("Mini Project 2: Streamlit Chatbot") | |
| # TODO: Replace with your actual OpenAI API key | |
| openai_key = "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" | |
| client = OpenAI(api_key=openai_key) | |
| # Define a function to get the conversation history (Not required for Part-2, will be useful in Part-3) | |
| def get_conversation() -> str: | |
| # return: A formatted string representation of the conversation. | |
| conversation = "" | |
| for message in st.session_state.messages: | |
| role = message["role"] | |
| content = message["content"] | |
| conversation += f"{role}: {content}\n" | |
| return conversation | |
| # Check for existing session state variables | |
| if "openai_model" not in st.session_state: | |
| st.session_state["openai_model"] = "gpt-3.5-turbo" # Initialize model | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [] # Initialize messages as an empty list | |
| # Display existing chat messages | |
| for message in st.session_state.messages: | |
| with st.chat_message(message["role"]): | |
| st.markdown(message["content"]) | |
| # Wait for user input | |
| if prompt := st.chat_input("What would you like to chat about?"): | |
| # Append user message to messages | |
| st.session_state.messages.append({"role": "user", "content": prompt}) | |
| # Display user message | |
| with st.chat_message("user"): | |
| st.markdown(prompt) | |
| # Generate AI response | |
| with st.chat_message("assistant"): | |
| # Send request to OpenAI API | |
| response = client.chat.completions.create( | |
| model=st.session_state["openai_model"], | |
| messages=[{"role": m["role"], "content": m["content"]} for m in st.session_state.messages] | |
| ) | |
| ai_response = response.choices[0].message.content | |
| # Display AI response | |
| st.markdown(ai_response) | |
| # Append AI response to messages | |
| st.session_state.messages.append({"role": "assistant", "content": ai_response}) |