The Secret Weapon: Prompt Engineering: 🪄

on

|

views

and

comments

Table of Contents

Introduction

Crafting the perfect prompt is like whispering secret instructions to your AI muse. But there’s no one-size-fits-all approach! Exploring different types of prompts unlocks a spectrum of possibilities in your Generative AI creations. Here’s a sneak peek:

Different Types of Prompt Engineering

1. The Classic Prompt: ✍️

  • Straightforward and clear, laying out the desired task or output.
  • Think: “Write a poem about a robot falling in love with the moon.”
  • Ideal for beginners and specific, focused tasks.

2. The N-Shot Prompt:

  • Provide a few examples (N) of the desired output to guide the AI.
  • Imagine: “Show me 3 examples of poems about nature written in free verse, then write your own.”
  • Useful for refining style and direction, fostering consistency.

3. The Chain-of-Thought Prompt:

  • Break down complex tasks into smaller, sequential steps.
  • Picture: “1. Identify emotions in this image. 2. Generate captions expressing those emotions in different tones. 3. Merge captions into a cohesive paragraph.”
  • Perfect for tackling intricate tasks, and promoting logical flow.

4. The Conditioned Prompt:

  • Sets specific constraints or parameters to shape the output.
  • Think: “Write a children’s story filled with puns, but avoid using clichés.”
  • Adds a layer of challenge and control, encouraging creative exploration within boundaries.

5. The Open-Ended Prompt:

  • Offers minimal guidance, leaving the AI to fill in the blanks.
  • Imagine: “Create a world where animals speak and build cities. Tell me a story about its most daring explorer.”
  • Sparks innovation and unexpected results, ideal for brainstorming and discovery.

6. Interactive Prompts:

  • Leverage user input or external data to dynamically adjust the narrative.
  • Picture: “You are a detective in a cyberpunk city. Tell me what you see as I describe the crime scene.”
  • Creates an immersive, personalized experience, blurring the lines between creator and creation.

Points to remember while writing prompt

  • Use clear and concise language in prompts.
  • Provide relevant context and data.
  • Adjust temperature for creativity or accuracy.
  • Experiment with different prompt formats and lengths.
  • Integrate model responses into Salesforce workflows using provided APIs.

Examples of Different Prompts

Classic Insight Prompt

Prompt: Analyze historical sales data of tech clients and identify key trends in purchasing behaviour.

				
					// Query tech client sales data
List<Opportunity> techSales = [
    SELECT Id, CloseDate, Amount, Product.Name
    FROM Opportunity
    WHERE AccountId IN (SELECT Id FROM Account WHERE Industry = 'Technology')
    AND IsClosed = true
    ORDER BY CloseDate DESC
];

// Calculate quarterly sales trends
Map<Date, Decimal> quarterlySales = new Map<Date, Decimal>();
for (Opportunity opp : techSales) {
    Date quarterStart = Date.newInstance(opp.CloseDate.year(), opp.CloseDate.month() - opp.CloseDate.month() % 3, 1);
    quarterlySales.put(quarterStart, quarterlySales.get(quarterStart) + opp.Amount);
}

// Identify top products by revenue
Map<String, Decimal> productRevenue = new Map<String, Decimal>();
for (Opportunity opp : techSales) {
    productRevenue.put(opp.Product.Name, productRevenue.get(opp.Product.Name) + opp.Amount);
}

// Display insights for developers to interpret
System.debug('Quarterly Sales Trends: ' + quarterlySales);
System.debug('Top Products by Revenue: ' + productRevenue);

				
			

Personalized Customer Prompt

Prompt: Recommend three relevant products for Customer X based on recent website visits and past purchases.

				
					// Gather customer data
Contact customerX = [SELECT Id, Name, RecentVisitedPages, PastPurchases FROM Contact WHERE Name = 'Customer X'];

// Collect product recommendations from Einstein (replace with your actual Einstein model)
List<ProductRecommendation> recommendations = EinsteinRecommendations.getRecommendationsForContact(customerX);

// Display top 3 recommendations
System.debug('Recommended Products for Customer X:');
for (Integer i = 0; i < 3; i++) {
    System.debug('- ' + recommendations[i].Product.Name);
}

				
			

Data-Driven Content Prompt

Prompt: Create a blog post addressing top customer concerns from surveys and support tickets.

				
					// Gather customer feedback data
List<Case> supportTickets = [SELECT Id, Subject, Description FROM Case WHERE Status = 'Closed' AND Type = 'Problem'];
List<SurveyResponse> surveyResponses = [SELECT Id, Question, Answer FROM SurveyResponse];

// Extract common topics and concerns
Set<String> topConcerns = new Set<String>();
for (Case ticket : supportTickets) {
    topConcerns.addAll(extractKeywords(ticket.Subject, ticket.Description));
}
for (SurveyResponse response : surveyResponses) {
    topConcerns.addAll(extractKeywords(response.Question, response.Answer));
}

// Generate blog content
String blogPost = '**Top Customer Concerns and How We're Addressing Them**\n\n';
for (String concern : topConcerns) {
    blogPost += '* **' + concern + ':**\n';
    blogPost += '    - Explanation of the concern\n';
    blogPost += '    - Steps we're taking to address it\n';
}

// Display blog post for developers to review and publish
System.debug(blogPost);

				
			

Predictive Scenario Prompt

Prompt 1: Predict the likelihood of a lead converting to an opportunity based on historical data and current lead attributes.

				
					public class LeadConversionPredictor {

    public PredictionResult predictLeadConversion(Lead lead) {
        // 1. Gather historical data for lead conversion analysis
        List<Lead> historicalLeads = [SELECT Id, ConvertedDate, ... FROM Lead WHERE ...];
        // 2. Train a prediction model (e.g., logistic regression, decision tree)
        Model model = trainPredictionModel(historicalLeads);
        // 3. Extract relevant lead attributes
        Map<String, Object> leadFeatures = extractLeadFeatures(lead);
        // 4. Generate prediction using the model
        Probability prediction = model.predict(leadFeatures);
        // 5. Return prediction result
        return new PredictionResult(prediction);
    }

    // Helper methods for model training and feature extraction
    private Model trainPredictionModel(List<Lead> leads) {
        // Implement model training logic
    }

    private Map<String, Object> extractLeadFeatures(Lead lead) {
        // Map lead attributes to features for the model
    }
}

				
			

Prompt 2: Identify customers most likely to churn within the next 6 months, considering past purchase patterns, engagement metrics, and support interactions.

				
					public class ChurnPredictor {

    public List<Customer> predictHighChurnRiskCustomers() {
        // 1. Gather relevant customer data from multiple objects
        List<Customer> customers = [SELECT Id, ... FROM Customer];
        List<Order> orders = [SELECT Id, CustomerId, ... FROM Order];
        List<Case> cases = [SELECT Id, CustomerId, ... FROM Case];
        // 2. Calculate churn risk scores based on defined criteria
        Map<Id, Decimal> churnScores = calculateChurnScores(customers, orders, cases);
        // 3. Identify customers with scores above a threshold
        List<Customer> highChurnRiskCustomers = new List<Customer>();
        for (Customer customer : customers) {
            if (churnScores.get(customer.Id) > churnThreshold) {
                highChurnRiskCustomers.add(customer);
            }
        }
        return highChurnRiskCustomers;
    }

    // Helper method for churn score calculation
    private Map<Id, Decimal> calculateChurnScores(List<Customer> customers, List<Order> orders, List<Case> cases) {
        // Implement churn score logic
    }
}

				
			

N-Shot Prompt

Prompt:

Generate a list of 3 email subject lines that are likely to get high open rates, based on the following examples:

  • Example 1: Your free trial is about to expire!
  • Example 2: Don’t miss out on this exclusive offer!
  • Example 3: 5 secrets to boosting your sales productivity

Response

  1. “Unlock VIP Access: Special Benefits Await You!”
  2. “Flash Sale Alert: Limited-time Savings Inside!”
  3. “Double Your Productivity with These Proven Strategies!”

Prompt: Write an Apex trigger that updates the ‘Last_Reviewed_Date’ field on the Account object to today’s date whenever a new Opportunity is created for that account.

				
					trigger UpdateContactLastContactedDate on Contact (after insert) {
    for (Contact c : Trigger.new) {
        c.Last_Contacted_Date__c = Date.today();
    }
}

				
			

Few Short Example

Prompt: Write an Apex method that calculates the total amount of all open opportunities for a given account, using only a few keywords as guidance: account ID, opportunity amount, and open opportunities.

Keywords:

  • account ID
  • opportunity amount
  • open opportunities
				
					public static Decimal calculateTotalOpenOpportunityAmount(Id accountId) {
    List<Opportunity> openOpps = [
        SELECT Amount
        FROM Opportunity
        WHERE AccountId = :accountId AND IsClosed = false
    ];

    Decimal totalAmount = 0;
    for (Opportunity opp : openOpps) {
        totalAmount += opp.Amount;
    }

    return totalAmount;
}

				
			

Resources

Exploring the world of prompt engineering can be exhilarating and empowering. To ignite your journey, here’s a curated list of resources and links to help you learn and master this fascinating skill:

Interactive Platforms:

Comprehensive Guides:

Blogs and Articles:

Online Courses:

Community and Discussion:

Amit Singh
Amit Singhhttps://www.pantherschools.com/
Amit Singh aka @sfdcpanther/pantherschools, a Salesforce Technical Architect, Consultant with over 8+ years of experience in Salesforce technology. 21x Certified. Blogger, Speaker, and Instructor. DevSecOps Champion
Share this

Leave a review

Excellent

SUBSCRIBE-US

Book a 1:1 Call

Must-read

How to Utilize Salesforce CLI sf (v2)

The Salesforce CLI is not just a tool; it’s the cornerstone of development on the Salesforce Platform. It’s your go-to for building, testing, deploying, and more. As one of the most important development tools in our ecosystem

Save the day of a Developer with Apex Log Analyzer

Table of Contents What is Apex Log Analyzer? Apex Log Analyzer, a tool designed with Salesforce developers in mind, is here to simplify and accelerate your...

Salesforce PodCast

Introduction Hey Everyone, Welcome to my podcast, the first-ever podcast in India for Salesforce professionals. Achievement We are happy to announce that we have been selected as Top...

Recent articles

More like this

LEAVE A REPLY

Please enter your comment!
Please enter your name here

5/5

Stuck in coding limbo?

Our courses unlock your tech potential