Prompt To Build

Create real apps with AI

Chapter 11: Advanced Prompting Techniques - Getting More from Your AI Assistant

Beyond the Basics: Mastering the Art of Conversation with AI

In previous chapters, you've learned the fundamentals of prompt engineering and how to get AI to generate basic JavaScript code, handle data structures, control program flow, and even create interactive web elements. Now, it's time to elevate your prompting skills. Just as a seasoned Forth programmer understands how to combine simple words into powerful, complex definitions, an advanced prompt engineer knows how to craft sophisticated instructions to unlock the full potential of AI code generation.

This chapter will delve into more advanced prompting techniques, including:

  • Few-Shot Prompting: Providing examples to guide the AI.
  • Chain-of-Thought Prompting: Encouraging the AI to reason step-by-step.
  • Role-Playing and Persona: Guiding the AI's perspective.
  • Iterative Prompting and Refinement: The conversational approach to code generation.
  • Constraint-Based Prompting: Imposing specific rules and limitations.

Few-Shot Prompting: Learning by Example

Few-shot prompting involves giving the AI a few examples of input-output pairs before asking it to complete a new task. This helps the AI understand the desired format, style, and logic, especially for tasks that are nuanced or require a specific pattern.

Example 1: Formatting Data

Goal:
Convert an array of objects into a specific string format.
Prompt:
Convert the following array of user objects into a comma-separated string of their names, formatted as "Name (Email)".

Example:
Input: [
  { name: "Alice", email: "alice@example.com" },
  { name: "Bob", email: "bob@example.com" }
]
Output: "Alice (alice@example.com), Bob (bob@example.com)"

Now, convert this input:
Input: [
  { name: "Charlie", email: "charlie@example.com" },
  { name: "David", email: "david@example.com" },
  { name: "Eve", email: "eve@example.com" }
]
AI-Generated Code (Expected):
const users = [
  { name: "Charlie", email: "charlie@example.com" },
  { name: "David", email: "david@example.com" },
  { name: "Eve", email: "eve@example.com" }
];

const formattedString = users.map(user => `${user.name} (${user.email}`)).join(', ');
console.log(formattedString);
// Expected Output: "Charlie (charlie@example.com), David (david@example.com), Eve (eve@example.com)"
Analysis: By providing a clear example, the AI understands the exact output format required, even for a slightly complex transformation.

Chain-of-Thought Prompting: Thinking Step-by-Step

Chain-of-thought prompting encourages the AI to break down a complex problem into intermediate steps, showing its reasoning process. This can lead to more accurate and reliable results, especially for multi-step coding tasks.

Example 2: Complex Logic with Explanation

Goal:
Generate a function to calculate Fibonacci numbers, explaining the logic.
Prompt:
Let's think step by step. First, define what a Fibonacci sequence is. 
Second, write a JavaScript function fibonacci that takes a number n and returns the nth Fibonacci number. 
Third, explain the logic of your function.
AI-Generated Response (Expected):
Step 1: Definition of Fibonacci Sequence
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. 
The sequence begins: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.

Step 2: JavaScript Function
javascript:

function fibonacci(n) {
  if (n <= 0) return 0;
  if (n === 1) return 1;

  let a = 0, b = 1;
  for (let i = 2; i <= n; i++) {
    let next = a + b;
    a = b;
    b = next;
  }
  return b;
}

Step 3: Explanation of Logic
  • Base Cases: The function first handles the base cases: if n is 0, it returns 0; if n is 1, it returns 1. These are the starting points of the sequence.
  • Iterative Approach: For n greater than 1, an iterative approach is used. Two variables, a and b, are initialized to 0 and 1 respectively, representing the previous two Fibonacci numbers.
  • Looping: The for loop starts from i = 2 up to n. In each iteration:
  • next calculates the sum of a and b (the next Fibonacci number).
  • a is updated to the value of b.
  • b is updated to the value of next.
  • Return Value: After the loop completes, b will hold the nth Fibonacci number.
Analysis: The AI provides a clear, step-by-step explanation along with the code, making it easier to understand the solution and verify its correctness.

Role-Playing and Persona: Guiding the AI's Perspective

Assigning a specific role or persona to the AI can influence its tone, style, and the type of code it generates. This is useful when you need code that adheres to certain professional standards or has a particular focus (e.g., security, performance).

Example 3: Security-Focused Code

Goal:
Generate a function to sanitize user input, with a focus on security.
Prompt:
Act as a cybersecurity expert. 
Write a JavaScript function sanitizeInput that takes a string of user input and 
removes any potentially malicious HTML or script tags to prevent XSS (Cross-Site Scripting) attacks. 
Explain your security considerations.
AI-Generated Response (Expected):
function sanitizeInput(input) {
  // Create a new DOM parser to safely parse the input string
  const doc = new DOMParser().parseFromString(input, 'text/html');

  // Create a temporary div to hold the parsed content
  const div = document.createElement('div');
  div.appendChild(doc.body);

  // Remove script tags and attributes that could lead to XSS
  // This is a simplified example; a robust solution would use a library like DOMPurify
  const scripts = div.getElementsByTagName('script');
  for (let i = scripts.length - 1; i >= 0; i--) {
    scripts[i].parentNode.removeChild(scripts[i]);
  }

  // Remove event handlers (e.g., onclick, onerror) from all elements
  const allElements = div.querySelectorAll('*');
  allElements.forEach(element => {
    Array.from(element.attributes).forEach(attr => {
      if (attr.name.startsWith('on')) {
        element.removeAttribute(attr.name);
      }
    });
  });

  return div.innerHTML;
}

/*
Security Considerations:

1.  Client-Side vs. Server-Side: 
    Client-side sanitization (like this example) is a first line of defense but is NOT sufficient on its own. 
    Server-side sanitization is crucial because malicious actors can bypass client-side checks.
    
2.  Complexity of XSS: 
    XSS attacks can be very sophisticated. 
    Manually implementing sanitization can be error-prone and incomplete. 
    For production applications, it is highly recommended to use well-vetted, 
    dedicated sanitization libraries (e.g., DOMPurify for client-side, 
    or server-side libraries appropriate for your backend language).
    
3.  Whitelisting vs. Blacklisting: 
    This simplified example uses a form of blacklisting (removing known bad elements/attributes). 
    A more secure approach is whitelisting, where you only allow known safe elements and attributes.
    
4.  Contextual Escaping: 
    Different contexts (HTML, attributes, JavaScript, CSS, URLs) require different escaping mechanisms. 
    A general-purpose sanitizer might not cover all edge cases.
*/
Analysis: The AI not only provides a function but also explains the security implications and best practices, demonstrating its understanding of the security issues.