Building a Social Media Advisor with Lyzr's RAG and VoiceBot Agent
Tags: beginners, python, ai, tutorial
Published: 2024-03-28 19:11:55

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](lyzr.ai) 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 ](https://docs.lyzr.ai/lyzr-sdk/opensource/chatbot/docx-chat)and [VoiceBot](https://docs.lyzr.ai/lyzr-sdk/opensource/voicebot).

---
{% embed https://docs.lyzr.ai/lyzr-sdk/opensource/ %}
---


## Setting up the Project

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

Clone the app:
   ```bash
   python3 -m venv venv
   source venv/bin/activate
   ```

Create an environment variable:
   Create a `.env` file and add your OpenAI API key:
   ```python
   OPENAI_API_KEY = "Paste your openai api key here"
   ```

Install the required dependencies:
   ```bash
   pip install lyzr streamlit docx2txt
   ```

## Project Structure

The project structure consists of several directories and files:

```scss
Social-Media-Advisor
│
├── utils/
│   ├── __init__.py
│   └── utils.py
│
├── app.py
│
├── README.md
│
└── .gitignore
```

## Utilizing Common Functions

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

### `get_files_in_directory()`

```python
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}")
```
### `get_files_in_directory()`
 

```python
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
```

### `save_uploaded_file()`

```python
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")
```

### `file_checker()`

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

    return file
```

## Implementing Core Functionalities

### Generating Social Media Content

```python
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
```

### Generating Content Summaries

```python
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
```

### Displaying Responses

```python
def get_response(response:dict):
    for platfrom, response in response.items():
        st.subheader(platfrom)
        st.write(response)
        st.markdown("---")  
```

### Generating Instagram Images

```python
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,
    )
```
## An entry point for an application ‘app.py’
Functions defined in `app.py`

```python
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)
```
## Initializing Social Media Advisor application

```python
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')
```

## 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](https://github.com/PrajjwalLyzr/Social-Media-Advisor)

Lyzr Website: [https://www.lyzr.ai/](https://www.lyzr.ai/)

Book a Demo: [https://www.lyzr.ai/book-demo/](https://www.lyzr.ai/book-demo/)

Lyzr Community Channels: [Discord](https://discord.gg/nm7zSyEFA2), [Slack](https://join.slack.com/t/genaiforenterprise/shared_invite/zt-2a7fr38f7-_QDOY1W1WSlSiYNAEncLGw)