To upload files, please first save the app
import requests
import streamlit as st
import time
# Define the API URL
URL = "https://your-api-endpoint.com/api" # Replace with your actual API endpoint
# Set the page configuration
st.set_page_config(
page_title="Simple Chat Bot",
layout="centered",
)
# Initialize session state variables
if "messages" not in st.session_state:
st.session_state["messages"] = [{"role": "assistant", "content": "Hello!"}]
st.session_state["ticket"] = False
# Display chat messages from history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Function to fetch topics from the API
def fetch_topics():
headers = {
"admin": "demo",
"channel": "WEB",
}
try:
response = requests.get(URL, headers=headers)
if response.status_code == 200:
topics_data = response.json()
topic_names = [topic["topic_name"] for topic in topics_data]
return topic_names
else:
st.error("Error al obtener los tópicos")
return []
except requests.exceptions.RequestException as e:
st.error(f"Solicitud fallida: {e}")
return []
# Function to display the ticket creation form
def popover():
with st.form("tickets", clear_on_submit=False):
st.markdown("**Nuevo ticket**")
name = st.text_input("Nombre")
email = st.text_input("Correo")
descripcion = st.text_area("Descripción")
submitted = st.form_submit_button("Enviar")
if submitted:
body = {
"name": name,
"email": email,
"description": descripcion,
}
try:
response_pop = requests.post(URL, json=body)
if response_pop.status_code == 200:
with st.spinner("Creando ticket..."):
time.sleep(2) # Simulate processing time
st.success("¡Ticket creado exitosamente!")
else:
st.error(f"Error al crear el ticket: {response_pop.status_code}")
except requests.exceptions.RequestException as e:
st.error(f"Solicitud fallida: {e}")
finally:
st.session_state["ticket"] = False # Reset the ticket flag
# Function to send user message and receive assistant response
def send_message(message, topic, language):
payload = {
"message": message,
"language": language,
"topic": "demo#" + topic,
"summary": "false",
"chat_history": [],
}
try:
response = requests.post(URL, json=payload)
if response.status_code == 200:
data_json = response.json()
message_text = data_json.get("message", "No response from assistant.")
nuevo_ticket = data_json.get("create_ticket", False)
with st.chat_message("assistant"):
st.markdown(message_text)
st.session_state.messages.append({"role": "assistant", "content": message_text})
if nuevo_ticket:
st.session_state["ticket"] = True
else:
st.error(f"Error al enviar el mensaje: {response.status_code}")
except requests.exceptions.RequestException as e:
st.error(f"Solicitud fallida: {e}")
# Sidebar configuration
sidebar = st.sidebar
# Fetch topics before displaying the selection box
topics_name = fetch_topics()
# Topic selection with user-friendly labels
if topics_name:
topic = sidebar.selectbox("Seleccione un tópico", topics_name)
else:
topic = sidebar.text_input("Tópico", "Default Topic")
# Language selection
language = sidebar.selectbox("Seleccione un idioma", ["Spanish", "English"])
# Accept user input
prompt = st.chat_input("Escribe una pregunta")
if prompt:
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
send_message(prompt, topic, language)
# Display the ticket creation form if required
if st.session_state.get("ticket", False):
popover()
# Reset button for chat history
reset_button = st.sidebar.button("Reiniciar Conversación")
if reset_button:
# Clear chat history and reset ticket flag
st.session_state.messages = [{"role": "assistant", "content": "Hello!"}]
st.session_state["ticket"] = False
st.experimental_rerun()
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?