ChatGPT Prompt Engineering for Developers 大语言模型引导词指导手册

以下内容均整理来自deeplearning.ai的同名课程

Location 课程访问地址

https://learn.deeplearning.ai/chatgpt-prompt-eng

一、Guidelines for Prompting 
引导语的编写原则

Prompting Principles 引导语编写原则

  • Principle 1: Write clear and specific instructions编写清晰明确的指令
  • Principle 2: Give the model time to “think”给模型足够的“思考”时间

Principle 1: Write clear and specific instructions编写清晰明确的指令

Tactic 1: Use delimiters to clearly indicate distinct parts of the input使用分隔符清晰地指示输入的不同部分。

  • Delimiters can be anything like: ```, """, < >, <tag> </tag>:

prompt = f"""

Summarize the text delimited by triple backticks \

into a single sentence.

```{text}```

"""

Tactic 2: Ask for a structured output要求结构化输出

  • JSON, HTML

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.

"""

文章来源地址https://www.uudwc.com/A/0R45/

Tactic 3: Ask the model to check whether conditions are satisfied要求模型检查条件是否满足

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}\"\"\"

"""

Tactic 4: "Few-shot" prompting 少样本引导

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.

"""

Principle 2: Give the model time to “think”给模型足够的“思考”时间

Tactic 1: Specify the steps required to complete a task明确指定完成任务所需的步骤

prompt_1 = f"""

Perform the following actions:

1 - Summarize the following text delimited by triple \

backticks 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.

Separate your answers with line breaks.

Text:

```{text}```

"""

Ask for output in a specified format要求按照特定格式输出

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}>

"""

Tactic 2: Instruct the model to work out its own solution before rushing to a conclusion在匆忙得出结论之前,指导模型自己解决问题

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:

"""

Model Limitations: Hallucinations 模型限制:虚假生成

  • Boie is a real company, the product name is not real.

二、Iterative Prompt Develelopment 迭代式提示开发

In this lesson, you'll iteratively analyze and refine your prompts to generate marketing copy from a product fact sheet.

issue示例问题

Issue 1: The text is too long

Issue 2. Text focuses on the wrong details

Issue 3. Description needs a table of dimensions

问题1:文本过长。 问题2:文本关注错误的细节。 问题3:说明需要一张尺寸表格。以下是完善后的引导词

prompt = f"""

Your task is to help a marketing team create a

description for a retail website of a product based

on a technical fact sheet.

Write a product description based on the information

provided in the technical specifications delimited by

triple backticks.

The description is intended for furniture retailers,

so should be technical in nature and focus on the

materials the product is constructed from.

At the end of the description, include every 7-character

Product ID in the technical specification.

After the description, include a table that gives the

product's dimensions. The table should have two columns.

In the first column include the name of the dimension.

In the second column include the measurements in inches only.

Give the table the title 'Product Dimensions'.

Format everything as HTML that can be used in a website.

Place the description in a <div> element.

Technical specifications: ```{fact_sheet_chair}```

"""

Load Python libraries to view HTML加载 Python 库以查看 HTML

from IPython.display import display, HTML

display(HTML(response))

三、Summarizing总结

In this lesson, you will summarize text with a focus on specific topics.

Summarize multiple product reviews对多个产品评论进行总结

for i in range(len(reviews)):

    prompt = f"""

    Your task is to generate a short summary of a product \

    review from an ecommerce site.

    Summarize the review below, delimited by triple \

    backticks in at most 20 words.

    Review: ```{reviews[i]}```

    """

    response = get_completion(prompt)

print(i, response, "\n")

四、Inferring推断

In this lesson, you will infer sentiment and topics from product reviews and news articles.

Extract product and company name from customer reviews从客户评论中提取产品和公司名称

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}'''

"""

Doing multiple tasks at once,Identify anger,Identify types of emotions,Sentiment (positive/negative)

同时执行多个任务,包括识别愤怒情绪、识别情绪类型、情感分析(积极/消极)

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}'''

"""

Inferring topics推断主题

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}'''

"""

Make a news alert for certain 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}'''

"""

五、Transforming转换

In this notebook, we will explore how to use Large Language Models for text transformation tasks such as language translation, spelling and grammar checking, tone adjustment, and format conversion.

Translation翻译

ChatGPT is trained with sources in many languages. This gives the model the ability to do translation. Here are some examples of how to use this capability.

prompt = f"""

Translate the following English text to Spanish: \

```Hi, I would like to order a blender```

"""

prompt = f"""

Tell me which language this is:

```Combien coûte le lampadaire?```

"""

prompt = f"""

Translate the following text to Spanish in both the \

formal and informal forms:

'Would you like to order a pillow?'

"""

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!

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")

Tone Transformation
语气转换

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.'

"""

Format Conversion格式转换

ChatGPT can translate between formats. The prompt should describe the input and output formats.

data_json = { "resturant employees" :[

    {"name":"Shyam", "email":"shyamjaiswal@gmail.com"},

    {"name":"Bob", "email":"bob32@gmail.com"},

    {"name":"Jai", "email":"jai87@gmail.com"}

]}

prompt = f"""

Translate the following python dictionary from JSON to an HTML \

table with column headers and title: {data_json}

"""

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)

六、Expanding扩展

In this lesson, you will generate customer service emails that are tailored to each customer's review.

Customize the automated reply to a customer email定制自动回复的客户电子邮件

prompt = f"""

You are a customer service AI assistant.

Your task is to send an email reply to a valued customer.

Given the customer email delimited by ```, \

Generate a reply to thank the customer for their review.

If the sentiment is positive or neutral, thank them for \

their review.

If the sentiment is negative, apologize and suggest that \

they can reach out to customer service.

Make sure to use specific details from the review.

Write in a concise and professional tone.

Sign the email as `AI customer agent`.

Customer review: ```{review}```

Review sentiment: { negative}

"""

response = get_completion(prompt)

print(response)

Remind the model to use details from the customer's email提醒模型使用客户电子邮件中的细节

通过调整 temperature值,来让回答更加随机。

prompt = f"""

You are a customer service AI assistant.

Your task is to send an email reply to a valued customer.

Given the customer email delimited by ```, \

Generate a reply to thank the customer for their review.

If the sentiment is positive or neutral, thank them for \

their review.

If the sentiment is negative, apologize and suggest that \

they can reach out to customer service.

Make sure to use specific details from the review.

Write in a concise and professional tone.

Sign the email as `AI customer agent`.

Customer review: ```{review}```

Review sentiment: {sentiment}

"""

response = get_completion(prompt, temperature=0.7)

print(response)

七、The Chat Format聊天格式

In this notebook, you will explore how you can utilize the chat format to have extended conversations with chatbots personalized or specialized for specific tasks or behaviors.

基于上下文对话message,得到回答response,代码如下

def get_completion(prompt, model="gpt-3.5-turbo"):

    messages = [{"role": "user", "content": prompt}]

    response = openai.ChatCompletion.create(

        model=model,

        messages=messages,

        temperature=0, # this is the degree of randomness of the model's output

    )

    return response.choices[0].message["content"]

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'}  ]

messages =  [  

{'role':'system', 'content':'You are friendly chatbot.'},    

{'role':'user', 'content':'Hi, my name is Isa'}  ]

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.

以一个订餐机器人作为实例,体现gpt的强大,代码如下

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

生成对话参考如下

Assistant:

Hello! Welcome to our pizza restaurant. What can I get for you today?

User:

i want a pizza

Assistant:

Great! Which type of pizza would you like? We have pepperoni, cheese, and eggplant pizza.

User:

pepperoni please

Assistant:

Sure thing! What size would you like? We have 12-inch for $12.95, 10-inch for $10.00, and 7-inch for $7.00.

User:

how about 9 inch

Assistant:

I’m sorry, we don’t have a 9-inch size for our pizzas. Would you like to go for a 10-inch pizza for $10.00 or a 7-inch pizza for $7.00?

User:

7-inch

Assistant:

Great! Would you like any toppings on your pizza? We have extra cheese for $2.00, mushrooms for $1.50, sausage for $3.00, Canadian bacon for $3.50, AI sauce for $1.50, and peppers for $1.00.

将以上内容转换为json格式的订单内容

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).

原文地址:https://blog.csdn.net/qq_36080693/article/details/130550685

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

h
上一篇 2023年06月13日 10:11
【ChatGPT工具篇-1】ChatGPT + MindShow 分分钟搞定PPT制作
下一篇 2023年06月13日 10:15