Traditional Salesforce chatbots were largely designed around predefined conversational paths. A user selected an option, entered a known type of request, and the bot followed a configured workflow. Modern AI chatbots are fundamentally different. They can understand natural language, retrieve relevant business context, reason about a request, and execute controlled actions across Salesforce and external systems.
That gives developers several architectural options. You might build with Agentforce, connect Salesforce to an external LLM, add RAG, expose business actions through Flow or Apex, or combine these approaches in a hybrid architecture. The right choice depends on how autonomous the assistant needs to be, where the data lives, which systems it must access, and how much control is required over security and business actions.
A custom AI chatbot inside Salesforce typically combines a conversational interface with an LLM or Agentforce reasoning layer, Salesforce CRM data, business knowledge, and controlled actions built with Flow, Apex, APIs, or other integrations. Production implementations also require permissions, grounding, guardrails, testing, monitoring, and human escalation.
This guide explains how to design that architecture, connect data, build actions, add RAG, secure the chatbot, test its behavior, deploy it, and monitor it after launch.
What Is a Custom Salesforce AI Chatbot?
A custom Salesforce AI chatbot is more than a chat window connected to a language model. It’s an application layer that allows users to interact with Salesforce data, business knowledge, and workflows using natural language.
Depending on its design, the chatbot can:
- Understand natural-language requests
- Access Salesforce records
- Retrieve company knowledge
- Summarize CRM information
- Create or update records
- Trigger workflows
- Call external APIs
- Execute approved business actions
- Maintain conversation context
- Escalate requests to human users
The important distinction is between chat and agency.
A traditional chatbot primarily follows this pattern:
An AI agent operates differently:
For example, a chatbot may answer, “XYZ Corp has three open opportunities.”
An agent could receive the request, “Review XYZ, identify stalled opportunities, and create follow-up tasks for the sales team.”
That requires the system to retrieve data, analyze it, apply business rules, recommend or perform actions, and potentially request approval before changing Salesforce records.
Traditional Salesforce Chatbot vs. Custom AI Chatbot vs. Agentforce
Before choosing an architecture, it helps to separate the three broad approaches.
| Capability | Traditional Bot | Custom LLM Chatbot | Agentforce |
|---|---|---|---|
| Natural Language | Limited/rule-driven | Strong | Strong |
| Salesforce Context | Native/configured | Custom integration | Native |
| Knowledge Retrieval | Configured | Custom RAG | Supported |
| Flow Integration | Yes | Custom | Yes |
| Apex Actions | Possible | Custom | Supported |
| External APIs | Possible | Yes | Yes |
| Business Actions | Rule-based | Custom | Agent actions |
| Reasoning | Limited | Model dependent | Agent reasoning |
| Governance | Salesforce controls | Must design | Salesforce ecosystem |
| Development Effort | Low-Medium | High | Low-High |
Three Ways to Build AI Chatbots in Salesforce
There is no single architecture for building an AI chatbot in Salesforce. The right approach depends on where your data lives, how much autonomy the AI needs, which systems it must access, and how much control you require over the underlying models and orchestration.
Option 1: Build with Agentforce
Agentforce is a strong option when Salesforce is the center of the business workflow. It’s particularly suitable when Salesforce is the primary data source, CRM processes are central to the use case, and the agent needs to access Salesforce-native data and actions.
Use Agentforce when:
- Salesforce is the primary data source.
- CRM workflows are central.
- Agents need Salesforce-native actions.
- You want a combination of Builder and pro-code development.
- Salesforce governance and security controls are important.
Agentforce Builder supports capabilities such as subagents, actions, variables, data sources, connections, Agent Script, previews, and debugging. This allows teams to start with declarative configuration while adding custom logic where more control is needed.
Option 2: Build a Custom LLM Integration
A custom LLM architecture gives developers greater control over the AI models, orchestration, and integrations used by the chatbot.
A typical architecture looks like:
This approach is useful when:
- You need specific AI models.
- AI is part of a larger custom application.
- Complex external systems are involved.
- You need greater control over orchestration.
- Salesforce is only one part of the overall application ecosystem.
The tradeoff is that your development team is responsible for more of the architecture, including model integration, security, retrieval, conversation management, error handling, and monitoring.
Option 3: Hybrid Agentforce + Custom Services
A hybrid approach combines Salesforce-native agent capabilities with custom services and external systems. This is often the most flexible architecture for enterprise use cases.
For example:
In this model, Agentforce can manage the conversation, Salesforce context, and agent behavior, while custom services handle specialized AI processing, complex orchestration, proprietary systems, or external data sources.
Recommended Architecture for a Salesforce AI Chatbot
A production-ready Salesforce AI chatbot should be designed as a layered architecture rather than a simple connection between a chat interface and an LLM. Each layer should have a clear responsibility, making the solution easier to secure, maintain, test, and scale.
1. User Interface Layer
This is where users interact with the chatbot. Depending on the audience and use case, the experience can be embedded in:
- Salesforce
- Experience Cloud
- Customer service applications
- A website
- A mobile app
The same AI capabilities can support multiple channels, although authentication, permissions, and available actions may differ depending on the user and interface.
2. Conversation Layer
The conversation layer manages the context needed to maintain a meaningful interaction. This includes:
- Session information
- User context
- Conversation state
- Intent
Instead of treating every message as an isolated request, this layer helps the chatbot understand what has already happened and what the user is trying to accomplish.
3. AI / Reasoning Layer
This is the intelligence layer, powered by Agentforce or another LLM and orchestration service. It interprets natural-language requests, determines what information is required, selects the appropriate actions or tools, and generates a response based on the available context.
4. Knowledge Layer
The knowledge layer provides the information required to answer questions accurately. It can combine:
- Salesforce records
- Salesforce Knowledge
- Internal documents
- RAG systems
- Enterprise data sources
Structured CRM data and unstructured business knowledge may require different retrieval approaches. RAG can help retrieve relevant information at runtime rather than sending large amounts of unnecessary context to the model.
5. Action Layer
The action layer turns AI recommendations into controlled business operations. Depending on the complexity of the task, actions can be implemented through:
- Flow
- Apex
- APIs
- MuleSoft
- External services
The AI should request an action, while the underlying workflow or code validates and executes it according to defined business rules.
6. Security Layer
Security should apply across the entire architecture rather than being added after development. Key controls include:
- Authentication
- User and system permissions
- Data access controls
- Guardrails
- Input and action validation
The chatbot should only access the information and actions required for its specific purpose and should never become an unrestricted path around existing Salesforce security.
7. Observability Layer
Once the chatbot is in production, teams need visibility into both technical performance and AI behavior. The observability layer should track:
- Logs
- Traces
- AI evaluations
- Action execution
- Errors and failures
- Cost and usage
This helps teams identify inaccurate responses, failed integrations, unsafe behavior, and performance issues while continuously improving the chatbot.
Step 1: Define What the Chatbot Is Allowed to Do
Before writing code or configuring an AI agent, define a clear capability boundary. Not every chatbot needs permission to perform every type of task. Separating capabilities into read, analyze, write, and execute functions helps developers design the right permissions, guardrails, and approval workflows from the beginning.
Read
Read capabilities allow the chatbot to retrieve information without modifying anything. For example, it might find accounts, retrieve opportunities, search knowledge, or check an order status. These are generally lower-risk actions but should still respect Salesforce object, field, and record-level permissions.
Analyze
Analysis capabilities allow the AI to interpret and summarize available information. The chatbot might summarize an account, analyze a sales pipeline, explain case history, or identify potential customer issues. AI reasoning is particularly valuable at this level because the task involves understanding context rather than simply retrieving a record.
Write
Write capabilities allow the chatbot to create or modify Salesforce data. Examples include updating opportunities, creating cases, adding notes, or creating follow-up tasks. These actions should be validated against business rules and user permissions before changes are made.
Execute
Execute capabilities involve triggering a broader business process or external action, such as sending communications, triggering workflows, creating orders, or processing other business operations. Because these actions can have a direct business impact, they often require additional validation, limits, or human approval.
Permission Matrix
A permission matrix provides a practical way to define exactly what each chatbot or user type is allowed to.
Step 2: Set Up the Agent or AI Layer
Once the chatbot’s capabilities and permissions are defined, the next step is to configure the agent or AI layer. This layer is responsible for understanding user requests, accessing relevant information, selecting appropriate actions, and managing the overall conversation.
Create the Agent
You should start by defining a clear purpose for the agent. Avoid building a general-purpose assistant that attempts to handle every Salesforce task. Instead, focus on a specific use case, such as supporting sales representatives, assisting service teams, or helping employees retrieve internal information.
Define Agent Instructions
Agent instructions establish the agent’s role, behavior, priorities, and boundaries. They should explain what the agent is expected to do, what it should avoid, when it should ask for clarification, and when it must escalate a request or seek human approval.
Configure Subagents
For more complex implementations, related capabilities can be organized into specialized subagents. For example, a sales assistant might include separate subagents for account research, opportunity analysis, and task management. This makes the overall agent easier to manage, test, and expand.
Define Actions
Actions connect the AI layer to actual business functionality. An agent might use actions to retrieve records, update an opportunity, create a task, trigger a Flow, or call an external API. Each action should have a clearly defined purpose, inputs, permissions, and expected result.
Add Variables
Variables allow the agent to maintain structured information throughout the conversation. Examples include an Account ID, Opportunity ID, customer identity, order number, or approval status. Using variables reduces the need to repeatedly infer important information from natural-language conversation history.
Configure Data Sources
Identify the information the agent needs to access, such as Salesforce records, Knowledge articles, documents, or enterprise data. Each source should be connected based on the chatbot’s specific use case rather than giving the agent unrestricted access to all available information.
Configure Connections
Connections allow the agent to interact with external systems and services. These may include APIs, ERP platforms, third-party applications, or external AI services. Authentication, permissions, error handling, and data validation should be configured before exposing these capabilities to users.
Test Initial Behavior
Before expanding the chatbot’s functionality, test a focused set of realistic user scenarios. Verify that the agent understands requests, selects the correct subagent or action, retrieves appropriate data, respects permissions, and handles unclear or failed requests safely. Starting with a narrow test scope makes issues easier to identify before the agent is deployed more broadly.
Step 3: Define Agent Behavior with Agent Script
Agent Script helps developers combine natural-language instructions with more structured, programmatic control. Rather than leaving every decision entirely to LLM interpretation, developers can use instructions, variables, conditions, routing, and action logic to create more predictable agent behavior.
Instructions
Instructions define how the agent should behave and respond. They can establish the agent’s role, priorities, boundaries, and expected behavior in different situations. Clear instructions should also define when the agent needs more information, when it should escalate a request, and which actions it should avoid.
Variables
Variables store structured information that the agent needs throughout a conversation or workflow. For example, an agent may store an Account ID, Opportunity ID, customer identity, order number, or approval status. This reduces reliance on the LLM to repeatedly infer important information from conversation history.
Conditional Logic
Conditional logic allows the agent to follow predictable rules when specific conditions are met. For example, the system might verify that a customer is authenticated before retrieving order information or check whether approval has been granted before executing a high-risk action.
Subagent Routing
Subagent routing helps direct requests to the appropriate specialized capability. A sales-related question might be routed to an account or pipeline analysis subagent, while a service request could be directed to a customer support subagent. This can improve organization and reduce the complexity of a single agent handling every responsibility.
Action Selection
The agent must determine which action is appropriate for a user’s request, such as retrieving a record, creating a task, triggering a Flow, or calling an API. Action selection should be constrained by the agent’s permissions, available inputs, and business rules rather than relying solely on model judgment.
Deterministic vs. AI-Driven Logic
The most important design decision is determining where AI reasoning should end and deterministic logic should begin. Use AI for natural-language understanding, contextual interpretation, and flexible reasoning. Use deterministic logic for permissions, validation, transaction rules, calculations, and high-risk business actions.
Step 4: Connect the Chatbot to Salesforce Data
A chatbot’s usefulness depends on its ability to access relevant business information. The data architecture should clearly define which records and knowledge sources the AI can retrieve, while ensuring that existing Salesforce permissions and access controls are respected.
Accounts
Accounts provide information about customers, companies, partners, or other organizations. The chatbot can use account data to answer questions, generate summaries, identify recent activity, and provide a broader view of the customer relationship.
Contacts
Contact records provide information about the people associated with accounts. An AI chatbot can retrieve contact details, interaction history, roles, and related activities to provide more personalized and context-aware responses.
Leads
Lead data can help sales teams quickly review potential customers, qualification status, engagement history, and next steps. The chatbot can summarize lead information or help users identify which leads require follow-up.
Opportunities
Opportunities are a key source of sales and pipeline information. The chatbot can retrieve opportunity details, analyze deal stages, identify stalled opportunities, summarize recent activity, and recommend appropriate follow-up actions.
Cases
Case data gives the chatbot access to customer service history and support information. It can summarize previous issues, explain case status, identify recurring problems, and help service teams understand the context before responding to a customer.
Knowledge
Salesforce Knowledge and other approved knowledge sources can provide answers to common questions, policies, procedures, troubleshooting guides, and product information. This is particularly useful for grounding AI responses in approved business content.
Custom Objects
Many organizations store critical business information in custom objects. Depending on the implementation, the chatbot can access these objects to support industry-specific workflows, internal processes, and data models that extend beyond standard Salesforce functionality.
Data 360 / Enterprise Data
Some AI use cases require information beyond the Salesforce CRM. Data 360 and other enterprise data sources can help connect customer, operational, transactional, or external information across the organization. This is particularly useful when the chatbot needs a broader view of the business rather than relying only on individual Salesforce records.
Step 5: Add RAG for Business Knowledge
RAG helps the chatbot access relevant business knowledge at the time of a user’s request. Instead of relying only on the AI model’s general knowledge, the system retrieves relevant information and provides it as context for generating the response.
The basic flow looks like this:
When RAG Is Necessary
RAG is useful when the chatbot needs access to information that is not available in structured Salesforce records or that changes frequently. This may include product documentation, internal policies, contracts, support articles, procedures, or other business knowledge.
What Data to Index
Only index information that is relevant to the chatbot’s use case. Potential sources include Salesforce records that change frequently. This may include product documentation, internal policies, contracts, support articles, procedures, or other business knowledge.
Chunking
Large documents are typically divided into smaller sections, or chunks, before indexing. Effective chunking keeps related information together while making it easier for the retrieval system to identify the most relevant content for a specific question.
Retrieval Quality
The quality of the final answer depends heavily on the quality of the retrieved information. Teams should test whether the system consistently finds the right documents and sections, rather than evaluating only whether the LLM produces a well-written response.
Permissions
RAG must respect existing access controls. A user should not be able to retrieve sensitive documents or business information simply by asking the chatbot a well-worded question. Permissions should be enforced before information is provided as AI context.
Citations/Sources
Where possible, the chatbot should show users which knowledge sources supported its answer. Source citations improve transparency, help users verify important information, and make it easier to investigate inaccurate or outdated responses.
Updating Knowledge
The knowledge base should be updated as business information changes. New policies, product documentation, and revised procedures should be reflected in the retrieval system so the chatbot can access the latest approved information.
Step 6: Give the Chatbot Actions
This is where an AI chatbot moves beyond answering questions and starts creating real business value. Actions allow the chatbot to interact with Salesforce workflows, records, and external systems to complete approved tasks.
Possible actions include:
- Create a Lead
- Update an Opportunity
- Create a Case
- Schedule a Task
- Retrieve Order Information
- Trigger an Approval
- Search Inventory
- Call an ERP
- Generate a Quote
Each action should have a clearly defined purpose, required inputs, permissions, validation rules, and expected outcome. For example, an agent may understand a user’s request to update an opportunity, but the underlying action should still verify record access, validate the requested changes, and enforce relevant business rules before updating Salesforce.
Agentforce can use actions backed by Salesforce capabilities, including Flow and custom code, allowing developers to connect AI reasoning with existing business processes. Salesforce also supports building custom Agentforce actions from Apex REST APIs exposed through its API catalog, providing another option for connecting agents to specialized logic and external services.
Flow vs. Apex vs. API: Which Should You Use?
| Requirement | Flow | Apex | External API |
|---|---|---|---|
| Simple CRM Automation | ✔ | ||
| Business Workflow | ✔ | ✔ | |
| Complex Logic | ✔ | ||
| Salesforce Transactions | ✔ | ✔ | |
| External Systems | ✔ | ✔ | ✔ |
| Complex Processing | ✔ | ✔ | |
| Low-Code Maintenance | ✔ | ||
| Highly Custom Behavior | ✔ | ✔ |
Step 7: Connect External AI or Business APIs
Custom Salesforce AI architectures often need to communicate with external services, such as LLM providers, ERP systems, inventory platforms, pricing engines, or other enterprise applications. A controlled integration layer keeps these connections secure and makes external responses easier to validate before they affect Salesforce.
A recommended pattern is:
Use Named Credentials for Secure Connections
Salesforce Named Credentials help separate API endpoints and authentication configuration from application code. This means developers don’t need to hardcode sensitive authentication details into Apex.
For modern implementations, teams should use the newer Named Credentials and External Credentials architecture rather than building new integrations around legacy credential patterns.
Handle Authentication
Use managed credentials rather than embedding API keys, tokens, or passwords directly in Apex. Access should also be limited to the external services and operations the integration actually requires.
Validate Inputs
Validate data before sending it to an external service. This helps prevent malformed requests, unintended data exposure, and potentially dangerous user-controlled input from reaching downstream systems.
Handle Timeouts and API Errors
External services can be unavailable, slow, or return unexpected responses. The integration should handle timeouts, HTTP errors, rate limits, and service failures gracefully rather than allowing the entire Salesforce transaction to fail unexpectedly.
Use Retries Carefully
Retries can help with temporary failures, but they should be implemented selectively. Retrying a read operation may be relatively safe, while automatically retrying a transaction that creates an order or sends a communication could result in duplicate actions.
Validate Responses
Never assume an external response is correct simply because the request succeeded. Validate the response structure, required fields, status, and business conditions before using the result in Salesforce.
Add Logging
Record enough information to troubleshoot failed integrations and monitor performance without necessarily logging sensitive customer or authentication data.
Step 8: Build the Chat Experience
Once the AI, data, and action layers are connected, the next step is to decide where users will interact with the chatbot. The interface should match the user’s workflow while maintaining the same security, permissions, and business rules across channels.
Salesforce Internal Users
For employees, the chatbot can be embedded directly into Salesforce so users can access AI assistance without switching applications. Sales teams might use it to summarize accounts and opportunities, while operations teams could retrieve records or trigger approved workflows.
Service Console
Customer service teams can use an AI assistant alongside cases and customer records. The chatbot can summarize case history, search Knowledge, recommend next steps, retrieve order information, or help agents resolve issues faster.
Experience Cloud
Experience Cloud can provide AI-powered self-service to customers, partners, or other external users. Access must be carefully restricted so external users only receive information and actions appropriate to their role and records.
Website
A website chatbot can support prospects and customers with product questions, lead qualification, FAQs, and basic support. When deeper Salesforce access is required, the chatbot can securely connect to CRM data and workflows through controlled APIs or agent actions.
Mobile
A mobile AI assistant can give sales and field teams access to Salesforce intelligence while they are away from their desks. Mobile experiences should prioritize concise responses, common actions, and fast access to information.
External Applications
Organizations may also expose AI capabilities through custom applications, portals, or other enterprise software. In these cases, Salesforce can act as one part of a broader architecture, with APIs or integration services connecting the chatbot to CRM data and business processes.
Security: Don’t Let Your AI Chatbot Become a Salesforce Super Admin
An AI chatbot may need broad access to be useful, but giving it unrestricted Salesforce permissions creates unnecessary risk. The chatbot should operate within clearly defined boundaries and enforce the same security principles as other Salesforce applications.
Principle of Least Privilege
Give the chatbot only the permissions required for its specific use case. A service assistant that needs to retrieve cases and Knowledge articles does not need permission to modify opportunities or delete records.
User Context
The chatbot should understand who is making the request and apply the appropriate user permissions and context. The AI should not become a way for a lower-privileged user to access information they could not normally see.
Object-Level Access
Control which Salesforce objects the chatbots can access. If an agent doesn’t need access to payroll, financial, or other sensitive objects, those objects should not be exposed to it.
Field-Level Security
Access should also be restricted at the field level. Sensitive fields such as financial information, personal data, or internal notes should only be exposed when the user and use case are authorized to access them.
Record-Level Access
The chatbot should respect record-level visibility and sharing rules. Being able to ask for a specific account, opportunity, or case in natural language should not automatically grant access to that record.
API Credentials
External API credentials should never be hardcoded into prompts, Apex, or client-side code. Use appropriate credential-management mechanisms and limit each integration to the permissions it actually requires.
Prompt Injection
Users, documents, or retrieved content may contain instructions designed to manipulate the agent into ignoring its rules. Treat prompts and retrieved content as untrusted input, and enforce security and authorization outside the LLM wherever possible.
Sensitive Data Leakage
The chatbot should avoid exposing confidential information through responses, retrieved context, logs, or external AI services. Data should be filtered according to the user’s permissions before it reaches the model.
Action Authorization
Every write or execution action should have explicit authorization and validation. The LLM can recommend or select an action, but deterministic Salesforce logic should verify permissions, inputs, business rules, and limits before execution.
Human Approval
High-impact actions should require human confirmation or approval. Changes to pricing, refunds, sensitive customer information, orders, or other consequential business processes should not depend entirely on autonomous AI decisions.
How to Prevent Dangerous AI Actions?
As an AI chatbot moves from answering questions to changing records or triggering business processes, the potential impact of mistakes increases. A useful approach is to classify actions by risk and apply stronger controls as the potential business impact increases.
| Action | Risk | Recommended Control |
|---|---|---|
| Search Knowledge | Low | Normal permissions |
| Read Account | Low-medium | User access |
| Update Opportunity | Medium | Validation |
| Send Customer Email | Medium | Preview/approval |
| Change Pricing | High | Human approval |
| Issue Refund | High | Approval + limits |
| Delete Records | Very High | Restrict |
Step 9: Test the Chatbot Properly
Testing an AI chatbot requires more than checking whether it produces convincing answers. A production Salesforce AI chatbot must be evaluated across its reasoning, data retrieval, actions, security, and failure handling. Testing should cover both normal business scenarios and intentionally difficult or malicious inputs.
Intent/Subagent Recognition
Verify that the chatbot correctly understands what the user is trying to accomplish and routes the requests to the appropriate subagent or capability. Test similar requests with different wording to ensure routing remains consistent.
Response Accuracy
Check whether responses are factually correct, relevant, complete, and based on available business data. Include scenarios where the correct answer is that the required information is unavailable.
Knowledge Retrieval
Test whether the chatbot retrieves the right Salesforce Knowledge articles, documents, or other sources. Poor retrieval can produce incorrect answers even when the underlying LLM performs well.
Action Selection
Verify that the agent chooses the correct action for each request. For example, a request to create a task should not accidentally trigger an opportunity update or another unrelated workflow.
Action Execution
Test whether selected actions actually produce the intended result. For example, a request to create a task should not accidentally trigger an opportunity update or another unrelated workflow.
Permissions
Test the chatbot using users with different roles and access levels. Confirm that it respects object, field, and record-level permissions and cannot expose information simply because a user asks for it conversationally.
Hallucinations
Deliberately test questions where information is missing, ambiguous, or unavailable. The chatbot should acknowledge uncertainty or ask for clarification rather than inventing Salesforce records, policies, prices, or business facts.
Prompt Injection
Test whether malicious instructions in user messages or retrieved documents can cause the agent to ignore its instructions, expose sensitive information, or perform unauthorized actions. Security controls should remain effective even when the model is manipulated.
Edge Cases
Test incomplete requests, ambiguous names, incorrect IDs, unusual data, conflicting instructions, duplicate requests, and unexpected system responses. These scenarios often reveal weaknesses that normal happy path testing misses.
Human Escalation
Verify that the chatbot knows when it should stop and involve a human. High-risk actions, unresolved requests, sensitive customer issues, and repeated failures should have clear escalation paths.
A strong testing strategy should therefore evaluate the complete workflow:
This ensures that the chatbot is not only conversationally capable but also reliable and safe when interacting with real Salesforce business processes.
Agent Testing: Manual vs. Automated
Manual Testing
Manual testing involves humans interacting with the AI agent to evaluate how it handles realistic conversations, ambiguous requests, unexpected inputs, and edge cases. It is especially useful during early development when workflows and prompts are still changing.
Testers should verify intent recognition, response quality, knowledge retrieval, action selection, permissions, error handling, and human escalation. Manual testing is also valuable for identifying subtle issues such as misleading responses or unexpected agent behavior that automated tests may miss.
Automated Testing
Automated testing uses predefined test cases, simulations, and evaluation frameworks to repeatedly test the agent at scale. It can validate hundreds or thousands of conversations, workflows, permissions, and expected outcomes without requiring a human to run each test.
Automated tests are particularly useful for regression testing after changes to prompts, knowledge sources, models, flows, or integrations. They help teams detect whether an update introduces hallucinations, breaks an existing workflow, triggers the wrong action, or changes response accuracy.
Step 10: Deploy Through a Proper Development Lifecycle
AI agents should not be moved directly from development into production. A controlled deployment lifecycle reduces the risk of broken automations, incorrect actions, security issues, and unexpected agent behaviors.
Development
Develop the Agentforce configuration, prompts, topics, actions, flows, Apex, and supporting components in a controlled development environment. Keep changes isolated so developers can experiment without affecting production users or data.
Sandbox
Deploy changes to a Salesforce sandbox that closely represents the production environment. Validate integrations, permissions, data access, flows, and agent behavior using realistic scenarios.
Testing
Run functional, integration, regression, security, and agent-specific tests. Confirm that the agent selects the correct intent, retrieves appropriate knowledge, performs authorized actions, and handles failures safely.
UAT
Business users should test the agent against real-world scenarios and workflows. UAT confirms that the agent’s behavior meets business expectations, not simply that the underlying technology works.
Security Review
Review permissions, sharing rules, authentication, sensitive data access, prompt-injection risks, Apex and Flow actions, and external integrations before production deployment.
Production
Deploy the approved and tested version through a controlled release process. Avoid making untested prompt, action, permission, or configuration changes directly in production.
Monitoring
Monitor conversations, action failures, escalations, response quality, usage, and unexpected behavior after launch. Treat deployment as the beginning of an improvement cycle rather than the end of development.
Salesforce DX
Salesforce DX provides a development workflow for managing Salesforce metadata, source code, environments, and deployments. Teams can use it to develop Salesforce components consistently and move changes between environments in a controlled way.
Source Control
Store Apex, Flows, metadata, agent configurations, prompts, and related code in a version-control system such as Git. This gives developers a history of changes, enables collaboration, and makes it easier to review or roll back changes.
Agentforce DX
Agentforce DX extends the Salesforce development workflow to agent development, allowing teams to manage agent-related metadata and configurations alongside the rest of their Salesforce source. This helps make AI agent changes traceable, reviewable, and deployable through established engineering practices.
CI/CD
Use CI/CD pipelines to automatically validate and deploy changes. A pipeline can run Apex tests, metadata validation, agent regression tests, security checks, and deployment validations before changes reach production.
Versioning
Version prompts, agent configurations, actions, knowledge sources, flows, and supporting code. When an agent behaves differently after an update, version history makes it easier to identify what changed and restore a known-good version.
Regression Tests
Maintain a collection of important agent scenarios and run them whenever the agent, prompt, knowledge base, model, Flow, Apex, or integration changes. Regression testing helps ensure that fixing one agent behavior doesn’t accidentally break another.
Step 11: Monitor the Chatbot After Launch
Launching the chatbot is not the end of the implementation. Continuous monitoring helps identify technical failures, declining AI quality, and business problems before they significantly affect customers or employees. Track both AI performance and business outcomes so the team can determine whether the agent is actually delivering value.
1. Technical Metrics
- Response latency: Measure how quickly the agent responds and identify slow conversations or bottlenecks.
- Errors: Track system, Flow, Apex, integration, and configuration errors.
- Failed actions: Monitor actions that the agent attempts but cannot complete successfully.
- Retrieval quality: Evaluate whether the agent is finding relevant and accurate information from its knowledge sources.
- API failures: Track failed or timed-out calls to Salesforce and external systems.
- Escalations: Monitor how frequently conversations are transferred to human agents and identify recurring reasons for escalation.
2. AI Quality Metrics
- Accuracy: Measure whether the agent provides the correct and relevant answers.
- Groundedness: Check whether responses are supported by approved knowledge or available data rather than unsupported claims.
- Action selection: Track whether the agent consistently chooses the correct Flow, Apex action, API, or other capability.
- Hallucination rate: Identify responses containing inaccurate, invented, or unsupported information.
- Task completion: Measure how often users complete their intended task without requiring additional assistance.
3. Business Metrics
- Cases deflected: Measure how many support cases are resolved by the agent without human intervention.
- Resolution time: Compare customer or employee resolution times before and after deployment.
- Sales productivity: Measure whether sales representatives spend less time on repetitive tasks and more time on revenue-generating activities.
- Lead response time: Track whether AI-powered lead handling reduces the time between lead creation and follow-up.
- User adoption: Monitor how frequently employees or customers actually use the chatbot and whether usage increases over time.
- Manual work reduced: Estimate the amount of repetitive human effort eliminated through automation.
Example: Build an AI Sales Assistant Inside Salesforce
Consider a sales representative who wants a quick view of an important customer without manually reviewing multiple Salesforce records.
User asks:
“Give me a summary of XYZ Corp and tell me which opportunities need attention.”
The agent can handle this request through a controlled workflow:
Identify User
Determine who is making the request and retrieve the appropriate Salesforce user context.
Verify Permissions
Confirm that the user has permission to access Acme Corp’s account, opportunities, activities, and related information.
Retrieve Account
Fetch the account record, including company details, account status, contacts, recent interactions, and other relevant fields.
Retrieve Opportunities + Activities
Review open opportunities, stages, amounts, close dates, recent activities, and upcoming tasks to identify potential sales risks.
Retrieve Relevant Knowledge
Pull relevant product information, sales guidelines, pricing policies, or other approved knowledge that can help interpret the account and opportunities.
Generate Account Summary
Combine the retrieved information into a concise summary highlighting the customer’s current status, recent activity, opportunities, and important risks.
Identify Stalled Opportunities
Analyze opportunity activity and stage information to identify deals with delayed follow-ups, inactive engagement, approaching close dates, or other warning signs.
Recommend Actions
Suggest practical next steps, such as contacting a decision-maker, scheduling a follow-up, updating an opportunity stage, or addressing a specific customer concern.
User Approves
Before making changes, the agent presents the proposed actions and asks the sales representative for confirmation.
Create Salesforce Tasks
After approval, the agent creates the appropriate Salesforce tasks and assigns them to the relevant users with suitable due dates.
This demonstrates a safe agent pattern:
The important distinction is that the AI can analyze and recommend autonomously, while consequential Salesforce changes require explicit user approval. This provides useful automation without giving the agent unrestricted control over business data or workflows.
Common Development Mistakes
Giving the LLM Too Much Responsibility
Do not expect the LLM to make every business decision. Use deterministic Salesforce Flows, Apex, validation rules, and permission controls for rules that must be predictable and enforceable.
Putting Business Rules Inside Prompts
Prompts should guide the agent’s behavior, not become the primary location for critical business logic. Business rules placed only in prompts can be difficult to test, maintain, and enforce consistently.
Skipping RAG and Sending Huge Contexts
Sending large amounts of data directly to the model increases cost, latency, and the risk of irrelevant responses. Use appropriate retrieval and grounding strategies to provide only the information needed for each task.
Giving Agents Excessive Permissions
Agents should follow the principle of least privilege. Give them access only to the records, fields, objects, and actions required for their specific responsibilities.
Allowing High-Risk Actions Without Approval
Actions such as deleting records, issuing refunds, changing important customer data, or sending sensitive communications should have appropriate safeguards. Require human approval when the consequences of an incorrect action are significant.
Ignoring Failed Tool Calls
Tool calls can fail because of permissions, invalid inputs, API problems, missing data, or system outages. Design agents to detect failures, explain them clearly, retry when appropriate, and escalate when necessary.
Testing Only Happy Paths
An agent may work perfectly with straightforward requests but fail with ambiguous, incomplete, conflicting, or malicious inputs. Test edge cases, permission boundaries, unexpected tool responses, prompt injection, and human escalation scenarios.
Hardcoding API Credentials
Never place API keys, passwords, tokens, or other credentials directly in prompts, Apex code, repositories, or configuration files. Use Salesforce-supported authentication and secure credential-management mechanisms.
Ignoring Cost and Latency
Every model call, retrieval operation, and external API request can add cost and delay. Monitor token usage, response times, model selection, and unnecessary tool calls, then optimize the workflow around business requirements.
Building a Chatbot When a Flow Would Be Better
Not every process needs an AI agent. If a workflow has predictable inputs, clear rules, and deterministic outcomes, a Salesforce Flow or traditional automation may be more reliable, cheaper, and easier to maintain. Use AI where reasoning, natural-language interaction, or dynamic decision-making genuinely adds value.
When Should You Use Agentforce vs. Build a Custom AI Chatbot?
| Scenario | Recommended Starting Point |
|---|---|
| Salesforce-native employee assistant | Agentforce |
| CRM sales agent | Agentforce |
| Service automation | Agentforce |
| Custom AI product embedded in Salesforce | Custom/Hybrid |
| Multiple external AI models | Custom/Hybrid |
| Complex external orchestration | Custom/Hybrid |
| Simple deterministic workflow | Flow/Apex |
| Enterprise agent using Salesforce + multiple systems | Agentforce/Hybrid |
How CodingCops Builds Custom AI Solutions for Salesforce?
CodingCops approaches Salesforce AI development as an end-to-end engineering process, combining Salesforce architecture with AI, data, automation, security, and continuous optimization.
Architecture
Start by understanding the business process, Salesforce environment, and AI use case. Design an architecture that clearly defines where Salesforce, AI models, agents, integrations, and external services fit together.
Data
Connect the AI solution to trusted business data, including CRM records, Data 360, enterprise knowledge, and relevant external sources. Use RAG where appropriate so agents can access current, context-specific information.
Intelligence
Select the right intelligence layer for the use case, including Agentforce, LLMs, specialized agents, or custom orchestration. The goal is to use AI for reasoning and decision support without unnecessarily placing deterministic logic inside the model.
Actions
Connect AI recommendations to real business processes through Salesforce Flow, Apex, MuleSoft, APIs, and external systems. Actions are designed with appropriate validation, permissions, and approval requirements.
Security
Build security into the architecture from the beginning. This includes Salesforce permissions, least-privilege access, guardrails, approval workflows, data protection, auditability, and governance controls.
Engineering
Apply established software engineering practices to AI development. Use Salesforce DX and source control alongside automated testing, CI/CD, versioning, controlled deployments, and production monitoring.
Optimization
After launch, measure both AI quality and business outcomes. Monitor accuracy, groundedness, task completion, latency, failures, adoption, productivity, and other relevant KPIs. Use these insights to continuously improve the agent and underlying Salesforce workflows.
Conclusion
Building a Salesforce AI chatbot requires more than connecting an LLM to CRM data. The strongest implementations combine intelligent reasoning with secure data access, controlled actions, rigorous testing, and monitoring. Whether you choose Agentforce, custom AI, or a hybrid architecture, success depends on aligning AI capabilities with business processes and governance.




