Spaces:
Sleeping
Sleeping
| from typing import Optional | |
| from smolagents import CodeAgent, HfApiModel, tool | |
| import os | |
| import requests | |
| import gradio as gr | |
| # Define tool for fetching book recommendations | |
| def get_book_recommendations(prompt: str) -> str: | |
| """Fetches book recommendations based on user prompt. | |
| Args: | |
| prompt: the user's query, e.g., "book about Mars" | |
| """ | |
| print(f"Received prompt: {prompt}") | |
| api_key = os.getenv("GOOGLE_BOOKS_API_KEY") | |
| print(f"Using API Key: {api_key}") | |
| search_query = prompt | |
| url = f"https://www.googleapis.com/books/v1/volumes?q={search_query}&key={api_key}" | |
| print(f"Request URL: {url}") | |
| response = requests.get(url) | |
| print(f"API Response Status Code: {response.status_code}") | |
| if response.status_code == 200: | |
| books = parse_google_books_response(response.json()) | |
| print(f"Parsed Books: {books}") | |
| top_books = books[:5] # Get top 5 books | |
| return format_book_recommendations(top_books) | |
| else: | |
| return "Error fetching book recommendations." | |
| def parse_google_books_response(json_content): | |
| books = [] | |
| for item in json_content.get('items', []): | |
| volume_info = item.get('volumeInfo', {}) | |
| title = volume_info.get('title', 'No title available') | |
| authors = ", ".join(volume_info.get('authors', ['No author available'])) | |
| books.append({ | |
| "title": title, | |
| "author": authors | |
| }) | |
| return books | |
| def format_book_recommendations(books): | |
| formatted_books = [] | |
| for index, book in enumerate(books, start=1): | |
| formatted_books.append(f"{index}. {book['title']} by {book['author']}") | |
| return "\n".join(formatted_books) | |
| # Create the AI agent | |
| agent = CodeAgent(tools=[get_book_recommendations], model=HfApiModel(), additional_authorized_imports=["requests"]) | |
| # Define Gradio interface | |
| def generate_recommendations(query: str) -> str: | |
| return agent.run(query) | |
| description_md = """ | |
| Get top 5 book recommendations based on your query. Simply enter your query, and receive a list of books with their names, authors. | |
| """ | |
| # Create Gradio UI | |
| iface = gr.Interface( | |
| fn=generate_recommendations, | |
| inputs=[ | |
| gr.Textbox(lines=1, placeholder="Enter a query", label="Book Topic") | |
| ], | |
| outputs="text", | |
| title="Book Beacon", | |
| description=description_md | |
| ) | |
| # Launch Gradio UI | |
| iface.launch(share=True) |