
Sf Agentforce
- 38 installs
- 12 repo stars
- Updated July 14, 2026
- clientell-ai/salesforce-skills
sf-agentforce is an agent skill that documents Agentforce Bot and GenAiTopic metadata templates aligned to Salesforce API 66.0.
About
sf-agentforce is a Salesforce Agentforce reference skill for solo builders and small teams wiring autonomous service agents in org metadata. It centers on API 66.0 XML patterns: Bot definitions with active versions, context variables such as ContactId, and GenAiTopic blocks that spell scope, out-of-scope guardrails, and step-by-step instructions. Install it when you are past the idea stage and actively building on Salesforce—not when you only need a generic chatbot prompt. The value is reducing rework from invalid or incomplete agent metadata and making topic boundaries explicit before you connect flows, actions, or data lookups. It pairs with Salesforce development skills for deployment and testing but does not replace org security review or production change management.
- Complete .agent-meta.xml Bot template with versions and context variables
- GenAiTopic XML with in-scope/out-of-scope boundaries and topic instructions
- Targets Salesforce API version 66.0 consistently across examples
- Covers autonomous customer-service agent patterns and topic scoping
- Metadata-first workflow for Agentforce rather than ad-hoc UI-only setup
Sf Agentforce by the numbers
- 38 all-time installs (skills.sh)
- Ranked #8,450 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Jul 28, 2026 (Skillselion catalog sync)
npx skills add https://github.com/clientell-ai/salesforce-skills --skill sf-agentforceAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 38 |
|---|---|
| repo stars | ★ 12 |
| Security audit | 3 / 3 scanners passed |
| Last updated | July 14, 2026 |
| Repository | clientell-ai/salesforce-skills ↗ |
What it does
Ship Salesforce Agentforce bots with correct Bot and GenAiTopic metadata instead of guessing XML against API 66.0.
Who is it for?
Best when you're shipping customer-service Agentforce agents inside an existing Salesforce org.
Skip if: Skip if you're not on Salesforce, or anyone and only needs non-Salesforce LLM agents without CRM metadata.
When should I use this skill?
You are authoring or updating Agentforce Bot and topic metadata in a Salesforce project.
What you get
You leave with copy-ready metadata patterns for bots and topics so your agent invokes the right scope and instructions in Salesforce.
- .agent-meta.xml Bot definitions
- GenAiTopic scope and instruction XML
By the numbers
- All examples target Salesforce API version 66.0
Files
Agentforce Development Guide
You are a Salesforce Agentforce specialist. Build production-ready autonomous and deterministic agents following Salesforce best practices. API version 66.0 for all Agentforce features.
Agent Setup
Creating an Agent
Agents are created in Setup > Agentforce > Agents or via metadata deployment.
Two agent types:
| Agent Type | API Name | Use Case |
|---|---|---|
| Service Agent | AgentforceServiceAgent | Customer-facing, runs as Agent User, deployed to channels |
| Employee Agent | AgentforceEmployeeAgent | Internal-facing, runs as logged-in user, embedded in apps |
Agent User Configuration (Service Agents Only)
Service Agents require a dedicated Einstein Agent User: 1. Create a user with the Salesforce Integration license 2. Assign the AgentforceServiceAgent permission set 3. Grant object/field permissions the agent needs via permission sets 4. Set as default_agent_user in agent configuration
Employee Agents run as the logged-in user and do not need a dedicated agent user.
Channel Configuration
Agents can be deployed to:
- Messaging channels (web chat, SMS, WhatsApp)
- Embedded Service deployments (Lightning Web Runtime)
- Slack (Employee Agent)
- API (Agent Runtime API for programmatic access)
Configure channels in Setup > Messaging Settings or Embedded Service Deployments.
---
Topics
Topics define the scope of what an agent can handle. Each topic is a logical domain with its own instructions, actions, and scope boundaries.
Topic Design Principles
- Specific scope: Each topic should have a clear, non-overlapping domain
- Natural language description: The description is the routing signal — the planner uses it to match user utterances
- Focused instructions: Tell the agent how to behave within this topic
- Bounded actions: Only attach actions relevant to the topic
Topic Structure
A topic consists of:
- Label and API Name: Human-readable name and developer reference
- Description: Natural language explanation of what this topic covers (this drives routing)
- Scope: Define what is in-scope and out-of-scope explicitly
- Instructions: Step-by-step guidance for agent behavior within this topic
- Actions: The tools available to the agent when this topic is active
Topic Routing
The planner matches user utterances to topics based on: 1. Topic description similarity to the utterance 2. Scope definitions (in-scope vs out-of-scope) 3. Instruction context
Avoid scope overlap between sibling topics. If two topics could match the same utterance, the planner may misroute. Use explicit scope boundaries:
In scope: Order status inquiries, order tracking, delivery estimates
Out of scope: Order creation, order cancellation (handled by Order Management topic)---
Agent Actions
Actions are the tools an agent can invoke. Each action wraps a target implementation.
Action Types
| Action Type | Target | Best For | Registered Via |
|---|---|---|---|
| Flow Action | Screen Flow or Autolaunched Flow | Declarative logic, guided interactions, multi-step processes | GenAiFunction |
| Apex Action | @InvocableMethod class | Complex business logic, callouts, calculations | GenAiFunction |
| PromptTemplate Action | PromptTemplate metadata | Generated text, summaries, recommendations, drafts | GenAiFunction |
| External Service Action | External Service registration | Third-party API calls via OpenAPI spec | GenAiFunction |
When to Use Each
- Flow: Default choice. Safest, most maintainable, supports guided user interaction
- Apex: When you need complex logic, external callouts, or custom data processing
- PromptTemplate: When the output is generated text (summaries, emails, recommendations)
- External Service: When calling external APIs registered via External Services
Action Configuration
Every action requires:
- Capability description: Natural language explaining when the agent should invoke this action
- Input parameters: Mapped from conversation context or user input
- Output parameters: Returned to the agent for response generation
Input/output parameter names must match the target contract exactly:
- For Flows: match Flow input/output variable API names
- For Apex: match
@InvocableVariablefield names - For PromptTemplates: match template input/output variable names
Action Grouping with GenAiPlugin
Group related GenAiFunction entries into a GenAiPlugin for logical organization. A plugin represents a capability domain (e.g., "Order Management" containing lookup, status, and cancel actions).
---
PromptTemplate
PromptTemplate metadata defines reusable prompt configurations for agent grounding, text generation, and structured responses.
Template Types
| Type | Use Case |
|---|---|
einstein_gpt__fieldCompletion | Single-field generation |
einstein_gpt__salesEmail | Email drafting |
einstein_gpt__flex | General-purpose flex templates |
einstein_gpt__chat | Conversational agent grounding |
Template Components
- Input variables: Data passed into the template (record fields, user input, context)
- Output variable: The generated result
- Resolution steps: Ordered prompt fragments, grounding data, and instructions
- Model configuration: Which model to use and parameters
PromptTemplate as Agent Action
When used as an agent action: 1. Create the PromptTemplate metadata 2. Activate the template (Draft templates cause publish errors) 3. Register it as a GenAiFunction 4. Attach to a topic 5. Map inputs from conversation context
Models API Integration
Use the Models API from Apex for custom model routing beyond PromptTemplates:
public with sharing class ModelService {
@InvocableMethod(label='Generate Summary')
public static List<String> generateSummary(List<String> inputs) {
ConnectApi.EinsteinLlmGenerateParams params =
new ConnectApi.EinsteinLlmGenerateParams();
params.promptTextorId = 'Summarize: ' + inputs[0];
ConnectApi.EinsteinLlmGenerationOutput output =
ConnectApi.EinsteinAI.generateMessages(params);
return new List<String>{ output.generatedMessages[0].text };
}
}---
Agent Scripts (Deterministic Agents)
Agent Scripts provide a code-first, FSM-based approach for building deterministic agents. Use .agent files with a declarative DSL.
When to Use Agent Scripts vs Setup UI
| Criteria | Agent Script | Setup UI / Agent Builder |
|---|---|---|
| Routing control | Deterministic (state machine) | LLM-directed (planner) |
| Version control | .agent files in source | Metadata XML retrieved from org |
| Repeatability | Identical behavior every time | May vary with planner interpretation |
| Complexity ceiling | High (FSM + guards + transitions) | Moderate (topic + actions) |
| Best for | Strict compliance flows, regulated processes | General customer service, flexible Q&A |
Agent Script DSL Structure
config:
developer_name: MyServiceAgent
master_label: My Service Agent
agent_description: Handles customer service inquiries
agent_type: AgentforceServiceAgent
default_agent_user: einstein_agent_user@company.com
variables:
caseNumber:
type: string
description: The case number provided by the customer
customerVerified:
type: boolean
description: Whether the customer has been verified
default: False
system:
greeting: Hello! I am your service agent. How can I help you today?
start_agent:
topic: Greeting
topic: Greeting
description: Initial greeting and intent identification
instructions: ->
Greet the customer and ask how you can help.
Identify their intent and route to the appropriate topic.
actions:
identifyIntent:
target: flow://Identify_Customer_Intent
inputs:
utterance: $input
outputs:
detectedIntent: intent
transitions:
- when: detectedIntent == "case_status"
go_to: CaseStatus
- when: detectedIntent == "new_case"
go_to: NewCaseKey DSL Rules
1. Exactly one `start_agent` block per file 2. No mixed tabs and spaces — pick one and be consistent 3. Booleans: True / False (capitalized) 4. No `else if` — use separate conditions or transitions 5. No nested `if` blocks 6. `linked` variables cannot have defaults and cannot use object/list types 7. Actions use `@actions.` prefix when referenced in instructions 8. `run @actions.X` only for topic-level actions with a target: definition
Agent Script CLI
# Validate an agent script
sf agent validate authoring-bundle --api-name MyAgent -o TARGET_ORG --json
# Publish an agent script
sf agent publish authoring-bundle --api-name MyAgent -o TARGET_ORG --json
# Activate the agent
sf agent activate --api-name MyAgent -o TARGET_ORGPublishing does not activate — always run sf agent activate separately.
---
Metadata Structure
Key metadata types for Agentforce:
| Metadata Type | File Suffix | Purpose |
|---|---|---|
| Bot | .agent-meta.xml | Agent definition, versions, context variables |
| GenAiTopic | .agentTopic-meta.xml | Topic with description, scope, instructions, actions |
| GenAiFunction | .genAiFunction-meta.xml | Single action wrapping a Flow, Apex, or PromptTemplate target |
| GenAiPlugin | .genAiPlugin-meta.xml | Logical grouping of related GenAiFunctions |
| PromptTemplate | .promptTemplate-meta.xml | Prompt configuration with inputs, outputs, and model settings |
Each GenAiFunction must specify:
targetType(Flow, Apex, PromptTemplate, ExternalService)targetName(API name of the target)capabilityDescription(when the agent should use this action)inputsandoutputswith names matching the target contract exactly
Full XML templates for all metadata types: references/agentforce-reference.md
---
Testing Agents
Agentforce Testing Center
The Testing Center (Setup > Agentforce > Testing Center) provides UI-based testing with multi-turn conversation validation.
CLI Testing Commands
sf agent test run --api-name MyAgent -o TARGET_ORG --json
sf agent test run --spec-file tests/order-status.yaml -o TARGET_ORG --json
sf agent test results --test-run-id 0Atxx0000000001 -o TARGET_ORG --jsonTest spec YAML format and multi-turn examples: references/agentforce-reference.md
Test Coverage Categories
Ensure tests cover: 1. Topic routing: Correct topic matched for each utterance 2. Action invocation: Expected actions called with correct parameters 3. Context preservation: Multi-turn conversations maintain state 4. Guardrails: Off-topic, harmful, or out-of-scope inputs handled 5. Escalation: Agent escalates to human when appropriate 6. Phrasing variation: Multiple ways of asking the same question
Test-Fix Loop
1. Run tests and capture failures 2. Classify failures (topic mismatch, action failure, context loss, guardrail failure) 3. Fix the agent (topic descriptions, action configs, instructions) 4. Re-publish and re-activate 5. Re-run focused tests before full regression
---
Agent Observability
Monitor agent behavior in production using the Session Tracing Data Model (STDM) and EventLogFile.
Session Tracing Data Model (STDM)
STDM captures structured telemetry for every agent session: sessions, interactions (turns), interaction steps, moments, and messages. Enable tracing in Setup > Einstein AI > Session Tracing. Data flows into Data Cloud for analysis.
Key STDM entities: Session, Interaction, InteractionStep, Moment, Message. Each interaction maps to a single user turn and the agent's response chain (topic match, action invocations, LLM calls).
Session Transcripts
Query session transcripts via the Agent Runtime API or Data Cloud. Use transcripts to debug topic routing failures, inspect action parameters, and verify context preservation across turns.
EventLogFile for Agent Events
EventLogFile captures agent-related platform events. Query with:
SELECT Id, EventType, LogDate, LogFileLength
FROM EventLogFile
WHERE EventType IN ('AIInteraction', 'AIInsightAction')
ORDER BY LogDate DESCUse EventLogFile data for aggregate monitoring: invocation counts, error rates, and latency trends.
---
Agent Persona Design
Design a consistent agent personality by defining voice attributes and encoding them into agent configuration.
Voice Attributes
Define: register (formal to casual), warmth (neutral to empathetic), brevity (concise to detailed), humor (none to light). Align these with brand guidelines and audience expectations.
System Instructions for Persona
Encode persona in the agent's system instructions or topic-level instructions. Include: identity statement, tone directives, a phrase book (preferred phrases), and a never-say list (banned phrases or topics). Keep instructions specific and testable.
Guardrails for Persona
Define tone boundaries: how the agent adjusts tone for frustrated users vs happy-path conversations. Set hard limits (never use slang, never promise timelines) and soft guidelines (prefer active voice, use customer's name).
---
GenAI Models API
The Models API provides programmatic access to LLMs through Apex via ConnectApi.EinsteinAI.generateMessages(). All calls are automatically protected by the Einstein Trust Layer (prompt defense, toxicity detection, PII masking, audit trail, data grounding, zero data retention).
Configure model routing in Setup > Einstein AI > Model Management. Override at the PromptTemplate level for per-template model selection.
See references/agentforce-reference.md for Apex usage examples and Trust Layer details.
---
Gotchas
Agent User License
Service Agents require an Einstein Agent User license. Without it, publish succeeds but the agent cannot execute actions at runtime. Verify the user has AgentforceServiceAgent permission set.
Topic Scope Overlap
Overlapping topic descriptions cause routing ambiguity. The planner may match the wrong topic or oscillate between topics. Fix by making scope boundaries explicit and non-overlapping.
Action Parameter Mapping
Input/output parameter names in GenAiFunction must exactly match the target contract. Mismatched names cause silent failures where the action is invoked but receives null inputs.
PromptTemplate Draft Status
A PromptTemplate in Draft status causes invalid input/output parameters errors during agent publish. Always activate templates before publishing the agent.
API Version Requirement
Agentforce features require API version 66.0 or higher. Metadata deployed at lower API versions will be rejected or ignored.
Publish vs Activate
Publishing an agent does not activate it. After sf agent publish, you must separately run sf agent activate. Forgetting this step means the agent is deployed but unreachable.
Agent Script Syntax Pitfalls
else ifis not supported — use separate conditions- Nested
ifblocks are not allowed linkedvariables cannot have default values- Booleans must be
True/False(case-sensitive) - Top-level
actions:block is invalid — actions belong inside topics
Deploy Order Matters
Supporting metadata must be deployed before the agent: 1. Custom objects/fields 2. Apex classes (InvocableMethod) 3. Flows 4. PromptTemplates (and activate them) 5. GenAiFunction / GenAiPlugin 6. Agent metadata 7. Publish, then activate
Test Coverage
While there is no enforced minimum test percentage for agents (unlike Apex), untested agents are risky. Cover at minimum: each topic, each action, off-topic handling, and escalation paths.
---
Workflow
Step-by-Step Agent Development
1. Define the agent purpose: Identify whether this is a Service Agent or Employee Agent. Determine the channels and use cases.
2. Design topics: Map out the conversation domains. Each topic should be distinct with clear scope boundaries.
3. Choose the authoring path:
- Setup UI / Agent Builder: For declarative, LLM-directed agents
- Agent Script DSL: For deterministic, state-machine-driven agents
4. Build supporting components:
- Create Flows for declarative actions
- Create Apex
@InvocableMethodclasses for complex logic - Create PromptTemplates for generated content
- Register External Services for third-party APIs
5. Configure actions: Create GenAiFunction metadata for each action. Ensure input/output mappings match targets exactly.
6. Wire topics to actions: Attach actions to topics. Write clear capability descriptions so the planner knows when to invoke each action.
7. Deploy metadata: Deploy in dependency order (objects, Apex, Flows, templates, functions, agent).
8. Publish and activate:
sf agent publish authoring-bundle --api-name MyAgent -o TARGET_ORG --json
sf agent activate --api-name MyAgent -o TARGET_ORG9. Test: Run test specs covering topic routing, action invocation, guardrails, and multi-turn context.
10. Iterate: Fix failures, re-publish, re-activate, re-test.
---
Review Checklist
When reviewing an Agentforce agent, verify: 1. Agent type matches use case (Service vs Employee) 2. Service Agent has a valid Einstein Agent User configured 3. Topic descriptions are specific and non-overlapping 4. Scope boundaries are explicitly defined for each topic 5. Action capability descriptions clearly state invocation criteria 6. Input/output parameter names match target contracts 7. PromptTemplates are in Active status 8. Deploy order is correct (dependencies before agent) 9. Agent is both published and activated 10. Tests cover all topics, actions, guardrails, and escalation paths
---
References
- Agentforce Reference — metadata templates, Agent Script DSL, testing specs, patterns, Trust Layer, debugging
Agentforce Reference
Comprehensive reference for Agentforce agent development. All examples target API version 66.0.
---
Agent Metadata Templates
Complete .agent-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<Bot xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Customer_Service_Agent</fullName>
<masterLabel>Customer Service Agent</masterLabel>
<description>Autonomous agent for handling customer service inquiries</description>
<type>Bot</type>
<botVersions>
<botVersion>
<fullName>v1</fullName>
<number>1</number>
<status>Active</status>
</botVersion>
</botVersions>
<contextVariables>
<contextVariable>
<name>ContactId</name>
<dataType>Text</dataType>
</contextVariable>
</contextVariables>
</Bot>Topic Definition XML
<?xml version="1.0" encoding="UTF-8"?>
<GenAiTopic xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>Order Management</masterLabel>
<developerName>Order_Management</developerName>
<description>Handles order status checks, shipment tracking, and delivery estimates</description>
<scope>
<inScope>Order status lookups, shipment tracking, delivery estimates</inScope>
<outOfScope>New order placement, returns, refunds, account management</outOfScope>
</scope>
<instructions>
<instruction>Ask for the order number before lookup</instruction>
<instruction>Use Order_Lookup to retrieve order details</instruction>
<instruction>Provide tracking info for shipped orders</instruction>
<instruction>Escalate if customer is dissatisfied after two attempts</instruction>
</instructions>
<actions>
<action>Order_Lookup</action>
<action>Shipment_Tracking</action>
</actions>
</GenAiTopic>---
Action Configuration Examples
Flow Action
<?xml version="1.0" encoding="UTF-8"?>
<GenAiFunction xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>Order Lookup</masterLabel>
<developerName>Order_Lookup</developerName>
<description>Retrieves order details by order number</description>
<capabilityDescription>Use when the customer asks about order status or delivery</capabilityDescription>
<targetType>Flow</targetType>
<targetName>Order_Lookup_Flow</targetName>
<inputs>
<input>
<name>orderNumber</name>
<description>The order number (e.g., ORD-12345)</description>
<dataType>String</dataType>
<required>true</required>
</input>
</inputs>
<outputs>
<output>
<name>orderStatus</name>
<description>Current order status</description>
<dataType>String</dataType>
</output>
<output>
<name>estimatedDelivery</name>
<description>Estimated delivery date</description>
<dataType>String</dataType>
</output>
</outputs>
</GenAiFunction>Apex Action
<GenAiFunction xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>Calculate Refund</masterLabel>
<developerName>Calculate_Refund</developerName>
<capabilityDescription>Use when the customer requests a refund</capabilityDescription>
<targetType>Apex</targetType>
<targetName>RefundCalculator</targetName>
<inputs>
<input><name>orderId</name><dataType>String</dataType><required>true</required></input>
<input><name>returnReason</name><dataType>String</dataType><required>true</required></input>
</inputs>
<outputs>
<output><name>refundAmount</name><dataType>Number</dataType></output>
<output><name>eligible</name><dataType>Boolean</dataType></output>
</outputs>
</GenAiFunction>The Apex target must use @InvocableMethod with @InvocableVariable fields matching the input/output names exactly.
PromptTemplate Action
<GenAiFunction xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>Draft Response Email</masterLabel>
<developerName>Draft_Response_Email</developerName>
<capabilityDescription>Use to compose email responses to customers</capabilityDescription>
<targetType>PromptTemplate</targetType>
<targetName>Customer_Response_Email_Template</targetName>
<inputs>
<input><name>caseId</name><dataType>String</dataType><required>true</required></input>
<input><name>resolution</name><dataType>String</dataType><required>true</required></input>
</inputs>
<outputs>
<output><name>emailBody</name><dataType>String</dataType></output>
</outputs>
</GenAiFunction>---
PromptTemplate Metadata
<?xml version="1.0" encoding="UTF-8"?>
<PromptTemplate xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>Customer Response Email Template</masterLabel>
<developerName>Customer_Response_Email_Template</developerName>
<templateType>einstein_gpt__flex</templateType>
<status>Active</status>
<promptVersions>
<promptVersion>
<versionNumber>1</versionNumber>
<isActive>true</isActive>
<messageList>
<message>
<role>System</role>
<content>You are a professional customer service representative.
Write an empathetic, clear response email.</content>
</message>
<message>
<role>User</role>
<content>Case: {!caseId} Resolution: {!resolution}
Write a customer response email.</content>
</message>
</messageList>
<inputVariables>
<variable><name>caseId</name><dataType>String</dataType></variable>
<variable><name>resolution</name><dataType>String</dataType></variable>
</inputVariables>
<outputVariable>
<name>emailBody</name><dataType>String</dataType>
</outputVariable>
</promptVersion>
</promptVersions>
</PromptTemplate>Rules: Status must be Active (Draft causes publish errors). Input names must match GenAiFunction inputs. Use {!variableName} merge fields.
---
Agent Script DSL Syntax Reference
Block Order
config: # Agent identity and type
variables: # Agent-level variables
system: # System prompt and greeting
connection: # Channel config (optional)
knowledge: # Knowledge base (optional)
language: # Language settings (optional)
start_agent: # Entry point (exactly one)
topic: # One or more topic definitionsConfig Block
config:
developer_name: Order_Service_Agent
master_label: Order Service Agent
agent_description: Handles order inquiries with deterministic routing
agent_type: AgentforceServiceAgent
default_agent_user: agent_user@company.comdeveloper_namemust match the folder/bundle name- Use
agent_description(notdescription) default_agent_user: required for Service Agents, forbidden for Employee Agents
Variables
variables:
orderNumber:
type: string
description: Customer order number
verified:
type: boolean
default: False
lookupResult:
type: string
linked: TrueTypes: string, boolean, number, date, datetime. Linked variables cannot have defaults or use object/list types.
States, Transitions, and Guards
topic: VerifyCustomer
description: Verifies customer identity
instructions: ->
Ask for email. Verify identity. Route accordingly.
actions:
verify:
target: flow://Verify_Customer_Identity
inputs:
email: $input
outputs:
isVerified: verified
transitions:
- when: verified == True
go_to: OrderService
- when: verified == False
go_to: VerificationFailed
topic: OrderModification
description: Handles order modifications
available when: verified == TrueTarget Prefixes
flow://— Flowapex://— Apex InvocableMethodprompt://— PromptTemplate
Deterministic vs LLM-Directed
| Mechanism | Behavior |
|---|---|
set, transition to, run @actions.X | Deterministic (always executes) |
{!@actions.X} in instructions | LLM-directed (model decides) |
@utils.transition | LLM-directed utility |
---
Testing Spec YAML Format
apiVersion: "66.0"
agentApiName: Order_Service_Agent
testCases:
- name: Order Status - Happy Path
turns:
- utterance: "I need to check on my order"
expectedTopic: Greeting
- utterance: "Order ORD-98765"
expectedTopic: Order_Management
expectedActions: [Order_Lookup]
expectedOutputContains: ["ORD-98765"]
- name: Off Topic
turns:
- utterance: "Can you help me write a poem?"
expectedBehavior: "Agent declines and redirects"
expectedTopic: null
- name: Escalation
turns:
- utterance: "I want to speak to a human"
expectedEscalation: true
- name: Phrasing Variation
turns:
- utterance: "Where is my package?"
expectedTopic: Order_Management
- utterance: "Track my shipment"
expectedTopic: Order_Managementsf agent test run --spec-dir tests/agent-specs/ -o TARGET_ORG --json
sf agent test run --spec-file tests/order-status.yaml -o TARGET_ORG --json --verbose
sf agent test results --test-run-id 0Atxx0000000001 -o TARGET_ORG --json---
Advanced Testing Patterns
Multi-Turn Test Specs
Multi-turn specs validate context preservation across turns. Each turn can assert expectedTopic, expectedActions, expectedOutputContains (substring match), and expectedOutputExcludes (negative assertion to prevent data leaks).
Test Coverage Metrics
Track five dimensions: topic coverage (% tested), action coverage (% invoked), guardrail coverage (harmful/off-topic inputs), escalation coverage (paths exercised), phrasing variation (3+ phrasings per top topic). Target 100% topic and action coverage.
Additional CLI Commands
sf agent test list -o TARGET_ORG --json---
Observability & Monitoring
STDM Trace Analysis
The Session Tracing Data Model (STDM) stores telemetry in Data Cloud. Entity hierarchy: Session > Interaction > InteractionStep > Moment > Message. Enable in Setup > Einstein AI > Session Tracing.
Session Transcript Queries
SELECT SessionId, InteractionId, StepType, TopicName,
ActionName, StartTime, EndTime, Status
FROM AgentforceInteractionStep
WHERE SessionId = '<session-id>'
ORDER BY StartTime ASCEventLogFile for Agent Events
SELECT Id, EventType, LogDate, LogFileLength
FROM EventLogFile
WHERE EventType = 'AIInteraction' AND LogDate >= LAST_N_DAYS:7
ORDER BY LogDate DESCDownload via /sobjects/EventLogFile/<id>/LogFileBody. Parse CSV for invocation counts, error rates, and p95 latency.
Parquet Export
Export STDM to Parquet via Data Cloud Query API for offline analysis. Use Polars for lazy evaluation on large datasets. Common patterns: session duration distribution, topic routing accuracy, action failure rates, escalation trends.
---
Persona Configuration
System Instruction Template
Identity: You are [Agent Name], a [role] for [Company].
Register: [Formal / Professional / Friendly-casual]
Tone: [Warm and empathetic / Neutral and efficient]
Rules:
- Use the customer's name when available
- Keep responses under 3 sentences for simple queries
- Never promise specific timelines or outcomesVoice Attributes
| Attribute | Range | Example |
|---|---|---|
| Register | Formal → Casual | Professional (3/5) |
| Warmth | Neutral → Empathetic | Warm (4/5) |
| Brevity | Verbose → Terse | Concise (4/5) |
| Humor | None → Light | Minimal (1/5) |
Brand Voice Encoding
1. Extract brand adjectives (e.g., "trustworthy, innovative") 2. Map to behavioral rules ("trustworthy" → "cite data, never speculate") 3. Create a phrase book (preferred expressions) and never-say list (banned terms) 4. Encode into system: block (Agent Script) or agent description (Agent Builder)
Persona Guardrails
- After two failed resolutions, shift to maximum empathy and offer human handoff
- Never provide medical, legal, or financial advice — redirect to qualified resources
- Never repeat back full SSN, credit card, or account numbers
---
Models API
Setup: Setup > Einstein AI > Model Management. Configure default model and per-template overrides.
public with sharing class AgentModelService {
@InvocableMethod(label='Generate AI Content')
public static List<GenerateResult> generate(List<GenerateRequest> requests) {
List<GenerateResult> results = new List<GenerateResult>();
for (GenerateRequest req : requests) {
try {
ConnectApi.EinsteinLlmGenerateParams params = new ConnectApi.EinsteinLlmGenerateParams();
params.promptTextorId = req.prompt;
ConnectApi.EinsteinLlmGenerationOutput output = ConnectApi.EinsteinAI.generateMessages(params);
results.add(new GenerateResult(output.generatedMessages[0].text, true, null));
} catch (Exception e) {
results.add(new GenerateResult(null, false, e.getMessage()));
}
}
return results;
}
public class GenerateRequest {
@InvocableVariable(required=true) public String prompt;
}
public class GenerateResult {
@InvocableVariable public String generatedText;
@InvocableVariable public Boolean success;
@InvocableVariable public String errorMessage;
public GenerateResult(String text, Boolean ok, String err) {
this.generatedText = text; this.success = ok; this.errorMessage = err;
}
}
}All Models API calls go through Einstein Trust Layer automatically.
---
Agent User Setup
1. Create user: Setup > Users > New User. License: Salesforce Integration. 2. Assign permset: sf org assign permset -n AgentforceServiceAgent -o TARGET_ORG 3. Grant access: Create a permission set with CRUD on required objects/fields. 4. Configure: Set default_agent_user in agent config.
| Issue | Fix |
|---|---|
| Actions fail silently | Grant object/field access to agent user |
| Agent non-functional after publish | Assign AgentforceServiceAgent permset |
| SOQL returns no results | Check sharing rules and role hierarchy |
---
Common Agent Patterns
Service Agent: Customer-facing, AgentforceServiceAgent, dedicated agent user. Topics: greeting, order management, returns, escalation. Always verify identity early; always have an escalation path.
Sales Agent: Internal, AgentforceEmployeeAgent, runs as logged-in user. Topics: lead qualification, opportunity analysis, meeting prep, next-best-action. Heavy use of PromptTemplate actions. Prefer read-only actions.
Knowledge Agent: Internal, AgentforceEmployeeAgent. Topics: knowledge search, article recommendations, FAQ, process guidance. Bind knowledge base. Include article links in responses.
---
Einstein Trust Layer
| Protection | Description |
|---|---|
| Prompt Defense | Blocks prompt injection attempts |
| Toxicity Detection | Filters harmful content |
| PII Masking | Redacts sensitive data before sending to model |
| Data Grounding | Anchors responses to CRM data |
| Audit Trail | Logs all LLM interactions |
| Zero Data Retention | Customer data not used for training |
Enabled by default. Configure in Setup > Einstein AI > Trust Layer.
---
Debugging Agent Responses
Approaches
1. Agent Preview (Setup > Agentforce > Agents > Preview): test utterances, observe routing and actions 2. Event Logs: Trust Layer events, action execution logs, session data 3. CLI: sf agent list, sf project retrieve start -m "Bot,GenAiFunction,GenAiPlugin,GenAiTopic" 4. Validation: sf agent validate authoring-bundle --api-name MyAgent -o TARGET_ORG --json
Debugging Checklist
| Symptom | Check |
|---|---|
| No response | Published AND activated? |
| Wrong topic | Overlapping descriptions? Review scope. |
| Action not invoked | Attached to topic? Capability description clear? |
| Null inputs | Parameter names match target contract? |
| Runtime failure | Agent user has permissions? |
| Empty PromptTemplate output | Template Active? Merge fields correct? |
| Topic loop | Transitions defined? Exit conditions present? |
| Preview vs runtime mismatch | Check linked variables and context passing |
Related skills
How it compares
Reference templates for Salesforce Agentforce metadata—not a generic multi-platform agent framework skill.
FAQ
Who is sf-agentforce for?
Developers and small teams implementing Salesforce Agentforce bots who want XML-first metadata examples instead of trial-and-error in Setup.
When should I use sf-agentforce?
Use it during Build when defining Bot versions, context variables, and GenAiTopic scope before wiring actions; also when revisiting topic boundaries after pilot feedback.
Is sf-agentforce safe to install?
Review the Security Audits panel on this Prism page and treat any Salesforce credentials and customer data policies as your responsibility before deploying agents to production.