Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Read by thought-leaders and decision-makers around the world. Phone Number: +1-650-246-9381 Email: [email protected]
228 Park Avenue South New York, NY 10003 United States
Website: Publisher: https://towardsai.net/#publisher Diversity Policy: https://towardsai.net/about Ethics Policy: https://towardsai.net/about Masthead: https://towardsai.net/about
Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Founders: Roberto Iriondo, , Job Title: Co-founder and Advisor Works for: Towards AI, Inc. Follow Roberto: X, LinkedIn, GitHub, Google Scholar, Towards AI Profile, Medium, ML@CMU, FreeCodeCamp, Crunchbase, Bloomberg, Roberto Iriondo, Generative AI Lab, Generative AI Lab Denis Piffaretti, Job Title: Co-founder Works for: Towards AI, Inc. Louie Peters, Job Title: Co-founder Works for: Towards AI, Inc. Louis-François Bouchard, Job Title: Co-founder Works for: Towards AI, Inc. Cover:
Towards AI Cover
Logo:
Towards AI Logo
Areas Served: Worldwide Alternate Name: Towards AI, Inc. Alternate Name: Towards AI Co. Alternate Name: towards ai Alternate Name: towardsai Alternate Name: towards.ai Alternate Name: tai Alternate Name: toward ai Alternate Name: toward.ai Alternate Name: Towards AI, Inc. Alternate Name: towardsai.net Alternate Name: pub.towardsai.net
5 stars – based on 497 reviews

Frequently Used, Contextual References

TODO: Remember to copy unique IDs whenever it needs used. i.e., URL: 304b2e42315e

Resources

Take our 85+ lesson From Beginner to Advanced LLM Developer Certification: From choosing a project to deploying a working product this is the most comprehensive and practical LLM course out there!

Publication

Building a Self-Learning AI Marketing Agent with LangMem + LangGraph (Part 2)
Latest   Machine Learning

Building a Self-Learning AI Marketing Agent with LangMem + LangGraph (Part 2)

Last Updated on February 21, 2025 by Editorial Team

Author(s): Reelfy

Originally published on Towards AI.

Building a Self-Learning AI Marketing Agent with LangMem + LangGraph (Part 2)

Ensuring Consistency in AI-Generated Marketing Campaigns

AI Agent Bot taking memory pills. As imagined by Dall-E 3

The Challenge: Creating a Consistent Brand Narrative with AI

In Part 1, we introduced the concept of AI-powered Social Media Agents β€” capable of analyzing brand presence, generating video content, and automating posts.

But what happens when AI starts creating content at scale?

🚨 Without a structured memory system, AI-generated marketing materials can lose coherence, creating disjointed messaging that fails to build a recognizable brand identity over time.

Imagine a brand posting one AI-generated video about sustainable fashion, followed by another completely unrelated clip encouraging clients to cut costs no matter whatβ€” confusing audiences and weakening brand trust.

This is where LangMem comes into play. By integrating long-term memory into our Social Media Agents, we can ensure that AI doesn’t just create isolated posts, but remembers the brand’s story, audience preferences, and marketing themes β€” resulting in a cohesive and evolving social media strategy.

Why LangMem? The Secret Sauce for AI-Driven Marketing Consistency

πŸ†• The LangMem SDK was just released on February 18, 2025, and here at Reelfy, we’re already experimenting with it to push the boundaries of AI-driven content marketing.

LangMem provides an advanced memory system that allows AI agents to retain and refine knowledge over time. It goes beyond short-term context windows by enabling agents to learn from past interactions, update brand guidelines dynamically, and improve storytelling consistency.

Which Type of Memory is Best for Social Media Marketing?

LangMem offers three key types of memory β€” each serving different functions in AI-driven workflows. To maintain brand consistency in AI-generated marketing videos, we focus on Semantic Memory and Procedural Memory:

Building a Social Media Agent with LangMem + LangGraph

LangMem alone isn’t enough β€” we need a structured way for our AI agent to access and update its memory. That’s where LangGraph comes in. By integrating LangMem’s memory tools into LangGraph’s agent framework, we create a self-learning marketing assistant that can analyze, generate, and refine content in real time.

In Part 1, we used SmolAgents to orchestrate our AI Social Media Agent. This time, we’re using LangGraph instead. Why?

🔹 LangGraph natively integrates with LangMem, making it easier to demonstrate the benefits of using a built-in memory approach.

Step 1: Initializing AI’s Memory – A Built-in RAG for Marketing Knowledge

Before our AI can generate strategic marketing content, it needs a place to store and retrieve knowledge over time. In this setup, LangMem serves as a built-in RAG.

Let’s initialize our long-term memory store, which will hold both Semantic Memory (facts & knowledge) and Procedural Memory (marketing workflows).

from langgraph.store.memory import InMemoryStore

# Initialize memory storage using LangGraph
store = InMemoryStore(index={"dims": 1536, "embed": "openai:text-embedding-3-small"})

🔹 Why? AI needs a persistent knowledge base to avoid generating disconnected, inconsistent content.

Step 2: Storing Key Marketing Knowledge with Semantic Memory

Let’s define a structure for storing key marketing knowledge and create memory management tools for later use. We will first:

1️⃣ Storing Key Marketing Knowledge in Semantic Memory

Instead of hardcoding knowledge into prompts, we store marketing facts in LangMem’s long-term memory, ensuring that AI can retrieve and apply them dynamically.

from langmem import create_memory_manager, create_manage_memory_tool, create_search_memory_tool
from pydantic import BaseModel

# Define structure for marketing knowledge
class MarketingKnowledge(BaseModel):
topic: str
key_insights: str

# Create memory manager to store facts
memory_manager = create_memory_manager(
"anthropic:claude-3-5-sonnet-latest",
schemas=[MarketingKnowledge],
instructions="Store key marketing facts and retrieve them for future campaign strategies.",
store=store,
)

# Store industry knowledge
marketing_facts = [
{"topic": "Startup Founders' Challenges", "key_insights": "Founders struggle with hiring, funding, and scaling."},
{"topic": "Engaging Video Content", "key_insights": "Short-form educational videos drive 3x more engagement than static posts."},
{"topic": "Brand Differentiation", "key_insights": "Successful startups use storytelling to highlight unique brand values."}
]

# Store facts in AI's memory
for fact in marketing_facts:
memory_manager.invoke({"messages": [{"role": "user", "content": f"Save this fact: {fact}"}]})

# Create tools for AI to interact with memory
manage_memory_tool = create_manage_memory_tool(namespace=("memories",))
search_memory_tool = create_search_memory_tool(namespace=("memories",))

🔹 Why? AI now has access to real-world knowledge that it can apply when generating marketing campaigns.

2️⃣ Updating Semantic Memory as New Insights Emerge

Marketing knowledge is not static β€” trends change, audience behaviors shift, and new insights emerge.

Let’s say we discover a new engagement trend (e.g., β€œLinkedIn carousels are outperforming videos”). We need to update AI’s memory accordingly.

Semantic Memory visual representation. Drawn in https://excalidraw.com/
# Update AI's marketing knowledge with new industry insights
new_insight = {
"topic": "Engaging Video Content",
"key_insights": "LinkedIn carousels now outperform short videos for B2B engagement."
}

# Store the updated fact in memory
memory_manager.invoke({"messages": [{"role": "user", "content": f"Update this fact: {new_insight}"}]})

🔹 Why? AI-generated content will now reflect the latest trends, ensuring it stays competitive and relevant.

Step 3: Creating and Refining Procedural Memory for AI Marketing Agents

With LangMem, we can teach our Social Media Agent how to structure marketing campaigns through procedural memory. To avoid inconsistent storytelling formats, our AI agent must learn the structure of effective marketing videos β€” such as hooks, storytelling arcs, and call-to-action placement.

But marketing is not static β€” brands evolve, strategies shift, and audience engagement fluctuates.

That’s why we don’t just define instructions once β€” we store them in memory and refine them over time based on market trends and performance insights. We’ll first:

1️⃣ Storing Initial Marketing Guidelines in Procedural Memory

Let’s start by defining how our AI should structure marketing campaigns. We store these rules in LangMem’s long-term memory, ensuring the agent follows a predictable format.

# Store initial campaign structure in procedural memory
store.put(("instructions",), key="marketing_campaigns", value={
"prompt": """You are a Social Media Agent. Every marketing campaign must follow this structure:

1. Hook: Start with an engaging question, bold statement, or surprising stat.
2. Educational Insight: Teach startup founders something valuable about the topic.
3. Call to Action: Encourage audience interaction with a thought-provoking question or challenge.

Maintain a playful yet professional tone. Focus on creating **educational content** for startup founders."""

})

🔹 Why? By saving these campaign guidelines in memory, our AI will remember and follow this structure across multiple campaigns β€” ensuring consistency.

2️⃣ Refining the Campaign Structure Based on Market Insights

As marketing strategies evolve, we may need to update our AI’s procedural memory β€” for example, if we realize that audience engagement increases when we add a success story to the campaign format.

Procedural Memory visual representation. Drawn in https://excalidraw.com/
from langmem import create_prompt_optimizer

# Initialize prompt optimizer to refine procedural memory
optimizer = create_prompt_optimizer("anthropic:claude-3-5-sonnet-latest")

# Retrieve current campaign structure
current_prompt = store.get(("instructions",), key="marketing_campaigns").value["prompt"]

# Market feedback suggests success stories increase engagement
feedback = {"request": "Include a success story in every campaign to increase engagement."}

# AI refines campaign structure based on feedback
updated_prompt = optimizer.invoke({"prompt": current_prompt, "trajectories": [(current_prompt, feedback)]})

# Store the updated procedural memory
store.put(("instructions",), key="marketing_campaigns", value={"prompt": updated_prompt})

🔹 Why? AI-generated campaigns keep improving, ensuring higher engagement.

Step 4: Generating AI-Driven Marketing Campaigns That Learn and Adapt

Now that our AI has both knowledge (Semantic Memory) and structured processes (Procedural Memory), let’s generate campaigns that evolve over time.

1️⃣ Creating the First Marketing Campaign

from langgraph.prebuilt import create_react_agent
from langgraph.config import get_store

# Define prompt function to fetch instructions from memory
def prompt(state):
item = store.get(("instructions",), key="marketing_campaigns")
instructions = item.value["prompt"]
sys_prompt = {"role": "system", "content": f"## Campaign Instructions\n\n{instructions}"}
return [sys_prompt] + state["messages"]

# Create AI Marketing Agent
agent = create_react_agent(
"anthropic:claude-3-5-sonnet-latest",
prompt=prompt,
tools=[manage_memory_tool, search_memory_tool],
store=store,
)

# Generate the first campaign
first_campaign = agent.invoke({
"messages": [{"role": "user", "content": "Create a campaign about Hiring and Team Building for startup founders."}]
})

print(first_campaign) # AI follows stored campaign structure

2️⃣ Generating a Second Campaign That Expands on the First One

Since AI remembers past campaigns, we don’t need to retrieve them manually β€” AI automatically keeps context.

# Generate a follow-up campaign while maintaining continuity
second_campaign = agent.invoke({
"messages": [{"role": "user", "content": "Create a follow-up campaign on Product Development that builds on the Hiring and Team Building insights."}]
})

print(second_campaign) # AI expands on previous campaign, ensuring continuity

🔹 Why? Instead of creating random standalone posts, AI develops a strategic campaign narrative.

Why LangMem is a Game-Changer for AI Marketing Agents

Without memory, AI agents generate one-off posts without continuity. With LangMem, we unlock:

Brand Consistency β†’ AI remembers brand identity, voice, and messaging across all content.

Content Quality Control β†’ AI follows structured campaign workflows, ensuring content remains polished and engaging.

Marketing Intelligence β†’ AI remembers past campaigns, industry insights, and audience preferences, enabling smarter content decisions.

Where Do We Go Next?

We’ve established the foundation for memory-driven marketing AI, but this is just the beginning. Here a few topics that we can explore to push the boundries further:

🔹 Advanced Personalization β†’ AI dynamically tailors content for different audience segments, ensuring higher engagement.

🔹 Cross-Platform Content Adaptation β†’ AI automatically repurposes content across multiple social media platforms.

🔹 Real-Time Performance Optimization β†’ AI analyzes audience reactions and refines marketing strategies continuously.

Stay tuned as we continue redefining AI-driven social media marketing! 🚀

Written by Garry Newball

References

[1] LangChain Conceptual Guide. Retrieved From: https://python.langchain.com/docs/concepts/

[2] LangMem Documentation. Retrieved From: https://langchain-ai.github.io/langmem/

[3] LangGraph Documentation. Retrieved From: https://langchain-ai.github.io/langgraph/

[4] LangMem SDK for agent long-term memory. Retrieved From: https://blog.langchain.dev/langmem-sdk-launch/

[5] LangMem Code Examples. Retrieved From: https://github.com/langchain-ai/langmem/tree/main/examples/intro_videos

Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming aΒ sponsor.

Published via Towards AI

Feedback ↓