DEV Community

Akshay Keerthi
Akshay Keerthi

Posted on

Building Book Recommendation Assistant with Lyzr Automata

In a world inundated with an endless stream of books, finding the perfect read can often feel like searching for a needle in a haystack. But what if there was a solution that could tailor book recommendations to your unique preferences? Enter our revolutionary Book Recommendation Assistant, a cutting-edge application powered by the Lyzr SDK, designed to transform the way you discover your next literary adventure.

Image description

With countless books published each year across a myriad of genres, readers are faced with the daunting task of sifting through an overwhelming sea of options to find their next favorite read. Traditional recommendation methods often fall short, offering generic suggestions that fail to capture the nuances of individual tastes and preferences.

Our Book Recommendation Assistant is poised to change the game, offering a personalized approach to book discovery. By harnessing the power of AI and the advanced capabilities of the Lyzr SDK, our assistant analyzes user preferences, reading habits, favorite authors, and current interests to deliver tailored recommendations that resonate on a deeper level.

Why use Lyzr SDK’s?

With Lyzr SDKs, crafting your own GenAI application is a breeze, requiring only a few lines of code to get up and running swiftly.

Checkout the Lyzr SDK’s

Lets get Started!

Create an app.py file first

import streamlit as st
from lyzr_automata.ai_models.openai import OpenAIModel
from lyzr_automata import Agent, Task
from lyzr_automata.pipelines.linear_sync_pipeline import LinearSyncPipeline
from PIL import Image
from lyzr_automata.tasks.task_literals import InputType, OutputType
import os
Enter fullscreen mode Exit fullscreen mode

This code imports essential libraries and modules for building a Streamlit app integrated with Lyzr Automata, a toolset for AI-driven tasks. Streamlit enables easy web app development in Python, while Lyzr Automata provides advanced AI models and task management capabilities, allowing for streamlined implementation of features like mood analysis or text generation.

The lines of code below sets the OpenAI API key by accessing a secret stored in the Streamlit app’s configuration. The API key is essential for authenticating and accessing OpenAI’s services, such as language models for text generation. By securely retrieving the API key from the app’s secrets, this ensures secure and authorized communication with the OpenAI platform within the application.

# Set the OpenAI API key
os.environ["OPENAI_API_KEY"] = st.secrets["apikey"]
Enter fullscreen mode Exit fullscreen mode
input = st.text_input("What kinds of books do you like? Do you have any favorite authors? Also, if there's a particular topic you're interested in right now, feel free to let me know. I'd love to suggest some books that match your preferences!",placeholder=f"""Type here""")
Enter fullscreen mode Exit fullscreen mode

This line of code initializes a text input field using the st.text_input function from the Streamlit library. It serves as a user interface component for gathering information from the user. The text displayed within the input field asks the user about their reading preferences, including the types of books they enjoy, their favorite authors, and any specific topics they're interested in at the moment. The placeholder parameter provides a hint to the user, indicating where they should input their response. The entered information is stored in the variable input, which will be used to tailor book recommendations based on the user's preferences.

open_ai_text_completion_model = OpenAIModel(
    api_key=st.secrets["apikey"],
    parameters={
        "model": "gpt-4-turbo-preview",
        "temperature": 0.2,
        "max_tokens": 1500,
    },
)
Enter fullscreen mode Exit fullscreen mode

This code initializes an instance of the OpenAIModel class, utilizing the Lyzr SDK. It sets up the model with specific parameters for text generation tasks. The api_key parameter retrieves the required API key from Streamlit's secrets. The parameters parameter is a dictionary containing settings for the model, including the version of the GPT model, temperature (controlling randomness), and maximum number of tokens to generate.

def book_generation(input):
    generator_agent = Agent(
        role=" BOOK RECOMMENDATION ASSISTANT expert",
        prompt_persona=f" Your task is to ANALYZE and SUGGEST books that align with a user's reading patterns, habits, genre preferences, favorite authors, reading goals, and current interests."
    )

    prompt = f"""
[prompts here]
 """
Enter fullscreen mode Exit fullscreen mode

This function book_generation, takes an input parameter representing user input. Within the function, it creates an instance of the Agent class named generator_agent. The agent is assigned a role as a "BOOK RECOMMENDATION ASSISTANT expert" and a prompt persona specifying its task: to analyze and suggest books that match a user's reading patterns, habits, genre preferences, favorite authors, reading goals, and current interests.

The prompt variable contains a formatted string with prompts or instructions for the agent to follow. This prompt guides the agent on how to fulfill its task of generating book recommendations tailored to the user's preferences. The actual prompts or instructions would be inserted within the string where [prompts here] is indicated.

    generator_agent_task = Task(
        name="book Generation",
        model=open_ai_text_completion_model,
        agent=generator_agent,
        instructions=prompt,
        default_input=input,
        output_type=OutputType.TEXT,
        input_type=InputType.TEXT,
    ).execute()

    return generator_agent_task 
Enter fullscreen mode Exit fullscreen mode

This code segment creates a Task object named generator_agent_task, which represents the task of generating book recommendations based on user input. The task is associated with a specific model (open_ai_text_completion_model) and agent (generator_agent).

The name parameter specifies the name of the task as "book Generation". The instructions parameter contains the prompt or instructions for the task, guiding the agent on how to generate personalized book recommendations.

The default_input parameter provides the input for the task, which is the user's input obtained earlier. This input is used by the agent and model to generate recommendations.

The output_type parameter specifies that the output of the task should be in text format. The input_type parameter specifies that the input to the task is also in text format.

Finally, the execute() method is called on the Task object to execute the task, which generates book recommendations based on the provided input. The resulting generator_agent_task object encapsulates the output of the task.The function then returns this generator_agent_task object, which contains the generated book recommendations.

if st.button("Recommend"):
    solution = book_generation(input)
    st.markdown(solution)
Enter fullscreen mode Exit fullscreen mode

This code snippet creates a button using st.button from the Streamlit library. The button is labeled "Recommend" and serves as a trigger for generating book recommendations when clicked.

When the “Recommend” button is clicked, the function book_generation(input) is called, passing the user input input as a parameter. This function generates personalized book recommendations based on the provided input.The resulting recommendations are stored in the solution variable.

Finally, the st.markdown function is used to display the recommendations on the Streamlit app interface. The solution variable, containing the generated book recommendations, is passed as an argument to st.markdown, rendering the recommendations as formatted text on the app interface.

In a world where choice is abundant and time is precious, our AI-powered Book Recommendation Assistant offers a beacon of hope for readers seeking their next literary escapade. By harnessing the power of AI and the Lyzr SDK, we’re revolutionizing the way books are discovered and enjoyed, one personalized recommendation at a time. Say goodbye to endless scrolling and generic suggestions — welcome to a new era of reading, where every book recommendation is as unique as you are.

App link: https://bookrecommendation-lyzr.streamlit.app/

Source Code: https://github.com/isakshay007/Book_Recommendation

Connect with Lyzr
To learn more about Lyzr and its SDK’s, visit our website or get in touch with our team:

Website: Lyzr.ai
Book a Demo: Book a Demo
Discord: Join our Discord community
Slack: Join our Slack channel

Top comments (0)