Record Summary: A Generic Lightning Web Component to view Record Summary based on Prompt Template

In the world of Salesforce, making data actionable is crucial. Often, we want to understand a record at a glance without having to go through every field and detail. That's where a generic solution like the Record Summary comes in. This blog post will guide you through how I built a Lightning Web Component (LWC) that leverages Einstein’s (Prompt Builder) to generate an instant summary for any record in Salesforce. Inspired by the advanced prompt template usage outlined here, I designed this component to simplify and accelerate the process of understanding your records.

What is Record Summary?

It is a Salesforce Lightning Web Component designed to work with Einstein GPT to provide a summarized view of any Salesforce record. Whether it is an account, a contact, or an opportunity, this LWC can generate a text-based summary that highlights the key details of the record, making it easier for users to make quick decisions.

Think of it as an instant overview that you can place on any record page. It works by utilizing prompts defined in Einstein to retrieve the relevant information and display it in a readable format.

Key Features of Record Summary

  • Einstein GPT Integration: Uses Einstein's powerful language model to summarize the record details in human-readable form.

  • Generic and Reusable: Can be placed on any record type, including custom objects, making it highly versatile.

  • Simple UI: Provides a straightforward user interface, including a "Refresh" button for re-generating summaries.

How Does It Work?

The Record Summary LWC works by calling an Apex class (PromptController) that interacts with Salesforce's Connect API. This class then uses an Einstein prompt to generate a summary for the given record. Let me walk you through each piece.

1. The Apex Class: PromptController

The core logic for generating the summary lives in this Apex class. Here's how it works:

public with sharing class PromptController {
    @AuraEnabled
    public static String summarizeRecord(String recordId, String promptDevName) {
        Map<String, String> property = new Map<String, String>();
        property.put('id', recordId);
        ConnectApi.WrappedValue propertyValue = new ConnectApi.WrappedValue();
        propertyValue.value = property;
        Map<String, ConnectApi.WrappedValue> inputParams = new Map<String, ConnectApi.WrappedValue>();
        inputParams.put('Input:' + Id.valueOf(recordId).getSobjectType().toString(), propertyValue); // Property is the API Name we gave to the input

        ConnectApi.EinsteinPromptTemplateGenerationsInput executeTemplateInput = new ConnectApi.EinsteinPromptTemplateGenerationsInput();
        executeTemplateInput.additionalConfig = new ConnectApi.EinsteinLlmAdditionalConfigInput();
        executeTemplateInput.additionalConfig.applicationName = 'PromptBuilderPreview';
        executeTemplateInput.isPreview = false;
        executeTemplateInput.inputParams = inputParams;
        ConnectApi.EinsteinPromptTemplateGenerationsRepresentation generationsOutput = ConnectApi.EinsteinLLM.generateMessagesForPromptTemplate(
                promptDevName,
                executeTemplateInput
        );
        String responses = '';
        if (!generationsOutput.generations.isEmpty()) {
            List<ConnectApi.EinsteinLLMGenerationItemOutput> einsteinLLMGenerationItemOutputs = generationsOutput.generations;
            for (ConnectApi.EinsteinLLMGenerationItemOutput eachResponse : einsteinLLMGenerationItemOutputs) {
                responses += eachResponse.text;
            }
        }
        return responses;
    }
}

This Apex class takes in the recordId and a promptDevName to generate the summary using Einstein GPT. It creates an input map, passes it to the Einstein template, and processes the output to return a simple string summary.

💡
ConnectApi.EinsteinLLM.generateMessagesForPromptTemplate gets considered as DML, hence do not add Cacheable=true

2. The Lightning Web Component: RecordSummary

The LWC is where the user interacts with the generated summary. The key elements include a simple UI and JavaScript logic to handle data fetching and state management.

<template>
    <lightning-card title="Record Summary (Einstein)">
        <template lwc:if={isDataLoading}>
            <lightning-spinner alternative-text="Loading" size="medium"></lightning-spinner>
        </template>
        <template lwc:else>
            <lightning-button label="Refresh" slot="actions" onclick={callApex}></lightning-button>
            <p class="slds-p-horizontal_small">
                <template lwc:if={dataFromController}>
                    <lightning-formatted-rich-text class="slds-m-around_medium" value={dataFromController}></lightning-formatted-rich-text>
                </template>
                <template lwc:else>
                    <lightning-formatted-rich-text class="slds-m-around_medium slds-text-color_error" value={errorFromController}></lightning-formatted-rich-text>
                </template>
            </p>
        </template>
    </lightning-card>
</template>

This template provides a simple card with a "Refresh" button to re-fetch the record summary. Depending on the state (isDataLoading), it either shows a spinner, an error, or the summary content.

import {api, LightningElement} from 'lwc';
import summarizeRecord from '@salesforce/apex/PromptController.summarizeRecord';

export default class RecordSummary extends LightningElement {
    @api recordId;
    @api promptDevName;
    dataFromController;
    errorFromController;
    isDataLoading;

    async connectedCallback() {
        await this.callApex();
    }

    async callApex() {
        this.isDataLoading = true;
        try {
            this.dataFromController = await summarizeRecord({recordId : this.recordId, promptDevName : this.promptDevName});
        } catch (e) {
            this.errorFromController = JSON.stringify(e);
        } finally {
            this.isDataLoading = false;
        }
    }
}

The JavaScript class handles the data flow for the component. It fetches data when the component is initialized or when the "Refresh" button is pressed. The callApex method uses asynchronous JavaScript to fetch the record summary from the Apex class and manages the loading state to ensure smooth user experience.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>62.0</apiVersion>
    <description>Record Summary</description>
    <isExposed>true</isExposed>
    <masterLabel>Record Summary</masterLabel>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <property name="promptDevName" label="Prompt Dev Name" type="String" required="true"/>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

The Heart of the Component: Prompt Builder

At the core of the RecordSummary component is the Prompt Builder. The Prompt Builder is used to define and configure the prompts that Einstein GPT uses to generate the record summary. This tool allows us to craft detailed instructions on what kind of summary we want Einstein to create, making it extremely flexible for different use cases.

Seeing It In Action

The RecordSummary LWC can be easily placed on any record page in Salesforce using the Lightning App Builder. Once added, it allows users to generate and view a summarized version of the record in real-time.

Here's an example of what the UI looks like:

As you can see, it provides a concise yet informative summary of the record. The Refresh button allows users to re-fetch the summary if data is updated.

In this blog post, I explain how to create a Salesforce Lightning Web Component (LWC) called Record Summary. This component uses Einstein GPT to generate quick, text-based summaries of Salesforce records, from accounts to opportunities, streamlining decision-making. The component integrates with an Apex class to fetch data via Salesforce's Connect API and render it through a simple user interface. The core functionality revolves around a Prompt Builder that defines the desired content for summaries, ensuring versatility and ease of use across various record types.

Did you find this article valuable?

Support Nagendra Singh's blog by becoming a sponsor. Any amount is appreciated!