Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import openai | |
| # Set your OpenAI API key | |
| openai.api_key = "YOUR_OPENAI_API_KEY" # Replace with your OpenAI API key | |
| # Initialize chat history | |
| if "chat_history" not in st.session_state: | |
| st.session_state["chat_history"] = [ | |
| {"role": "system", "content": "You are a friendly and knowledgeable assistant. Answer questions accurately and helpfully. Always reply directly and avoid vague or unclear responses."} | |
| ] | |
| # Streamlit App Layout | |
| st.title("π€ GM Chatbot") | |
| st.markdown("Hi! I'm **GM Chatbot**, your friendly assistant. Ask me anything! π") | |
| # User input | |
| user_input = st.text_input("Your Message:", placeholder="Type your question or start a conversation...") | |
| if user_input: | |
| # Add user input to chat history | |
| st.session_state["chat_history"].append({"role": "user", "content": user_input}) | |
| # Generate response from OpenAI GPT | |
| try: | |
| response = openai.ChatCompletion.create( | |
| model="gpt-4", # Use "gpt-3.5-turbo" if GPT-4 is unavailable | |
| messages=st.session_state["chat_history"], | |
| temperature=0.7, | |
| max_tokens=150 | |
| ) | |
| bot_reply = response['choices'][0]['message']['content'] | |
| # Add bot reply to chat history | |
| st.session_state["chat_history"].append({"role": "assistant", "content": bot_reply}) | |
| # Display chat history | |
| for message in st.session_state["chat_history"]: | |
| if message["role"] == "assistant": | |
| st.write(f"π€ GM Chatbot: {message['content']}") | |
| elif message["role"] == "user": | |
| st.write(f"π You: {message['content']}") | |
| except Exception as e: | |
| st.error(f"Something went wrong: {e}") | |
| # Reset Chat Button | |
| if st.button("Reset Chat"): | |
| st.session_state["chat_history"] = [ | |
| {"role": "system", "content": "You are a friendly and knowledgeable assistant. Answer questions accurately and helpfully. Always reply directly and avoid vague or unclear responses."} | |
| ] | |
| st.write("Chat reset! Let's start fresh. π") | |
| # Footer | |
| st.markdown("---") | |
| st.caption("Powered by OpenAI GPT and Streamlit") | |