File size: 3,321 Bytes
8839c56 02b4a70 8839c56 02b4a70 df2f655 8839c56 df2f655 8839c56 df2f655 8839c56 df2f655 8839c56 02b4a70 df2f655 8839c56 df2f655 8839c56 df2f655 8839c56 df2f655 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
from typing import List, Dict
import requests
from smolagents.tools import Tool
class BookSearchTool(Tool):
name = "search_books"
description = "Search for books using the Open Library API"
inputs = {'query': {'type': 'string', 'description': 'The search query to find books.'}}
output_type = "string"
def forward(self, query: str) -> str:
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)
# Format results as a string
formatted_results = "## Book Search Results\n\n"
for book in results:
formatted_results += f"### {book['title']}\n"
formatted_results += f"- Author: {book['author']}\n"
formatted_results += f"- Year: {book['first_publish_year']}\n"
formatted_results += f"- Subjects: {', '.join(book['subject'])}\n\n"
return formatted_results
except Exception as e:
return f"Error searching books: {str(e)}"
class BookDetailsTool(Tool):
name = "get_book_details"
description = "Get detailed information about a specific book from Open Library"
inputs = {'book_key': {'type': 'string', 'description': 'The Open Library key for the book.'}}
output_type = "string"
def forward(self, book_key: str) -> str:
try:
url = f"https://openlibrary.org{book_key}.json"
response = requests.get(url)
response.raise_for_status()
data = response.json()
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')
# Format as a string
details = f"## {data.get('title', 'Unknown Title')}\n\n"
details += "### Description\n"
details += f"{description}\n\n"
details += "### Subjects\n"
details += ', '.join(subjects) + "\n\n"
details += "### First Sentence\n"
details += f"{first_sentence}\n"
return details
except Exception as e:
return f"Error fetching book details: {str(e)}" |