ChatGPT Prompt Engineering for Developers
💬

ChatGPT Prompt Engineering for Developers

Tactics

Principle 1: Write clear and specific instructions

  1. Tactic 1: Use delimiters
    1. Triple quotes:”””
    2. Triple backticks:**
    3. Triple dashes:```
    4. Angle brackets:<>
    5. XML tags: ‹tag> </tag>
    6. Example
      text = f""" You should express what you want a model to do by \ providing instructions that are as clear and \ specific as you can possibly make them. \ This will guide the model towards the desired output, \ and reduce the chances of receiving irrelevant \ or incorrect responses. Don't confuse writing a \ clear prompt with writing a short prompt. \ In many cases, longer prompts provide more clarity \ and context for the model, which can lead to \ more detailed and relevant outputs. """ prompt = f""" Summarize the text delimited by triple backticks \ into a single sentence. ```{text}``` """ response = get_completion(prompt) print(response)
  1. Tactic 2: Ask for structured output
    1. HTML,
    2. JSON
    3. Markdown
    4. Example
      prompt = f""" Generate a list of three made-up book titles along \ with their authors and genres. Provide them in JSON format with the following keys: book_id, title, author, genre. """ response = get_completion(prompt) print(response)
  1. Tactic 3: Check whether conditions are satisfied
    1. Check assumptions required to do the task
    2. Example
      text_1 = f""" Making a cup of tea is easy! First, you need to get some \ water boiling. While that's happening, \ grab a cup and put a tea bag in it. Once the water is \ hot enough, just pour it over the tea bag. \ Let it sit for a bit so the tea can steep. After a \ few minutes, take out the tea bag. If you \ like, you can add some sugar or milk to taste. \ And that's it! You've got yourself a delicious \ cup of tea to enjoy. """ prompt = f""" You will be provided with text delimited by triple quotes. If it contains a sequence of instructions, \ re-write those instructions in the following format: Step 1 - ... Step 2 - … … Step N - … If the text does not contain a sequence of instructions, \ then simply write \"No steps provided.\" \"\"\"{text_1}\"\"\" """ response = get_completion(prompt) print("Completion for Text 1:") print(response)
  1. Tactic 4: Few-shot prompting
    1. Give successful examples of completing tasks
    2. Then ask model to perform the task
    3. Example
      prompt = f""" Your task is to answer in a consistent style. <child>: Teach me about patience. <grandparent>: The river that carves the deepest \ valley flows from a modest spring; the \ grandest symphony originates from a single note; \ the most intricate tapestry begins with a solitary thread. <child>: Teach me about resilience. """ response = get_completion(prompt) print(response)
 

Principle 2: Give the model time to think

  1. Tactic 1: Specify the steps required to complete a task
    1. Example
      prompt_2 = f""" Your task is to perform the following actions: 1 - Summarize the following text delimited by <> with 1 sentence. 2 - Translate the summary into French. 3 - List each name in the French summary. 4 - Output a json object that contains the following keys: french_summary, num_names. Use the following format: Text: <text to summarize> Summary: <summary> Translation: <summary translation> Names: <list of names in Italian summary> Output JSON: <json with summary and num_names> Text: <{text}> """ response = get_completion(prompt_2) print("\nCompletion for prompt 2:") print(response)
  1. Tactic 2: Instruct the model to work out its own solution before rushing to a conclusion
    1. Aam Zindegi
    2. Example
      prompt = f""" Determine if the student's solution is correct or not. Question: I'm building a solar power installation and I need \ help working out the financials. - Land costs $100 / square foot - I can buy solar panels for $250 / square foot - I negotiated a contract for maintenance that will cost \ me a flat $100k per year, and an additional $10 / square \ foot What is the total cost for the first year of operations as a function of the number of square feet. Student's Solution: Let x be the size of the installation in square feet. Costs: 1. Land cost: 100x 2. Solar panel cost: 250x 3. Maintenance cost: 100,000 + 100x Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000 """ response = get_completion(prompt) print(response)
      b. Mentos zindegi
      Example
      prompt = f""" Your task is to determine if the student's solution \ is correct or not. To solve the problem do the following: - First, work out your own solution to the problem. - Then compare your solution to the student's solution \ and evaluate if the student's solution is correct or not. Don't decide if the student's solution is correct until you have done the problem yourself. Use the following format: Question: ``` question here ``` Student's solution: ``` student's solution here ``` Actual solution: ``` steps to work out the solution and your solution here ``` Is the student's solution the same as actual solution \ just calculated: ``` yes or no ``` Student grade: ``` correct or incorrect ``` Question: ``` I'm building a solar power installation and I need help \ working out the financials. - Land costs $100 / square foot - I can buy solar panels for $250 / square foot - I negotiated a contract for maintenance that will cost \ me a flat $100k per year, and an additional $10 / square \ foot What is the total cost for the first year of operations \ as a function of the number of square feet. ``` Student's solution: ``` Let x be the size of the installation in square feet. Costs: 1. Land cost: 100x 2. Solar panel cost: 250x 3. Maintenance cost: 100,000 + 100x Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000 ``` Actual solution: """ response = get_completion(prompt) print(response)

Model limitations

Hallucinations

Makes statements that sound plausible, but are not true.

Reducing Hallucinations

First find relevant information, then answer the question based on the relevant information.

Iterative Prompt Development

notion image
notion image

Summarization

  • A text can be summarized for:
    • A specific audience/profession.
    • With in a specific number of sentences or characters.

Inference

Extracting labels, names, sentiments, topics, creating alerts on specific topics from a given text.
Examples
prompt = f""" What is the sentiment of the following product review, which is delimited with triple backticks? Give your answer as a single word, either "positive" \ or "negative". Review text: '''{lamp_review}''' """ response = get_completion(prompt) print(response)
prompt = f""" Identify a list of emotions that the writer of the \ following review is expressing. Include no more than \ five items in the list. Format your answer as a list of \ lower-case words separated by commas. Review text: '''{lamp_review}''' """ response = get_completion(prompt) print(response)
A series of expressions
prompt = f""" Is the writer of the following review expressing anger?\ The review is delimited with triple backticks. \ Give your answer as either yes or no. Review text: '''{lamp_review}''' """ response = get_completion(prompt) print(response)
Identify angry user feedback
prompt = f""" Identify the following items from the review text: - Item purchased by reviewer - Company that made the item The review is delimited with triple backticks. \ Format your response as a JSON object with \ "Item" and "Brand" as the keys. If the information isn't present, use "unknown" \ as the value. Make your response as short as possible. Review text: '''{lamp_review}''' """ response = get_completion(prompt) print(response)
Extract product and company name from customer reviews
prompt = f""" Identify the following items from the review text: - Sentiment (positive or negative) - Is the reviewer expressing anger? (true or false) - Item purchased by reviewer - Company that made the item The review is delimited with triple backticks. \ Format your response as a JSON object with \ "Sentiment", "Anger", "Item" and "Brand" as the keys. If the information isn't present, use "unknown" \ as the value. Make your response as short as possible. Format the Anger value as a boolean. Review text: '''{lamp_review}''' """ response = get_completion(prompt) print(response)
Doing multiple tasks at once
prompt = f""" Determine five topics that are being discussed in the \ following text, which is delimited by triple backticks. Make each item one or two words long. Format your response as a list of items separated by commas. Text sample: '''{story}''' """ response = get_completion(prompt) print(response)
Infer 5 topics
prompt = f""" Determine whether each item in the following list of \ topics is a topic in the text below, which is delimited with triple backticks. Give your answer as list with 0 or 1 for each topic.\ List of topics: {", ".join(topic_list)} Text sample: '''{story}''' """ response = get_completion(prompt) print(response)
Make a news alert on certain topics

Transforming

  • Language Translation
  • Language detection
Universal Translator Example

Universal Translator

Imagine you are in charge of IT at a large multinational e-commerce company. Users are messaging you with IT issues in all their native languages. Your staff is from all over the world and speaks only their native languages. You need a universal translator!
def get_completion(prompt, model="gpt-3.5-turbo", temperature=0): messages = [{"role": "user", "content": prompt}] response = openai.ChatCompletion.create( model=model, messages=messages, temperature=temperature, ) return response.choices[0].message["content"] user_messages = [ "La performance du système est plus lente que d'habitude.", # System performance is slower than normal "Mi monitor tiene píxeles que no se iluminan.", # My monitor has pixels that are not lighting "Il mio mouse non funziona", # My mouse is not working "Mój klawisz Ctrl jest zepsuty", # My keyboard has a broken control key "我的屏幕在闪烁" # My screen is flashing ] for issue in user_messages: prompt = f"Tell me what language this is: ```{issue}```" lang = get_completion(prompt) print(f"Original message ({lang}): {issue}") prompt = f""" Translate the following text to English \ and Korean: ```{issue}``` """ response = get_completion(prompt) print(response, "\n")
notion image
Tone Transformation example
Writing can vary based on the intended audience. ChatGPT can produce different tones.
prompt = f""" Translate the following from slang to a business letter: 'Dude, This is Joe, check out this spec on this standing lamp.' """ response = get_completion(prompt) print(response)
 
Format Conversion example
ChatGPT can translate between formats. The prompt should describe the input and output formats.
data_json = { "resturant employees" :[ {"name":"Shyam", "email":"[email protected]"}, {"name":"Bob", "email":"[email protected]"}, {"name":"Jai", "email":"[email protected]"} ]} prompt = f""" Translate the following python dictionary from JSON to an HTML \ table with column headers and title: {data_json} """ response = get_completion(prompt) print(response)
Spellcheck/Grammar check
Here are some examples of common grammar and spelling problems and the LLM's response.
To signal to the LLM that you want it to proofread your text, you instruct the model to 'proofread' or 'proofread and correct'.
text = [ "The girl with the black and white puppies have a ball.", # The girl has a ball. "Yolanda has her notebook.", # ok "Its going to be a long day. Does the car need it’s oil changed?", # Homonyms "Their goes my freedom. There going to bring they’re suitcases.", # Homonyms "Your going to need you’re notebook.", # Homonyms "That medicine effects my ability to sleep. Have you heard of the butterfly affect?", # Homonyms "This phrase is to cherck chatGPT for speling abilitty" # spelling ] for t in text: prompt = f"""Proofread and correct the following text and rewrite the corrected version. If you don't find and errors, just say "No errors found". Don't use any punctuation around the text: ```{t}```""" response = get_completion(prompt) print(response)
notion image
 

Expanding

  • Temperature use

Chatbot

Code examples
def get_completion_from_messages(messages, model="gpt-3.5-turbo", temperature=0): response = openai.ChatCompletion.create( model=model, messages=messages, temperature=temperature, # this is the degree of randomness of the model's output ) # print(str(response.choices[0].message)) return response.choices[0].message["content"] messages = [ {'role':'system', 'content':'You are an assistant that speaks like Shakespeare.'}, {'role':'user', 'content':'tell me a joke'}, {'role':'assistant', 'content':'Why did the chicken cross the road'}, {'role':'user', 'content':'I don\'t know'} ] response = get_completion_from_messages(messages, temperature=1) print(response)
OrderBot We can automate the collection of user prompts and assistant responses to build a OrderBot. The OrderBot will take orders at a pizza restaurant.
def collect_messages(_): prompt = inp.value_input inp.value = '' context.append({'role':'user', 'content':f"{prompt}"}) response = get_completion_from_messages(context) context.append({'role':'assistant', 'content':f"{response}"}) panels.append( pn.Row('User:', pn.pane.Markdown(prompt, width=600))) panels.append( pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'}))) return pn.Column(*panels) import panel as pn # GUI pn.extension() panels = [] # collect display context = [ {'role':'system', 'content':""" You are OrderBot, an automated service to collect orders for a pizza restaurant. \ You first greet the customer, then collects the order, \ and then asks if it's a pickup or delivery. \ You wait to collect the entire order, then summarize it and check for a final \ time if the customer wants to add anything else. \ If it's a delivery, you ask for an address. \ Finally you collect the payment.\ Make sure to clarify all options, extras and sizes to uniquely \ identify the item from the menu.\ You respond in a short, very conversational friendly style. \ The menu includes \ pepperoni pizza 12.95, 10.00, 7.00 \ cheese pizza 10.95, 9.25, 6.50 \ eggplant pizza 11.95, 9.75, 6.75 \ fries 4.50, 3.50 \ greek salad 7.25 \ Toppings: \ extra cheese 2.00, \ mushrooms 1.50 \ sausage 3.00 \ canadian bacon 3.50 \ AI sauce 1.50 \ peppers 1.00 \ Drinks: \ coke 3.00, 2.00, 1.00 \ sprite 3.00, 2.00, 1.00 \ bottled water 5.00 \ """} ] # accumulate messages inp = pn.widgets.TextInput(value="Hi", placeholder='Enter text here…') button_conversation = pn.widgets.Button(name="Chat!") interactive_conversation = pn.bind(collect_messages, button_conversation) dashboard = pn.Column( inp, pn.Row(button_conversation), pn.panel(interactive_conversation, loading_indicator=True, height=300), ) dashboard messages = context.copy() messages.append( {'role':'system', 'content':'create a json summary of the previous food order. Itemize the price for each item\ The fields should be 1) pizza, include size 2) list of toppings 3) list of drinks, include size 4) list of sides include size 5)total price '}, ) #The fields should be 1) pizza, price 2) list of toppings 3) list of drinks, include size include price 4) list of sides include size include price, 5)total price '}, response = get_completion_from_messages(messages, temperature=0) print(response)
 

Conclusion

notion image

Further reading

🔮
Generative AI learning path by Google
🤖
ChatGPT for Creatives: Al-Powered SEO, Marketing, & Productivity
Building Systems with the ChatGPT API

⚠️Disclaimer: All the screenshots, materials, and other media documents used in this article are copyrighted to the original platform or authors.