└── README.md
/README.md:
--------------------------------------------------------------------------------
1 | # Prompt engineering cheatsheet (for JavaScript developers)
2 |
3 | Notes summarized from [this tutorial](https://learn.deeplearning.ai/chatgpt-prompt-eng/).
4 |
5 | ## Principle 1: Write clear and specific instructions
6 |
7 | ### Tactic 1: Use delimiters to clearly indicate distinct parts of the input
8 |
9 | Delimiters can be anything like this:
10 |
11 | ```
12 | '''text'''
13 |
14 | """text"""
15 |
16 | < text >
17 |
18 | text
19 | ```
20 |
21 | For instance:
22 |
23 | ```javascript
24 | const text = `
25 | You should express what you want a model to do by \
26 | providing instructions that are as clear and \
27 | specific as you can possibly make them. \
28 | This will guide the model towards the desired output, \
29 | and reduce the chances of receiving irrelevant \
30 | or incorrect responses. Don't confuse writing a \
31 | clear prompt with writing a short prompt. \
32 | In many cases, longer prompts provide more clarity \
33 | and context for the model, which can lead to \
34 | more detailed and relevant outputs.
35 | `
36 |
37 | const prompt = `
38 | Summarize the text delimited by triple quotes into a single sentence.
39 | """${text}"""
40 | `
41 | ```
42 |
43 | ### Tactic 2: Ask for a structured output
44 |
45 | Like JSON or HTML
46 |
47 | ```javascript
48 | const prompt = `
49 | Generate a list of three made-up book titles along \
50 | with their authors and genres.
51 | Provide them in JSON format with the following keys:
52 | book_id, title, author, genre.
53 | `
54 | ```
55 |
56 | ### Tactic 3: Ask the model to check whether conditions are satisfied
57 |
58 | ```javascript
59 | const text = `
60 | Making a cup of tea is easy! First, you need to get some \
61 | water boiling. While that's happening, \
62 | grab a cup and put a tea bag in it. Once the water is \
63 | hot enough, just pour it over the tea bag. \
64 | Let it sit for a bit so the tea can steep. After a \
65 | few minutes, take out the tea bag. If you \
66 | like, you can add some sugar or milk to taste. \
67 | And that's it! You've got yourself a delicious \
68 | cup of tea to enjoy.
69 | `
70 |
71 | const prompt = `
72 | You will be provided with text delimited by triple quotes.
73 | If it contains a sequence of instructions, \
74 | re-write those instructions in the following format:
75 |
76 | Step 1 - ...
77 | Step 2 - ...
78 | ...
79 | Step N - ...
80 |
81 | If the text does not contain a sequence of instructions, \
82 | then simply write \"No steps provided.\"
83 |
84 | """${text}"""
85 | `
86 | ```
87 |
88 | ### Tactic 4: "Few-shot" prompting
89 |
90 | "Few-shot" prompting refers to providing a limited number of examples to an AI model, then having it generate new responses in a similar domain. It's a technique commonly used for training and utilizing large language models (LLMs).
91 |
92 | The steps for few-shot prompting are:
93 |
94 | 1. Select a domain or topic you want the model to generate responses for. This could be a genre of text, way of speaking, etc.
95 |
96 | 2. Provide a small set of examples (the "prompts") from that domain for the model to condition on. Usually just 2-5 examples is sufficient for "few-shot" learning.
97 |
98 | 3. The model will analyze the patterns, styles, and structures in the prompts. It will learn the attributes that define responses in that domain.
99 |
100 | 4. Have the model generate a new response in that same domain. By conditioning on the prompts, it can produce a response that matches the desired style, structure, etc.
101 |
102 | 5. Review the response and provide feedback to further improve the model. This can either be explicit feedback to the model, or just note areas for generating the next set of prompts.
103 |
104 | #### Example:
105 |
106 | ```javascript
107 | const prompt = `
108 | Your task is to answer in a consistent style.
109 |
110 | : Teach me about patience.
111 |
112 | : The river that carves the deepest \
113 | valley flows from a modest spring; the \
114 | grandest symphony originates from a single note; \
115 | the most intricate tapestry begins with a solitary thread.
116 |
117 | : Teach me about resilience.
118 | `
119 | ```
120 |
121 | ## Principle 2: Give the model time to “think”
122 |
123 | ### Tactic 1: Specify the steps required to complete a task
124 |
125 | ```javascript
126 | const text = `
127 | In a charming village, siblings Jack and Jill set out on \
128 | a quest to fetch water from a hilltop \
129 | well. As they climbed, singing joyfully, misfortune \
130 | struck—Jack tripped on a stone and tumbled \
131 | down the hill, with Jill following suit. \
132 | Though slightly battered, the pair returned home to \
133 | comforting embraces. Despite the mishap, \
134 | their adventurous spirits remained undimmed, and they \
135 | continued exploring with delight.
136 | `
137 |
138 | // example 1
139 | const prompt_1 = `
140 | Perform the following actions:
141 | 1 - Summarize the following text delimited by triple quotes with 1 sentence.
142 | 2 - Translate the summary into French.
143 | 3 - List each name in the French summary.
144 | 4 - Output a json object that contains the following keys: french_summary, num_names.
145 |
146 | Separate your answers with line breaks.
147 |
148 | Text:
149 | """${text}"""
150 | `
151 | ```
152 |
153 | ### Tactic 2: Instruct the model to work out its own solution before rushing to a conclusion
154 |
155 | ```javascript
156 | const prompt = `
157 | Your task is to determine if the student's solution \
158 | is correct or not.
159 | To solve the problem do the following:
160 | - First, work out your own solution to the problem.
161 | - Then compare your solution to the student's solution \
162 | and evaluate if the student's solution is correct or not.
163 | Don't decide if the student's solution is correct until
164 | you have done the problem yourself.
165 |
166 | Use the following format:
167 |
168 | Question:
169 |
170 | """
171 | question here
172 | ""
173 |
174 | Student's solution:
175 |
176 | """
177 | student's solution here
178 | """
179 |
180 | Actual solution:
181 |
182 | """
183 | steps to work out the solution and your solution here
184 | """
185 |
186 | Is the student's solution the same as actual solution just calculated:
187 |
188 | ""
189 | yes or no
190 | """
191 |
192 | Student grade:
193 |
194 | """
195 | correct or incorrect
196 | """
197 |
198 | Question:
199 |
200 | """
201 | I'm building a solar power installation and I need help \
202 | working out the financials.
203 | - Land costs $100 / square foot
204 | - I can buy solar panels for $250 / square foot
205 | - I negotiated a contract for maintenance that will cost \
206 | me a flat $100k per year, and an additional $10 / square \
207 | foot
208 | What is the total cost for the first year of operations \
209 | as a function of the number of square feet.
210 | """
211 |
212 | Student's solution:
213 |
214 | """
215 | Let x be the size of the installation in square feet.
216 | Costs:
217 | 1. Land cost: 100x
218 | 2. Solar panel cost: 250x
219 | 3. Maintenance cost: 100,000 + 100x
220 | Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000
221 | """
222 |
223 | Actual solution:
224 | `
225 | ```
226 |
227 | ## Iterative Prompt Develelopment
228 |
229 | Rarely will your first prompt work as effectively as you'd like the first time (duh!).
230 |
231 | Instead, recognize that it usually takes quite a few iterations before you can get it a place that works as well as you'd like.
232 |
233 | ## Summarizing
234 |
235 | ### Summarize with a word/sentence/character limit
236 |
237 | ```javascript
238 | const prod_review = `
239 | Got this panda plush toy for my daughter's birthday, \
240 | who loves it and takes it everywhere. It's soft and \
241 | super cute, and its face has a friendly look. It's \
242 | a bit small for what I paid though. I think there \
243 | might be other options that are bigger for the \
244 | same price. It arrived a day earlier than expected, \
245 | so I got to play with it myself before I gave it \
246 | to her.
247 | `
248 |
249 | const prompt = `
250 | Your task is to generate a short summary of a product review from an ecommerce site.
251 |
252 | Summarize the review below, delimited by triple quotes, in at most 30 words.
253 |
254 | Review: """${prod_review}"""
255 | `
256 | ```
257 |
258 | ## Summarize with a focus
259 |
260 | ```javascript
261 | const prompt = `
262 | Your task is to generate a short summary of a product \
263 | review from an ecommerce site to give feedback to the \
264 | Shipping deparmtment.
265 |
266 | Summarize the review below, delimited by triple \
267 | quotes, in at most 30 words, and focusing on any aspects \
268 | that mention shipping and delivery of the product.
269 |
270 | Review: """${prod_review}"""
271 | `
272 | ```
273 |
274 | ## Try "extract" instead of "summarize"
275 |
276 | ```javascript
277 | const prompt = `
278 | Your task is to extract relevant information from \
279 | a product review from an ecommerce site to give \
280 | feedback to the Shipping department.
281 |
282 | From the review below, delimited by triple quotes \
283 | extract the information relevant to shipping and \
284 | delivery. Limit to 30 words.
285 |
286 | Review: """${prod_review}"""
287 | `
288 | ```
289 |
290 | ## Inferring
291 |
292 | Infer sentiment and topics from given text.
293 |
294 | ### Sentiment analysis
295 |
296 | ```javascript
297 | const prod_review = `
298 | Needed a nice lamp for my bedroom, and this one had \
299 | additional storage and not too high of a price point. \
300 | Got it fast. The string to our lamp broke during the \
301 | transit and the company happily sent over a new one. \
302 | Came within a few days as well. It was easy to put \
303 | together. I had a missing part, so I contacted their \
304 | support and they very quickly got me the missing piece! \
305 | Lumina seems to me to be a great company that cares \
306 | about their customers and products!!
307 | `
308 |
309 | const prompt = `
310 | What is the sentiment of the following product review,
311 | which is delimited with triple quotes?
312 |
313 | Review text: """${prod_review}"""
314 | `
315 |
316 | const prompt = `
317 | What is the sentiment of the following product review,
318 | which is delimited with triple quotes?
319 |
320 | Give your answer as a single word, either "positive" \
321 | or "negative".
322 |
323 | Review text: """${prod_review}"""
324 | `
325 | ```
326 |
327 | ### Types of emotions
328 |
329 | ```javascript
330 | const prompt = `
331 | Identify a list of emotions that the writer of the \
332 | following review is expressing. Include no more than \
333 | five items in the list. Format your answer as a list of \
334 | lower-case words separated by commas.
335 |
336 | Review text: """${prod_review}"""
337 | `
338 |
339 | const prompt = `
340 | Is the writer of the following review expressing anger?\
341 | The review is delimited with triple quotes. \
342 | Give your answer as either yes or no.
343 |
344 | Review text: """${prod_review}"""
345 | `
346 | ```
347 |
348 | ### Extracting data
349 |
350 | ```javascript
351 | const prompt = `
352 | Identify the following items from the review text:
353 | - Item purchased by reviewer
354 | - Company that made the item
355 |
356 | The review is delimited with triple quotes. \
357 | Format your response as a JSON object with \
358 | "Item" and "Brand" as the keys.
359 | If the information isn't present, use "unknown" \
360 | as the value.
361 | Make your response as short as possible.
362 |
363 | Review text: """${prod_review}"""
364 | `
365 | ```
366 |
367 | ### Multiple tasks at once
368 |
369 | ```javascript
370 | const prompt = `
371 | Identify the following items from the review text:
372 | - Sentiment (positive or negative)
373 | - Is the reviewer expressing anger? (true or false)
374 | - Item purchased by reviewer
375 | - Company that made the item
376 |
377 | The review is delimited with triple quotes. \
378 | Format your response as a JSON object with \
379 | "Sentiment", "Anger", "Item" and "Brand" as the keys.
380 | If the information isn't present, use "unknown" \
381 | as the value.
382 | Make your response as short as possible.
383 | Format the Anger value as a boolean.
384 |
385 | Review text: """${prod_review}"""
386 | `
387 | ```
388 |
389 | ### Inferring topics
390 |
391 | ```javascript
392 | const story = `
393 | In a recent survey conducted by the government,
394 | public sector employees were asked to rate their level
395 | of satisfaction with the department they work at.
396 | The results revealed that NASA was the most popular
397 | department with a satisfaction rating of 95%.
398 |
399 | One NASA employee, John Smith, commented on the findings,
400 | stating, "I'm not surprised that NASA came out on top.
401 | It's a great place to work with amazing people and
402 | incredible opportunities. I'm proud to be a part of
403 | such an innovative organization."
404 |
405 | The results were also welcomed by NASA's management team,
406 | with Director Tom Johnson stating, "We are thrilled to
407 | hear that our employees are satisfied with their work at NASA.
408 | We have a talented and dedicated team who work tirelessly
409 | to achieve our goals, and it's fantastic to see that their
410 | hard work is paying off."
411 |
412 | The survey also revealed that the
413 | Social Security Administration had the lowest satisfaction
414 | rating, with only 45% of employees indicating they were
415 | satisfied with their job. The government has pledged to
416 | address the concerns raised by employees in the survey and
417 | work towards improving job satisfaction across all departments.
418 | `
419 |
420 | const prompt = `
421 | Determine five topics that are being discussed in the \
422 | following text, which is delimited by triple quotes.
423 |
424 | Make each item one or two words long.
425 |
426 | Format your response as a list of items separated by commas.
427 |
428 | Text sample: """${story}"""
429 | `
430 | ```
431 |
432 | ## Transforming
433 |
434 | How to use LLMs for text transformation tasks such as language translation, spelling and grammar checking, tone adjustment, and format conversion.
435 |
436 | Models have the ability to do language translation.
437 |
438 | ```javascript
439 | const prompt = `
440 | Translate the following English text to Spanish:
441 |
442 | """Hi, I would like to order a blender"""
443 | `
444 |
445 | const prompt = `
446 | Tell me which language this is:
447 | """Combien coûte le lampadaire?"""
448 | `
449 | ```
450 |
451 | ### Tone Transformation
452 |
453 | Writing can vary based on the intended audience. ChatGPT can produce different tones.
454 |
455 | ```javascript
456 | const prompt = `
457 | Translate the following from slang to a business letter:
458 | 'Dude, This is Joe, check out this spec on this standing lamp.'
459 | `
460 | ```
461 |
462 | ### Format Conversion
463 |
464 | ChatGPT can translate between formats. The prompt should describe the input and output formats.
465 |
466 | ```javascript
467 | const json = {
468 | "resturant employees" :[
469 | {"name":"Shyam", "email":"shyamjaiswal@gmail.com"},
470 | {"name":"Bob", "email":"bob32@gmail.com"},
471 | {"name":"Jai", "email":"jai87@gmail.com"}
472 | ]
473 | }
474 |
475 | const prompt = `
476 | Translate the following python dictionary from JSON to an HTML \
477 | table with column headers and title: ${json}
478 | `
479 | ```
480 |
481 | ### Spellcheck / grammar check and proofreading
482 |
483 | ```javascript
484 | const prompt = `
485 | Proofread and correct the following text
486 | and rewrite the corrected version. If you don't find
487 | and errors, just say "No errors found". Don't use
488 | any punctuation around the text:
489 |
490 | """${text}"""
491 | `
492 |
493 | const prompt = `
494 | proofread and correct this review. Make it more compelling.
495 | Ensure it follows APA style guide and targets an advanced reader.
496 | Output in markdown format.
497 |
498 | Text: """${text}"""
499 | `
500 | ```
501 |
502 | ## Expanding
503 |
504 | Taking a small group of text to expand it into a much larger group of text.
505 |
506 | ### Customizing the automated reply to a customer email
507 |
508 | ```javascript
509 | const review = `
510 | So, they still had the 17 piece system on seasonal \
511 | sale for around $49 in the month of November, about \
512 | half off, but for some reason (call it price gouging) \
513 | around the second week of December the prices all went \
514 | up to about anywhere from between $70-$89 for the same \
515 | system. And the 11 piece system went up around $10 or \
516 | so in price also from the earlier sale price of $29. \
517 | So it looks okay, but if you look at the base, the part \
518 | where the blade locks into place doesn’t look as good \
519 | as in previous editions from a few years ago, but I \
520 | plan to be very gentle with it (example, I crush \
521 | very hard items like beans, ice, rice, etc. in the \
522 | blender first then pulverize them in the serving size \
523 | I want in the blender then switch to the whipping \
524 | blade for a finer flour, and use the cross cutting blade \
525 | first when making smoothies, then use the flat blade \
526 | if I need them finer/less pulpy). Special tip when making \
527 | smoothies, finely cut and freeze the fruits and \
528 | vegetables (if using spinach-lightly stew soften the \
529 | spinach then freeze until ready for use-and if making \
530 | sorbet, use a small to medium sized food processor) \
531 | that you plan to use that way you can avoid adding so \
532 | much ice if at all-when making your smoothie. \
533 | After about a year, the motor was making a funny noise. \
534 | I called customer service but the warranty expired \
535 | already, so I had to buy another one. FYI: The overall \
536 | quality has gone done in these types of products, so \
537 | they are kind of counting on brand recognition and \
538 | consumer loyalty to maintain sales. Got it in about \
539 | two days.
540 | `
541 |
542 | const prompt = `
543 | You are a customer service AI assistant.
544 | Your task is to send an email reply to a valued customer.
545 | Given the customer email delimited by """, \
546 | Generate a reply to thank the customer for their review.
547 | If the sentiment is positive or neutral, thank them for \
548 | their review.
549 | If the sentiment is negative, apologize and suggest that \
550 | they can reach out to customer service.
551 | Make sure to use specific details from the review.
552 | Write in a concise and professional tone.
553 | Sign the email as 'AI customer agent'.
554 | Customer review: """${review}"""
555 | `
556 | ```
557 |
558 | ## Chatbot
559 |
560 | Explore how you can utilize the chat format to have extended conversations with chatbots personalized or specialized for specific tasks or behaviors.
561 |
562 | ### OrderBot
563 |
564 | We can automate the collection of user prompts and assistant responses to build a OrderBot. The OrderBot will take orders at a pizza restaurant.
565 |
566 | ```javascript
567 | const prompt = `
568 | You are OrderBot, an automated service to collect orders for a pizza restaurant. \
569 | You first greet the customer if they ask an empty or introductory question, then collect the order, \
570 | and then ask if it's a pickup or delivery. \
571 | You wait to collect the entire order, then summarize it and check for a final \
572 | time if the customer wants to add anything else. \
573 | If it's a delivery, you ask for an address. \
574 | Finally you collect the payment.\
575 | Make sure to clarify all options, extras and sizes to uniquely \
576 | identify the item from the menu.\
577 |
578 | You will be provided with "previous conversation" data if it exists so you have context about what was alrady discussed.
579 |
580 | You respond in a short, very conversational friendly style. \
581 | The menu includes \
582 | pepperoni pizza 12.95, 10.00, 7.00 \
583 | cheese pizza 10.95, 9.25, 6.50 \
584 | eggplant pizza 11.95, 9.75, 6.75 \
585 | fries 4.50, 3.50 \
586 | greek salad 7.25 \
587 | Toppings: \
588 | extra cheese 2.00, \
589 | mushrooms 1.50 \
590 | sausage 3.00 \
591 | canadian bacon 3.50 \
592 | AI sauce 1.50 \
593 | peppers 1.00 \
594 | Drinks: \
595 | coke 3.00, 2.00, 1.00 \
596 | sprite 3.00, 2.00, 1.00 \
597 | bottled water 5.00
598 |
599 | """
600 | previous conversation: ${oldContext}
601 |
602 | question for this order: ${newContext}
603 | """
604 | `
605 | ```
606 |
--------------------------------------------------------------------------------