Simplify your users’ daily tasks by integrating generative-AI moments powered by prompt templates into their workflow. Create, test, revise, customize, and manage prompt templates that incorporate your CRM data from merge fields that reference record fields, flows, related lists, and Apex. Prompt Builder helps you to make effective prompts that safely connect you and your data with LLMs.So we will demonstrate how to we are calling a Flex Prompt template in Apex.
Create different types of prompt templates in Prompt Builder.
- A Sales Email prompt template helps your sales team to draft personalized emails for a contact or a lead.
- A Field Generation prompt template brings generative AI-assisted workflows to fields within Lightning record pages. Enable your users to populate a field with a summary or description created by an LLM to facilitate more productive conversations with your customers.
- A Flex prompt template takes a variable number of inputs of different object types. This flexibility opens up a wide array of possibilities, such as generating a newsletter based on product and campaign objects.
Call a prompt template through an invocable action anywhere on the Salesforce Platform or by using the Connect REST API or Connect in Apex.
In this blog post, we’ll walk through the step-by-step process of calling a Flex Prompt template in an Apex class.
Table of Contents
ToggleUse Case
Let’s say you’re working with Task records related to Opportunities, and each task has a Priority field (High, Normal, Low). You want to get the reason for why that priority might make sense — based on task and opportunity data from the LLM models.
This guide demonstrates how to:
- Fetch tasks related to Opportunities.
- Call a Prompt Template created in Prompt Builder (
task_Priority_Reason
) using Apex. - Return a structured response to Lightning Web Components (LWC).
What is a Flex Prompt Template?
Craft a flex prompt template that uses AI to generate content for your unique business cases.These templates can be called from Apex by name and accept input parameters to generate intelligent responses.
Example :

This prompt accepts input as a string and generates output based on the provided instructions.
Apex Class for Calling a Flex Prompt template in Apex
public with sharing class ApexFlexPromptLWCService {
public class TaskDetail {
@AuraEnabled public String taskId;
@AuraEnabled public String subject;
@AuraEnabled public String status;
@AuraEnabled public String activityDate;
@AuraEnabled public String opportunityName;
@AuraEnabled public String opportunityStage;
@AuraEnabled public String priority;
@AuraEnabled public String reason;
}
@AuraEnabled(cacheable=false)
public static List<TaskDetail> getOpportunityTasksPrompt() {
List<Task> taskList = [
SELECT Id, Subject, Status, ActivityDate, Priority, WhatId
FROM Task
WHERE WhatId IN (SELECT Id FROM Opportunity)
ORDER BY ActivityDate DESC
LIMIT 20
];
Set<Id> oppIds = new Set<Id>();
for (Task t : taskList) {
if (t.WhatId != null && String.valueOf(t.WhatId).startsWith('006')) {
oppIds.add(t.WhatId);
}
}
Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>(
[SELECT Id, Name, StageName FROM Opportunity WHERE Id IN :oppIds]
);
List<TaskDetail> results = new List<TaskDetail>();
for (Task t : taskList) {
TaskDetail detail = new TaskDetail();
detail.taskId = t.Id;
detail.subject = t.Subject;
detail.status = t.Status;
detail.activityDate = String.valueOf(t.ActivityDate);
detail.priority = t.Priority;
Opportunity opp = oppMap.get(t.WhatId);
if (opp != null) {
detail.opportunityName = opp.Name;
detail.opportunityStage = opp.StageName;
}
detail.reason = getPriorityReason(detail);
results.add(detail);
}
return results;
}
public static String getPriorityReason(TaskDetail task) {
String input = 'Task Subject: ' + task.subject +
', Status: ' + task.status +
', Due Date: ' + task.activityDate +
', Priority: ' + task.priority +
', Opportunity Name: ' + task.opportunityName +
', Opportunity Stage: ' + task.opportunityStage;
ConnectApi.WrappedValue wrappedInput = new ConnectApi.WrappedValue();
wrappedInput.value = input;
Map<String, ConnectApi.WrappedValue> inputParams = new Map<String, ConnectApi.WrappedValue>();
inputParams.put('Input:Task', wrappedInput);
ConnectApi.EinsteinPromptTemplateGenerationsInput executeTemplateInput =
new ConnectApi.EinsteinPromptTemplateGenerationsInput();
executeTemplateInput.additionalConfig = new ConnectApi.EinsteinLlmAdditionalConfigInput();
executeTemplateInput.additionalConfig.applicationName = 'PromptBuilderPreview';
executeTemplateInput.isPreview = false;
executeTemplateInput.inputParams = inputParams;
try {
ConnectApi.EinsteinPromptTemplateGenerationsRepresentation response =
ConnectApi.EinsteinLLM.generateMessagesForPromptTemplate(
'task_Priority_Reason',
executeTemplateInput
);
if (response != null && response.generations != null && !response.generations.isEmpty()) {
String responseText = response.generations[0].text;
return responseText;
} else {
return 'No reason generated — empty response.';
}
} catch (Exception e) {
return 'Error: ' + e.getMessage();
}
}
}
Explanation
1. Define the Data Wrapper Class
public class TaskDetail {
@AuraEnabled public String taskId;
@AuraEnabled public String subject;
@AuraEnabled public String status;
@AuraEnabled public String activityDate;
@AuraEnabled public String opportunityName;
@AuraEnabled public String opportunityStage;
@AuraEnabled public String priority;
@AuraEnabled public String reason;
}
This is the wrapper to hold the data.
2. Fetch Tasks Related to Opportunities
List<Task> taskList = [
SELECT Id, Subject, Status, ActivityDate, Priority, WhatId
FROM Task
WHERE WhatId IN (SELECT Id FROM Opportunity)
ORDER BY ActivityDate DESC
LIMIT 20
];
Here we retrieve the 20 most recent tasks that are linked to Opportunity records.
3. Map Related Opportunity Details
Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>(
[SELECT Id, Name, StageName FROM Opportunity WHERE Id IN :oppIds]
);
We prepare a map of Opportunity IDs to their Name
and StageName
.
4. Combine Task + Opportunity Data
for (Task t : taskList) {
TaskDetail detail = new TaskDetail();
...
detail.opportunityName = opp.Name;
detail.opportunityStage = opp.StageName;
detail.reason = getPriorityReason(detail); // ← GPT call
results.add(detail);
}
We map everything into TaskDetail
, and then generate the reason for the task’s priority via getPriorityReason()
.
5. Call Flex Prompt in Apex
public static String getPriorityReason(TaskDetail task) {
String input = 'Task Subject: ' + task.subject +
', Status: ' + task.status +
', Due Date: ' + task.activityDate +
', Priority: ' + task.priority +
', Opportunity Name: ' + task.opportunityName +
', Opportunity Stage: ' + task.opportunityStage;
// Create WrappedValue
ConnectApi.WrappedValue wrappedInput = new ConnectApi.WrappedValue();
wrappedInput.value = input;
// Pass input param map
Map<String, ConnectApi.WrappedValue> inputParams = new Map<String, ConnectApi.WrappedValue>();
inputParams.put('Input:Task', wrappedInput); // name must match prompt template variable
// Configure generation request
ConnectApi.EinsteinPromptTemplateGenerationsInput executeTemplateInput = new ConnectApi.EinsteinPromptTemplateGenerationsInput();
executeTemplateInput.additionalConfig = new ConnectApi.EinsteinLlmAdditionalConfigInput();
executeTemplateInput.additionalConfig.applicationName = 'PromptBuilderPreview';
executeTemplateInput.isPreview = false;
executeTemplateInput.inputParams = inputParams;
try {
ConnectApi.EinsteinPromptTemplateGenerationsRepresentation response =
ConnectApi.EinsteinLLM.generateMessagesForPromptTemplate(
'task_Priority_Reason', // prompt template API name
executeTemplateInput
);
if (response != null && response.generations != null && !response.generations.isEmpty()) {
return response.generations[0].text;
} else {
return 'No reason generated — empty response.';
}
} catch (Exception e) {
return 'Error: ' + e.getMessage();
}
}
In the getPriorityReason
method, we first combine all the relevant task and opportunity data into a single descriptive string. This string acts as a natural language input and is passed to the Flex Prompt Template, which is designed to accept a simple string value .
The prompt template processes this input and uses it to generate a meaningful explanation, the reason behind the task’s priority. The output returned from the prompt template is then stored in the reason
field.
Conclusion
In this blog post, we demonstrated how to call a Flex Prompt Template within an Apex class and effectively use the AI-generated responses for any specific business requirements. By seamlessly integrating Prompt Builder with Apex, you can bring the power of AI into your Salesforce applications — enabling smarter automation, better decision-making, and enhanced user experiences.
Checkout our youtube video on Flex Template.
You can deepen your understanding of Data Cloud by exploring our comprehensive course on Salesforce Data Cloud and Agentforce – Building Agents and also check out our latest blogs on our websites for additional knowledge about salesforce.