Snippet: How to Use Generative AI in Salesforce for Real-Time Case Classification and Data Validation

Learn how to integrate Google Gemini with Salesforce Apex to automatically classify Cases and validate data in real time, improving routing accuracy and SLA compliance.

image
AI working behind the scenes to bring order to data, generated by Gemini Pro

Why This Matters

Salesforce orgs are evolving beyond static validation rules. Service teams face a recurring challenge: incoming cases are often misclassified by users or customers, causing poor routing, SLA breaches, and manual rework.

This post shows you how to go beyond summarization use cases for AI by integrating Salesforce with Google’s Gemini to intelligently validate and classify Case records — all in real time, directly within your org.

Problem Statement

Incorrect picklist values for fields like Priority or Category can create:

  • SLA breaches from delayed routing
  • Extra workload from manual re-triaging
  • Lost productivity for support agents

Traditional validation rules can’t interpret unstructured text like case descriptions. This is where generative AI changes the game.

Solution Architecture

We’ll use:

  • Apex Trigger: Captures new Case IDs after insert
  • @future Method: Makes asynchronous AI callouts without blocking the transaction
  • Named Credentials: Securely stores API authentication
  • Google Gemini API: Interprets case text and classifies Priority
image

Implementation Guide

This implementation uses Google’s Gemini Pro as the external LLM, but the pattern is adaptable to other providers like OpenAI.

1. Setup in Google AI and Salesforce

  • Get a Google Gemini API Key: Visit Google AI Studio, create a project, and generate an API key.
  • Create a Remote Site Setting: In Salesforce Setup, add a Remote Site Setting for the Google API endpoint: https://generativelanguage.googleapis.com.
  • Create a Named Credential (Alternative to Remote Site): For a more robust solution, create a Named Credential. This would involve creating an External Credential to store the API key and a Named Credential that references it. For this simplified example, we will use the API key directly in the code, but a Named Credential is the best practice.

2. The Apex Trigger (CaseTrigger.cls)

This trigger runs after a Case is inserted and passes new record IDs to the async method.

trigger CaseTrigger on Case (after insert) {
if (Trigger.isAfter && Trigger.isInsert) {
CaseClassifier.classifyCases(Trigger.newMap.keySet());
}
}

3. The Future Method (CaseClassifier.cls)

The @future method queries case details, calls the AI service, and updates Priority if the classification matches expected values.

public class CaseClassifier {
@future(callout=true)
public static void classifyCases(Set<Id> caseIds) {
List<Case> casesToUpdate = new List<Case>();
List<Case> casesToQuery = [
SELECT Id, Subject, Description
FROM Case
WHERE Id IN :caseIds
];

for (Case c : casesToQuery) {
String classification = AIAssistantService.getCasePriority(c.Subject, c.Description);
if (String.isNotBlank(classification) &&
(classification == 'High' || classification == 'Medium'
|| classification == 'Low')) {
c.Priority = classification;
casesToUpdate.add(c);
}
}

if (!casesToUpdate.isEmpty()) {
update casesToUpdate;
}
}
}

4. The Callout Service (AIAssistantService.cls)

This service builds and sends the API request to Google Gemini.

public class AIAssistantService {
// IMPORTANT: Store the API Key in a Named Credential, not in code.
private static final String API_KEY = 'YOUR_GEMINI_API_KEY';

public static String getCasePriority(String subject, String description) {
String endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent';
endpoint += '?key=' + API_KEY;

HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');

String prompt = 'Based on the following case subject and description, classify the priority as only one of the following: High, Medium, or Low. Return only the single word classification and nothing else. Subject: ' + subject + '. Description: ' + description;

// Construct the JSON body for the Gemini API
Map<String, Object> payload = new Map<String, Object>{
'contents' => new List<Object>{
new Map<String, Object>{
'parts' => new List<Object>{
new Map<String, Object>{
'text' => prompt
}
}
}
}
};
req.setBody(JSON.serialize(payload));

try {
Http http = new Http();
HttpResponse res = http.send(req);

if (res.getStatusCode() == 200) {
Map<String, Object> responseBody = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
List<Object> candidates = (List<Object>) responseBody.get('candidates');
if (candidates!= null &&!candidates.isEmpty()) {
Map<String, Object> firstCandidate = (Map<String, Object>) candidates[0];
Map<String, Object> content = (Map<String, Object>) firstCandidate.get('content');
List<Object> parts = (List<Object>) content.get('parts');
Map<String, Object> firstPart = (Map<String, Object>) parts[0];
return ((String) firstPart.get('text')).trim();
}
}
} catch (Exception e) {
System.debug('Error calling AI service: ' + e.getMessage());
}
return null;
}
}

Best Practices

  • Use Named Credentials for API keys — never hardcode.
  • Batch Requests when possible to reduce API costs.
  • Validate AI Responses before updating Salesforce records.
  • Add Fallback Logic for low-confidence or null responses.
  • Monitor API Limits to avoid callout failures during peak load.

Limitations

  • API costs scale with volume — estimate before deploying org-wide.
  • Current logic only classifies Priority, but can be extended.
  • Requires async processing — classification is not instant on save.
  • Works best for languages the AI model supports well.

Alternate Implementation: Using Salesforce Flow Instead of Apex

While the example in this post uses Apex, the same outcome — automatically classifying Case priority with an AI model — can also be achieved using a Record-Triggered Flow.

How It Works in Flow:

  1. Trigger: A Record-Triggered Flow runs after a Case is created.
  2. API Callout: Use an HTTP Callout action (via Named Credentials) to send the case Subject and Description to the Gemini API.
  3. Parse Response: Extract the returned priority classification from the JSON response.
  4. Update Record: Set the Case’s Priority field accordingly.

Pros of the Flow Approach

  • No Code Deployment: Can be built and adjusted entirely within Salesforce Setup.
  • Admin-Friendly: Ideal for orgs without Apex development resources.
  • Faster Iteration: Small prompt changes or endpoint updates can be made without a deployment cycle.

Cons of the Flow Approach

  • Bulk Handling Limits: Flow can struggle with large data volumes or concurrent callouts; Apex handles batching more efficiently.
  • Error Handling: Flow fault paths are simpler but less flexible than try-catch logic in Apex.
  • Complex Logic Scaling: Apex is better suited when the logic extends beyond simple field updates (e.g., multiple classifications, complex routing rules).
  • Performance Tuning: Apex provides more options for optimization and async control.

Bottom line: Flow is a great low-code alternative for smaller-scale, low-volume use cases or when rapid iteration is needed. For high-volume production scenarios with complex error handling, Apex remains the stronger choice.

Alternative AI Providers You Can Use

While this example uses Google Gemini, the architecture works with a variety of AI services — both Salesforce-native and external — depending on your organization’s tools, licensing, and data residency needs.

Salesforce-Native Options

  • Einstein GPT — Fully embedded in Salesforce, allowing prompts and responses to run inside the platform without external API management. Ideal for strict data residency requirements.
  • Einstein Bots + NLP Classification — Can handle simpler classification tasks directly, especially if you want to combine conversational AI with case triaging.
  • Einstein Prediction Builder — No-code model training for classification; great when you have historical data to train on, but lacks the flexibility of LLMs for free-form text interpretation.

External Non-Salesforce Options

  • OpenAI — Widely used LLM with excellent natural language understanding and fine-tuning options. Rich API ecosystem.
  • Anthropic Claude — Known for producing more concise, controlled outputs; good for structured classification tasks.
  • Azure OpenAI Service — Microsoft-hosted GPT models with Azure compliance and enterprise controls.
  • Cohere Command R — Strong at retrieval-augmented generation (RAG) tasks; can be paired with Salesforce knowledge base for context-aware classification.
  • AWS Bedrock — Access to multiple foundation models (Anthropic, AI21, Amazon Titan) under one managed service.

Key Factors in Choosing an AI Provider

  • Data Residency & Compliance: Do you need to keep all data within Salesforce or a specific region?
  • Latency & Throughput: Some APIs handle bulk requests better than others.
  • Cost Structure: Pricing can vary significantly per token or per request.
  • Model Specialization: Some models handle conversational text better, others excel at structured extraction and classification.

Final Thoughts

This integration pattern lets Salesforce move from static validation rules to intent-aware automation, improving both data quality and process efficiency.

By applying generative AI at the point of data entry, you can reduce manual clean-up, route cases faster, and enhance customer experience — without disrupting your existing Salesforce workflows.

💡 Next Step: Try adapting this pattern for Category classification or Case summarization before routing. The same architecture applies with only minor changes to your prompt.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top