All articles

Agentforce

Calling an LLM from Apex: the Models API, and the 2,000-RPM wall

The Models API lets your own Apex call a governed LLM without managing provider keys. The method shape, the model API names, and the per-org rate limit you have to design around.

Sometimes you don’t want an agent. You want one governed LLM call inside your own Apex, with your logic deciding what to send and what to do with the answer. The Models API is the surface for that, and the part that bites in production is the rate limit, not the syntax.

Reach for the Models API when a prompt template or an agent is the wrong shape for the job. If an admin should own the wording, build a Prompt Builder template instead. If the task is a conversation that plans and picks tools, that’s an agent.

The Models API is for the case in between: code that needs a model’s output as a step, like summarising a case before it routes, scoring text against a rubric, or generating an embedding for a lookup.

My one piece of advice before you write a line of it: design for the per-org ceiling of 2,000 generation requests per minute from the start. The method call is a few lines. The thing that turns an afternoon’s prototype into a production incident is a batch job that fans out past that limit and starts collecting 429s.

What the Models API gives you

The Models API runs your call through the Einstein Trust Layer and against the models registered in your org’s Model Library. You don’t manage a provider API key, configure a Named Credential, or write auth plumbing for OpenAI or Anthropic. You name a model that’s already registered and send a prompt, and Salesforce handles the provider side and the trust controls on the way through.

Two consequences follow. First, you can only call models that exist in your Library, so a bring-your-own or region-pinned model has to be registered before your Apex can reach it.

Second, the calls aren’t free. They draw on your org’s generative AI usage the same way a prompt template or an agent does, so an embedding pipeline that runs nightly shows up on the same meter as your agents. Worth modelling against your Flex Credit budget before you schedule it.

The Apex shape, and the model API name

The Apex classes live in the aiplatform namespace, under the ModelsAPI class. The method you’ll use most is createGenerations for text. Every method except feedback submission requires the API name of the model as part of the request.

That model API name is where first attempts stall, because it isn’t the friendly name you see in Setup. It follows a pattern: the sfdc_ai namespace, a double underscore, a configuration name (usually Default), an optional provider, and the model. So GPT-4o mini is sfdc_ai__DefaultOpenAIGPT4OmniMini.

Salesforce keeps the current list in its model API names reference, and it’s the authority, because the exact strings change as models are added and retired.

A minimal text generation looks like this:

aiplatform.ModelsAPI.createGenerations_Request request =
    new aiplatform.ModelsAPI.createGenerations_Request();
request.modelName = 'sfdc_ai__DefaultOpenAIGPT4OmniMini';

aiplatform.ModelsAPI_GenerationRequest body =
    new aiplatform.ModelsAPI_GenerationRequest();
body.prompt = 'Summarise this case in two sentences: ' + caseText;
request.body = body;

try {
    aiplatform.ModelsAPI.createGenerations_Response response =
        new aiplatform.ModelsAPI().createGenerations(request);
    String summary = response.Code200.generation.generatedText;
    // persist or route on summary
} catch (aiplatform.ModelsAPI.createGenerations_ResponseException e) {
    // a non-2xx from the Models API, 429 included
    System.debug(e.responseCode + ': ' + e.getMessage());
}

The success path reads the text off response.Code200.generation.generatedText. A null check on Code200 before you read it is worth the line, because a response that came back without a 200 leaves that property empty. Failures surface as a createGenerations_ResponseException, which is where the 429 you care about arrives.

One caveat worth stating plainly: these Apex classes are autogenerated from the Models REST API specification through External Services, so the exact class and property names can shift between releases. Confirm them against your org’s Apex reference rather than pasting a snippet, this one included, and assuming it compiles.

Embeddings and chat use the same door

createEmbeddings turns text into a vector, which is the call behind any custom semantic lookup you build, whether you’re matching an incoming email to a knowledge article or feeding your own retriever. Use an embeddings-specific model for it, not a generation model, and store the vector where you’ll actually query it.

createChatGenerations is the chat-shaped call that carries message history, for when you’re maintaining a turn-by-turn exchange rather than firing a single prompt. And submitFeedback records a thumbs-up or thumbs-down signal against a prior generation, the one method that doesn’t need a model name. Most code that calls the Models API only ever touches createGenerations and createEmbeddings, so start there and add the others when a real need shows up.

The rate limit you build around: 2,000 RPM per org

The ceiling that shapes your design is a production cap of 2,000 generation requests per minute, per org, for each REST endpoint or its equivalent Apex method. The exact figure can vary by model based on usage and provider capacity, so treat 2,000 as the planning number and confirm the current per-model figure in the Models API docs.

Embeddings and feedback are metered separately, at 1,000 requests per minute per org, and that pool is shared across everything in the org. An embedding-heavy grounding pipeline running next to your agents draws from the same 1,000, which is the collision most teams don’t see coming. When you exceed either limit, the Models API returns a 429.

The non-production numbers are lower and measured differently, which trips people moving from a sandbox demo to a load test. Apex calls in a sandbox get 500 requests per hour, and demo or trial orgs get 150 per hour. There’s also a documented quirk worth knowing: a request from the Agentforce reasoning engine to the Models API in a sandbox isn’t rate limited, which Salesforce flags as a known issue that can change. So a sandbox agent that never hits a wall is not evidence your own Apex calls won’t, because they’re counted under the Apex limit and the agent’s reasoning calls aren’t.

Handling the 429 without making it worse

You can’t sleep in Apex, so the retry patterns you’d write in Python don’t port. The one that fits the platform is to catch the 429 and re-queue the work with delay, rather than hammering the endpoint inside the same transaction.

  • Move bulk model work into Queueable or Batch Apex, not a synchronous trigger, so a large volume processes in controlled slices instead of one burst.
  • On a 429, catch the exception and chain a delayed Queueable to retry that slice, so a transient spike backs off instead of failing the record outright.
  • Size your batch scope to the per-minute ceiling. If you’re generating for thousands of records, a scope that paces calls under 2,000 a minute keeps you off the limit by design, rather than relying on retries to clean up after it.
  • Keep generation and embedding work on separate schedules where you can, since they count against different pools, and a nightly embedding run colliding with daytime generation is avoidable.

These are platform rate limits, so they sit on top of the usual governor and agent limits, not instead of them. A synchronous Apex transaction still caps at 100 callouts and its CPU budget, and each Models API call is a callout. For anything past a handful of records, async isn’t a nicety, it’s the only shape that holds.

Where I’d start

Prototype in Execute Anonymous with a single createGenerations call and the current model API name from the reference, so you confirm the shape against your actual org before you build around it. Then decide the surface with care: if an admin should own the prompt, this isn’t the tool, a template is.

When you do keep it in Apex, write the 429 handling before you write the batch job, not after the first failed run. The limit is generous for interactive, per-record calls and unforgiving for a fan-out that forgets it exists. Build for 2,000 a minute from the first commit and the Models API is a well-behaved part of your stack. Discover the number in production and it’s a page at 2am.

Understanding the basics

What’s the difference between the Models API and Prompt Builder?

Prompt Builder is a declarative tool where an admin owns a reusable, grounded prompt template. The Models API is a developer surface, Apex and REST, where your own code sends a prompt or text to a model and handles the response. Use Prompt Builder when the wording should be configurable without code, and the Models API when a model’s output is a programmatic step inside your logic.

Which Apex class calls the Models API?

The classes are in the aiplatform namespace, under ModelsAPI. Use createGenerations for text, createEmbeddings for vectors, createChatGenerations for chat with history, and submitFeedback to record a feedback signal. Every method except submitFeedback requires the API name of a model registered in your org’s Model Library.

What is the Models API rate limit?

In production, generation requests are capped at 2,000 per minute per org for each endpoint, and the figure can vary by model. Embeddings and feedback share a separate pool of 1,000 requests per minute per org. Exceeding either returns HTTP 429. Sandbox Apex calls get 500 per hour and demo or trial orgs get 150 per hour.

How do I handle a 429 from the Models API?

Catch the ResponseException, and because Apex can’t wait, re-queue the work with a delayed Queueable rather than retrying inside the same transaction. Move bulk model work into Queueable or Batch Apex, and size the batch scope so your call rate stays under the per-minute limit by design instead of relying on retries.


Building a governed LLM call into Apex, and sizing it so it doesn’t collide with your agents or your credit budget, is everyday work for our Agentforce and AI practice. If your team is moving model calls out of a prototype and into production, talk to us.

Keep reading

All articles