taha-the-data-scientist's picture
Update app.py
9ab2545 verified
raw
history blame
2.68 kB
import streamlit as st
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
from huggingface_hub import login
import warnings
warnings.filterwarnings("ignore")
# Set page configuration
st.set_page_config(
page_title="DuckDuckGo Search Tool",
page_icon="πŸ”",
layout="wide",
)
# Function to initialize the API with user-provided token
def initialize_api(token=None):
if token:
login(token)
try:
return HfApiModel(model_id="meta-llama/Llama-3.3-70B-Instruct")
except Exception as e:
st.error(f"Error initializing model: {str(e)}")
return None
return None
# Initialize tools
search_tool = DuckDuckGoSearchTool()
def main():
st.title("DuckDuckGo Search Tool")
st.markdown("Search the web using DuckDuckGo and get AI-powered responses")
# Initialize session state
if "hf_token" not in st.session_state:
st.session_state.update({
"hf_token": "",
"model": None
})
# Sidebar configuration
with st.sidebar:
st.title("Configuration")
token_input = st.text_input(
"Hugging Face API Token:",
value=st.session_state.hf_token,
type="password",
help="Get token from huggingface.co/settings/tokens"
)
if token_input != st.session_state.hf_token:
st.session_state.hf_token = token_input
st.session_state.model = None
if st.button("Initialize API"):
with st.spinner("Testing token..."):
model = initialize_api(st.session_state.hf_token)
if model:
st.session_state.model = model
st.success("βœ… API initialized!")
else:
st.error("❌ Initialization failed")
# Main app logic
if st.session_state.model:
st.header("AI Web Search")
query = st.text_input("Search query:", placeholder="Latest renewable energy advancements?")
if st.button("Search") and query:
with st.spinner("Searching..."):
agent = CodeAgent(tools=[search_tool], model=st.session_state.model)
response = agent.run(query)
st.success("Search complete!")
st.markdown("### Results")
st.markdown(response)
else:
st.info("Please enter your Hugging Face API token in the sidebar")
# ... rest of your info message ...
# Hugging Face Spaces requires this specific structure
if __name__ == "__main__":
main()
# Keep the server running
while True:
pass