import requests def fetch_openlibrary_by_title_or_subject(query, limit=5): """ Search OpenLibrary for books matching the query. Returns a list of dictionaries with title, author, year, and description. """ # API endpoint for search url = "https://openlibrary.org/search.json" # Query parameters params = {"q": query, "limit": limit} # Make a request to the OpenLibrary API response = requests.get(url, params=params, timeout=15) # Convert to JSON (Python dictionary) data = response.json() # Extract book details results = [] docs = data.get("docs", [])[:limit] for book in docs: title = book.get("title") author = ", ".join(book.get("author_name", [])) if book.get("author_name") else "Unknown" year = book.get("first_publish_year") subjects = book.get("subject", []) desc = subjects[0] if subjects else "" results.append({ "title": title, "author": author, "year": year, "desc": desc }) return results # to check # from ai_agent import fetch_openlibrary_by_title_or_subject books = fetch_openlibrary_by_title_or_subject("Atomic Habits") print(books)