Hey there! In this blog post, we'll create simple generate soical post component using LWC, Apex and Prompt Template. To generate social media posts we need to setup of advanced Prompt Template. We'll use Connect API in apex to execute a Prompt Template. After that we'll call apex method inside lightnin web component.
Here what step we'll do follow:
- Create an Advanced Prompt Template.
- Execute the Prompt Template in apex using Connect API.
- Check the code from "Execute Anonymous Window".
- Create a LWC component to Generative AI.
- Last is Add LWC component on record page.
1. First create Advanced Prompt Template
-
Click on setup. In quick find, enter Prompt Builder and click on Prompt Builder.
-
Click on New Prompt Template.
-
Configure the prompt template as follows:
- Enter Flex in Prompt Template Type.
- Enter Generate Social Media Posts in Prompt Template Name.
- Api Name automatically will be apear.
- Add Template Description as you wish.
-
In Define resource:
- Enter Experience Session in Name.
- Enter experienceSession in Api Name.
- Select Experience Session object.
-
Add the below text in Prompt Template
You're the community manager for Coral Cloud Resorts, which offers booking fun and lovely experiences. Create social media posts for Twitter, LinkedIn & Slack describing the experience. Formatting rules you must follow: """ > Use clear, concise, and straightforward language using the active voice and strictly avoiding the use of filler words and phrases and redundant language. > Make sure the response is valid JSON. > The Twitter post should include emojis, and have less than 280 characters > The LinkedIn post should include emojis, bullets, and have between 1500 and 2000 characters > Both the Twitter and the LinkedIn posts can have Unicode formatting. Use symbols from Unicode’s Mathematical Alphanumeric Symbols block liberally to produce facsimiles of bold, italics, line separation, and other formatting. Examples for a sample sentence: italics sans: 𝘛𝘩𝘦 𝘘𝘶𝘪𝘤𝘬 𝘉𝘳𝘰𝘸𝘯 𝘍𝘰𝘹 𝘑𝘶𝘮𝘱𝘦𝘥 𝘖𝘷𝘦𝘳 𝘵𝘩𝘦 𝘭𝘢𝘻𝘺 𝘥𝘰𝘨. bold sans: 𝗧𝗵𝗲 𝗤𝘂𝗶𝗰𝗸 𝗕𝗿𝗼𝘄𝗻 𝗙𝗼𝘅 𝗝𝘂𝗺𝗽𝗲𝗱 𝗢𝘃𝗲𝗿 𝘁𝗵𝗲 𝗹𝗮𝘇𝘆 𝗱𝗼𝗴. bold italic sans: 𝙏𝙝𝙚 𝙌𝙪𝙞𝙘𝙠 𝘽𝙧𝙤𝙬𝙣 𝙁𝙤𝙭 𝙅𝙪𝙢𝙥𝙚𝙙 𝙊𝙫𝙚𝙧 𝙩𝙝𝙚 𝙡𝙖𝙯𝙮 𝙙𝙤𝙜. italics serif: 𝑇ℎ𝑒 𝑄𝑢𝑖𝑐𝑘 𝐵𝑟𝑜𝑤𝑛 𝐹𝑜𝑥 𝐽𝑢𝑚𝑝𝑒𝑑 𝑂𝑣𝑒𝑟 𝑡ℎ𝑒 𝑙𝑎𝑧𝑦 𝑑𝑜𝑔. > The block kit code should be valid block kit code for Slack. Example of block kit code: { "blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": "🌴 *Tropical Snorkel Adventure* 🐠" } }, { "type": "section", "text": { "type": "mrkdwn", "text": "Swim alongside colorful marine life in our coral-rich tropical waters on this guided snorkeling tour.\n\n *Experience characteristics:*" }, "accessory": { "type": "image", "image_url": "{!$Input:experienceSession.Experience__r.Picture_URL__c}", "alt_text": "alt text for image" } }, { "type": "divider" }, { "type": "section", "text": { "type": "mrkdwn", "text": "• Swim alongside colorful marine life in our coral-rich tropical waters on this guided snorkeling tour." } }, { "type": "section", "text": { "type": "mrkdwn", "text": "• Date: 3/11/2024, starting at 16:00, and finishing at 20:00." } }, { "type": "section", "text": { "type": "mrkdwn", "text": "• Price: $50. Spots are limited, secure your spot today! 🏖️" } }, { "type": "divider" }, { "type": "divider" }, { "type": "actions", "elements": [ { "type": "button", "text": { "type": "plain_text", "text": "Book Experience", "emoji": true }, "value": "click_me_123", "url": "https://coralclouds.com/book/{!$Input:experienceSession.Id}" } ] } ] } """ Instructions regarding the content to generate: """ For each post: - Add a title including the name of the experience, {!$Input:experienceSession.Experience__r.Name} - Add a section including the experience characteristics, such as: + Description: {!$Input:experienceSession.Experience__r.Description__c} + Date and time: {!$Input:experienceSession.Date__c}, starting at {!$Input:experienceSession.Start_Time__c}, and finishing at {!$Input:experienceSession.End_Time__c} - Also include a link to the picture of the experience: {!$Input:experienceSession.Experience__r.Picture_URL__c}, or the picture directly in the case of the slack post. - Finally mention the price {!$Input:experienceSession.Experience__r.Price__c} and say spots are limited. The final response should have the next format: { "twitter": [here goes the twitter post], "linkedin": [here goes the linkedin post], "blockkit": [here goes the slack post] } """ Now generate the social media posts.
-
Type & Select Expereince Session Record Number.
-
Click on Save & Preview, and verify the it is generating correct output.
-
Click on Active button.
2. Execute the Prompt Template in apex using Connect API
- Open Developer Console and Click on File -> New -> Apex Class -> Entere apex class name SocialMediaPostsController
SocialMediaPostsController.apxcpublic with sharing class SocialMediaPostsController { @AuraEnabled public static String generateSocialMediaPosts(String experienceSessionId) { // Create inputs Map<String, String> experienceSession = new Map<String, String>(); experienceSession.put('id', experienceSessionId); ConnectApi.WrappedValue experienceSessionValue = new ConnectApi.WrappedValue(); experienceSessionValue.value = experienceSession; Map<String, ConnectApi.WrappedValue> inputParams = new Map<String, ConnectApi.WrappedValue>(); inputParams.put('Input:experienceSession', experienceSessionValue); // Configure invocation parameters ConnectApi.EinsteinPromptTemplateGenerationsInput executeTemplateInput = new ConnectApi.EinsteinPromptTemplateGenerationsInput(); executeTemplateInput.additionalConfig = new ConnectApi.EinsteinLlmAdditionalConfigInput(); executeTemplateInput.additionalConfig.applicationName = 'PromptBuilderPreview'; executeTemplateInput.isPreview = false; executeTemplateInput.inputParams = inputParams; try { // Call the service ConnectApi.EinsteinPromptTemplateGenerationsRepresentation generationsOutput = ConnectApi.EinsteinLLM.generateMessagesForPromptTemplate( 'Generate_Social_Media_Posts', executeTemplateInput ); ConnectApi.EinsteinLLMGenerationItemOutput response = generationsOutput.generations[0]; return response.text; } catch (Exception e) { System.debug(e.getMessage()); throw e; } } }
In SocialMediaPostsController class we have defined generateSocialMediaPosts method. Which will be call in LWC component later. First let's we understand about class. The generateSocialMediaPosts method accept the experienceSessionId. We have stored this id into Map<String, String>. Then assigned into ConnectApi.WrappedValue. Which accept the value property as object that's required. Here we are using the Connect Api. The Connect in Apex provides programmatic access to B2B Commerce, CMS managed content, Experience Cloud sites, topics, and more. In this class we use connect service as ConnectApi.WrappedValue which is Map of wrapped values, such as free-form user feedback, that can be used to resolve a specified prompt template. It is optional. Now have used of ConnectApi.EinsteinLlmAdditionalConfigInput which is use to configuration information for the LLM provider. it is required. Now we have used of Map<String, ConnectApi.WrappedValue> which is Parameters and values to resolve the specified prompt template. it is also required.
3. Check the code from "Execute Anonymous Window"
Enter_Apex_CodeSession__c experienceSession = [SELECT Id FROM Session__c LIMIT 1]; String socialPosts = SocialMediaPostsController.generateSocialMediaPosts(experienceSession.Id); System.debug(socialPosts);
Click on Execute to run the code
4. Create a LWC component to Generative AI
In this step we'll create lwc component to call generateSocialMediaPosts method. Let's create the create component. Give the component name generateSocialMediaPosts. In this component we have call generateSocialMediaPost() This method will take experienceSessionId parameter which current recordId.
generateSocialMediaPosts.html<template> <lightning-card title="Generate Social Media Posts" icon-name="utility:socialshare"> <div class="slds-var-p-around_small"> <template lwc:if={error}> {error} <lightning-button onclick={generateSocialMediaPosts} label="Try again!" class="slds-align_absolute-center" ></lightning-button> </template> <template lwc:else> <lightning-button onclick={generateSocialMediaPosts} label="Generate Social Media Posts"></lightning-button> <div class="slds-var-p-top_small"> <lightning-textarea name="twitter" readonly value={twitterPost} label="Twitter Post" ></lightning-textarea> </div> <div class="slds-var-p-top_small"> <lightning-textarea name="linkedin" readonly value={linkedinPost} label="Linkedin Post"></lightning-textarea> </div> <div class="slds-var-p-top_small"> <lightning-textarea name="slack" readonly value={slackPost} label="Slack Post"></lightning-textarea> </div> </template> <template lwc:if={showSpinner}> <lightning-spinner alternative-text="Loading..." size="small"></lightning-spinner> </template> </div> </lightning-card> </template>
generateSocialMediaPosts.jsimport { api, LightningElement } from "lwc"; import generateSocialMediaPosts from "@salesforce/apex/SocialMediaPostsController.generateSocialMediaPosts"; export default class GenerateSocialMediaPosts extends LightningElement { twitterPost; linkedinPost; slackPost; error; showSpinner = false; @api recordId; async generateSocialMediaPosts() { this.showSpinner = true; try { const posts = await generateSocialMediaPosts({ experienceSessionId: this.recordId }); const parsedPosts = JSON.parse(posts); this.twitterPost = parsedPosts.twitter; this.linkedinPost = parsedPosts.linkedin; this.slackPost = JSON.stringify(parsedPosts.blockkit); this.error = undefined; } catch (error) { this.twitterPost = undefined; this.linkedinPost = undefined; this.error = error; } finally { this.showSpinner = false; } } }
generateSocialMediaPosts.js-meta.xml<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>64.0</apiVersion> <isExposed>true</isExposed> <masterLabel>Generate Social Media Posts</masterLabel> <targets> <target>lightning__RecordPage</target> </targets> <targetConfigs> <targetConfig targets="lightning__RecordPage"> <objects> <object>Session__c</object> </objects> <supportedFormFactors> <supportedFormFactor type="Large" /> <supportedFormFactor type="Small" /> </supportedFormFactors> </targetConfig> </targetConfigs> </LightningComponentBundle>
5. Last is Add LWC component on record page
Now our code is ready to deploy.
- To deploye right click and click on Deploy This Source to Org.
- Go to Experience Session record page.
- Click on Gear icon and Click on Edit Page.
- Drag and drop generateSocialMediaPosts component at the right side.
- Now it's ready to use. Click on Generate Social Media Posts button.
Now we can see here social media post is generated.
Summary
Perfect for businesses that need to automatically generate social media content from their Salesforce data, particularly useful for experience-based businesses like resorts, event organizers, or service providers who want to streamline their social media marketing efforts. The solution demonstrates the power of combining Salesforce's AI capabilities with custom development to create practical, business-focused applications that enhance productivity and marketing efficiency.