Spaces:
Runtime error
Runtime error
Update src/st-chat-app.py
Browse files- src/st-chat-app.py +132 -96
src/st-chat-app.py
CHANGED
|
@@ -5,113 +5,149 @@ import os
|
|
| 5 |
from dotenv import load_dotenv
|
| 6 |
load_dotenv()
|
| 7 |
|
| 8 |
-
|
| 9 |
-
client_secret = os.getenv("CLIENT_SECRET")
|
| 10 |
-
base_url = os.getenv("BASE_URL")
|
| 11 |
-
|
| 12 |
-
def get_access_token():
|
| 13 |
-
url = base_url+"/services/oauth2/token"
|
| 14 |
-
payload = {
|
| 15 |
-
"grant_type": "client_credentials",
|
| 16 |
-
"client_id": client_id,
|
| 17 |
-
"client_secret": client_secret
|
| 18 |
-
}
|
| 19 |
-
response = requests.post(url, data=payload)
|
| 20 |
-
# Add error handling for response
|
| 21 |
-
if response.status_code != 200:
|
| 22 |
-
st.error(f"Error fetching access token: {response.status_code} - {response.text}")
|
| 23 |
-
return None
|
| 24 |
-
data = response.json()
|
| 25 |
-
access_token = data.get('access_token', 'Token not found')
|
| 26 |
-
return access_token
|
| 27 |
-
|
| 28 |
-
# Add model selection dictionary
|
| 29 |
-
MODEL_OPTIONS = {
|
| 30 |
-
"GPT4Omni": "sfdc_ai__DefaultOpenAIGPT4Omni",
|
| 31 |
-
"Gemini": "sfdc_ai__DefaultVertexAIGemini20Flash001",
|
| 32 |
-
"Claude": "sfdc_ai__DefaultBedrockAnthropicClaude37Sonnet"
|
| 33 |
-
}
|
| 34 |
-
|
| 35 |
-
# Configure Streamlit page settings
|
| 36 |
st.set_page_config(
|
| 37 |
page_title="Chat with Einstein LLMs!",
|
| 38 |
-
page_icon=":brain:",
|
| 39 |
-
layout="wide",
|
| 40 |
)
|
| 41 |
|
| 42 |
-
#
|
| 43 |
-
|
| 44 |
-
st.
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
)
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
#
|
| 53 |
-
st.
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
"
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
}
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
st.error(f"Error parsing response: {str(e)}")
|
| 79 |
-
return "I apologize, but I received an invalid response. Please try again."
|
| 80 |
|
| 81 |
-
#
|
| 82 |
-
|
| 83 |
-
st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you?"}]
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
"
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
# Get AI response if there's any input
|
| 114 |
-
if prompt.text or prompt.get("files"):
|
| 115 |
-
msg = get_gpt_response(st.session_state.messages)
|
| 116 |
-
st.session_state.messages.append({"role": "assistant", "content": msg})
|
| 117 |
-
st.chat_message("assistant", avatar="π€").write(msg)
|
|
|
|
| 5 |
from dotenv import load_dotenv
|
| 6 |
load_dotenv()
|
| 7 |
|
| 8 |
+
# Page config should be the first Streamlit command
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
st.set_page_config(
|
| 10 |
page_title="Chat with Einstein LLMs!",
|
| 11 |
+
page_icon=":brain:",
|
| 12 |
+
layout="wide",
|
| 13 |
)
|
| 14 |
|
| 15 |
+
# Initialize session state for authentication
|
| 16 |
+
if "authenticated" not in st.session_state:
|
| 17 |
+
st.session_state.authenticated = False
|
| 18 |
+
|
| 19 |
+
def check_password():
|
| 20 |
+
"""Returns `True` if the user had the correct password."""
|
| 21 |
+
password_input = os.getenv("PASSWORD")
|
| 22 |
+
def password_entered():
|
| 23 |
+
"""Checks whether a password entered by the user is correct."""
|
| 24 |
+
if st.session_state["password"] == password_input:
|
| 25 |
+
st.session_state.authenticated = True
|
| 26 |
+
del st.session_state["password"] # Remove password from session state for security
|
| 27 |
+
else:
|
| 28 |
+
st.session_state.authenticated = False
|
| 29 |
+
st.error("π Password incorrect")
|
| 30 |
+
|
| 31 |
+
# Show input for password
|
| 32 |
+
st.text_input(
|
| 33 |
+
"Please enter the password to access the Einstein Assistant",
|
| 34 |
+
type="password",
|
| 35 |
+
on_change=password_entered,
|
| 36 |
+
key="password"
|
| 37 |
)
|
| 38 |
+
|
| 39 |
+
# if not st.session_state.authenticated:
|
| 40 |
+
# st.error("π Password incorrect")
|
| 41 |
+
# return False
|
| 42 |
+
# return True
|
| 43 |
|
| 44 |
+
# Show chat interface only if authenticated
|
| 45 |
+
if st.session_state.authenticated:
|
| 46 |
+
client_id = os.getenv("CLIENT_ID")
|
| 47 |
+
client_secret = os.getenv("CLIENT_SECRET")
|
| 48 |
+
base_url = os.getenv("BASE_URL")
|
| 49 |
|
| 50 |
+
def get_access_token():
|
| 51 |
+
url = base_url+"/services/oauth2/token"
|
| 52 |
+
payload = {
|
| 53 |
+
"grant_type": "client_credentials",
|
| 54 |
+
"client_id": client_id,
|
| 55 |
+
"client_secret": client_secret
|
| 56 |
+
}
|
| 57 |
+
response = requests.post(url, data=payload)
|
| 58 |
+
# Add error handling for response
|
| 59 |
+
if response.status_code != 200:
|
| 60 |
+
st.error(f"Error fetching access token: {response.status_code} - {response.text}")
|
| 61 |
+
return None
|
| 62 |
+
data = response.json()
|
| 63 |
+
access_token = data.get('access_token', 'Token not found')
|
| 64 |
+
return access_token
|
| 65 |
+
|
| 66 |
+
# Add model selection dictionary
|
| 67 |
+
MODEL_OPTIONS = {
|
| 68 |
+
"GPT4-Omni": "sfdc_ai__DefaultOpenAIGPT4Omni",
|
| 69 |
+
"Gemini": "sfdc_ai__DefaultVertexAIGemini20Flash001",
|
| 70 |
+
"Claude": "sfdc_ai__DefaultBedrockAnthropicClaude37Sonnet"
|
| 71 |
}
|
| 72 |
|
| 73 |
+
# Add sidebar with model selection
|
| 74 |
+
with st.sidebar:
|
| 75 |
+
st.title("Model Settings")
|
| 76 |
+
selected_model_name = st.selectbox(
|
| 77 |
+
"Choose AI Model",
|
| 78 |
+
options=list(MODEL_OPTIONS.keys()),
|
| 79 |
+
index=0
|
| 80 |
+
)
|
| 81 |
+
model = MODEL_OPTIONS[selected_model_name]
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
# Update the page title to reflect selected model
|
| 84 |
+
st.subheader(f"π€ Chat with {selected_model_name}")
|
|
|
|
| 85 |
|
| 86 |
+
# Modify get_gpt_response function to use selected model
|
| 87 |
+
def get_gpt_response(prompt):
|
| 88 |
+
url = f"https://api.salesforce.com/einstein/platform/v1/models/{model}/chat-generations"
|
| 89 |
+
access_token = get_access_token()
|
| 90 |
+
headers = {
|
| 91 |
+
"Authorization": f"Bearer {access_token}",
|
| 92 |
+
"Content-Type": "application/json;charset=utf-8",
|
| 93 |
+
'x-sfdc-app-context': 'EinsteinGPT',
|
| 94 |
+
'x-client-feature-id': 'ai-platform-models-connected-app'
|
| 95 |
+
}
|
| 96 |
+
chat_payload = {
|
| 97 |
+
"messages": prompt
|
| 98 |
+
}
|
| 99 |
|
| 100 |
+
try:
|
| 101 |
+
response = requests.post(url, headers=headers, data=json.dumps(chat_payload))
|
| 102 |
+
response.raise_for_status() # Raise exception for bad status codes
|
| 103 |
+
data = response.json()
|
| 104 |
+
return data["generationDetails"]["generations"][0]["content"]
|
| 105 |
+
except requests.exceptions.RequestException as e:
|
| 106 |
+
st.error(f"Error calling the API: {str(e)}")
|
| 107 |
+
return "I apologize, but I encountered an error. Please try again."
|
| 108 |
+
except (KeyError, IndexError) as e:
|
| 109 |
+
st.error(f"Error parsing response: {str(e)}")
|
| 110 |
+
return "I apologize, but I received an invalid response. Please try again."
|
| 111 |
+
|
| 112 |
+
# Display the chatbot's title on the page
|
| 113 |
+
if "messages" not in st.session_state:
|
| 114 |
+
st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you?"}]
|
| 115 |
|
| 116 |
+
for msg in st.session_state.messages:
|
| 117 |
+
st.chat_message(msg["role"], avatar="π€").write(msg["content"])
|
| 118 |
+
if "image" in msg:
|
| 119 |
+
st.image(msg["image"])
|
| 120 |
+
|
| 121 |
+
prompt = st.chat_input(
|
| 122 |
+
"Say something and/or attach an image",
|
| 123 |
+
accept_file=True,
|
| 124 |
+
file_type=["jpg", "jpeg", "png"],
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
if prompt:
|
| 128 |
+
# Handle text input
|
| 129 |
+
if prompt.text:
|
| 130 |
+
st.session_state.messages.append({"role": "user", "content": prompt.text})
|
| 131 |
+
st.chat_message("user").write(prompt.text)
|
| 132 |
+
|
| 133 |
+
# Handle image upload
|
| 134 |
+
if prompt.get("files"):
|
| 135 |
+
uploaded_file = prompt["files"][0]
|
| 136 |
+
st.session_state.messages.append({
|
| 137 |
+
"role": "user",
|
| 138 |
+
"content": "Uploaded an image",
|
| 139 |
+
"image": uploaded_file
|
| 140 |
+
})
|
| 141 |
+
st.chat_message("user").write("Uploaded an image")
|
| 142 |
+
st.image(uploaded_file)
|
| 143 |
|
| 144 |
+
# Get AI response if there's any input
|
| 145 |
+
if prompt.text or prompt.get("files"):
|
| 146 |
+
msg = get_gpt_response(st.session_state.messages)
|
| 147 |
+
st.session_state.messages.append({"role": "assistant", "content": msg})
|
| 148 |
+
st.chat_message("assistant", avatar="π€").write(msg)
|
| 149 |
+
else:
|
| 150 |
+
# Show login page
|
| 151 |
+
st.title("Welcome to Einstein Assistant")
|
| 152 |
+
#st.markdown("Please log in to continue")
|
| 153 |
+
check_password()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|