Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,52 +6,27 @@ from langchain.schema import HumanMessage, AIMessage
|
|
| 6 |
|
| 7 |
# Load environment variables
|
| 8 |
load_dotenv()
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
temperature=0.7,
|
| 16 |
-
max_retries=3 # Automatically retry failed requests
|
| 17 |
-
)
|
| 18 |
-
|
| 19 |
-
# Streamlit UI setup
|
| 20 |
-
st.set_page_config(
|
| 21 |
-
page_title="ChatGPT",
|
| 22 |
-
page_icon="",
|
| 23 |
-
layout="centered",
|
| 24 |
-
)
|
| 25 |
-
|
| 26 |
-
# Chat history initialization
|
| 27 |
if "messages" not in st.session_state:
|
| 28 |
-
st.session_state
|
| 29 |
|
| 30 |
-
# Display the chat history
|
| 31 |
-
st.markdown(
|
| 32 |
-
"<h1 style='text-align: center;'><b> Chatgpt <b/>.</h1>",
|
| 33 |
-
unsafe_allow_html=True
|
| 34 |
-
)
|
| 35 |
for msg in st.session_state.messages:
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
with st.spinner("Thinking..."):
|
| 51 |
-
try:
|
| 52 |
-
# Use .invoke() instead of calling chat directly
|
| 53 |
-
response = chat.invoke(st.session_state.messages)
|
| 54 |
-
st.write(f"**Assistant:** {response.content}")
|
| 55 |
-
st.session_state.messages.append(AIMessage(content=response.content))
|
| 56 |
-
except Exception as e:
|
| 57 |
-
st.error(f"Error: {e}")
|
|
|
|
| 6 |
|
| 7 |
# Load environment variables
|
| 8 |
load_dotenv()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 13 |
+
st.title("💬 Chatbot")
|
| 14 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
if "messages" not in st.session_state:
|
| 16 |
+
st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you?"}]
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
for msg in st.session_state.messages:
|
| 19 |
+
st.chat_message(msg["role"]).write(msg["content"])
|
| 20 |
+
|
| 21 |
+
if prompt := st.chat_input():
|
| 22 |
+
if not openai_api_key:
|
| 23 |
+
st.info("Please add your OpenAI API key to continue.")
|
| 24 |
+
st.stop()
|
| 25 |
+
|
| 26 |
+
client = OpenAI(api_key=openai_api_key)
|
| 27 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 28 |
+
st.chat_message("user").write(prompt)
|
| 29 |
+
response = client.chat.completions.create(model="gpt-3.5-turbo", messages=st.session_state.messages)
|
| 30 |
+
msg = response.choices[0].message.content
|
| 31 |
+
st.session_state.messages.append({"role": "assistant", "content": msg})
|
| 32 |
+
st.chat_message("assistant").write(msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|