Package homeAgentforce SpecialistStudy guide
Study guide

Chapter 120% of the exam50 min

Prompt Engineering

When a prompt template is the right tool, the four template types and where each one runs, how to choose a grounding technique, how to build, version, activate and run a template and who may do it, how to write prompts that work, and how the Trust Layer and model settings protect your data.

By the end of this chapter you can

  • Decide when a business requirement calls for a Prompt Builder template, and choose the right template type
  • Pick a grounding technique for a scenario: merge fields, related lists, a flow, Apex or a retriever
  • Create, preview, version, activate and run a prompt template, and give builders and users the access they need
  • Write effective prompts using role, context, task, format and constraints, and choose a model and temperature
  • Match each Trust Layer feature to a security or privacy requirement, and know where data masking applies
  • Control which models your templates and agents use

Prompt Builder and the four template types

A prompt is the text you send to a large language model (LLM). A prompt template is a reusable prompt with placeholders that Salesforce fills with real data each time it runs, so one template can write a thousand different case summaries. Prompt Builder is where you create, test and manage templates. Open it from Setup > Prompt Builder or from Agentforce Studio > Prompt Templates.

When a template is the right tool

Scenario: A solar installer has three requests. Service wants a summary of each case's comments. Sales wants follow-up emails written from the customer's record. And leadership wants a chat assistant that can look up orders and book site visits.

The first two are clear template jobs: the task is the same every time, the output is one piece of text, and it lands somewhere specific (a field, an email). The third request is a conversation in which the AI has to decide what to do next, so it calls for an agent. That agent can still use templates as actions.

Need Best fit
One piece of generated text inside a workflow (a field, an email, a flow step), written the same way each time Prompt Builder template
An interactive conversation in which the AI chooses and runs actions Agentforce agent, which can call templates as actions
Developer access to models from code, including embeddings and multi-turn chat Models API
A result that must be identical every time, such as a calculation or a routing rule A formula, flow or Apex, with no LLM

The four template types

Type Built around Where it runs
Sales Email A recipient, such as a contact, and an optional related object Draft with AI in the email composer, plus Flow, Apex and the API
Field Generation One object and one field on it The field's Einstein button on a record page, plus Flow, Apex and the API
Record Summary A record, summarised from its data Agent actions
Flex Up to five inputs that you define, each an Object or Free Text No predefined entry point: Flow, Apex, the REST API and agent actions

Field Generation writes its response into a field, so the field must be writable text: Text, Text Area, Text Area (Long) or Text Area (Rich). Read-only fields, such as formula fields, can't be used. To give users the Einstein button, open the record page in Lightning App Builder and place the field in a Field Section component, or upgrade the Record Detail component to Dynamic Forms. Then select the field and assign the template in the Einstein generative AI section of its properties. Users click the button, review the draft and save it, so a person always checks the text.

Design the prompt for the field it fills. A Text field holds only 255 characters, so tell the model to stay under that. Long and rich text areas hold 131,072 characters.

Flex is the most versatile type. Choose it when a requirement doesn't fit the others: it needs several objects at once (an account, an asset and a contact), free-text input typed by a user or passed in by a flow, or a template that no page button runs. The standard types are quicker to set up, but each one is limited to its own job.

Since Spring '26, a template can also return structured output. Switch its response format from Default to JSON and, optionally, attach an object-based Lightning type. Flow then receives typed output fields instead of one block of text. Those Lightning types hold only simple values (text, true or false, whole numbers, dates and date-times), not nested objects or lists.

Exam tip: Match the requirement to the type. "Fill this field from a button" means Field Generation. "Draft an email to this contact" means Sales Email. "Several objects", "free-text input" or "called only from a flow or an agent" means Flex.

Grounding a template

Grounding means adding specific, current business data to the prompt, so the model writes from facts instead of guessing. When a template runs, Salesforce first resolves it: every placeholder is replaced with real values, and every flow or Apex class it references runs and returns its text. Only then does the resolved prompt go through the Trust Layer to the model.

Five grounding sources feed a prompt template: merge fields for record, sender and org fields; related lists for child records; a flow for logic and filters without code; Apex for queries and external systems; and a retriever for passages from documents. At run time the template is resolved into a complete prompt, which then goes through the Trust Layer to the LLM. Merge fields Record, sender and org fields Related lists Child records of the input Flow Logic and filters, no code Apex Queries and external systems Retriever Passages from documents Prompt template resolved at run time Resolved prompt real data filled in Trust Layer then the LLM
Grounding sources feed a prompt template, which is resolved into a complete prompt before it goes to the Trust Layer and the model

You add every source with Insert Resource in the template workspace.

Technique Use it when Key facts
Merge fields You need values from the input record, its parent records, the sender or the org For example {!$Input:Account.Name}. The simplest and fastest option
Related lists You need child records of the input record, such as a case's comments Inserted as a related list of the input object
Flow You need logic without code: conditions, filters or loops over records A Template-Triggered Prompt Flow, which runs only when a template calls it. It sends text back with the Add Prompt Instructions element
Apex You need a SOQL query, a call to an external system, or data filtered or formatted in code An @InvocableMethod whose CapabilityType matches the template type. It returns a Prompt value for each request
Retriever You need passages from unstructured content, such as knowledge articles, PDFs or long text Searches a Data 360 search index and returns only the most relevant chunks
Data 360 data You need unified customer data from several systems Data model objects and data graphs supply a joined view of the customer

Merge fields and related lists reach CRM data. Flow and Apex can reach CRM data, Data 360 data and external systems. A Template-Triggered Prompt Flow adds its text one record at a time, so to include many records you loop over them and add instructions inside the loop. Each Add Prompt Instructions element adds to the text that the flow returns.

Choosing by scenario

Scenario: The solar installer's admin is building an account briefing template and has four more requirements:

  1. Greet the contact by first name and mention the account's industry. These are fields on the input record and its parent, so use merge fields.
  2. List only the high-priority cases opened in the last 90 days. This needs a filter, and the admin doesn't write code, so use a Template-Triggered Prompt Flow that gets the matching cases and loops over them.
  3. Include the live shipment status from the logistics system. This needs a call to an external system. A developer writes an Apex class that makes the callout and returns the status as text.
  4. Answer from 2,000 product manuals. The answer is somewhere in a large body of unstructured text, so use a retriever. It searches a search index built from the manuals and returns only the relevant passages, an approach called retrieval augmented generation (RAG). The Data 360 chapter explains how indexes, chunking and retrievers work.

A custom retriever, built in AI Models (formerly Einstein Studio), can filter its results, for example to only the manuals for the customer's product line. Each change creates a new version, and a retriever can't be used in templates until you activate one of its versions.

Exam tip: Read the requirement's key phrase. "A field on the record" points to a merge field. "Without code" with conditions points to Flow. "External system" or "complex query" points to Apex. "Knowledge articles", "documents" or "manuals" points to a retriever.

Building, activating and running templates

The template workspace

To create a template, click New Prompt Template in Prompt Builder and fill in its type, name, API name, description and the objects the type needs. The template opens in the Prompt Template Workspace:

  • Prompt: where you write the template and insert resources.
  • Template Settings: the model the template uses and other options.
  • Preview Settings: the sample record or input values to test with.
  • Resolved Prompt: after Save & Preview, the exact prompt with every merge field, related list, flow and Apex output filled in, and any masked values shown as placeholders.
  • Response: what the model wrote.

When a response is wrong, check the Resolved Prompt first. If the data in it is missing or wrong, fix the grounding. If the data is right but the response is still poor, fix the instructions.

Versions and activation

Save As > Save as New Version records a change under the same template name and API name. Save as New Template creates a separate template with a new name and API name. Saving changes nothing for users: pages, flows and agents always use the active version, so you Save and Activate the version you want live. An inactive template doesn't appear when you assign it to a field in Lightning App Builder or add it as an agent action.

Who can build and who can run

Person What they need
Template builder The Prompt Template Manager permission set, which opens Prompt Builder
A user who runs a template, for example through a flow The Prompt Template User permission set
An agent that runs a template action A permission set on the agent's user that lets it run templates and read every object the template grounds on, including Data 360 objects

Underneath these sit the permissions Manage Prompt Templates and Execute Prompt Templates, so building and running are separate rights. Grounding also respects the running user's object and field access, so a template can't merge in a field that the user isn't allowed to see.

Where templates run

  • On a record page: the Einstein button on a Field Generation field.
  • In the email composer: Draft with AI, for Sales Email templates.
  • In Flow: every saved and activated template appears as an action in the Action element, in the Prompt Template category. The flow receives the response as text, or as typed fields if the template returns structured output.
  • From Apex: the ConnectApi.EinsteinLLM class runs a template by its API name.
  • Through the API: the generatePromptResponse invocable action and a Connect REST API resource run a template from outside Salesforce.
  • In an agent: add an action whose reference action type is Prompt Template, then describe in the action's instructions and input descriptions when to use it and what to pass in.

Exam tip: "We fixed the template but users still get the old output" means the new version was saved but not activated. "The template doesn't appear in the list" (in Lightning App Builder or an agent action) means it isn't active yet.

Writing prompts that work

Scenario: The first briefing template produces long, rambling text that sometimes invents contract values. The admin rewrites it using a clear structure.

The six building blocks

A strong prompt reads like a brief to a capable new colleague. Not every prompt needs all six parts, but most good ones use several:

Part Example
Role You are a customer success manager at a solar installer
Context The account details and open cases, merged in
Task Write a briefing for a colleague who is about to call this customer
Instructions Cover the situation, open issues and one next step
Format Three short paragraphs, under 200 words
Constraints Use only the data provided. If something is missing, say "not recorded"
You are a customer success manager at a solar installer.
Write a briefing for a colleague who is about to call this customer.
 
"""
Account: {!$Input:Account.Name}
Industry: {!$Input:Account.Industry}
Open cases: {!$Flow:Open_Cases_Summary.Prompt}
"""
 
Write three short paragraphs: the situation, open issues and one next step.
Use only the data between the triple quotes. If something is missing, write "not recorded".
Keep it under 200 words, in a friendly, professional tone.

Practices that make a difference

  • Fence your data. Triple quotes (""") around merged data tell the model the block is data to use, not instructions to follow.
  • Mention each piece of data once. Merging the same field twice, or two overlapping fields, wastes space and can confuse the model.
  • Be specific. Name the audience, the length and the format. Vague instructions produce vague text.
  • Show examples when the format matters. A zero-shot prompt gives only the instruction. A few-shot prompt adds one or two examples of the output you want, which steers format and tone.
  • Ask for steps when the logic matters. Chain-of-thought prompting asks the model to reason step by step, which helps with multistep tasks such as qualifying a lead against several criteria.
  • Test, refine and retest. Preview against several different records, including ones with missing data, and keep notes on what changed and why.

When you review responses, check them against clear criteria: Is it on topic? Did it complete the task? Is the tone right? Is every fact in the grounded data? Does it repeat itself? Is it free of toxic or biased content? Users who review the draft before saving it remain the human in the loop.

Model and temperature

Temperature controls how predictable the output is. Near 0, the model picks the most likely words, which suits summaries and field values that should be consistent. Near 1, it varies more, which suits creative work such as campaign ideas.

Choose the model by testing, not by release date or size. Decide two or three success criteria, run 10 to 20 realistic examples through each candidate model, and pick on the results, weighing cost against accuracy.

Exam tip: "The response invents facts" means stronger grounding and a constraint such as "use only the data provided". "The format varies every time" means a clearer format instruction, examples, or a lower temperature. A different model is rarely the first fix.

The Trust Layer and model access

Scenario: A bank's compliance team will approve generative AI only if users can't see data they're not entitled to, personal data stays protected, the AI provider keeps nothing, harmful output is caught, and every interaction can be reviewed.

The Einstein Trust Layer (titled the Agentforce Trust Layer on Trailhead, though Setup still says Einstein Trust Layer) is the set of protections that every prompt and response passes through.

The prompt journey: a prompt template is grounded with secure data retrieval, sensitive data is masked with placeholders, prompt defense adds guardrails, and the secure LLM gateway sends the encrypted prompt to the LLM, which retains no data. The response journey: the response is scored for toxicity, masked values are restored, and the response reaches the app. Prompts, responses, scores and feedback are kept in an audit trail in Data 360. Prompt journey Trust Layer step Prompt template Grounding secure retrieval Data masking placeholders Prompt defense guardrails LLM gateway encrypted LLM zero retention Response journey Toxicity scored 0 to 1 Demasking values restored Response to the app Audit trail and feedback in Data 360 Prompts, masked prompts, responses, toxicity scores and user feedback
The prompt journey through grounding, masking, prompt defense and the secure gateway to the LLM, and the response journey back through toxicity scoring, demasking and the audit trail

Feature What it does Requirement it answers
Secure data retrieval Grounding respects the running user's object and field permissions "Only data the user is allowed to see"
Dynamic grounding Fills the template with merge fields, page context and relevant knowledge "Accurate, specific answers"
Data masking Replaces sensitive values with typed placeholders such as <NAME_1> before the prompt leaves Salesforce, then restores them in the response "Personal data must not reach the model"
Prompt defense Adds guardrail instructions to reduce unintended output and prompt injection "Stop users tricking the AI"
Secure LLM gateway Sends prompts to external models over an encrypted connection "Protect data in transit"
Zero data retention External LLM partners don't store prompts or responses "The provider keeps nothing"
Toxicity scoring Scores prompts and responses in five categories (violence, sexual, profanity, hate and physical) from 0 to 1, and returns the score to the app that called the model "Detect harmful output"
Audit trail and feedback Records prompts, masked prompts, responses, toxicity scores and user feedback in Data 360 "Review every interaction"

Where data masking applies

Data masking works in Prompt Builder (you can see the placeholders in the Resolved Prompt) and for embedded AI features such as Einstein Service Replies and Work Summaries. It is currently turned off for agents. For an agent, protecting data rests on secure data retrieval and a least-privilege agent user.

An admin turns masking on in Setup > Einstein Setup > Einstein Trust Layer, under Large Language Model Data Masking, then chooses which data types to mask, such as names, email addresses, phone numbers and credit card numbers. Masking uses pattern matching and machine learning, so it has trade-offs: a company name, or an order number that looks like a phone number, may be masked and make the response less useful. Values that don't match a valid format, such as an invalid card number, aren't masked.

Zero data retention covers the external model provider. Salesforce still keeps the audit trail in Data 360, which the Trust Layer needs in order to work fully.

Managing which models are used

Salesforce-managed models are enabled by default. You can also use third-party models hosted inside Salesforce's infrastructure, or bring your own LLM from a provider account such as OpenAI, Azure OpenAI, Amazon Bedrock or Vertex AI. Requests to your own model still go through the LLM gateway and the Trust Layer.

Models are managed in AI Models (formerly Einstein Studio) in Data 360, where you can also create a configured model: a model with fixed settings, such as a low temperature. Managing models there needs its own permission. Each template then chooses its model in Template Settings: Standard for a Salesforce-managed model, or Custom for a configured one. To control which models are used, limit who can manage models and who can edit templates, and set each template's model deliberately.

An agent's own reasoning runs on Salesforce-managed models. To use another model inside an agent, call it through an action, such as a prompt template that uses that model. Beta models are turned off by default, so try them in a sandbox before production.

Exam tip: Match the concern to the feature. "Users must only see their own data" means secure data retrieval. "Hide personal data from the model" means data masking, except for agents. "The provider must not keep our data" means zero data retention. "Review what the AI said" means the audit trail.

Hands-on exercise

Build, test and place a Field Generation template

Create a grounded Field Generation template that writes an account briefing into a field, test it against real records, version and activate it, and add its Einstein button to the account page.

Use a free Salesforce Developer Edition org — never a production org.

0 of 8 steps done

How to check your work: The field fills with a draft briefing that uses only that account's real data and includes your new next-step instruction, you can edit the text before saving, and Prompt Builder shows your second version as the active one.

Domain quiz: Prompt Engineering

10 questions from the 52 in this domain, different each time and checked as you go. Anything you miss is saved to Mistakes review.

Questions
10
Time
Untimed
Feedback
After each answer

New questions each time you start, drawn from the bank, unseen ones first.

Data 360 Fundamentals