Spaces:
Sleeping
Sleeping
| # app.py | |
| import os | |
| import openai | |
| import streamlit as st | |
| # Initialize OpenAI client using v1.x API | |
| client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY")) | |
| # Streamlit page configuration | |
| st.set_page_config(page_title="OpenAI Chatbot", layout="centered") | |
| st.title("🤖 OpenAI Chatbot") | |
| st.markdown("Jo Pocho k Wo Bataiya Jai Ga") | |
| # Initialize conversation history | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [ | |
| {"role": "system", "content": "You are a helpful assistant."} | |
| ] | |
| # Display chat history | |
| for msg in st.session_state.messages[1:]: | |
| with st.chat_message(msg["role"]): | |
| st.markdown(msg["content"]) | |
| # Chat input box | |
| if prompt := st.chat_input("Type your message here..."): | |
| st.chat_message("user").markdown(prompt) | |
| st.session_state.messages.append({"role": "user", "content": prompt}) | |
| try: | |
| # Send chat completion request | |
| response = client.chat.completions.create( | |
| model="gpt-3.5-turbo", # ✅ Compatible for all OpenAI API users | |
| messages=st.session_state.messages, | |
| temperature=0.7 | |
| ) | |
| reply = response.choices[0].message.content | |
| st.chat_message("assistant").markdown(reply) | |
| st.session_state.messages.append({"role": "assistant", "content": reply}) | |
| except Exception as e: | |
| st.chat_message("assistant").markdown(f"❌ Error: {e}") | |