Tuesday, 2 January 2024

Evaluate Dynamic Formulas in Apex (Spring 24 Developer Preview)

 The Dynamic Formula brings enhanced capabilities for evaluating user-defined formulas for Apex objects and sObjects.


With the new ‘FormulaEval’ namespace, you can now optimise database CPU demands and avoid static expressions when evaluating formula expressions.


Note : To leverage this feature, ensure that the FormulaEvalInApex feature is enabled in your scratch orgs.Without the feature enabled, Apex code utilising this feature can be compiled but not executed.


Creating a formula instance is made easy with the FormulaBuilder class.


Simply call the static method builder() with the formula text, return type, and context object.


Validate the formula instance by using the build() method, which may trigger the FormulaValidationException exception if the validation fails.


Once your formula instance is validated, you can calculate the formula expression and retrieve the result using the evaluate() method in the FormulaInstance class.


If an error occurs during evaluation, the method will trigger the FormulaEvaluationException exception.


Ex : The usage of the build() and evaluate() methods


global class MotorYacht {

  global Integer lengthInYards;

  global Integer numOfGuestCabins;

  global String name;

  global Account owner;

}


MotorYacht aBoat = new MotorYacht();

aBoat.lengthInYards = 52;

aBoat.numOfGuestCabins = 4;

aBoat.name = 'Go Boat';


// Example 1: Evaluate 'isItSuper' formula instance


FormulaEval.FormulaInstance isItSuper = FormulaEval.FormulaBuilder.builder()

.withReturnType(FormulaEval.FormulaReturnType.STRING)

.withType(MotorYacht.class)

.withFormula('IF(lengthInYards < 100, "Not Super", "Super")')

.build();


isItSuper.evaluate(aBoat); //=> "Not Super"


// Example 2: Evaluate 'ownerDetails' formula instance


aBoat.owner = new Account(Name='Acme Watercraft', Site='New York');

FormulaEval.FormulaInstance ownerDetails = FormulaEval.FormulaBuilder.builder()

.withReturnType(FormulaEval.FormulaReturnType.STRING)

.withType(MotorYacht.class)

.withFormula(‘owner.Name & " (" & owner.Site & ")"')

.build();


ownerDetails.evaluate(aBoat); //=> "Acme Watercraft (New York)"


Monday, 1 January 2024

Make Callout After DML Rollback and Releasing Savepoint (Spring 24 apex)

 Roll back all uncommitted DML by using a savepoint. Then use the new Database.releaseSavepoint method to explicitly release savepoints before making a desired callout.Previously, callouts after creating savepoints resulted in a CalloutException regardless of whether there was uncommitted DML or the changes were rolled back to a savepoint.


To execute callouts post-rollback, adhere to these steps:


  1. Revert all uncommitted changes using a savepoint.
  2. Please make sure to explicitly release the savepoint via the Database.releaseSavepoint method.
  3. Now, perform your intended callout without encountering any hindrances.


Ex :

Savepoint mySavepoint = Database.setSavepoint();


try {

    // Attempt a database operation

    insert new Account(name='Foo');

    Integer divisor = 1 / 0;

} catch (Exception e) {

    // Roll back to the savepoint in case of an exception

    Database.rollback(mySavepoint);

    Database.releaseSavepoint(mySavepoint); // Release any savepoints created after 'mySavepoint'

    

    // Perform a callout as uncommitted work is rolled back and savepoints are released

    initiateCallout();

}

Null Coalescing Operator (Spring 24 Apex)

The ?? Operator returns the left-hand argument if the left-hand argument isn't null. Otherwise, it returns the right-hand argument.

 

// Left operand SOQL is empty, return defaultAccount from right operand:

Ex :

Account defaultAccount = new Account(name = 'Acme');

Account a = [SELECT Id FROM Account WHERE Id = '001000000FAKEID'] ?? defaultAccount;

Assert.areEqual(defaultAccount, a);

Thursday, 19 October 2023

How Data cloud works?

 


  • Connect all your data sources whether batch or streaming data.
  • Prepare your data through transformation and data governance features.
  • Harmonize your data to a standard data model.
  • Unify data with identity resolution rulesets.
  • Query and analyze data using insights.
  • Use AI to predict behavior.
  • Segment your data and activate to use in various channels to create personalized experiences.
  • Analyze your data using supported analytic tools.
  • Output data to multiple sources to act on data based on your business needs.
  • Continue to review, measure, and optimize data.

Saturday, 14 October 2023

Einstein Trust Layer

 Interacting with generative AI is a simple as sending a prompt to a large language model and getting a response.


Salesforce Introduced Einstein trust layer as part of the Einstein 1 Platform.


The trust layer is a secure intermediary for user interactions with LLM’s. Masking PII checking output toxicity etc.


Every prompt that runs through the trust layer starts out in the Einstein 1 platform and usually originates from one of our CRM applications.


Once the prompt hits the trust layer it goes through a multi-step process to ensure that the response is generated and sent back to the user.


  1. Secure Data Retrieval

   If the prompt uses merge fields to pull in record data for example from a contact. It pulls that record data from the page context in one instance or if that prompt starts out on the server it pulls via SOQL.


      2. Dynamic Grounding 


Dynamic grounding is able to bring business logic into the transaction itself.


Ex : 


If that prompt requires you to go out and pull data from flow or from data cloud you can bring in that additional context into to enrich the prompt and further grounded in detail so that it’s more knowledgeable about the case at hand .


   3. Data Masking


To prevent sharing PII we use data masking a detection tool identify sensitive data like government IDs replacing them with placeholders like Person_0,Person_1 etc.


Trust layer maintains this placeholder origin mapping for you.


Once masking is completed we apply additional ‘prompt Defense’ 


  4. Prompt Defense


Ensuring that model responses remain reliable and avoid misleading outputs.


Once prompt is secured it then proceeds to the LLM  Gateway.


LMM Gateway :


This manages connections with various model providers and on reaching out to the gateway the prompt roots to the necessary model.


If sent to external models like Open AI the data is encrypted and never stored externally.


  5. Zero Retention :


Open AI is our first LLM partner operates a zero retention basis for prompts.


They also have a Content moderation API that flags unusual or harmful content and alerts salesforce of this immediately.


Once the response has been generated from the LLM gateway it’s ready to present back to the user.


But first we want to take that response and ensure that it’s safe with the first step of the after generation process and that is toxicity detection .


  6.Toxicity Detection :


We are going to take that response and run it through our toxicity filter to ensure that there is no harmful content any negative language and make sure that it’s safe and secure for your users.


  7.Data Demasking :


We are going to take all of the data that was masked in the original step through the masking process and we’re going to rehydrate that through demasking so that all of the data like the name , first name and addresses are all put back into the response and then it’s ready to be presented back to the user.


8.Feedback Framework


We have feedback framework in place with api’s so that you can provide feedback to the generation so whether or not it was useful or not whether or not it was successful is all logged and will be used for us to retrain the models and ensure that we’re providing the responses that you need.


9.Audit Trail 


We allow you to store the prompt any actions that were taken the toxicity so that you can provide trusted generative AI at scale.


This is just the first step towards creating the trust between yourself your company and generative AI.




Understanding 4 Waves of AI

 1.Predictive AI

2.Generative AI

3.Autonomous AI

4.Artificial General Intelligence


1.Predictive AI :


Uses historical data to forecast future events.


Predictive AI  generic use cases


Data analytics, Stock market predictions, Weather forecasting etc


Ex : Einstein Lead Scoring


Automatically scores and prioritises leads based on their likelihood to convert.


Ex : Einstein Opportunity Insights


Predicts the likelihood of an opportunity closing Successfully, providing real-time insights.


Ex: Einstein Prediction Builder


Allows the creation of custom AI models to predict business-specific outcomes like churn.


Ex: Einstein Vision 


Can analyse images for predictive maintenance, such as when machinery parts may fail.


Note : Predictive AI is specialised in forecasting based on existing data.


2.Generative AI :


Creates new data that resembles a given dataset.


Generative AI generic Use cases


Tech behind deep fakes, chatbots , MidJourney, Call-e,Stable Diffusion,ChatGPT etc.


Generative AI Salesforce Use cases 


Einstein Copilot :


A conversational assistant that can generate responses and prompts.


Einstein for Developers :


Can generate Apex code using natural language, aiding in rapid development.


Einstein Email Insights :


Generates suggested follow-ups or actions based on the content of emails.


DataWeave Codegen :


A generative AI tool that simplifies the use of MuleSoft’s DataWeave language by generating DataWeave scripts from sample input and output data.


Note : Generative AI is focused on creating new , similar data.



3.Autonomous AI :


Can make decisions and perform tasks without human intervention.


Autonomous AI generic use cases 


Self-driving cars and drones are prime examples.


Autonomous AI salesforce use cases


Einstein Bots :


Automates routine customer service tasks by handling inquiries without human intervention.


Einstein Case Classification :

Automatically categorises and routes customer service cases to the right agents.


Einstein Automated Contacts :


Uses email and event activity to fine new contacts and opportunity contact roles.


Note : Autonomous AI is all about making decisions and acting without human intervention.


  1. Artificial general intelligence (AGI)


Machines that possess the ability to understand , learn , and apply to knowledge across different domains, much like a human.


AGI is still very far away and will need significant breakthroughs in AI research before it can be achieved.


Note : Artificial General Intelligence aims to be as versatile and capable as humans in multiple domains.