Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,11 +1,6 @@
|
|
1 |
# app.py
|
2 |
-
import os
|
3 |
-
import random
|
4 |
-
import requests
|
5 |
import streamlit as st
|
6 |
-
from
|
7 |
-
from PIL import Image
|
8 |
-
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, Tool
|
9 |
from huggingface_hub import login
|
10 |
import warnings
|
11 |
|
@@ -13,10 +8,9 @@ warnings.filterwarnings("ignore")
|
|
13 |
|
14 |
# Set page configuration
|
15 |
st.set_page_config(
|
16 |
-
page_title="
|
17 |
-
page_icon="
|
18 |
layout="wide",
|
19 |
-
initial_sidebar_state="expanded"
|
20 |
)
|
21 |
|
22 |
# Function to initialize the API with user-provided token
|
@@ -33,91 +27,22 @@ def initialize_api(token=None):
|
|
33 |
st.warning("Please enter your Hugging Face API token to use this app.")
|
34 |
return None
|
35 |
|
36 |
-
# Define all your tools
|
37 |
-
class RandomComicFetcher(Tool):
|
38 |
-
name = "fetch_random_comic_image"
|
39 |
-
description = "Fetches the image of a random XKCD comic"
|
40 |
-
inputs = {}
|
41 |
-
output_type = "string"
|
42 |
-
|
43 |
-
def __init__(self):
|
44 |
-
super().__init__()
|
45 |
-
self.xkcd_base_url = "https://xkcd.com/"
|
46 |
-
self.xkcd_latest_url = f"{self.xkcd_base_url}info.0.json"
|
47 |
-
|
48 |
-
def forward(self):
|
49 |
-
try:
|
50 |
-
# Fetch the latest comic info to get max comic number
|
51 |
-
latest_resp = requests.get(self.xkcd_latest_url)
|
52 |
-
latest_resp.raise_for_status()
|
53 |
-
latest_data = latest_resp.json()
|
54 |
-
max_comic_id = latest_data["num"]
|
55 |
-
|
56 |
-
# Pick a random comic ID between 1 and latest
|
57 |
-
selected_id = random.randint(1, max_comic_id)
|
58 |
-
comic_info_url = f"{self.xkcd_base_url}{selected_id}/info.0.json"
|
59 |
-
|
60 |
-
# Fetch comic metadata
|
61 |
-
comic_resp = requests.get(comic_info_url)
|
62 |
-
comic_resp.raise_for_status()
|
63 |
-
comic_data = comic_resp.json()
|
64 |
-
comic_img_url = comic_data["img"]
|
65 |
-
comic_title = comic_data["title"]
|
66 |
-
comic_alt = comic_data["alt"]
|
67 |
-
|
68 |
-
# Download and return the comic image
|
69 |
-
image_resp = requests.get(comic_img_url)
|
70 |
-
image_resp.raise_for_status()
|
71 |
-
img = Image.open(BytesIO(image_resp.content))
|
72 |
-
|
73 |
-
return img, comic_title, comic_alt, comic_img_url
|
74 |
-
except requests.exceptions.RequestException as err:
|
75 |
-
st.error(f"Could not fetch comic: {err}")
|
76 |
-
return None, "Error fetching comic", "Error details", ""
|
77 |
-
|
78 |
-
class PrimeCheckTool(Tool):
|
79 |
-
name = "prime_check"
|
80 |
-
description = "Checks if a given number is a prime number."
|
81 |
-
inputs = {
|
82 |
-
"number": {
|
83 |
-
"type": "integer",
|
84 |
-
"description": "The number to check for primality.",
|
85 |
-
}
|
86 |
-
}
|
87 |
-
output_type = "boolean"
|
88 |
-
|
89 |
-
def forward(self, number: int) -> bool:
|
90 |
-
if number < 2:
|
91 |
-
return False
|
92 |
-
for i in range(2, int(number**0.5) + 1):
|
93 |
-
if number % i == 0:
|
94 |
-
return False
|
95 |
-
return True
|
96 |
-
|
97 |
# Initialize tools
|
98 |
search_tool = DuckDuckGoSearchTool()
|
99 |
-
random_comic = RandomComicFetcher()
|
100 |
-
prime_check_tool = PrimeCheckTool()
|
101 |
|
102 |
# Streamlit App
|
103 |
-
st.title("
|
104 |
-
st.markdown("
|
105 |
|
106 |
# Initialize session state for token
|
107 |
if "hf_token" not in st.session_state:
|
108 |
st.session_state.hf_token = ""
|
109 |
st.session_state.model = None
|
110 |
|
111 |
-
# Sidebar for
|
112 |
with st.sidebar:
|
113 |
st.title("Configuration")
|
114 |
|
115 |
-
# Check for token in environment first
|
116 |
-
env_token = os.environ.get("HF_TOKEN")
|
117 |
-
if env_token and not st.session_state.hf_token:
|
118 |
-
st.session_state.hf_token = env_token
|
119 |
-
st.success("HF_TOKEN found in environment variables")
|
120 |
-
|
121 |
# Token input
|
122 |
token_input = st.text_input(
|
123 |
"Enter your Hugging Face API Token:",
|
@@ -140,23 +65,6 @@ with st.sidebar:
|
|
140 |
st.success("✅ API initialized successfully!")
|
141 |
else:
|
142 |
st.error("❌ Failed to initialize the API with the provided token.")
|
143 |
-
|
144 |
-
st.divider()
|
145 |
-
|
146 |
-
st.title("Tool Selection")
|
147 |
-
tool_choice = st.radio(
|
148 |
-
"Choose a tool:",
|
149 |
-
["Search Tool", "XKCD Comic Fetcher", "Prime Number Checker"]
|
150 |
-
)
|
151 |
-
|
152 |
-
st.divider()
|
153 |
-
st.markdown("### About")
|
154 |
-
st.markdown("""
|
155 |
-
This app demonstrates the capabilities of SmolaAgents, allowing you to:
|
156 |
-
- Search the web with an AI assistant
|
157 |
-
- Fetch random XKCD comics with AI commentary
|
158 |
-
- Check if numbers are prime with creative explanations
|
159 |
-
""")
|
160 |
|
161 |
# Check if the model is initialized
|
162 |
if not st.session_state.model and st.session_state.hf_token:
|
@@ -167,105 +75,24 @@ if not st.session_state.model and st.session_state.hf_token:
|
|
167 |
|
168 |
# Main content area - only show if token is provided
|
169 |
if st.session_state.hf_token and st.session_state.model:
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
with st.spinner("Searching and processing..."):
|
180 |
-
agent = CodeAgent(tools=[search_tool], model=st.session_state.model)
|
181 |
-
response = agent.run(query)
|
182 |
-
st.success("Search complete!")
|
183 |
-
st.markdown("### Results")
|
184 |
-
st.markdown(response)
|
185 |
-
else:
|
186 |
-
st.warning("Please enter a search query")
|
187 |
-
|
188 |
-
elif tool_choice == "XKCD Comic Fetcher":
|
189 |
-
st.header("XKCD Comic Explorer")
|
190 |
-
st.markdown("Fetch a random XKCD comic and get AI commentary")
|
191 |
-
|
192 |
-
if "comic_fetched" not in st.session_state:
|
193 |
-
st.session_state.comic_fetched = False
|
194 |
-
st.session_state.comic_img = None
|
195 |
-
st.session_state.comic_title = ""
|
196 |
-
st.session_state.comic_alt = ""
|
197 |
-
st.session_state.comic_url = ""
|
198 |
-
|
199 |
-
col1, col2 = st.columns([1, 2])
|
200 |
-
|
201 |
-
with col1:
|
202 |
-
if st.button("Fetch Random Comic"):
|
203 |
-
with st.spinner("Fetching a random comic..."):
|
204 |
-
img, title, alt, url = random_comic.forward()
|
205 |
-
if img:
|
206 |
-
st.session_state.comic_fetched = True
|
207 |
-
st.session_state.comic_img = img
|
208 |
-
st.session_state.comic_title = title
|
209 |
-
st.session_state.comic_alt = alt
|
210 |
-
st.session_state.comic_url = url
|
211 |
-
st.experimental_rerun()
|
212 |
-
|
213 |
-
if st.session_state.comic_fetched:
|
214 |
-
with col1:
|
215 |
-
st.image(st.session_state.comic_img, caption=st.session_state.comic_title)
|
216 |
-
st.caption(f"Alt text: {st.session_state.comic_alt}")
|
217 |
-
st.markdown(f"[View on XKCD]({st.session_state.comic_url})")
|
218 |
-
|
219 |
-
with col2:
|
220 |
-
st.subheader("Ask AI about this comic")
|
221 |
-
query = st.text_input("What would you like to know about this comic?",
|
222 |
-
placeholder="Explain this comic in a funny way")
|
223 |
-
|
224 |
-
if st.button("Ask AI"):
|
225 |
-
with st.spinner("Generating response..."):
|
226 |
-
agent = CodeAgent(tools=[random_comic], model=st.session_state.model)
|
227 |
-
response = agent.run(query if query else "Tell me about this XKCD comic.")
|
228 |
-
st.markdown("### AI Response")
|
229 |
-
st.markdown(response)
|
230 |
-
|
231 |
-
elif tool_choice == "Prime Number Checker":
|
232 |
-
st.header("Prime Number Checker")
|
233 |
-
st.markdown("Check if a number is prime and get a creative explanation")
|
234 |
-
|
235 |
-
number = st.number_input("Enter a number to check:", min_value=1, step=1, value=23)
|
236 |
-
explanation_style = st.selectbox(
|
237 |
-
"Choose explanation style:",
|
238 |
-
["Poetic", "Nursery Rhyme", "Scientific", "Humorous", "Historical"]
|
239 |
-
)
|
240 |
-
|
241 |
-
if st.button("Check Prime"):
|
242 |
-
with st.spinner("Checking and generating response..."):
|
243 |
-
is_prime = prime_check_tool.forward(int(number))
|
244 |
-
|
245 |
-
# Format query based on selected style
|
246 |
-
query = f"Check if the number {number} is a prime number and explain it in a {explanation_style.lower()} style."
|
247 |
-
|
248 |
-
agent = CodeAgent(tools=[prime_check_tool], model=st.session_state.model)
|
249 |
response = agent.run(query)
|
250 |
-
|
251 |
-
|
252 |
-
prime_status = "✅ PRIME" if is_prime else "❌ NOT PRIME"
|
253 |
-
st.markdown(f"### Result: {prime_status}")
|
254 |
-
|
255 |
-
st.markdown("### AI Explanation")
|
256 |
st.markdown(response)
|
257 |
-
|
258 |
-
|
259 |
-
if st.checkbox("Show mathematical details"):
|
260 |
-
if is_prime:
|
261 |
-
st.markdown(f"{number} has no factors other than 1 and itself.")
|
262 |
-
else:
|
263 |
-
# Find the factors
|
264 |
-
factors = [i for i in range(1, number + 1) if number % i == 0]
|
265 |
-
st.markdown(f"Factors of {number}: {', '.join(map(str, factors))}")
|
266 |
else:
|
267 |
# Token not provided
|
268 |
-
st.info("
|
269 |
|
270 |
# Show more information to help users understand what they need
|
271 |
st.markdown("""
|
@@ -275,15 +102,4 @@ else:
|
|
275 |
2. Visit your [settings page](https://huggingface.co/settings/tokens)
|
276 |
3. Create a new token with read access
|
277 |
4. Copy the token and paste it in the sidebar
|
278 |
-
|
279 |
-
Your token will be used to access the language models needed for this application.
|
280 |
-
|
281 |
-
### Why is a token required?
|
282 |
-
|
283 |
-
This app uses Hugging Face's API to access powerful language models like Llama 3. Your API token
|
284 |
-
grants access to these models, which do the heavy lifting of understanding and responding to your queries.
|
285 |
-
""")
|
286 |
-
|
287 |
-
# Add footer
|
288 |
-
st.sidebar.divider()
|
289 |
-
st.sidebar.markdown("Made with ❤️ using SmolaAgents")
|
|
|
1 |
# app.py
|
|
|
|
|
|
|
2 |
import streamlit as st
|
3 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
|
|
|
|
|
4 |
from huggingface_hub import login
|
5 |
import warnings
|
6 |
|
|
|
8 |
|
9 |
# Set page configuration
|
10 |
st.set_page_config(
|
11 |
+
page_title="DuckDuckGo Search Tool",
|
12 |
+
page_icon="🔍",
|
13 |
layout="wide",
|
|
|
14 |
)
|
15 |
|
16 |
# Function to initialize the API with user-provided token
|
|
|
27 |
st.warning("Please enter your Hugging Face API token to use this app.")
|
28 |
return None
|
29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
# Initialize tools
|
31 |
search_tool = DuckDuckGoSearchTool()
|
|
|
|
|
32 |
|
33 |
# Streamlit App
|
34 |
+
st.title("DuckDuckGo Search Tool")
|
35 |
+
st.markdown("Search the web using DuckDuckGo and get AI-powered responses")
|
36 |
|
37 |
# Initialize session state for token
|
38 |
if "hf_token" not in st.session_state:
|
39 |
st.session_state.hf_token = ""
|
40 |
st.session_state.model = None
|
41 |
|
42 |
+
# Sidebar for token input
|
43 |
with st.sidebar:
|
44 |
st.title("Configuration")
|
45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
# Token input
|
47 |
token_input = st.text_input(
|
48 |
"Enter your Hugging Face API Token:",
|
|
|
65 |
st.success("✅ API initialized successfully!")
|
66 |
else:
|
67 |
st.error("❌ Failed to initialize the API with the provided token.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
# Check if the model is initialized
|
70 |
if not st.session_state.model and st.session_state.hf_token:
|
|
|
75 |
|
76 |
# Main content area - only show if token is provided
|
77 |
if st.session_state.hf_token and st.session_state.model:
|
78 |
+
st.header("AI Web Search")
|
79 |
+
st.markdown("Ask any question and the AI will search the web for answers")
|
80 |
+
|
81 |
+
query = st.text_input("Enter your search query:", placeholder="What are the latest advancements in renewable energy?")
|
82 |
+
|
83 |
+
if st.button("Search"):
|
84 |
+
if query:
|
85 |
+
with st.spinner("Searching and processing..."):
|
86 |
+
agent = CodeAgent(tools=[search_tool], model=st.session_state.model)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
response = agent.run(query)
|
88 |
+
st.success("Search complete!")
|
89 |
+
st.markdown("### Results")
|
|
|
|
|
|
|
|
|
90 |
st.markdown(response)
|
91 |
+
else:
|
92 |
+
st.warning("Please enter a search query")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
else:
|
94 |
# Token not provided
|
95 |
+
st.info("Please enter your Hugging Face API token in the sidebar to get started.")
|
96 |
|
97 |
# Show more information to help users understand what they need
|
98 |
st.markdown("""
|
|
|
102 |
2. Visit your [settings page](https://huggingface.co/settings/tokens)
|
103 |
3. Create a new token with read access
|
104 |
4. Copy the token and paste it in the sidebar
|
105 |
+
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|