File size: 2,119 Bytes
2d574a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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()