Spaces:
Sleeping
Sleeping
🚑🔧 Add error handling to validate image URLs and flag non-working links
Browse files
app.py
CHANGED
|
@@ -20,7 +20,7 @@ def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return
|
|
| 20 |
|
| 21 |
@tool
|
| 22 |
def get_cat_images(limit: int = 1) -> list:
|
| 23 |
-
"""A tool that gets random cat images
|
| 24 |
Args:
|
| 25 |
limit: Number of images to return between 1 and 100
|
| 26 |
"""
|
|
@@ -33,18 +33,26 @@ def get_cat_images(limit: int = 1) -> list:
|
|
| 33 |
|
| 34 |
# Send the GET request to the API
|
| 35 |
response = requests.get(url)
|
| 36 |
-
print(limit)
|
| 37 |
-
print(response)
|
| 38 |
|
| 39 |
# Check if the request was successful
|
| 40 |
if response.status_code == 200:
|
| 41 |
# Extract the URLs of the images from the response JSON
|
| 42 |
data = response.json() # Parse the response as JSON
|
| 43 |
-
image_urls = [
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
return image_urls
|
| 49 |
else:
|
| 50 |
return f"Failed to fetch data. Status code: {response.status_code}"
|
|
|
|
| 20 |
|
| 21 |
@tool
|
| 22 |
def get_cat_images(limit: int = 1) -> list:
|
| 23 |
+
"""A tool that gets random cat images using TheCatAPI (https://developers.thecatapi.com/)
|
| 24 |
Args:
|
| 25 |
limit: Number of images to return between 1 and 100
|
| 26 |
"""
|
|
|
|
| 33 |
|
| 34 |
# Send the GET request to the API
|
| 35 |
response = requests.get(url)
|
|
|
|
|
|
|
| 36 |
|
| 37 |
# Check if the request was successful
|
| 38 |
if response.status_code == 200:
|
| 39 |
# Extract the URLs of the images from the response JSON
|
| 40 |
data = response.json() # Parse the response as JSON
|
| 41 |
+
image_urls = []
|
| 42 |
+
|
| 43 |
+
for item in data:
|
| 44 |
+
image_url = item['url']
|
| 45 |
+
# Verify if the image URL is accessible
|
| 46 |
+
try:
|
| 47 |
+
# Make a HEAD request to only check if the resource exists
|
| 48 |
+
img_response = requests.head(image_url)
|
| 49 |
+
if img_response.status_code == 200:
|
| 50 |
+
image_urls.append(image_url)
|
| 51 |
+
else:
|
| 52 |
+
image_urls.append(f"Non-working link: {image_url}")
|
| 53 |
+
except requests.exceptions.RequestException:
|
| 54 |
+
image_urls.append(f"Non-working link: {image_url}")
|
| 55 |
+
|
| 56 |
return image_urls
|
| 57 |
else:
|
| 58 |
return f"Failed to fetch data. Status code: {response.status_code}"
|