Site icon Salesforce Diaries

Agentforce Models AI API in Batch Class

Agentforce Models AI API is opening exciting doors for developers by integrating AI natively into Apex. A powerful pattern emerging (AI + Apex) by using Database.Batchable to orchestrate generative model calls at scale. Let’s break it down with a practical use case: generating welcome emails for new developers using Salesforce AI Models API.

The approach involves implementing a Database.Batchable<SObject> class that iterates over Contact records. For each record, we construct a prompt using basic String.format, inject the Contact’s name and title, and send it to the AI platform.

Key Benefits:

Gotchas:

This design pattern can be extended to onboarding sequences, support replies, or summary generation. Agentforce is here—and with it, Apex just got smarter.

The BatchGenerateWelcomeEmails class is an Apex batch job that uses Salesforce’s AI Models API to generate personalized welcome emails for Contact records.

BatchGenerateWelcomeEmails.cls

global class BatchGenerateWelcomeEmails implements Database.Batchable<SObject>, Database.Stateful {

    private static final String MODEL_NAME = 'sfdc_ai__DefaultOpenAIGPT4OmniMini';
    private static final String PROMPT_TEMPLATE = 
        'Generate a friendly welcome email for a new developer named {0} {1}, who recently joined as a {2}.';

    global Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([
            SELECT Id, FirstName, LastName, Email, Title, Description FROM Contact
        ]);
    }

    global void execute(Database.BatchableContext context, List<SObject> scope) {
        if (scope == null || scope.isEmpty()) {
            return;
        }

        List<Contact> contactsToUpdate = new List<Contact>();
        aiplatform.ModelsAPI modelsAPI = new aiplatform.ModelsAPI();

        for (SObject sObj : scope) {
            Contact contact = (Contact) sObj;

            String prompt = String.format(
                PROMPT_TEMPLATE,
                new List<String>{
                    String.valueOf(contact.FirstName),
                    String.valueOf(contact.LastName),
                    String.valueOf(contact.Title)
                }
            );

            aiplatform.ModelsAPI.createGenerations_Request request = new aiplatform.ModelsAPI.createGenerations_Request();
            request.modelName = MODEL_NAME;

            aiplatform.ModelsAPI_GenerationRequest requestBody = new aiplatform.ModelsAPI_GenerationRequest();
            requestBody.prompt = prompt;
            request.body = requestBody;

            try {
                aiplatform.ModelsAPI.createGenerations_Response response = modelsAPI.createGenerations(request);
                String emailText = (response != null && response.Code200 != null)
                    ? response.Code200.generation.generatedText
                    : null;

                if (String.isNotBlank(emailText)) {
                    contact.Description = emailText; // Use a custom field if available
                    contactsToUpdate.add(contact);
                }

            } catch (aiplatform.ModelsAPI.createGenerations_ResponseException apiEx) {
                System.debug(LoggingLevel.ERROR, 'AI API error for Contact: ' + contact.Id + ' => ' + apiEx.getMessage());
            } catch (Exception ex) {
                System.debug(LoggingLevel.ERROR, 'Unexpected error for Contact: ' + contact.Id + ' => ' + ex.getMessage());
            }
        }

        if (!contactsToUpdate.isEmpty()) {
            try {
                Database.SaveResult[] results = Database.update(contactsToUpdate, false);

                for (Integer i = 0; i < results.size(); i++) {
                    Contact c = contactsToUpdate[i];
                    if (results[i].isSuccess()) {
                        System.debug(LoggingLevel.INFO, 'Successfully updated Contact: ' + c.Id);
                    } else {
                        for (Database.Error err : results[i].getErrors()) {
                            System.debug(LoggingLevel.ERROR, 'Failed to update Contact: ' + c.Id + ' => ' + err.getMessage());
                        }
                    }
                }

            } catch (DmlException dmlEx) {
                System.debug(LoggingLevel.ERROR, 'Bulk DML error while updating contacts => ' + dmlEx.getMessage());
            }
        }
    }

    global void finish(Database.BatchableContext context) {
        System.debug(LoggingLevel.INFO, 'BatchGenerateWelcomeEmails batch completed successfully.');
    }
}

🚀 Demo: Running the AI-Powered Welcome Email Generator using Agentforce Models AI API

Execute this in anonymous Apex to start the batch:

Database.executeBatch(new BatchGenerateWelcomeEmails(), 10);

Check the Results

Go to Contacts in Salesforce and open the records you have. You’ll see the AI-generated welcome email in the Description field

Monitor the Batch

Use Setup → Apex Jobs to monitor batch progress and check for errors or logs in the Developer Console.

Do you need help?

Are you stuck while working on this requirement? Do you want to get review of your solution? Now, you can book dedicated 1:1 with me on Lightning Web Component and Agentforce completely free.

GET IN TOUCH

Schedule a 1:1 Meeting with me

Exit mobile version