Appearance
Exercise 1: Invoke Prompt Templates from Apex and Lightning Web Components โ
In this exercise, you will create a Flex Template that generates social media posts for resort experiences. You will instruct the template to output the posts content in JSON. You will then invoke that template from an Apex class. Finally, you will create Lightning Web Component that allows users to generate social media posts using the Apex class and the Flex template you created.
Step 1: Create an Advanced Prompt Template โ
In this step youโll create a prompt template that creates social media posts for Coral Cloud Resorts experiences.
Open the Setup Menu and click Setup.
In the quick find, search for Prompt Builder and click Prompt Builder.
Click on New Prompt Template.
Configure the prompt template as follows
Field Value Prompt Template Type Flex Prompt Template Name Generate Social Media Posts
API Name Leave default Template Description This template is used to generate social media posts that promote an experience session for Twitter, LinkedIn and Slack
Add a new resource and configure it as follows
Field Value Name Experience Session
API Name experienceSession
Object Experience Session TIP
Make sure you spell the API Name exactly as above (lowercase e, upper case S, no hyphen).
Click on Next.
Add the following text to the prompt template:
txtYou'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.
TIP
The technique of passing examples of the format that it should return to the LLM is called โfew-shot promptingโ.
In the Preview panel, select EI-00002108 for the Experience Session.
Click Save & Preview, and explore the prompt Resolution and Response.
Activate the prompt template.
Step 2: Execute a Prompt Template using the Connect API in Apex โ
In this step youโll use the Connect API to execute a prompt from Apex.
From App Launcher, open Code Builder.
Click Launch.
Once it is loaded, open the command palette (CMD+SHIFT+ P on Mac or CTRL+SHIFT+P on PC).
Search for Apex and click Create Apex Class.
Enter SocialMediaPostsController as the class name and accept the default directory.
Replace the default Apex class with the following code:
apexpublic 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; } } }
The
generateSocialMediaPosts()
method is defined as an@AuraEnabled
so that it can be invoked from a Lightning Component. The method takes in an Experience Session record Id that it passes into the Generate Social Media Posts prompt template.
The Connect API exposes an EinsteinLLM class that can be used to set up your inputs and invoke prompt templates.Save the file. (CMD+S on Mac or CTRL+S on PC).
Right click anywhere in the code and click SFDX: Deploy This Source to Org.
Step 3: Test the code with anonymous Apex โ
Test the class in execute anonymous, passing in an experienceSessionId
and make sure it returns the LLM response correctly.
Navigate to the scripts/apex directory in your dx-project
Open the hello.apex file
Paste the following code:
apexSession__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
Review the output
Step 4: Create a Lightning Web Component that uses Generative AI โ
In this step youโll invoke the generateSocialMediaPosts()
method from a Lightning Web Component (LWC) to allowusers to generate social media posts directly from an experience session record page.
In Code Builder, open the command palette (CMD+SHIFT+ P on Mac or CTRL+SHIFT+P on PC).
Search for LWC and click Create Lightning Web Component.
Enter generateSocialMediaPosts as the name
Accept the default location
Open generateSocialMediaPosts.html
Replace its content with the following code:
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>
This HTML file defines the UI of the component and includes a button that will execute the prompt template.
Save the file. (CMD+S on Mac or CTRL+S on PC).
Open generateSocialMediaPosts.js
Replace its content with the following code:
javascriptimport { 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; } } }
This JavaScript code imports the
generateSocialMediaPosts()
method from the SocialMediaPostsController Apex Class. When the Generate Social Media Posts button is clicked it passes the experienceSessionId into the method and returns the response generated by the LLM.Save the file. (CMD+S on Mac or CTRL+S on PC).
Open the generateSocialMediaPosts.js-meta.xml.
Replace its content with the following code:
xml<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>60.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>
This XML will allow the component to be exposed on the Experience Session record page.
Save the file. (CMD+S on Mac or CTRL+S on PC).
Right click anywhere in the code and click SFDX: Deploy This Source to Org.
Step 5: Add your component to the Experience Session record page โ
In the App Launcher, select the Coral Cloud app, click the Experiences tab, and click the Aqua Fitness in Paradise record.
Click the Related tab and click one of the sessions to open the Experience Session record page
Open the Setup menu and click Edit Page.
Drag the Generate Social Media Posts custom component and drop it into the right hand side area of the record page.
Click Save.
Click Activate and Assign as Org Default for Desktop and Phone.
Click the back arrow button to get back to Experience Session record
Go back to the Experience Session record page and click on the Generate Social Media Posts button.
You can see that the prompt was invoked and created social media posts for Twitter, LinkedIn and Slack.