Apex Aide apexaide

Invoke Salesforce Prompt Template from LWC using Apex

www.infallibletechie.com· ·Intermediate ·Developer ·5 min read
Summary

This content explains how to leverage Apex as a bridge to invoke Salesforce GenAI Prompt Templates from Lightning Web Components, overcoming current technical limitations. It demonstrates a complete pattern where LWC captures user input, calls Apex which in turn invokes the Einstein LLM ConnectApi to generate AI responses, and then renders those responses back in the UI. Salesforce teams can use this approach to embed AI-generated knowledge base answers within custom Experience Cloud or Lightning interfaces. The guide includes detailed Apex controller code and an LWC example for practical implementation.

Takeaways
  • Use Apex ConnectApi to invoke GenAI Prompt Templates not accessible directly from LWC.
  • Structure communication: LWC sends user input to Apex, Apex calls Prompt Template, returns AI response.
  • Implement safe error handling in Apex with AuraHandledException to protect user experience.
  • Use lightning-textarea and lightning-button in LWC to collect input and trigger Apex calls.
  • Disable submit button during in-progress calls and empty input to avoid redundant requests.

How to Invoke a Salesforce Prompt Template from a Lightning Web Component (LWC)? With the rise of Einstein GenAI, developers are looking for ways to bring the power of Generative AI directly into custom user interfaces. While Salesforce provides robust tools like Prompt Builder, there is currently a technical limitation: you cannot invoke a Prompt Template directly from a Lightning Web Component (LWC). However, there is a powerful workaround. By using Apex as a bridge, you can trigger these templates and surface AI-generated responses within your custom LWC. In this guide, we will walk through the architecture and code required to invoke a GenAI Prompt Template from an LWC. The Architecture: LWC → Apex → Prompt Template Since LWCs cannot call the ConnectApi for Einstein LLM directly, the flow follows these steps: LWC: Captures user input and calls an Apex method. Apex: Uses the ConnectApi.EinsteinLLM class to provide input to the Prompt Template and generate a response.

ApexLightning Web ComponentsExperience CloudSalesforceSalesforce ApexSalesforce Lightning Web ComponentSalesforce Prompt Template