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:

  • Scalability: Apex batchable class handle large volumes via scope processing.
  • Resilience: Errors per record are logged; one failure won’t block the rest.
  • Native AI Integration: No external calls—Salesforce-hosted Gen AI via aiplatform.ModelsAPI.

Gotchas:

  • Be mindful of governor limits, especially around callouts.
  • Handle empty or null AI responses gracefully.
  • Use Database.Stateful if you need to retain intermediate state across batches.

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

  • Implements: Database.Batchable<SObject>, Database.Stateful
    Enables scalable processing and state retention if needed.
  • start():
    Queries all Contact records with FirstName, LastName, Title, and Description.
  • execute():
    • Loops over each Contact in the current scope.
    • Constructs a prompt using contact details.
    • Calls aiplatform.ModelsAPI.createGenerations() using the GPT-4 Omni Mini model.
    • Parses the AI-generated email from the response.
    • Updates the Description field with the generated content
    • Handles per-record and bulk DML errors gracefully.
  • finish():
    Logs successful batch completion.
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

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’s AI Models API.

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

One comment

Leave a Reply