Spaces:
Runtime error
Runtime error
Create book_tool.py
Browse files- tools/book_tool.py +56 -0
tools/book_tool.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Dict
|
| 2 |
+
import requests
|
| 3 |
+
from smolagents import Tool
|
| 4 |
+
|
| 5 |
+
class BookSearchTool(Tool):
|
| 6 |
+
name = "search_books"
|
| 7 |
+
description = "Search for books using the Open Library API"
|
| 8 |
+
input_types = {"query": str}
|
| 9 |
+
output_type = List[Dict]
|
| 10 |
+
|
| 11 |
+
def __call__(self, query: str) -> List[Dict]:
|
| 12 |
+
try:
|
| 13 |
+
url = f"https://openlibrary.org/search.json?q={query}&limit=5"
|
| 14 |
+
response = requests.get(url)
|
| 15 |
+
response.raise_for_status()
|
| 16 |
+
data = response.json()
|
| 17 |
+
|
| 18 |
+
results = []
|
| 19 |
+
for book in data.get('docs', [])[:5]:
|
| 20 |
+
result = {
|
| 21 |
+
'title': book.get('title', 'Unknown Title'),
|
| 22 |
+
'author': book.get('author_name', ['Unknown Author'])[0] if book.get('author_name') else 'Unknown Author',
|
| 23 |
+
'first_publish_year': book.get('first_publish_year', 'Unknown Year'),
|
| 24 |
+
'subject': book.get('subject', [])[:3] if book.get('subject') else [],
|
| 25 |
+
'key': book.get('key', '')
|
| 26 |
+
}
|
| 27 |
+
results.append(result)
|
| 28 |
+
return results
|
| 29 |
+
except Exception as e:
|
| 30 |
+
return [{"error": f"Error searching books: {str(e)}"}]
|
| 31 |
+
|
| 32 |
+
class BookDetailsTool(Tool):
|
| 33 |
+
name = "get_book_details"
|
| 34 |
+
description = "Get detailed information about a specific book from Open Library"
|
| 35 |
+
input_types = {"book_key": str}
|
| 36 |
+
output_type = Dict
|
| 37 |
+
|
| 38 |
+
def __call__(self, book_key: str) -> Dict:
|
| 39 |
+
try:
|
| 40 |
+
url = f"https://openlibrary.org{book_key}.json"
|
| 41 |
+
response = requests.get(url)
|
| 42 |
+
response.raise_for_status()
|
| 43 |
+
data = response.json()
|
| 44 |
+
|
| 45 |
+
return {
|
| 46 |
+
'title': data.get('title', 'Unknown Title'),
|
| 47 |
+
'description': data.get('description', {}).get('value', 'No description available')
|
| 48 |
+
if isinstance(data.get('description'), dict)
|
| 49 |
+
else data.get('description', 'No description available'),
|
| 50 |
+
'subjects': data.get('subjects', [])[:5],
|
| 51 |
+
'first_sentence': data.get('first_sentence', {}).get('value', 'Not available')
|
| 52 |
+
if isinstance(data.get('first_sentence'), dict)
|
| 53 |
+
else data.get('first_sentence', 'Not available')
|
| 54 |
+
}
|
| 55 |
+
except Exception as e:
|
| 56 |
+
return {"error": f"Error fetching book details: {str(e)}"}
|