def extract_topic_from_query(user_message): prompt = f""" Extract only the main topic or subject from this user query. Return 1–4 words only. No sentences. No extra text. Query: "{user_message}" Topic: """ try: response = chat(model="llama3.2", messages=[{"role": "user", "content": prompt}]) topic = response["message"]["content"].strip() return topic except: return user_message def fetch_openlibrary_by_title_or_subject(query, limit=5): topic = extract_topic_from_query(query) url = "https://www.googleapis.com/books/v1/volumes" search_query = f"title:({topic}) OR subject:({topic})" params = {"q": search_query, "limit": limit} try: response = requests.get(url, params=params, timeout=10) data = response.json() except Exception as e: print("Google Books Error:", e) return [] items = data.get("items", []) results = [] for item in items: volume = item.get("volumeInfo", {}) title = volume.get("title") or "Unknown Title" authors = volume.get("authors", []) author = ", ".join(authors) if authors else "Unknown" year = volume.get("publishedDate", "") desc = volume.get("description", "")[:300] link = volume.get("infoLink", "") results.append({ "title": title, "author": author, "year": year, "desc": desc, "link": link }) return results