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

这篇具有很好参考价值的文章主要介绍了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.

"""

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://www.toymoban.com/news/detail-453332.html

到了这里,关于ChatGPT Prompt Engineering for Developers 大语言模型引导词指导手册的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

领支付宝红包 赞助服务器费用

相关文章

  • ChatGPT Prompt Engineering for Developers from DeepLearning.AI

    链接:https://learn.deeplearning.ai/chatgpt-prompt-eng/lesson/1/introduction In this course, there are some example codes that you can already run in Jupyter Notebook. Below, I will write down the core knowledge points, such as how to build a prompt and how the prompt looks like in each application. Therefore, this blog contains more notes than tutorials.

    2024年02月08日
    浏览(34)
  • LLM学习《Prompt Engineering for Developer》

    教程地址:https://github.com/datawhalechina/prompt-engineering-for-developers 分割符 :分隔符就像是 Prompt 中的墙,将不同的指令、上下文、输入隔开,避免意外的混淆。你可以选择用 ```,“”\\\", , ,: 等做分隔符,只要能明确起到隔断作用即可。 寻求结构化的输出 。按照某种格式组织

    2024年02月11日
    浏览(34)
  • Openai+Coursera: ChatGPT Prompt Engineering(二)

    这是我写的ChatGPT Prompt Engineerin的第二篇博客,如何还没看过第一篇的请先看我写的第一篇博客: ChatGPT Prompt Engineerin(一) 今天我们的重点关注按特定主题来总结文本。 下面我们来定义一段文本,该文本来自于一个电商网站的客户评论,我们要让ChatGPT来对这段文本进行总结,由

    2024年02月05日
    浏览(35)
  • Openai+Coursera: ChatGPT Prompt Engineering(一)

    今天我学习了DeepLearning.AI的 Prompt Engineering 的在线课程,我想和大家一起分享一下该门课程的一些主要内容。 下面是我们访问大型语言模(LLM)的主要代码: 原则1:写出清晰和具体的说明 ( Write clear and specific instructions ) 原则2:给模型时间“思考” ( Give the model time to “think”

    2024年02月07日
    浏览(36)
  • Prompt工程师指南[应用篇]:Prompt应用、ChatGPT|Midjouney Prompt Engineering

    主题: 与 ChatGPT 对话 Python 笔记本 Topics: ChatGPT介绍 审查对话任务 与ChatGPT对话 Python笔记本 ChatGPT介绍 ChatGPT是OpenAI训练的一种新型模型,可以进行对话交互。该模型经过训练,可以按照提示中的指令,在对话上下文中提供适当的回应。ChatGPT 可以帮助回答问题、建议菜谱、按

    2024年02月04日
    浏览(55)
  • ChatGPT prompt engineering (中文版)笔记 |吴恩达ChatGPT 提示工程

    出处:https://download.csdn.net/download/weixin_45766780/87746321 感谢中文版翻译https://github.com/datawhalechina/prompt-engineering-for-developers/tree/main/content 国内 == 需要对openapi的endpoint做一个反向代理,并修改本地openai包的源代码== 如下图: completion 原则一:编写清晰、具体的指令 你应该通过提供

    2024年02月03日
    浏览(51)
  • Openai+Deeplearning.AI: ChatGPT Prompt Engineering(六)

    想和大家分享一下最近学习的Deeplearning.AI和openai联合打造ChatGPT Prompt Engineering在线课程.以下是我写的关于该课程的前五篇博客: ChatGPT Prompt Engineering(一) ChatGPT Prompt Engineering(二) ChatGPT Prompt Engineering(三) ChatGPT Prompt Engineering(四) ChatGPT Prompt Engineering(五) 今天我们来学习第五部分

    2024年02月07日
    浏览(34)
  • 提升ChatGPT性能的实用指南:Prompt Engineering的艺术

    提示工程是一门新兴学科,就像是为大语言模型(LLM)设计的\\\"语言游戏\\\"。通过这个\\\"游戏\\\",我们可以更有效地引导 LLM 来处理问题。只有熟悉了这个游戏的规则,我们才能更清楚地认识到 LLM 的能力和局限。 这个\\\"游戏\\\"不仅帮助我们理解 LLM,它也是提升 LLM 能力的途径。有效

    2024年02月13日
    浏览(31)
  • 使用 ChatGPT 的 7 个技巧 | Prompt Engineering 学习笔记

    前段时间在 DeepLearning 学了一门大火的 Prompt 的课程,吴恩达本人授课,讲的通俗易懂,感觉受益匪浅,因此在这里总结分享一下我的学习笔记。 为什么要学习 Prompt ? 因为在未来的 AIGC 年代,学习有效的 Promot 提示词有效的利用 AI 来完成一些重复性的工作。这也我认为未来

    2024年02月07日
    浏览(48)
  • 【简单入门】ChatGPT prompt engineering (中文版)笔记 |吴恩达ChatGPT 提示工程

    出处:https://download.csdn.net/download/weixin_45766780/87746321 感谢中文版翻译https://github.com/datawhalechina/prompt-engineering-for-developers/tree/main/content 国内 == 需要对openapi的endpoint做一个反向代理,并修改本地openai包的源代码== 如下图: completion 原则一:编写清晰、具体的指令 你应该通过提供

    2024年02月05日
    浏览(48)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包