To upload files, please first save the app
import streamlit as st
import requests
import json
import os
from datetime import datetime
# API configuration
API_ENDPOINT = os.environ.get("API_ENDPOINT", "https://emea.snaplogic.com/api/1/rest/slsched/feed/ConnectFasterInc/snapLogic4snapLogic/PartnerTrainingSandbox24022025/ja_salesforce_chatbot")
API_KEY = os.environ.get("API_KEY", "yac4pkteKy94PSKhH9b8b1vy2UZ4A9eP")
# Set page configuration
st.set_page_config(
page_title="AI Chat Assistant",
page_icon=":speech_balloon:",
layout="wide"
)
# Initialize session state variables if they don't exist
if "messages" not in st.session_state:
st.session_state.messages = []
# Application title and description
st.title("AI Chat Assistant")
st.markdown("Enter your question and get responses from the AI assistant.")
# Sidebar for optional settings
with st.sidebar:
st.header("Chat Settings")
# Optional advanced settings
temperature = st.slider("Temperature", min_value=0.0, max_value=1.0, value=0.7, step=0.1,
help="Controls randomness. Lower values make responses more deterministic.")
max_tokens = st.number_input("Max Tokens", min_value=50, max_value=4000, value=1000, step=50,
help="Maximum length of response.")
# Add SSL verification toggle option for users experiencing connection issues
ssl_verify = st.checkbox("Enable SSL Verification", value=True,
help="Disable this if you're experiencing connection issues")
# Display chat history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input
if prompt := st.chat_input("Type your message here..."):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message
with st.chat_message("user"):
st.markdown(prompt)
# Display assistant response with a spinner while waiting
with st.chat_message("assistant"):
message_placeholder = st.empty()
message_placeholder.markdown("Thinking...")
try:
# Prepare the request payload
payload = {
"prompt": prompt,
"temperature": temperature,
"max_tokens": max_tokens,
"timestamp": datetime.now().isoformat()
}
# Prepare headers with Bearer token (from environment variable)
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
# Make the API request with configurable SSL verification
response = requests.post(
API_ENDPOINT,
headers=headers,
data=json.dumps(payload),
verify=ssl_verify # Use the user's SSL verification preference
)
# Handle the API response
if response.status_code == 200:
try:
# Parse the JSON response
response_data = response.json()
# Handle the array format where response is the first object's "response" field
if isinstance(response_data, list) and len(response_data) > 0 and "response" in response_data[0]:
assistant_response = response_data[0]["response"]
# Fallback to the previous format if needed
elif isinstance(response_data, dict) and "response" in response_data:
assistant_response = response_data["response"]
else:
assistant_response = "No valid response found in API result"
# Update placeholder with actual response
message_placeholder.markdown(assistant_response)
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": assistant_response})
except json.JSONDecodeError:
message_placeholder.error("Error: Could not parse API response")
else:
message_placeholder.error(f"Error: API returned status code {response.status_code}")
except requests.exceptions.SSLError:
message_placeholder.error("SSL Certificate Verification Error. Try disabling SSL verification in the sidebar settings.")
except Exception as e:
message_placeholder.error(f"Error: {str(e)}")
# Add some helpful information at the bottom
st.markdown("---")
st.caption("AI Chat Assistant powered by a secure backend API. If you experience connection issues, try disabling SSL verification in the sidebar.")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?