Spaces:
Sleeping
Sleeping
| 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)}" |