Drop files here
or click to upload
import streamlit as st
import requests
import json
# --- CONFIGURATION ---
# The backend URL for your AI agent
BACKEND_API_URL = "https://emea.snaplogic.com/api/1/rest/slsched/feed/ConnectFasterInc/snapLogic4snapLogic/Bootcamp_EMEA_August_2025/AgentDriver_Anjana_Task"
# The authorization token
AUTH_TOKEN = "Bearer 2345"
# Set up the Streamlit page configuration
st.set_page_config(page_title="AI Chatbot", page_icon="🤖")
# App title and a brief description
st.title("🤖 AI Agent Chatbot")
st.markdown("Feel free to ask me anything!")
# --- STATE MANAGEMENT ---
# Initialize chat history if it doesn't exist
if "messages" not in st.session_state:
st.session_state.messages = []
# --- DISPLAY CHAT MESSAGES ---
# Display all previous messages on app rerun
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# --- API CALL FUNCTION ---
def send_message_to_backend(prompt):
"""Sends a user message to the backend API and returns the response."""
# Define the request headers, including the Authorization token
headers = {
"Content-Type": "application/json",
"Authorization": AUTH_TOKEN
}
# Define the JSON payload. This example assumes the API expects a single key like "prompt".
# Adjust this payload format if your backend requires something different.
payload = json.dumps({
"prompt": prompt
})
try:
# Make the POST request to the backend API
response = requests.post(BACKEND_API_URL, headers=headers, data=payload)
# Raise an exception for HTTP errors (4xx or 5xx)
response.raise_for_status()
# Parse the JSON response and return it
return response.json()
except requests.exceptions.RequestException as e:
# Handle connection errors or other request issues
st.error(f"Error communicating with the backend: {e}")
return None
# --- USER INPUT AND CHAT LOGIC ---
# Get user input from the chat box
if prompt := st.chat_input("Enter your message here..."):
# 1. Add user message to chat history and display it
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
# 2. Call the backend API with the user's prompt
with st.spinner("Thinking..."):
api_response = send_message_to_backend(prompt)
# 3. Handle the API response
if api_response:
# NOTE: You need to inspect the exact format of the JSON response from your API.
# This example assumes the response is a dictionary with a "response" key.
# e.g., {"response": "Hello, how can I help?"}
# We'll use a more robust approach to handle potential variations in the API response structure.
# This code will try to find a response in a few common formats.
if isinstance(api_response, list) and len(api_response) > 0 and "Response" in api_response[0]:
assistant_response = api_response[0]["Response"]
elif isinstance(api_response, dict) and "response" in api_response:
assistant_response = api_response["response"]
else:
assistant_response = f"Sorry, I received an unexpected response format: {api_response}"
# Display the assistant's response
with st.chat_message("assistant"):
st.markdown(assistant_response)
# Add the assistant's response to the chat history
st.session_state.messages.append({"role": "assistant", "content": assistant_response})
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?