File size: 1,557 Bytes
7d7015d
 
 
 
b115b7b
7d7015d
 
 
6f7c8f8
7d7015d
 
b115b7b
 
 
7d7015d
 
 
 
d97aa7f
 
 
7d7015d
 
 
 
 
 
 
 
 
b115b7b
7d7015d
 
 
 
 
 
 
 
b115b7b
7d7015d
 
 
b115b7b
7d7015d
b115b7b
7d7015d
 
 
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
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)