Spaces:
Sleeping
Sleeping
import streamlit as st | |
import json | |
import requests | |
def main(): | |
st.title("🤖 Simple Chatbot Interface") | |
# Input for API URL | |
api_url = st.text_input("Enter API URL", placeholder="https://example.com/query") | |
# Display the chatbot interface only if an API URL is provided | |
if api_url: | |
st.write("Chatbot is ready to use!") | |
if "chat_history" not in st.session_state: | |
st.session_state["chat_history"] = [] | |
user_input = st.chat_input(placeholder="Type your query here...") | |
if user_input: | |
# Append user query to the chat history | |
st.session_state["chat_history"].append({"role": "user", "content": user_input}) | |
# Prepare the query for the API | |
input_data_for_model = {"query": user_input} | |
with st.spinner("Generating response..."): | |
try: | |
# Send the user query to the API | |
response = requests.post( | |
api_url, | |
data=json.dumps(input_data_for_model), | |
headers={"Content-Type": "application/json"} | |
) | |
if response.status_code == 200: | |
response_data = response.json() # Parse API response | |
bot_reply = response_data.get("answer", "I'm sorry, I didn't understand that.") | |
else: | |
bot_reply = f"Error: Received status code {response.status_code}" | |
except Exception as e: | |
bot_reply = f"Error: {str(e)}" | |
# Append the assistant's reply to the chat history | |
st.session_state["chat_history"].append({"role": "assistant", "content": bot_reply}) | |
# Display the conversation history | |
for chat in st.session_state["chat_history"]: | |
if chat["role"] == "user": | |
st.chat_message("user").write(chat["content"]) | |
elif chat["role"] == "assistant": | |
st.chat_message("assistant").write(chat["content"]) | |
if __name__ == "__main__": | |
main() | |