Sunday, 10 May 2026

Mastering Agentforce: The Power of Agent Script

Hi,

In the rapidly evolving world of AI, the challenge for developers has always been balancing the creative reasoning of Large Language Models (LLMs) with the rigid predictability required by enterprise business logic. Salesforce has bridged this gap with Agent Script, the foundational language for building intelligent agents in the new Agentforce Builder.

Whether you are a "low-code" admin or a "pro-code" developer, understanding Agent Script is the key to moving beyond simple chatbots to sophisticated, autonomous agents. 

What is Agent Script?

Agent Script is a hybrid language designed specifically for Agentforce. It combines natural language instructions with programmatic expressions. Think of it as a way to give your AI "guardrails" and "blueprints."

While an LLM can figure out what a user wants, Agent Script ensures the agent follows how your business requires that task to be handled. It allows you to define:

  • Predictable Workflows: Control exactly when an agent moves from one topic (now called Subagents) to another
  • Deterministic Logic: Use if/else conditions to handle business rules (e.g., "If a customer is Gold tier, offer a 20% discount").
  • State Management: Use variables to store data reliably rather than hoping the LLM "remembers" it in the conversation history.
The Best of Both Worlds: Reasoning vs. Determinism

The standout feature of Agent Script is its ability to toggle between LLM reasoning and hardcoded logic.

  • Reasoning Instructions: You can define areas where the LLM has the freedom to reason through a user's request.

  • Action Chaining: You can programmatically sequence actions so they happen in a specific order every single time, regardless of how the user phrases their request.

Three Ways to Build

Salesforce has made Agent Script accessible regardless of your technical background:

  1. The Conversational Approach: You can literally chat with Agentforce. Tell it, "If the order total is over $100, offer free shipping," and the builder will automatically generate the underlying Agent Script, actions, and instructions for you.
  2. The Canvas View: For those who prefer a visual interface, the Canvas summarizes script into "blocks." You can use shortcuts like / to add logic patterns or @ to reference resources like variables and subagents.
  3. The Script View (Pro-Code): Advanced developers can switch to a full IDE-like experience within Salesforce or use the Agentforce DX extension for Visual Studio Code. This supports syntax highlighting, autocompletion, and version control via Salesforce DX projects.
A Look at the Syntax

Agent Script is designed to be readable. A common pattern involves using reasoning instructions combined with conditional logic. For example:

// Example of a simple transition logic
if (customer.is_vip) {
    -> transition(VIP_Support_Subagent)
} else {
    | "Ask the customer how we can help them today."
}

In this snippet, the "->" indicates a deterministic transition, while the "|" provides a natural language prompt for the LLM to execute.

Example Agent Script:

system:
    instructions: "You are a friendly and empathetic agent that helps customers with their questions."
    messages:
        error: "Sorry, something went wrong."
        welcome: "Hello! How are you feeling today?"

config:
    agent_name: "HelloWorldBot"
    default_agent_user: "hello@world.com"

language:
    default_locale: "en_US"
    additional_locales: ""

variables:
    isPremiumUser: mutable boolean = False
        description: "Indicates whether the user is a premium user."

start_agent hello_world:
    description: "Respond to the user."
    reasoning:
        instructions: ->
            if @variables.isPremiumUser:
                | ask the user if they want to redeem their Premium points
            else:
                | ask the user if they want to upgrade to Premium service


Why It Matters for Developers

The shift from "Agent Topics" to Subagents (effective April 2026) signals Salesforce’s commitment to modular, scalable AI. By using Agent Script, you aren't just building a one-off bot; you are building a library of skills and subagents that can be reused across your entire enterprise.

With the ability to manage scripts locally in VS Code and deploy them via standard CI/CD pipelines, Agentforce brings AI development into the modern DevOps lifecycle.

Reference:

https://developer.salesforce.com/docs/ai/agentforce/guide/agent-script.html






Wednesday, 11 February 2026

When to Use Prompt Templates?

 Hi,

Understanding when to use Prompt Templates instead of full AI agents helps you design scalable, predictable, and maintainable AI solutions in Salesforce.

What Is a Prompt Template in Salesforce?

In Salesforce, a Prompt Template is a predefined prompt that dynamically injects Salesforce data at runtime and generates a response using generative AI.

Prompt templates can be used in two ways:

  • Standalone, embedded directly into a Salesforce experience (Flows (Eg:Invoking Prompt Template from Flow), Lightning pages(eg:Field Generation etc.,), custom UI (Eg: LWC with Apex invoking Prompt Template))
  • As an Agent Action within an Agentforce AI agent

They are designed for structured, repeatable AI outputs, not autonomous decision-making.

When Prompt Templates Are the Best Choice?

Using a Prompt Template on its own is ideal when the following conditions apply:

Using a Prompt Template on its own is ideal when the following conditions apply:

✅ Business Context Is Clear and Stable

The use case is well understood—such as summarizing a case or drafting a response—and doesn’t change frequently.

✅ Output Structure Is Predictable

You expect the AI to return content in a specific format (sections, bullet points, fields), even though the exact wording may vary.

✅ No Autonomous Decisions Are Required

The AI does not need to evaluate multiple paths, select actions, or trigger follow-up processes.

✅ No Persistent Context or State Is Needed

Each request is handled independently, without relying on conversation history or memory.

✅ Single-Step Reasoning Is Sufficient

The task can be completed in one pass without chaining logic or conditional reasoning.

When these criteria are met, prompt templates offer a lighter, faster, and more controllable alternative to full AI agents.

Common Prompt Template Use Cases in Salesforce

Prompt templates are especially effective for operational and productivity-driven scenarios, such as:

  • Structured record summaries
    Summarizing Case, Opportunity, or Account details for quick consumption by agents.

  • Meeting and interaction notes
    Converting call logs or activity records into structured summaries.

  • Templated email responses
    Drafting consistent, on-brand replies for service or sales teams.

  • Next Best Action suggestions
    Providing recommendations based on existing Salesforce data (without executing actions).

  • Sentiment analysis
    Identifying customer sentiment from case descriptions, emails, or chat transcripts.

These use cases benefit from consistency, speed, and minimal logic complexity—exactly where prompt templates shine.


Prompt Templates vs Agentforce AI Agents

It’s important to understand the boundary between Prompt Templates and AI agents:






Prompt templates generate content, while AI agents reason and act.

In many Agentforce implementations, prompt templates are used inside agents as reusable building blocks—keeping the agent logic clean while maintaining consistent output.


Key Limitations to Keep in Mind

While powerful, prompt templates have intentional limitations:

  • They cannot reason through multiple options

  • They cannot evaluate outcomes

  • They cannot execute actions or workflows

If your use case requires branching logic, decision-making, or orchestration across systems, an Agentforce AI agent is the right choice.


Final Thoughts

Prompt Templates in Salesforce Agentforce are best suited for well-defined, repeatable, and structured AI tasks. They help teams scale AI adoption quickly while maintaining control and predictability.

Use prompt templates when you want clarity and consistency.
Use AI agents when you need intelligence and autonomy.

Designing with this distinction in mind is the key to building effective, enterprise-ready AI solutions in Salesforce.


Reference:

https://trailhead.salesforce.com/content/learn/trails/get-ready-for-agentforce

https://trailhead.salesforce.com/content/learn/trails/get-started-with-prompts-and-prompt-studio?trailmix_creator_id=manoj535&trailmix_slug=prompt-builder

https://trailhead.salesforce.com/content/learn/modules/prompt-builder-basics?trail_id=get-started-with-prompts-and-prompt-studio&trailmix_creator_id=manoj535&trailmix_slug=prompt-builder






Saturday, 27 December 2025

How to Execute Einstein Prompt Templates Using Apex (Calling Salesforce Prompt Templates Programmatically with Apex)

 Hi,

Here, we’ll explore how to execute a Prompt Template using Apex.

To understand this better, let’s take a sample Flex Prompt Template called

“AccountSummaryTemplate”. This template accepts the following inputs:

• query — Free Text  

• account — Object  

Note: Input Names are case sensitive

When you want to execute a Prompt Template programmatically from Apex, you must use the Salesforce Connect API. The Connect API enables Apex to interact with Einstein generative AI features, including Prompt Templates.

Prompt: AccountSummaryTemplate




Prompt Preview:




Apex Code: 

 //Create inputs

        //For Free Text types

        ConnectApi.WrappedValue queryValue = new ConnectApi.WrappedValue();

        queryValue.value = 'Provide a brief summary of account in a few lines'; // The actual string value

        //For Object types

        Map<String, String> accountMap = new Map<String, String>();

        accountMap.put('id', '001J900000HlQWeIAN'); //Here we just need to pass record id instead of complete record (Object)

        ConnectApi.WrappedValue accountValue = new ConnectApi.WrappedValue();

        accountValue.value = accountMap;

    //Prepare InputParams 

        Map<String, ConnectApi.WrappedValue> inputParams = new Map<String, ConnectApi.WrappedValue>();

        inputParams.put('Input:account', accountValue);

        inputParams.put('Input:query', queryValue);


        // Configure invocation parameters

        ConnectApi.EinsteinPromptTemplateGenerationsInput executeTemplateInput = new ConnectApi.EinsteinPromptTemplateGenerationsInput();

        executeTemplateInput.additionalConfig = new ConnectApi.EinsteinLlmAdditionalConfigInput();

        executeTemplateInput.additionalConfig.applicationName = 'PromptBuilderPreview';

        executeTemplateInput.isPreview = false;

        executeTemplateInput.inputParams = inputParams;


        try {

            // Call the service

            ConnectApi.EinsteinPromptTemplateGenerationsRepresentation generationsOutput = ConnectApi.EinsteinLLM.generateMessagesForPromptTemplate(

                'AccountSummaryTemplate',

                executeTemplateInput

            );

            ConnectApi.EinsteinLLMGenerationItemOutput response = generationsOutput.generations[0];

            System.debug('Output----'+response.text);

           

        } catch (Exception e) {

            System.debug(e.getMessage());

            throw e;

        }





Output:



Reference:


Sunday, 14 December 2025

Account Hierarchy with (Account,Contact,Case)

Hi, the following component and Apex class help you display the Account hierarchy in a Lightning component and keep the hierarchy logic completely within the Apex class.

 Expected Output:






Source Code:

LWC Component:
---------------------
accountHierarchyTreeGrid.html

<template>
<lightning-card title="Account, Contact, and Case Hierarchy">
<div class="slds-p-around_medium">
<template if:true={gridData}>
<lightning-tree-grid
columns={gridColumns}
data={gridData}
key-field={keyField}>
</lightning-tree-grid>
</template>
<template if:false={gridData}>
<p class="slds-align_absolute-center">Loading or No Accounts found to display.</p>
</template>
</div>
</lightning-card>
</template>



accountHierarchyTreeGrid.js



import { LightningElement, wire } from 'lwc';
import getAccountHierarchy from '@salesforce/apex/HierarchyController.getAccountHierarchy';

export default class AccountHierarchyTreeGrid extends LightningElement {
// Key-field for unique identification
keyField = 'id';
// Data property to hold the hierarchical records
gridData = [];
// Column definitions for lightning-tree-grid
gridColumns = [
{
// This column holds the expandable node and the main name/number
type: 'text',
fieldName: 'name',
label: 'Name / Number',
initialWidth: 300
},
// --- Account Field ---
{
type: 'text',
fieldName: 'industry',
label: 'Account Industry',
initialWidth: 150
},
// --- Contact Field ---
{
type: 'email',
fieldName: 'email',
label: 'Contact Email',
initialWidth: 200
},
// --- Case Fields ---
{
type: 'text',
fieldName: 'subject',
label: 'Case Subject'
},
{
type: 'text',
fieldName: 'status',
label: 'Case Status',
initialWidth: 150
}
];

// Wire service calls the simplified Apex method
@wire(getAccountHierarchy)
wiredAccounts({ error, data }) {
if (data) {
// The data is a List<Object> (Maps) and is directly usable by the tree grid
this.gridData = data;
} else if (error) {
console.error('Error fetching hierarchy data:', error);
// Optional: Add logic to display an error toast message here
}
}
}


accountHierarchyTreeGrid.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>


Apexclass:

/**
* @description Controller to fetch Account, Contact, and Case data for the LWC Tree Grid.
* This builds the hierarchy directly using Maps instead of using the Javascript
manipulation of data.
*/
public with sharing class HierarchyController {

/**
* @description Fetches Accounts, Contacts, and Cases, and formats them directly into maps.
* @return List<Object> The root list of Accounts as Map<String, Object> structures.
*/
@AuraEnabled(cacheable=true)
public static List<Object> getAccountHierarchy() {
// Use SOQL to fetch Accounts, Contacts, and Cases
List<Account> accountResults = [
SELECT
Id, Name, Industry,
(SELECT Id, FirstName, LastName, Email, (SELECT Id, CaseNumber, Subject, Status FROM Cases) FROM Contacts)
FROM Account
ORDER BY Name
LIMIT 10
];
List<Object> rootList = new List<Object>();

// 1. Process Accounts (Level 1)
for (Account acc : accountResults) {
// Create the Account map node
Map<String, Object> accNode = new Map<String, Object>();
accNode.put('id', acc.Id);
accNode.put('name', acc.Name);
accNode.put('industry', acc.Industry);
List<Object> contactChildren = new List<Object>();

if (acc.Contacts != null && !acc.Contacts.isEmpty()) {
// 2. Process Contacts (Level 2)
for (Contact con : acc.Contacts) {
// Create the Contact map node
Map<String, Object> conNode = new Map<String, Object>();
conNode.put('id', con.Id);
conNode.put('name', con.FirstName + ' ' + con.LastName);
conNode.put('firstName', con.FirstName);
conNode.put('lastName', con.LastName);
conNode.put('email', con.Email);
List<Object> caseChildren = new List<Object>();

if (con.Cases != null && !con.Cases.isEmpty()) {
// 3. Process Cases (Level 3)
for (Case c : con.Cases) {
Map<String, Object> caseNode = new Map<String, Object>();
caseNode.put('id', c.Id);
caseNode.put('name', c.CaseNumber);
caseNode.put('caseNumber', c.CaseNumber);
caseNode.put('subject', c.Subject);
caseNode.put('status', c.Status);
caseChildren.add(caseNode);
}
// Add Cases to the Contact node using the required '_children' key
conNode.put('_children', caseChildren);
}
contactChildren.add(conNode);
}
// Add Contacts to the Account node using the required '_children' key
accNode.put('_children', contactChildren);
}
rootList.add(accNode);
}
return rootList;
}
}


Reference:




Sunday, 16 November 2025

Grounding Prompt Templates with Apex Merge Fields

 Hi,

You can include an Apex merge field in a prompt template to surface data retrieved from a SOQL query or an external API. Apex is also useful when you need to generate structured JSON or apply programmatic data filtering.

To use Apex within Prompt Builder, create an Apex class that contains at least one method annotated with @InvocableMethod.

If needed, you can specify a CapabilityType in the annotation so it aligns with the prompt template’s type.

Example:
@InvocableMethod(CapabilityType='PromptTemplateType://einstein_gpt__salesEmail')


Prompt Template TypeCapabilityType
Sales EmailPromptTemplateType://einstein_gpt__salesEmail
Field GenerationPromptTemplateType://einstein_gpt__fieldCompletion
Record PrioritizationPromptTemplateType://einstein_gpt__recordPrioritization
Record SummaryPromptTemplateType://einstein_gpt__recordSummary


The Flex capability has been retired, so it should no longer be used in Apex classes. Salesforce recommends refactoring any Apex code that specifies CapabilityType=FlexTemplate://* to remove the FlexTemplate reference entirely. Simply delete the CapabilityType attribute, save the class, and then confirm that your prompt template still functions correctly with its Apex merge fields.

Notes:

  • Do not specify a CapabilityType for the prompt template type einstein_gpt__caseEmailDraft, used by Service Email Assistant. This template type uses Case as its input API name, so choose a different API name for the input—such as CaseObject.

  • If you change the inputs for a Flow or Apex class used as a resource in a prompt template, the template will no longer function, and you won’t be able to save new versions.


Method Input Requirements

The method’s input parameter must be a List<Request>. The Request class must define an InvocableVariable for each input required by the prompt template type. All inputs from the prompt template are passed into the invocable method, and only the first list element contains data.

When a prompt template type includes a CapabilityType, it effectively acts as an interface for the Request class. Each CapabilityType requires that the Request class include specific InvocableVariable fields.
For example, the field generation CapabilityType requires a RelatedEntity member. If the prompt template includes additional objects, the Request class must define matching InvocableVariable members using exact spelling and case sensitivity.
In this example, the prompt template specifies Account as the object being updated, so the Request class must declare a corresponding Account variable.


public class Request {
    @InvocableVariable
    public Account RelatedEntity;
}



Method Output

The method must return a List<Response>. The Response class contains a single string field named Prompt, which must be annotated with @InvocableVariable.

Adding an Apex Resource to a Prompt Template

In the Prompt Template Workspace, you can add an Apex class to a prompt template by selecting Insert Resource in the Prompt section and choosing Apex from the list.









Reference:

https://help.salesforce.com/s/articleView?id=ai.prompt_builder_ground_apex.htm&type=5

https://help.salesforce.com/s/articleView?id=ai.prompt_builder_add_apex_flex.htm&type=5

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_InvocableMethod.htm



Tuesday, 21 October 2025

How Agentforce Is Redefining Productivity: My Take on Employee AI Agents

Hi,  

I’ve been working on Agentforce and several related projects recently, and it’s been fascinating to see firsthand how Salesforce is shaping the next wave of workplace AI. We’ve all heard about AI tools that help with sales, marketing, and customer service — but what about AI designed to empower the people who keep everything running behind the scenes?

That’s where Agentforce for Employees really stands out. It’s like giving everyone in your organization a smart digital sidekick that helps them work faster, stay focused, and remove the repetitive parts of their day

What Exactly Is an Agent?

At its simplest, an agent is an AI-powered assistant that performs or helps with a specific task. You give it a request — something like “Summarize this account before my meeting” or “Help me file an IT ticket” — and it figures out what needs to be done.

Behind the scenes, Agentforce uses what’s called the reasoning engine, which helps each agent decide the best way to complete a request. Guardrails prevent misinformation and ensure agents operate within company data rules — so everything stays secure and accurate.

Meet Employee Agents — Digital Coworkers You’ll Actually Love

Imagine having a helpful coworker who never gets tired and always knows where to find the right information. That’s what employee agents are built to be.

They can:

  • Draft sales emails or proposals.

  • Find HR or benefits details in seconds.

  • Help onboard new hires.

  • Surface knowledge or assist with IT issues.

And they’re available right where you already work — in Salesforce, Slack, or even on your phone.

How It Works

Each employee agent comes preconfigured with actions and topics, but you can also customize them in Agentforce Builder to fit your organization’s unique needs.

They also work with role-based permissions, so data access automatically matches the employee’s level. That means a manager and an associate can use the same agent safely — each seeing only what they’re authorized to see.

Why Slack + Agentforce Is a Game-Changer

One of my favorite aspects of Agentforce is how seamlessly it integrates with Slack. You can simply @mention your agent in any channel or direct message, and it’s instantly ready to help.

Even non-CRM users can access Agentforce in Slack through Salesforce identity licenses — no extra Salesforce seat required. It’s a small detail, but one that opens up powerful automation across entire organizations.

Real Use Cases I’ve Seen and Loved

Working with Agentforce has shown me how flexible these employee agents can be. Some of the most exciting real-world examples include:

  • HR: Automating onboarding and answering benefits questions.

  • IT: Managing help desk tickets and automating incident updates.

  • Sales: Preparing executive briefings and proposals.

  • Marketing: Creating campaign content and tracking performance.

  • Engineering: Assisting with QA and sprint management.

  • Legal: Simplifying compliance and approval workflows.

Anywhere you have repetitive processes or scattered information, Agentforce can help simplify and automate.

Built on Trust and Security

Since this is Salesforce, trust is baked in. Agentforce relies on the Einstein Trust Layer, which ensures your data is secure, private, and never stored. It also monitors for toxicity and inappropriate content — so responses stay professional and safe.

That trust foundation makes it easier to experiment and scale AI without fear of compromising sensitive company information.

Getting Started with Agentforce for Employees

Employee agents use Flex Credits, Salesforce’s flexible, usage-based system. This means you can roll out Agentforce for Employees across your existing Salesforce and Slack setup. If your team already uses Agentforce for Sales or Service, this is the perfect way to extend that power internally.

Final Thoughts

After working with Agentforce on multiple projects, I’ve come to appreciate how it strikes the right balance between intelligence, security, and usability. It’s not about replacing people — it’s about helping them focus on what matters most.

AI should feel like collaboration, not automation. And with Agentforce, it really does. It brings AI into the natural flow of work, making every employee more capable, informed, and efficient.

The future of work isn’t humans vs. AI — it’s humans with AI. And Agentforce is making that future happen right now.


Reference:

https://trailhead.salesforce.com/content/learn/modules/einstein-copilot-quick-look

https://trailhead.salesforce.com/content/learn/modules/agentforce-for-employees-quick-look/get-started-with-agentforce-for-employees

https://trailhead.salesforce.com/content/learn/modules/the-einstein-trust-layer

https://trailhead.salesforce.com/content/learn/projects/connect-your-agentforce-org-with-slack

https://trailhead.salesforce.com/content/learn/modules/agentforce-configuration-for-slack-deployment





Mastering Agentforce: The Power of Agent Script

Hi, In the rapidly evolving world of AI, the challenge for developers has always been balancing the creative reasoning of Large Language Mod...