In this blog, we’ll take a dive into the code that makes it all happen, discuss how you can build your own, and explore why this setup is a game-changer for content creators, marketers, and businesses alike. Spoiler alert: This guide is packed with actionable insights and code snippets to help you create newsletters that get noticed!
Code Walkthrough
1. Environment Setup
import os
from lyzr_agent import LyzrAgent
import streamlit as st
from dotenv import load_dotenv
from PIL import Image
# Load environment variables
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
LYZR_API_KEY = os.getenv("LYZR_API_KEY")
Imports: The code imports necessary libraries, including os for environment variable management, lyzr_agent for interacting with the Lyzr Agent API, streamlit for creating the web app, dotenv for loading environment variables, and PIL for image handling.
Environment Variables: The load_dotenv() function loads the API keys from a .env file, which are essential for authentication with the Lyzr and OpenAI APIs.
2. LyzrAgent Initialization
Agent = LyzrAgent(api_key=LYZR_API_KEY, llm_api_key=OPENAI_API_KEY)
Agent Initialization: An instance of LyzrAgent is created, using the loaded API keys to authenticate with the Lyzr service.
3. Defining the System Prompt
prompt = """
Act like an experienced newsletter writer skilled in crafting engaging and informative content.
Use a perplexity search to find the most relevant and current information on Given Topic.
Your goal is to summarize the key insights and trends into a concise, well-structured newsletter that keeps readers informed and interested.
Include engaging headlines, clear sections, and a call to action.
Take a deep breath and work on this problem step-by-step.
"""
System Prompt: This prompt guides the agent’s behavior, instructing it to act as a newsletter writer and use the perplexity search tool to gather relevant information.
4. Creating the Agent
@st.cache_resource(show_spinner=True)
def create_agent():
env_id = Agent.create_environment(
name="Newsletter Environment",
features=[{
"type": "TOOL_CALLING",
"config": {"max_tries": 3},
"priority": 0
},
{
"type": "SHORT_TERM_MEMORY",
"config": {},
"priority": 0
}],
tools=["perplexity_search"]
)
agent_id = Agent.create_agent(
env_id=env_id['env_id'],
system_prompt=prompt,
name="Newsletter Agent"
)
return agent_id
This code defines a create_agent() function that builds an agent environment for a "Newsletter Environment" using two modules and a registered external tool. Let's break down the code based on the provided environment structure:
Features/Modules
The environment in this code uses two sync modules:
a. TOOL_CALLING (Sync Module):
Type: Sync
Functionality: This module allows the agent to call external APIs that are registered using OpenAPI schemas. In this code, it is configured with "max_tries": 3 meaning the agent will attempt up to three retries when calling the specified tool.
Execution: It runs in series during the message processing pipeline, has read/write access, and can mutate the message stream.
b. SHORT_TERM_MEMORY (Sync Module):
Type: Sync
Functionality: This module gives the agent short-term contextual memory by retaining information for a configurable number of recent messages. This allows the agent to manage small-scale, context-dependent tasks effectively.
Execution: Like other sync modules, it runs in series, has read/write access, and can impact the message stream during processing.
Tools
The code registers the perplexity_search tool for this environment:
Tools are external APIs used by the agent. In this case, the agent will access the Perplexity search tool, likely to assist in information retrieval for newsletter content.
Note: Since the TOOL_CALLING module is enabled, the tool is accessible to the agent.
Environment ID (env_id)
The env_id variable stores the unique identifier of the created environment. This ID can be used for further agent configuration or interactions within the broader system.
Agent Creation
The code is creating a new agent using the Agent.create_agent method, which takes in the environment ID, system prompt, and agent name as arguments. The agent_id returned represents the unique ID of the newly created agent.
7. Session State Management
if "agent_id" not in st.session_state:
st.session_state.agent_id = create_agent()
Session Management: The agent ID is stored in the Streamlit session state to maintain the agent’s context across user interactions.
8. User Input and Newsletter Generation
query = st.text_area("Enter Topic and description", height=150)
if st.button("Generate NewsLetter"):
if query.strip():
with st.spinner("Generating NewsLetter..."):
response = Agent.send_message(
agent_id=st.session_state.agent_id['agent_id'],
user_id="default_user",
session_id="new_session",
message=query
)
st.markdown(f"**Generated NewsLetter:**\n\n{response['response']}")
else:
st.warning("Please provide Topic")
Input Area: Users can enter a topic and description in a text area.
Generate Button: When clicked, it checks if the input is not empty. If valid, it sends a message to the agent using Agent.send_message(), which triggers the generation of the newsletter. The generated content is then displayed.
Join Discord: https://discord.gg/dxKFHS6t
Project Link: https://github.com/harshit-lyzr/Newsletter_automation
Try it out: https://lyzr-newsletter.streamlit.app/
Top comments (0)