DEV Community

Cover image for Building a Social Media Advisor with Lyzr's RAG and VoiceBot Agent
Prajjwal Sule
Prajjwal Sule

Posted on

Building a Social Media Advisor with Lyzr's RAG and VoiceBot Agent

In today's digital landscape, social media plays a crucial role in reaching and engaging with audiences. However, creating compelling content tailored for different platforms can be challenging. In this article, we'll explore how to leverage Lyzr's RAG (Retrieval-Augmented Generation) and VoiceBot Agent to streamline the process of generating social media content.

Introduction

In the fast-paced world of social media, creating engaging content that resonates with your audience is paramount. Lyzr's Social Media Advisor simplifies the content creation process by leveraging advanced technologies such as ChatBot and VoiceBot.


Lyzr Open Source SDKs 🚀 | Lyzr Documentation

Welcome to the Lyzr Open Source Software Development Kit (SDK)!

favicon docs.lyzr.ai

Setting up the Project

Let's dive into the steps required to set up the Social Media Advisor project:

Clone the app:

   python3 -m venv venv
   source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

Create an environment variable:
Create a .env file and add your OpenAI API key:

   OPENAI_API_KEY = "Paste your openai api key here"
Enter fullscreen mode Exit fullscreen mode

Install the required dependencies:

   pip install lyzr streamlit docx2txt
Enter fullscreen mode Exit fullscreen mode

Project Structure

The project structure consists of several directories and files:

Social-Media-Advisor
│
├── utils/
│   ├── __init__.py
│   └── utils.py
│
├── app.py
│
├── README.md
│
└── .gitignore
Enter fullscreen mode Exit fullscreen mode

Utilizing Common Functions

Let's explore the common utility functions defined in utils.py

get_files_in_directory()

import os
import shutil
import streamlit as st
from dotenv import load_dotenv; load_dotenv()
from openai import OpenAI


API_KEY = os.getenv('OPENAI_API_KEY')


def remove_existing_files(directory):
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
        except Exception as e:
            st.error(f"Error while removing existing files: {e}")
Enter fullscreen mode Exit fullscreen mode

get_files_in_directory()

def get_files_in_directory(directory):
    files_list = []

    if os.path.exists(directory) and os.path.isdir(directory):
        for filename in os.listdir(directory):
            file_path = os.path.join(directory, filename)

            if os.path.isfile(file_path):
                files_list.append(file_path)


    return files_list
Enter fullscreen mode Exit fullscreen mode

save_uploaded_file()

def save_uploaded_file(directory, uploaded_file):
    remove_existing_files(directory=directory)
    file_path = os.path.join(directory, uploaded_file.name)
    with open(file_path, "wb") as file:
        file.write(uploaded_file.read())
    st.success("File uploaded successfully")
Enter fullscreen mode Exit fullscreen mode

file_checker()

def file_checker():
    file = []
    for filename in os.listdir('data'):
        file_path = os.path.join('data', filename)
        file.append(file_path)

    return file
Enter fullscreen mode Exit fullscreen mode

Implementing Core Functionalities

Generating Social Media Content

def social_media(agent):
    content = {}
    prompts = {'LinkedIn': """
                        Craft an engaging LinkedIn post based on this article.
                        Share a concise yet compelling overview of article's key points to capture the audience's attention.
                        Remember to include relevant hashtags and a call-to-action to encourage further engagement and drive traffic to your article. Let's create an impactful post that resonates with your LinkedIn network!
            """,


            "Twitter":"""
                        Craft a captivating tweet inspired by the essence of this article.
                        Condense the key insights into 1-2 punchy lines that grab attention and leave readers intrigued.
                        Ensure the tweet is concise yet impactful, and don't forget to add relevant hashtags to expand your reach. Let's compose a tweet that sparks curiosity and drives engagement!


            """,




            "Facebook":"""
                        Compose an engaging Facebook post that encapsulates the essence of this article.
                        Share a brief summary that highlights the most compelling aspects, aiming to captivate your audience's interest.
                        Consider adding an eye-catching image or video to enhance the post's appeal, and encourage interaction by asking a thought-provoking question or inviting comments. Let's craft a post that resonates with your Facebook followers and sparks meaningful conversations!


            """}


    for platfrom, prompt in prompts.items():
        response = agent.chat(prompt)
        content[platfrom] = response.response


    return content
Enter fullscreen mode Exit fullscreen mode

Generating Content Summaries

def prompts(agent):
    results = {}
    prompt = {'Voice_Ad':'create an article summary for advertisement in 150-200 words',
               'Instagram_post':'create an article summary for Instagram post in 10-20 words.' }  


    for platfrom, prompt in prompt.items():        
        response = agent.chat(prompt)
        results[platfrom] = response.response


    return results
Enter fullscreen mode Exit fullscreen mode

Displaying Responses

def get_response(response:dict):
    for platfrom, response in response.items():
        st.subheader(platfrom)
        st.write(response)
        st.markdown("---")  
Enter fullscreen mode Exit fullscreen mode

Generating Instagram Images

def instagram_img(prompt):
    client = OpenAI(api_key=API_KEY)
    response = client.images.generate(
    model="dall-e-3",
    prompt=prompt,
    size="1024x1024",
    quality="standard",
    n=1,
    )
Enter fullscreen mode Exit fullscreen mode

An entry point for an application ‘app.py’

Functions defined in app.py

import os
from PIL import Image
from utils import utils
import streamlit as st
from dotenv import load_dotenv; load_dotenv()
from lyzr import VoiceBot, ChatBot


# Social Media Advisor Application
data = 'data'
audio_directory = 'audio'
os.makedirs(data, exist_ok=True)
os.makedirs(audio_directory, exist_ok=True)
original_directory = os.getcwd()


# replace this with your openai api key or create an environment variable for storing the key.
API_KEY = os.getenv('OPENAI_API_KEY')

def qabot_agent():
    path = utils.get_files_in_directory(data)
    qa_agent = ChatBot.docx_chat(
        input_files=path
    )

    return qa_agent



def voicebot_agent(add_summary):
    vb = VoiceBot(api_key=API_KEY)
    try:
        os.chdir(audio_directory)
        vb.text_to_speech(add_summary)
    finally:
        os.chdir(original_directory)
Enter fullscreen mode Exit fullscreen mode

Initializing Social Media Advisor application

if __name__ == "__main__":
    article = st.file_uploader('Upload your article documet',type=["docx"])
    if article:
        utils.save_uploaded_file(directory=data, uploaded_file=article)
        file = utils.file_checker()
        if len(file)>0:
            if st.button('Create'):
                agent = qabot_agent()
                response = utils.social_media(agent=agent)
                results = utils.prompts(agent=agent)
                if response:
                    utils.get_response(response=response)
                    if results:
                        voicebot_agent(add_summary=results['Voice_Ad'])
                        st.subheader('Voice Advertisment')
                        files = utils.get_files_in_directory(audio_directory)
                        audio_file = files[0]
                        st.audio(audio_file)  
                        st.markdown('---')
                        st.subheader('Instagram')
                        insta_img_prompt = results['Instagram_post'] + " " + "Avoid any text or numbers in the image"
                        insta_image = utils.instagram_img(insta_img_prompt)
                        st.image(insta_image, caption='Instagram Image', use_column_width=True)


    else:
        utils.remove_existing_files(data)
        st.warning('Please Upload article document file')
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, we've explored how to build a Social Media Advisor application using Lyzr's RAG and VoiceBot Agent. By leveraging these technologies, content creators can streamline the process of generating engaging social media content tailored for different platforms.

References

For further exploration and engagement, refer to Lyzr’s website, book a demo, or join the community channels on Discord and Slack.

Social Media Advisor: GitHub

Lyzr Website: https://www.lyzr.ai/

Book a Demo: https://www.lyzr.ai/book-demo/

Lyzr Community Channels: Discord, Slack

Top comments (0)