File size: 2,455 Bytes
8839c56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)}"}