Beyond Einstein: Building a Custom AI Sales Agent in Salesforce
A hands-on build for Salesforce developers. You store an OpenAI key in an External Credential, write one invocable Apex action that sends Opportunity facts to the Responses API, call it from the asynchronous path of a record-triggered Flow, and test it with HttpCalloutMock. Includes the callout limits that shape the design and when Prompt Builder is the better choice.

This guide is for Salesforce developers who want an LLM to write something useful onto a record, without middleware. You will build one invocable Apex action that sends Opportunity facts to an LLM, call it from a record-triggered Flow, and keep the API key out of your code. The result is a short meeting brief that appears on the Opportunity when a rep moves it to a new stage.
Key takeaways
- Keep the API key in an External Credential. Apex points at
callout:Your_Named_Credentialand never sees the secret. - A record-triggered Flow can't make a callout while the record is saving. Put the Apex action on the asynchronous path.
- Send only the facts the model needs, ask for plain text, and test the action with
HttpCalloutMockbefore it calls a real model.
What you are building
A rep moves an Opportunity to "Value Proposition". A few seconds later, a field called AI Brief fills with three talking points based on the account, industry, stage and amount.
The pieces:
| Piece | Job |
|---|---|
| External Credential + Named Credential | Store the API key and the base URL |
| Invocable Apex action | Read the record, call the model, return the text |
| Record-triggered Flow (async path) | Decide when to run, then write the result to the record |
HttpCalloutMock test |
Prove the parsing works without a real call |
Strictly speaking, this is a single LLM call inside a workflow, not an agent. The model doesn't pick tools or steps. If that difference matters to your design, read LLMs vs AI agents vs workflows first. For most CRM tasks, a fixed workflow like this is easier to test and to trust.
Pick the right tool first
An invocable Apex action is an Apex method marked with @InvocableMethod, which Flow, REST and Agentforce can run as an action. It's one of three ways to get an LLM answer onto a record:
| Option | What it does | Trade-off | Use it when |
|---|---|---|---|
| Prompt Builder | Prompt templates grounded in record fields, flows, related lists and Apex | Needs the Salesforce generative AI features in your org | Your org already has them and the built-in models fit |
| Flow HTTP Callout | Admins call an external API from Flow without code | You map the JSON response by hand in Flow | The response is simple and an admin owns it |
| Invocable Apex (this guide) | Your code builds the prompt, calls the model and parses the reply | You own the code, tests and upgrades | You need custom parsing, error handling or a specific provider |
The Prompt Builder and HTTP Callout rows come from the Salesforce docs listed under Sources. Which one is cheaper for you depends on your licences, so check your own contract.
Step 1: Store the key in an External Credential
Never put the key in Apex, a custom setting or a custom label. Salesforce's guide recommends storing an API key as an authentication parameter on an External Credential principal, where it's encrypted and granted only through permission sets.
// Don't: the key lives in code, in every sandbox copy and in version control.
req.setEndpoint('https://api.openai.com/v1/responses');
req.setHeader('Authorization', 'Bearer sk-...');
// Do: the Named Credential supplies the URL and the header.
req.setEndpoint('callout:OpenAI_API/v1/responses');
Set it up in Setup > Named Credentials:
- External Credential. Create one named
OpenAIand set Authentication Protocol to Custom. - Principal. Under Principals, click New. Add an authentication parameter named
ApiKeyand paste your OpenAI key as its value. Custom authentication always uses the Named Principal identity type, so every mapped user shares this one key. - Custom header. Under Custom Headers, add a header named
Authorizationwith the value{!'Bearer ' & $Credential.OpenAI.ApiKey}. OpenAI expects a Bearer token in that header. - Named Credential. Create one named
OpenAI_APIwith the URLhttps://api.openai.com, and pick theOpenAIexternal credential. Turn off Generate Authorization Header, and turn on Allow Formulas in HTTP Header. - Access. Map the principal to a permission set, and assign it to the users the flow runs as. Salesforce's guide also says to enable user external credentials for those users.
The Apex guide adds a bonus: a callout to a Named Credential skips Remote Site Settings, and Salesforce handles the authentication. If the URL changes, you edit the credential, not the code.
Check who the flow runs as
The principal mapping only works for users who hold that permission set. After your first test run, open the debug log for the async path and confirm the running user. If the callout fails with an authentication error, that user is usually missing the permission set.
Step 2: Write the invocable action
The action takes a list of requests and returns one result per request, in the same order. The InvocableMethod docs require this so that bulk runs from a record-triggered flow map each result to the right record.
The callout=true modifier tells Flow this method calls an external system. Per the Apex guide, Flow uses it to decide whether a screen flow can run the action safely in the current transaction. It costs nothing to add, so add it.
public with sharing class OpportunityBriefAction {
private static final String SYSTEM_PROMPT =
'You are a sales assistant. Reply in plain text, at most 120 words. '
+ 'Give three talking points for the next meeting. '
+ 'Use only the facts provided. If a fact is missing, say so.';
public class LlmException extends Exception {}
public class BriefRequest {
@InvocableVariable(label='Opportunity ID' required=true)
public Id opportunityId;
@InvocableVariable(label='Model ID' description='Copy it from the provider models page' required=true)
public String modelId;
}
public class BriefResult {
@InvocableVariable(label='Brief')
public String brief;
@InvocableVariable(label='Error')
public String error;
}
@InvocableMethod(
label='Generate Opportunity Brief'
description='Asks an LLM for three talking points about an Opportunity'
category='AI'
callout=true
)
public static List<BriefResult> generate(List<BriefRequest> requests) {
Set<Id> oppIds = new Set<Id>();
for (BriefRequest r : requests) {
oppIds.add(r.opportunityId);
}
Map<Id, Opportunity> opps;
String queryError;
try {
opps = new Map<Id, Opportunity>([
SELECT Id, Name, StageName, Amount, Account.Name, Account.Industry
FROM Opportunity
WHERE Id IN :oppIds
WITH USER_MODE
]);
} catch (QueryException e) {
// The running user can't read a field; report it on every result instead of failing the batch.
queryError = 'Query failed: ' + e.getMessage();
}
List<BriefResult> results = new List<BriefResult>();
for (BriefRequest r : requests) {
BriefResult res = new BriefResult();
Opportunity opp = opps == null ? null : opps.get(r.opportunityId);
if (queryError != null) {
res.error = queryError;
} else if (opp == null) {
res.error = 'Opportunity not found or not visible to the running user';
} else if (Limits.getCallouts() >= Limits.getLimitCallouts()) {
res.error = 'Callout limit reached in this transaction';
} else {
try {
res.brief = callModel(r.modelId, buildPrompt(opp));
} catch (Exception e) {
res.error = e.getMessage();
}
}
results.add(res);
}
return results;
}
@TestVisible
private static String buildPrompt(Opportunity opp) {
return 'Account: ' + orNotSet(opp.Account?.Name) + '\n'
+ 'Industry: ' + orNotSet(opp.Account?.Industry) + '\n'
+ 'Opportunity: ' + opp.Name + '\n'
+ 'Stage: ' + opp.StageName + '\n'
+ 'Amount: ' + orNotSet(opp.Amount);
}
private static String orNotSet(Object value) {
return value == null ? 'not set' : String.valueOf(value);
}
private static String callModel(String modelId, String prompt) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:OpenAI_API/v1/responses');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(60000); // the HttpRequest maximum is 120,000 ms
req.setBody(JSON.serialize(new Map<String, Object>{
'model' => modelId,
'instructions' => SYSTEM_PROMPT,
'input' => prompt,
'max_output_tokens' => 600,
'store' => false
}));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new LlmException('LLM call failed with HTTP ' + res.getStatusCode());
}
return extractText(res.getBody());
}
@TestVisible
private static String extractText(String body) {
Map<String, Object> parsed = (Map<String, Object>) JSON.deserializeUntyped(body);
if (!'completed'.equals(parsed.get('status'))) {
// e.g. "incomplete" when max_output_tokens is hit: still HTTP 200, but no usable text
throw new LlmException('LLM response status ' + parsed.get('status')
+ ', details: ' + JSON.serialize(parsed.get('incomplete_details')));
}
List<Object> output = (List<Object>) parsed.get('output');
String text = '';
for (Object itemObj : output == null ? new List<Object>() : output) {
Map<String, Object> item = (Map<String, Object>) itemObj;
if (!'message'.equals(item.get('type'))) {
continue;
}
for (Object partObj : (List<Object>) item.get('content')) {
Map<String, Object> part = (Map<String, Object>) partObj;
if ('output_text'.equals(part.get('type'))) {
text += (String) part.get('text');
}
}
}
if (String.isBlank(text)) {
throw new LlmException('LLM response contained no text');
}
return text;
}
}
Checked against the Apex Developer Guide (Winter '27, API 68.0) and the OpenAI Responses API reference, 2026-10-29. Apex can't run outside an org, so this code was reviewed against the docs but not compiled or run.
A few choices in that code are worth a closer look.
The model id comes from Flow, not Apex. Apex has no environment variables. Passing the id as an input lets an admin change models in Flow Builder without a deployment. On 2026-10-29, OpenAI's models page lists gpt-6-luna as its cheapest model for high-volume, focused tasks, which suits a short brief. Model ids change often, so check that page before you pick one.
store: false asks OpenAI not to keep the response. The API reference says responses are stored for at least 30 days when this is left out. CRM data has no reason to sit there.
The reply is read by type, not by position. OpenAI's text guide warns that the output array often holds more than one item, such as reasoning data. It says it's not safe to assume the text is at output[0].content[0].text.
// Don't: breaks as soon as a reasoning item comes first.
String text = (String) ((Map<String, Object>) ((List<Object>)
((Map<String, Object>) ((List<Object>) parsed.get('output'))[0]).get('content'))[0]).get('text');
// Do: walk the items and keep only message text, as extractText does.
String text = extractText(res.getBody());
A 200 isn't always an answer. The API reference lists six response statuses: completed, failed, in_progress, cancelled, queued and incomplete. A reply cut off by max_output_tokens comes back as incomplete, with the reason in incomplete_details. extractText throws on anything but completed, and on blank text, so the Flow never writes an empty brief.
Errors come back as data. The InvocableMethod docs say the method must return as many results as it received, even when some fail. So each failure fills the error field instead of throwing. A failed callout or parse affects only its own record. If the query itself fails, for example because the running user can't read a field, every result carries that error and the Flow can report it.
Step 3: Call it from a record-triggered Flow
Salesforce's Record-Triggered Flow Considerations page is clear: a flow fails if it tries to reach an external system in its synchronous path, because callouts can't run while a record is saving. The fix is the asynchronous path, which runs after the save is committed.
- Create a Record-Triggered Flow on Opportunity, triggered when a record is updated.
- Set the entry condition to
StageNameequalsValue Proposition, and choose Only when a record is updated to meet the condition requirements. That stops the flow from firing again when it writes the brief. - Choose Actions and Related Records, then turn on the Add Asynchronous Path toggle.
- On the Run Asynchronously path, add an Action element and pick Generate Opportunity Brief. Map
{!$Record.Id}to Opportunity ID, and type the model id into Model ID. - Add a Decision: if the action's Error output is null, go on. Otherwise, log or notify, and stop.
- Add an Update Records element that sets the triggering Opportunity's
AI_Brief__cto the action's Brief output.
Create AI_Brief__c as a Long Text Area field first. The same page notes that asynchronous paths don't support the ISCHANGED operator, which is why the entry condition does the filtering.
Want a button instead?
Build a screen flow that calls the same action. For screen flows, the callout=true modifier lets Flow commit pending work and start a new transaction before the callout, when the action's transaction setting lets the flow decide.
Step 4: Test it without a real call
You don't want a test to call a real model. The Apex guide's answer is HttpCalloutMock: you register a fake response with Test.setMock, and the runtime returns it instead of calling out. The first test puts a reasoning item before the message, so it proves the parser doesn't depend on position. The second sends an incomplete reply and checks that it comes back as an error, not a blank brief.
@IsTest
private class OpportunityBriefActionTest {
private static final String COMPLETED = '{"status":"completed","output":['
+ '{"type":"reasoning","summary":[]},'
+ '{"type":"message","role":"assistant","content":'
+ '[{"type":"output_text","text":"Point one."}]}]}';
private static final String INCOMPLETE = '{"status":"incomplete",'
+ '"incomplete_details":{"reason":"max_output_tokens"},'
+ '"output":[{"type":"reasoning","summary":[]}]}';
private class FakeLlm implements HttpCalloutMock {
private String body;
FakeLlm(String body) {
this.body = body;
}
public HttpResponse respond(HttpRequest req) {
Assert.areEqual('callout:OpenAI_API/v1/responses', req.getEndpoint());
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setHeader('Content-Type', 'application/json');
res.setBody(body);
return res;
}
}
private static OpportunityBriefAction.BriefRequest makeRequest() {
Account acc = new Account(Name = 'Acme');
insert acc;
Opportunity opp = new Opportunity(
Name = 'Acme renewal',
AccountId = acc.Id,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
);
insert opp;
OpportunityBriefAction.BriefRequest r = new OpportunityBriefAction.BriefRequest();
r.opportunityId = opp.Id;
r.modelId = 'test-model';
return r;
}
@IsTest
static void returnsOneBriefPerRequest() {
OpportunityBriefAction.BriefRequest r = makeRequest();
Test.setMock(HttpCalloutMock.class, new FakeLlm(COMPLETED));
Test.startTest();
List<OpportunityBriefAction.BriefResult> out =
OpportunityBriefAction.generate(new List<OpportunityBriefAction.BriefRequest>{ r });
Test.stopTest();
Assert.areEqual(1, out.size());
Assert.areEqual('Point one.', out[0].brief);
Assert.isNull(out[0].error);
}
@IsTest
static void reportsIncompleteReplyAsError() {
OpportunityBriefAction.BriefRequest r = makeRequest();
Test.setMock(HttpCalloutMock.class, new FakeLlm(INCOMPLETE));
Test.startTest();
List<OpportunityBriefAction.BriefResult> out =
OpportunityBriefAction.generate(new List<OpportunityBriefAction.BriefRequest>{ r });
Test.stopTest();
Assert.isNull(out[0].brief);
Assert.isNotNull(out[0].error);
Assert.isTrue(out[0].error.contains('max_output_tokens'));
}
}
Each test inserts its records before Test.startTest() and calls out inside it. If your org uses custom stage values, swap Prospecting for one that exists. Like the action, these tests were checked against the docs but not run in an org.
Limits that shape the design
The numbers below come from Salesforce's Execution Governors and Limits page and the HttpRequest reference.
| Limit | Value | What it means here |
|---|---|---|
| Callouts per transaction | 100 | The action checks Limits.getCallouts() and returns an error instead of crashing |
| Cumulative callout timeout per transaction | 120 seconds | A few slow model replies can use it all up |
| Default callout timeout | 10 seconds | Too short for many LLM replies, so the code sets 60 seconds |
setTimeout range |
1 to 120,000 ms | No single call can wait longer than two minutes |
As a rule of thumb, this design suits one record at a time, such as a rep changing a stage. A data load that updates hundreds of Opportunities at once would queue hundreds of model calls and hit the timeout budget. Exclude bulk loads in the entry condition, or move that path to Batch Apex with a small scope.
Send less, trust less
The prompt sends the account name, industry, stage and amount. It sends no contact names, emails or contract terms. Before you add a field to the prompt, ask whether the model needs it, and whether your data agreement allows it to leave Salesforce.
The query runs WITH USER_MODE, so the running user's field and object access applies. The security architecture day of the Headless 360 series covers least-privilege setup in more depth.
Treat the reply as untrusted text. OWASP lists improper output handling as a top LLM risk and advises treating the model like any other user. This build asks for plain text and stores it in a Long Text Area, so nothing the model writes is rendered as HTML.
The earlier version of this post asked the model for "recent news" about the account. A model without a search tool can't know recent news, so it may invent it. The prompt now uses only facts from the record, and tells the model to say when a fact is missing. Giving the model your own record data like this is often called grounding.
Where to go next
When the brief works, the next questions are about validation, evaluation and cost. Calling an LLM from Apex: where Python still wins covers the parts Apex handles least well. If you want an AI client to read and update Salesforce data through MCP instead, start with the 15 Days of Salesforce Headless 360 series.
Frequently asked questions
Can a record-triggered Flow call an external API?
Yes, but not on the path that runs immediately. Salesforce blocks callouts while a record is saving, so a callout there makes the flow fail. Turn on the asynchronous path and put the Apex action there; it runs after the save is committed.
Do I still need @future or Queueable for the callout?
Not for this build. The asynchronous path already runs the action outside the save, so the action can call out directly. You'd reach for Queueable or Batch Apex when you process many records in one go and need to spread callouts across transactions.
Where should the OpenAI API key live in Salesforce?
In an authentication parameter on an External Credential principal, sent through a custom Authorization header. Salesforce stores it encrypted and grants access through permission sets. Apex only references the Named Credential, as callout:OpenAI_API/....
Why does the action return an error field instead of throwing?
The InvocableMethod docs require one result per input, in the same order, even when some inputs fail. Returning the error as data keeps that promise. It also lets the Flow decide what to do, such as notifying an admin.
Can I use Claude or another model instead of OpenAI?
Yes. Point a new Named Credential at the provider's API, change the request body to that provider's format, and update extractText to match its response. Check the provider's models page for current ids, and pass the id from Flow as before.
Sources
Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.
- Apex Developer Guide: InvocableMethod Annotation
- Apex Developer Guide: Making Callouts to External Systems from Invocable Actions
- Apex Developer Guide: Named Credentials as Callout Endpoints
- Salesforce Help: Use API Keys in Custom Headers with Named Credentials
- Salesforce Help: Record-Triggered Flow Considerations
- Apex Developer Guide: Execution Governors and Limits
- Apex Reference Guide: HttpRequest Class
- Apex Developer Guide: Testing HTTP Callouts with HttpCalloutMock
- Salesforce Help: Connecting to an API Without a Connector Using HTTP Callout
- Agentforce Developer Guide: Get Started with Prompt Builder
- OpenAI API: Text generation guide
- OpenAI API reference: Create a response
- OpenAI API: Models
- OWASP GenAI: LLM05 Improper Output Handling



Comments
Loading comments...