Spaces:
Sleeping
Sleeping
File size: 1,342 Bytes
e503c3b 8a6a99a e503c3b 0859b7e e503c3b 0859b7e 8a6a99a 0859b7e e503c3b 8a6a99a e503c3b 0859b7e 8a6a99a 0859b7e 8a6a99a 0859b7e 8a6a99a 0859b7e 8a6a99a 0859b7e 8a6a99a 0859b7e 8a6a99a 0859b7e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | # app.py
import os
import openai
import streamlit as st
# Load API key from environment variable
client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# Page setup
st.set_page_config(page_title="OpenAI Chatbot", layout="centered")
st.title("🤖 OpenAI Chatbot")
st.markdown("Talk to GPT-4 using OpenAI's latest API.")
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = [
{"role": "system", "content": "You are a helpful assistant."}
]
# Show chat history
for msg in st.session_state.messages[1:]:
with st.chat_message(msg["role"]):
st.markdown(msg["content"])
# User input
if prompt := st.chat_input("Type your message..."):
# Show user message
st.chat_message("user").markdown(prompt)
st.session_state.messages.append({"role": "user", "content": prompt})
try:
# Call OpenAI's chat model using v1.x API
response = client.chat.completions.create(
model="gpt-4", # or "gpt-3.5-turbo"
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.error(f"Error: {e}")
|