Spaces:
Sleeping
Sleeping
from typing import List, Dict | |
import requests | |
from smolagents import Tool | |
class BookSearchTool(Tool): | |
name = "search_books" | |
description = "Search for books using the Open Library API" | |
input_types = {"query": str} | |
output_type = List[Dict] | |
def __call__(self, query: str) -> List[Dict]: | |
try: | |
url = f"https://openlibrary.org/search.json?q={query}&limit=5" | |
response = requests.get(url) | |
response.raise_for_status() | |
data = response.json() | |
results = [] | |
for book in data.get('docs', [])[:5]: | |
result = { | |
'title': book.get('title', 'Unknown Title'), | |
'author': book.get('author_name', ['Unknown Author'])[0] if book.get('author_name') else 'Unknown Author', | |
'first_publish_year': book.get('first_publish_year', 'Unknown Year'), | |
'subject': book.get('subject', [])[:3] if book.get('subject') else [], | |
'key': book.get('key', '') | |
} | |
results.append(result) | |
return results | |
except Exception as e: | |
return [{"error": f"Error searching books: {str(e)}"}] | |
class BookDetailsTool(Tool): | |
name = "get_book_details" | |
description = "Get detailed information about a specific book from Open Library" | |
input_types = {"book_key": str} | |
output_type = Dict | |
def __call__(self, book_key: str) -> Dict: | |
try: | |
url = f"https://openlibrary.org{book_key}.json" | |
response = requests.get(url) | |
response.raise_for_status() | |
data = response.json() | |
return { | |
'title': data.get('title', 'Unknown Title'), | |
'description': data.get('description', {}).get('value', 'No description available') | |
if isinstance(data.get('description'), dict) | |
else data.get('description', 'No description available'), | |
'subjects': data.get('subjects', [])[:5], | |
'first_sentence': data.get('first_sentence', {}).get('value', 'Not available') | |
if isinstance(data.get('first_sentence'), dict) | |
else data.get('first_sentence', 'Not available') | |
} | |
except Exception as e: | |
return {"error": f"Error fetching book details: {str(e)}"} |