Saturday, 27 December 2025

How to Execute Einstein Prompt Templates Using Apex (Calling Salesforce Prompt Templates Programmatically with Apex)

 Hi,

Here, we’ll explore how to execute a Prompt Template using Apex.

To understand this better, let’s take a sample Flex Prompt Template called

“AccountSummaryTemplate”. This template accepts the following inputs:

• query — Free Text  

• account — Object  

When you want to execute a Prompt Template programmatically from Apex, you must use the Salesforce Connect API. The Connect API enables Apex to interact with Einstein generative AI features, including Prompt Templates.

Prompt: AccountSummaryTemplate




Prompt Preview:




Apex Code: 

 //Create inputs

        //For Free Text types

        ConnectApi.WrappedValue queryValue = new ConnectApi.WrappedValue();

        queryValue.value = 'Provide a brief summary of account in a few lines'; // The actual string value

        //For Object types

        Map<String, String> accountMap = new Map<String, String>();

        accountMap.put('id', '001J900000HlQWeIAN'); //Here we just need to pass record id instead of complete record (Object)

        ConnectApi.WrappedValue accountValue = new ConnectApi.WrappedValue();

        accountValue.value = accountMap;

    //Prepare InputParams 

        Map<String, ConnectApi.WrappedValue> inputParams = new Map<String, ConnectApi.WrappedValue>();

        inputParams.put('Input:account', accountValue);

        inputParams.put('Input:query', queryValue);


        // 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(

                'AccountSummaryTemplate',

                executeTemplateInput

            );

            ConnectApi.EinsteinLLMGenerationItemOutput response = generationsOutput.generations[0];

            System.debug('Output----'+response.text);

           

        } catch (Exception e) {

            System.debug(e.getMessage());

            throw e;

        }



Output:



Reference:


No comments:

Post a Comment

How to Execute Einstein Prompt Templates Using Apex (Calling Salesforce Prompt Templates Programmatically with Apex)

 Hi, Here, we’ll explore how to execute a Prompt Template using Apex. To understand this better, let’s take a sample Flex Prompt Template ca...