Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import requests | |
| import os | |
| # Load API key | |
| HF_API_KEY = os.getenv("HF_API_KEY") | |
| # Hugging Face API URL | |
| API_URL = "https://api-inference.huggingface.co/models/facebook/blenderbot-3B" | |
| HEADERS = {"Authorization": f"Bearer {HF_API_KEY}"} | |
| # App | |
| st.title("Chatbot") | |
| st.write("Using Facebook Blenderbot") | |
| # Initialize chat history | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [] | |
| # Add initial bot welcome message | |
| initial_message = "Hello! I'm a chatbot. You can upload an image or ask me anything to get started!" | |
| st.session_state.messages.append({"role": "assistant", "content": initial_message}) | |
| # Display chat history | |
| for msg in st.session_state.messages: | |
| with st.chat_message(msg["role"]): | |
| st.write(msg["content"]) | |
| # User input | |
| user_input = st.chat_input("Ask me anything...") | |
| if user_input: | |
| # Append user message to history | |
| st.session_state.messages.append({"role": "user", "content": user_input}) | |
| with st.chat_message("user"): | |
| st.write(user_input) | |
| # Send request to Hugging Face API | |
| payload = {"inputs": user_input} | |
| response = requests.post(API_URL, headers=HEADERS, json=payload) | |
| # Extract response text, print error text. | |
| if response.status_code == 200: | |
| bot_reply = response.json()[0]["generated_text"] | |
| else: | |
| bot_reply = "Error." | |
| # Append bot response to history | |
| st.session_state.messages.append({"role": "assistant", "content": bot_reply}) | |
| with st.chat_message("assistant"): | |
| st.write(bot_reply) | |