DEV Community

Akshay Keerthi
Akshay Keerthi

Posted on

Building a LinkedIn Post Generator using Lyzr Agent-API

In this Blog, we’ll walk through building a LinkedIn Post Generator using the Lyzr SDK, Streamlit for the front-end interface.

Image description

This application will allow users to create and publish LinkedIn posts seamlessly by entering their text content and image URL.

We’ll utilize LyzrAgent to interact with Lyzr’s API and harness the power of AI for automating content generation and posting on LinkedIn.

Prerequisites:

Before diving into the code, ensure you have the following:

-Python 3.8 or higher installed.
-Lyzr SDK installed.
-Streamlit installed.
-An OpenAI API key and Lyzr API key.
-A .env file containing your API keys (OPENAI_API_KEY and LYZR_API_KEY).

Setting Up the Environment:

First, let’s set up our environment by loading the necessary libraries and API keys. We’ll create a .env file to securely store our API keys and use the dotenv library to load them into our application.

import os
from lyzr_agent import LyzrAgent
import streamlit as st
from dotenv import load_dotenv
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
LYZR_API_KEY = os.getenv("LYZR_API_KEY")
Enter fullscreen mode Exit fullscreen mode

Creating the LyzrAgent:

The core of our application is the LyzrAgent, which will be responsible for creating environments, agents, and handling user inputs to generate and post content on LinkedIn.

Agent = LyzrAgent(
        api_key=LYZR_API_KEY,
        llm_api_key=OPENAI_API_KEY
    )
Enter fullscreen mode Exit fullscreen mode

Building the Agent Environment:

We define a function create_agent() to set up the agent's environment. This environment is configured to use the TOOL_CALLING feature and will be equipped with a specific tool for posting images and text to LinkedIn.

@st.cache_resource
def create_agent():
    env_id = Agent.create_environment(
        name="Post_linkedin",
        features=[{
            "type": "TOOL_CALLING",
            "config": {"max_tries": 3},
            "priority": 0
        }],
        tools=["post_image_and_text_linkedin"]
    )
    print(env_id)
prompt = """
    You are an Expert Linkedin Post Creator. Your task is to compose and publish a LinkedIn post using the user provided Title, Image Url , and Text Content. You must follow these guidelines meticulously:
[prompts here]
    agent_id = Agent.create_agent(
        env_id=env_id['env_id'],
        system_prompt=prompt,
        name="Linkedin"
    )
    print(agent_id)
    return agent_id
Enter fullscreen mode Exit fullscreen mode

Handling User Input:

We then use Streamlit’s text_area function to capture the user's input, including the post content and image URL. Upon clicking the "Generate" button, the app calls create_agent() to create an agent and uses the send_message function to generate the LinkedIn post.

query = st.text_area("Give the textual context of the post and the relevant image url.")
if st.button("Generate"):
    agent = create_agent()
    print(agent)
    chat = Agent.send_message(
        agent_id=agent['agent_id'],
        user_id="default_user",
        session_id="akshay@lyzr.ai",
        message=query
    )
    st.markdown(chat['response'])
Enter fullscreen mode Exit fullscreen mode

Defining the LyzrAgent Class:

Finally, we define the LyzrAgent class in lyzr_agent.py. This class handles all interactions with the Lyzr API, including creating environments, agents, and sending messages.

import requests
import json
class LyzrAgent:
    def __init__(self, api_key, llm_api_key):
        self.url = "https://agent.api.lyzr.app/v2/"
        self.headers = {
            "accept": "application/json",
            "x-api-key": api_key
        }
        self.llm_api_key = llm_api_key
    def create_environment(self, name, features, tools):
        payload = json.dumps({
            "name": name,
            "features": features,
            "tools": tools,
            "llm_api_key": self.llm_api_key
        })
        url = self.url + "environment"
        response = requests.post(url, headers=self.headers, data=payload)
        if response.status_code == 200:
            return response.json()
        else:
            print(f"Error: {response.status_code} - {response.text}")
            return None
    def create_agent(self, env_id, system_prompt, name):
        payload = json.dumps({
            "env_id": env_id,
            "system_prompt": system_prompt,
            "name": name,
            "agent_persona": "",
            "agent_instructions": "",
            "agent_description": ""
        })
        url = self.url + "agent"
        response = requests.post(url, headers=self.headers, data=payload)
        if response.status_code == 200:
            return response.json()
        else:
            print(f"Error: {response.status_code} - {response.text}")
            return None
    def send_message(self, agent_id, user_id, session_id, message):
        payload = json.dumps({
            "user_id": user_id,
            "agent_id": agent_id,
            "session_id": session_id,
            "message": message
        })
        url = self.url + "chat/"
        response = requests.post(url, headers=self.headers, data=payload)
        if response.status_code == 200:
            return response.json()
        else:
            print(f"Error: {response.status_code} - {response.text}")
            return None
    def create_task(self, agent_id, session_id, input_message):
        payload = json.dumps({
            "agent_id": agent_id,
            "session_id": session_id,
            "input": input_message
        })
        url = self.url + "task"
        response = requests.post(url, headers=self.headers, data=payload)
        if response.status_code == 200:
            return response.json()
        else:
            print(f"Error: {response.status_code} - {response.text}")
            return None
Enter fullscreen mode Exit fullscreen mode

With this setup, you’ve built a simple yet powerful LinkedIn Post Generator using Lyzr and Streamlit. The application takes user input, leverages the power of GPT-4 Turbo, and automates the process of creating and publishing LinkedIn posts.

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

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

For any inquiries or support, feel free to contact Lyzr. You can learn more about Lyzr and their offerings through the following links:

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

Top comments (0)