
Building a Self-Learning AI Marketing Agent with LangMem + LangGraph (Part 2)
towardsai.net
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 CampaignsAI Agent Bot taking memory pills. As imagined by Dall-E 3The Challenge: Creating a Consistent Brand Narrative with AIIn 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 doesnt just create isolated posts, but remembers the brands 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, were 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 + LangGraphLangMem alone isnt enough we need a structured way for our AI agent to access and update its memory. Thats where LangGraph comes in. By integrating LangMems memory tools into LangGraphs 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, were 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 AIs Memory A Built-in RAG for Marketing KnowledgeBefore 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.Lets 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 LangGraphstore = 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 MemoryLets 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 MemoryInstead of hardcoding knowledge into prompts, we store marketing facts in LangMems 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_toolfrom pydantic import BaseModel# Define structure for marketing knowledgeclass MarketingKnowledge(BaseModel): topic: str key_insights: str# Create memory manager to store factsmemory_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 knowledgemarketing_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 memoryfor fact in marketing_facts: memory_manager.invoke({"messages": [{"role": "user", "content": f"Save this fact: {fact}"}]})# Create tools for AI to interact with memorymanage_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 EmergeMarketing knowledge is not static trends change, audience behaviors shift, and new insights emerge.Lets say we discover a new engagement trend (e.g., LinkedIn carousels are outperforming videos). We need to update AIs memory accordingly.Semantic Memory visual representation. Drawn in https://excalidraw.com/# Update AI's marketing knowledge with new industry insightsnew_insight = { "topic": "Engaging Video Content", "key_insights": "LinkedIn carousels now outperform short videos for B2B engagement."}# Store the updated fact in memorymemory_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 AgentsWith 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.Thats why we dont just define instructions once we store them in memory and refine them over time based on market trends and performance insights. Well first:1 Storing Initial Marketing Guidelines in Procedural MemoryLets start by defining how our AI should structure marketing campaigns. We store these rules in LangMems long-term memory, ensuring the agent follows a predictable format.# Store initial campaign structure in procedural memorystore.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 InsightsAs marketing strategies evolve, we may need to update our AIs 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 memoryoptimizer = create_prompt_optimizer("anthropic:claude-3-5-sonnet-latest")# Retrieve current campaign structurecurrent_prompt = store.get(("instructions",), key="marketing_campaigns").value["prompt"]# Market feedback suggests success stories increase engagementfeedback = {"request": "Include a success story in every campaign to increase engagement."}# AI refines campaign structure based on feedbackupdated_prompt = optimizer.invoke({"prompt": current_prompt, "trajectories": [(current_prompt, feedback)]})# Store the updated procedural memorystore.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 AdaptNow that our AI has both knowledge (Semantic Memory) and structured processes (Procedural Memory), lets generate campaigns that evolve over time.1 Creating the First Marketing Campaignfrom langgraph.prebuilt import create_react_agentfrom langgraph.config import get_store# Define prompt function to fetch instructions from memorydef 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 Agentagent = create_react_agent( "anthropic:claude-3-5-sonnet-latest", prompt=prompt, tools=[manage_memory_tool, search_memory_tool], store=store,)# Generate the first campaignfirst_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 structure2 Generating a Second Campaign That Expands on the First OneSince AI remembers past campaigns, we dont need to retrieve them manually AI automatically keeps context.# Generate a follow-up campaign while maintaining continuitysecond_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 AgentsWithout 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?Weve 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 NewballReferences[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_videosJoin 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 asponsor. Published via Towards AI
0 Comments
·0 Shares
·38 Views