关于人工智能:吴恩达与OpenAI官方合作的ChatGPT提示工程课程笔记

4次阅读

共计 39585 个字符,预计需要花费 99 分钟才能阅读完成。

吴恩达与 OpenAI 官网单干的 ChatGPT 提醒工程课程笔记

<aside>
🥸 下述代码均在煮皮特上运行喔

</aside>

LLMs(large language models)

  • Base LLM:基于文本训练数据来预测做“文字接龙”
  • Instruction Tuned LLM(指令调整型 LLM): 承受了遵循批示的培训,能够依据提前培训的输入输出对后果进行调整

提醒指南

两个要害准则

编写明确和具体的指令(明确 ≠ 短)

  • 策略一:用分隔符分明的批示输出的不同局部

    能够应用”””`- - -< ><tag> </tag>。应用分隔符的益处:能够防止提醒词抵触,提醒抵触是指如果容许用户向提醒中增加一些输出,则他们可能会给出与咱们想要的工作不符的指令,导致模型遵循用户的指令而不是咱们本人想要的指令

    • 栗子:

      import openai
      import os
      
      from dotenv import load_dotenv, find_dotenv
      _ = load_dotenv(find_dotenv())
      
      openai.api_key = os.environ.get("OPENAI_API_KEY")
      
      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"]
      
      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)

      输入:

      Clear and specific instructions should be provided to guide a model towards the desired output, and longer prompts can provide more clarity and context for the model, leading to more detailed and relevant outputs.
  • 策略二:要求结构化输入

    能够应用 HTML 或 JSON 等结构化输入

    • 栗子:

      import openai
      import os
      
      from dotenv import load_dotenv, find_dotenv
      _ = load_dotenv(find_dotenv())
      
      openai.api_key = os.environ.get("OPENAI_API_KEY")
      
      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"]
      
      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)s s  

      输入:

      [
        {
          "book_id": 1,
          "title": "The Lost City of Zorath",
          "author": "Aria Blackwood",
          "genre": "Fantasy"
        },
        {
          "book_id": 2,
          "title": "The Last Survivors",
          "author": "Ethan Stone",
          "genre": "Science Fiction"
        },
        {
          "book_id": 3,
          "title": "The Secret of the Haunted Mansion",
          "author": "Lila Rose",
          "genre": "Mystery"
        }
      ]
  • 策略三:要求模型查看是否满足条件

    如果模型存在其余状况,能够要求模型查看并返回不满足条件时的响应

    • 栗子 1

      
      import openai
      import os
      
      from dotenv import load_dotenv, find_dotenv
      _ = load_dotenv(find_dotenv())
      
      openai.api_key = os.environ.get("OPENAI_API_KEY")
      
      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"]
      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)

      输入

      Completion for Text 1:
      Step 1 - Get some water boiling.
      Step 2 - Grab a cup and put a tea bag in it.
      Step 3 - Once the water is hot enough, pour it over the tea bag.
      Step 4 - Let it sit for a bit so the tea can steep.
      Step 5 - After a few minutes, take out the tea bag.
      Step 6 - Add some sugar or milk to taste.
      Step 7 - Enjoy your delicious cup of tea!
    • 栗子 2

      import openai
      import os
      
      from dotenv import load_dotenv, find_dotenv
      _ = load_dotenv(find_dotenv())
      
      openai.api_key = os.environ.get("OPENAI_API_KEY")
      
      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"]
      text_2 = f"""
      The sun is shining brightly today, and the birds are \
      singing. It's a beautiful day to go for a \ 
      walk in the park. The flowers are blooming, and the \ 
      trees are swaying gently in the breeze. People \ 
      are out and about, enjoying the lovely weather. \ 
      Some are having picnics, while others are playing \ 
      games or simply relaxing on the grass. It's a \ 
      perfect day to spend time outdoors and appreciate the \ 
      beauty of nature.
      """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_2}\"\"\"
      """
      response = get_completion(prompt)
      print("Completion for Text 2:")
      print(response)

      输入:

      Completion for Text 2:
      No steps provided.
  • 策略四:大量训练提醒

    这是在要求模型执行工作之前,提醒胜利执行工作的示例

    • 栗子

      import openai
      import os
      
      from dotenv import load_dotenv, find_dotenv
      _ = load_dotenv(find_dotenv())
      
      openai.api_key = os.environ.get("OPENAI_API_KEY")
      
      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"]
      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)

      输入:

      <grandparent>: Resilience is like a tree that bends with the wind but never breaks. It is the ability to bounce back from adversity and keep moving forward, even when things get tough. Just like a tree that grows stronger with each storm it weathers, resilience is a quality that can be developed and strengthened over time.

给模型足够的工夫来思考

如果模型急于做出谬误的论断而呈现推理谬误,应该尝试从新查问申请相干推理的链或序列,直到模型提供最终答案。如果咱们给模型一个太简单的工作,让他在短时间内或用多数词实现,他可能会猜想后果,但后果可能不正确。就像人一样,如果咱们要短时间内实现简单的数学计算可能也会呈现谬误。

  • 策略一:指定实现工作所需的步骤

    • 栗子 1

      text = f"""
      In a charming village, siblings Jack and Jill set out on \ 
      a quest to fetch water from a hilltop \ 
      well. As they climbed, singing joyfully, misfortune \ 
      struck—Jack tripped on a stone and tumbled \ 
      down the hill, with Jill following suit. \ 
      Though slightly battered, the pair returned home to \ 
      comforting embraces. Despite the mishap, \ 
      their adventurous spirits remained undimmed, and they \ 
      continued exploring with delight.
      """
      # example 1
      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}```
      """
      response = get_completion(prompt_1)
      print("Completion for prompt 1:")
      print(response)

      输入:

      Completion for prompt 1:
      Two siblings, Jack and Jill, go on a quest to fetch water from a hilltop well, but misfortune strikes as they both fall down the hill, yet they return home slightly battered but with their adventurous spirits undimmed.
      
      Deux frères et sœurs, Jack et Jill, partent en quête d'eau d'un puits au sommet d'une colline, mais ils tombent tous les deux et retournent chez eux légèrement meurtris mais avec leur esprit d'aventure intact. 
      Noms: Jack, Jill.
      
      {
      "french_summary": "Deux frères et sœurs, Jack et Jill, partent en quête d'eau d'un puits au sommet d'une colline, mais ils tombent tous les deux et retournent chez eux légèrement meurtris mais avec leur esprit d'aventure intact.",
      "num_names": 2
      }

      这个后果呈现了英语和法语交替呈现的状况,咱们须要只在后果外面生成法语

    • 栗子 2

      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)

      输入

      Completion for prompt 2:
      Summary: Jack and Jill go on a quest to fetch water, but misfortune strikes and they tumble down the hill, returning home slightly battered but with their adventurous spirits undimmed. 
      Translation: Jack et Jill partent en quête d'eau, mais la malchance frappe et ils dégringolent la colline, rentrant chez eux légèrement meurtris mais avec leurs esprits aventureux intacts.
      Names: Jack, Jill
      Output JSON: {"french_summary": "Jack et Jill partent en quête d'eau, mais la malchance frappe et ils dégringolent la colline, rentrant chez eux légèrement meurtris mais avec leurs esprits aventureux intacts.","num_names": 2}
  • 策略二:批示模型在做出论断之前思考解决方案

    有时候当咱们在模型给出论断之前,先让模型推理出本人的解决方案时,咱们能够取得更好的后果,也就是在让模型说出答案是否正确之前,为模型提供足够工夫去思考问题

    • 栗子 1

      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)

      输入:

      The student's solution is correct.

      但这个后果尽管看起来是正确的,但实际上是谬误的。模型只是依照思考形式看了一遍,但后批准了学生的解决方案。为了解决这个问题,咱们能够通过让模型先计算本人的解决方案,而后再比拟学生的解决方案和本人的解决方案来修改这个问题

    • 栗子 2

        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)
      
      输入
      

      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 + 10x

      Total cost: 100x + 250x + 100,000 + 10x = 360x + 100,000

      Is the student’s solution the same as actual solution just calculated:
      No

      Student grade:
      Incorrect

模型限度

幻觉

即使应用了大量的常识训练模型,但他并没有齐全记住他所看到的信息,因而他并不是十分理解其常识的边界,这意味着他在答复某些问题的时候,会假造听起来正当但实际上不正确的内容,这些内容就叫做幻觉

  • 栗子

    Boie 是一个实在的公司,但产品不是真的

    prompt = f"""Tell me about AeroGlide UltraSlim Smart Toothbrush by Boie"""
    response = get_completion(prompt)
    print(response)

    输入

    The AeroGlide UltraSlim Smart Toothbrush by Boie is a high-tech toothbrush that uses advanced sonic technology to provide a deep and thorough clean. It features a slim and sleek design that makes it easy to hold and maneuver, and it comes with a range of smart features that help you optimize your brushing routine.
    
    One of the key features of the AeroGlide UltraSlim Smart Toothbrush is its advanced sonic technology, which uses high-frequency vibrations to break up plaque and bacteria on your teeth and gums. This technology is highly effective at removing even the toughest stains and buildup, leaving your teeth feeling clean and refreshed.
    
    In addition to its sonic technology, the AeroGlide UltraSlim Smart Toothbrush also comes with a range of smart features that help you optimize your brushing routine. These include a built-in timer that ensures you brush for the recommended two minutes, as well as a pressure sensor that alerts you if you're brushing too hard.
    
    Overall, the AeroGlide UltraSlim Smart Toothbrush by Boie is a highly advanced and effective toothbrush that is perfect for anyone looking to take their oral hygiene to the next level. With its advanced sonic technology and smart features, it provides a deep and thorough clean that leaves your teeth feeling fresh and healthy.

缩小幻觉的策略(步骤)

  1. 从文本中找到任何相干的援用
  2. 要求他应用这些援用来答复问题
  3. 能够追溯答案

迭代提醒开发过程

  1. 有一个想要实现的工作的想法
  2. 尝试编写一个清晰、具体、如果适合的话,让零碎有足够工夫思考的提醒
  3. 运行并查看后果,如果后果不称心,剖析后果,找出 prompt 哪里不清晰,或者是不是没有给模型足够的工夫
  4. 从新构建想法和 prompt
  5. 反复上述步骤,直到后果称心

示例

  • 依据说明书生成一份在线批发网站的形容

    fact_sheet_chair = """
    OVERVIEW
    - Part of a beautiful family of mid-century inspired office furniture, 
    including filing cabinets, desks, bookcases, meeting tables, and more.
    - Several options of shell color and base finishes.
    - Available with plastic back and front upholstery (SWC-100) 
    or full upholstery (SWC-110) in 10 fabric and 6 leather options.
    - Base finish options are: stainless steel, matte black, 
    gloss white, or chrome.
    - Chair is available with or without armrests.
    - Suitable for home or business settings.
    - Qualified for contract use.
    
    CONSTRUCTION
    - 5-wheel plastic coated aluminum base.
    - Pneumatic chair adjust for easy raise/lower action.
    
    DIMENSIONS
    - WIDTH 53 CM | 20.87”- DEPTH 51 CM | 20.08”- HEIGHT 80 CM | 31.50”- SEAT HEIGHT 44 CM | 17.32”- SEAT DEPTH 41 CM | 16.14”OPTIONS
    - Soft or hard-floor caster options.
    - Two choices of seat foam densities: 
     medium (1.8 lb/ft3) or high (2.8 lb/ft3)
    - Armless or 8 position PU armrests 
    
    MATERIALS
    SHELL BASE GLIDER
    - Cast Aluminum with modified nylon PA6/PA66 coating.
    - Shell thickness: 10 mm.
    SEAT
    - HD36 foam
    
    COUNTRY OF ORIGIN
    - Italy
    """

第一次尝试

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.

Technical specifications: ```{fact_sheet_chair}```
"""
response = get_completion(prompt)
print(response)

输入

Introducing our stunning mid-century inspired office chair, part of a beautiful family of furniture that includes filing cabinets, desks, bookcases, meeting tables, and more. With several options of shell color and base finishes, you can customize this chair to perfectly match your decor. Choose between plastic back and front upholstery or full upholstery in 10 fabric and 6 leather options. The base finish options are stainless steel, matte black, gloss white, or chrome, and you can opt for armrests or no armrests.

Constructed with a 5-wheel plastic coated aluminum base and a pneumatic chair adjust for easy raise/lower action, this chair is both sturdy and comfortable. It's suitable for home or business settings and is even qualified for contract use.

The dimensions of this chair are as follows: WIDTH 53 CM | 20.87”, DEPTH 51 CM | 20.08”, HEIGHT 80 CM | 31.50”, SEAT HEIGHT 44 CM | 17.32”, SEAT DEPTH 41 CM | 16.14”. You can also choose between soft or hard-floor caster options and two choices of seat foam densities: medium (1.8 lb/ft3) or high (2.8 lb/ft3).

The materials used in this chair are of the highest quality. The shell base glider is made of cast aluminum with modified nylon PA6/PA66 coating and has a shell thickness of 10 mm. The seat is made of HD36 foam.

This chair is made in Italy and is sure to add a touch of elegance to any space.

论断

太长啦!想要短一点

第二次尝试

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.

Use at most 50 words.

Technical specifications: ```{fact_sheet_chair}```
"""
response = get_completion(prompt)
print(response)

输入

Introducing the mid-century inspired office chair, part of a beautiful furniture family. Available in various shell colors and base finishes, with plastic or full upholstery options in fabric or leather. Suitable for home or business use, with pneumatic chair adjust and soft/hard-floor caster options. Made in Italy.

论断

  • 问题一:模型可能对长度比拟含糊,然而问题不大。
  • 问题二:这个网站次要面向的是家具零售商,他们更关系椅子的技术细节和资料

第三次尝试

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.

Use at most 50 words.

Technical specifications: ```{fact_sheet_chair}```
"""
response = get_completion(prompt)
print(response)

输入

Introducing our mid-century inspired office chair, perfect for both home and business settings. With a range of shell colors and base finishes, including stainless steel and matte black, this chair is available with or without armrests and in 10 fabric and 6 leather options. Constructed with a 5-wheel plastic coated aluminum base and HD36 foam seat, it also features a pneumatic chair adjust for easy raise/lower action. Made in Italy and qualified for contract use.

论断

在形容开端,加上产品 ID

第四次尝试

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.

Use at most 50 words.

Technical specifications: ```{fact_sheet_chair}```
"""
response = get_completion(prompt)
print(response)

输入

Introducing our mid-century inspired office chair, perfect for home or business settings. With a range of shell colors and base finishes, and the option of plastic or full upholstery in various fabrics and leathers, this chair is both stylish and versatile. Constructed with a 5-wheel plastic coated aluminum base and pneumatic chair adjust, it's also practical and comfortable. Available with or without armrests and suitable for contract use. Product ID: SWC-100, SWC-110.

论断

形容要清晰具体,并在必要时给模型一些思考工夫,有了这些,先进行一次尝试,看看模型会给出什么后果,而后逐渐改良提醒以靠近所需的后果

最初最初

或者咱们想要一个表格来展现数据

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

response = get_completion(prompt)
print(response)

并通过展现得出一个 HTML

from IPython.display import display, HTML
display(HTML(response))

LLMs 在软件应用程序中的用处

文本摘要

总结和提取单个文本信息

上面是一个总结评论的示例,总结评论个别用在购物网站对评论进行剖析

prod_review = """Got this panda plush toy for my daughter's birthday, \
who loves it and takes it everywhere. It's soft and \ 
super cute, and its face has a friendly look. It's \ 
a bit small for what I paid though. I think there \ 
might be other options that are bigger for the \ 
same price. It arrived a day earlier than expected, \ 
so I got to play with it myself before I gave it \ 
to her.
"""

生成摘要

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 30 words. 

Review: ```{prod_review}```
"""

response = get_completion(prompt)
print(response)

输入

Soft and cute panda plush toy loved by daughter, but a bit small for the price. Arrived early.

批改 prompt,使总结更实用于某个部门,例如运输部门

prompt = f"""
Your task is to generate a short summary of a product \
review from an ecommerce site to give feedback to the \
Shipping deparmtment. 

Summarize the review below, delimited by triple 
backticks, in at most 30 words, and focusing on any aspects \
that mention shipping and delivery of the product. 

Review: ```{prod_review}```
"""

response = get_completion(prompt)
print(response)

输入

The panda plush toy arrived a day earlier than expected, but the customer felt it was a bit small for the price paid.

如果是交给定价部门,再次批改 prompt

prompt = f"""
Your task is to generate a short summary of a product \
review from an ecommerce site to give feedback to the \
pricing deparmtment, responsible for determining the \
price of the product.  

Summarize the review below, delimited by triple 
backticks, in at most 30 words, and focusing on any aspects \
that are relevant to the price and perceived value. 

Review: ```{prod_review}```
"""

response = get_completion(prompt)
print(response)

输入

The panda plush toy is soft, cute, and loved by the recipient, but the price may be too high for its size compared to other options.

下面的 prompt 都是总结,他也能够提取文本

prompt = f"""
Your task is to extract relevant information from \ 
a product review from an ecommerce site to give \
feedback to the Shipping department. 

From the review below, delimited by triple quotes \
extract the information relevant to shipping and \ 
delivery. Limit to 30 words. 

Review: ```{prod_review}```
"""

response = get_completion(prompt)
print(response)

输入

"The product arrived a day earlier than expected."

总结多个文本信息

review_1 = prod_review 

# review for a standing lamp
review_2 = """
Needed a nice lamp for my bedroom, and this one \
had additional storage and not too high of a price \
point. Got it fast - arrived in 2 days. The string \
to the lamp broke during the transit and the company \
happily sent over a new one. Came within a few days \
as well. It was easy to put together. Then I had a \
missing part, so I contacted their support and they \
very quickly got me the missing piece! Seems to me \
to be a great company that cares about their customers \
and products. 
"""

# review for an electric toothbrush
review_3 = """
My dental hygienist recommended an electric toothbrush, \
which is why I got this. The battery life seems to be \
pretty impressive so far. After initial charging and \
leaving the charger plugged in for the first week to \
condition the battery, I've unplugged the charger and \
been using it for twice daily brushing for the last \
3 weeks all on the same charge. But the toothbrush head \
is too small. I’ve seen baby toothbrushes bigger than \
this one. I wish the head was bigger with different \
length bristles to get between teeth better because \
this one doesn’t.  Overall if you can get this one \
around the $50 mark, it's a good deal. The manufactuer's \
replacements heads are pretty expensive, but you can \
get generic ones that're more reasonably priced. This \
toothbrush makes me feel like I've been to the dentist \
every day. My teeth feel sparkly clean! 
"""

# review for a blender
review_4 = """
So, they still had the 17 piece system on seasonal \
sale for around $49 in the month of November, about \
half off, but for some reason (call it price gouging) \
around the second week of December the prices all went \
up to about anywhere from between $70-$89 for the same \
system. And the 11 piece system went up around $10 or \
so in price also from the earlier sale price of $29. \
So it looks okay, but if you look at the base, the part \
where the blade locks into place doesn’t look as good \
as in previous editions from a few years ago, but I \
plan to be very gentle with it (example, I crush \
very hard items like beans, ice, rice, etc. in the \ 
blender first then pulverize them in the serving size \
I want in the blender then switch to the whipping \
blade for a finer flour, and use the cross cutting blade \
first when making smoothies, then use the flat blade \
if I need them finer/less pulpy). Special tip when making \
smoothies, finely cut and freeze the fruits and \
vegetables (if using spinach-lightly stew soften the \ 
spinach then freeze until ready for use-and if making \
sorbet, use a small to medium sized food processor) \ 
that you plan to use that way you can avoid adding so \
much ice if at all-when making your smoothie. \
After about a year, the motor was making a funny noise. \
I called customer service but the warranty expired \
already, so I had to buy another one. FYI: The overall \
quality has gone done in these types of products, so \
they are kind of counting on brand recognition and \
consumer loyalty to maintain sales. Got it in about \
two days.
"""

reviews = [review_1, review_2, review_3, review_4]

生成论断

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

<aside>
🥸 留神,api 的 qps 是 3 /min

</aside>

推理

LLMs 一个十分好的特点是,对于很多剖析工作,只须要编写提醒即可立刻开始生成后果。

分类

上面是对评论进行情感分类的示例

lamp_review = """
Needed a nice lamp for my bedroom, and this one had \
additional storage and not too high of a price point. \
Got it fast.  The string to our lamp broke during the \
transit and the company happily sent over a new one. \
Came within a few days as well. It was easy to put \
together.  I had a missing part, so I contacted their \
support and they very quickly got me the missing piece! \
Lumina seems to me to be a great company that cares \
about their customers and products!!
"""

判断语气

prompt = f"""
What is the sentiment of the following product review, 
which is delimited with triple backticks?

Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)

输入

The sentiment of the product review is positive.

然而这个后果我心愿他更简练一些,批改 prompt

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)

能够看到输入了

positive

定义评论的情绪

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)

输入

happy, satisfied, grateful, impressed, content

p 判断用户是否称心

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)

s 输入

No

信息提取

上面是针对评论提取信息的例子

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)

输入

{
  "Item": "lamp with additional storage",
  "Brand": "Lumina"
}

一次实现多个工作

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)
{
  "Sentiment": "positive",
  "Anger": false,
  "Item": "lamp with additional storage",
  "Brand": "Lumina"
}

依据文章提取主题

上面是一段文本形容,用来测试

story = """
In a recent survey conducted by the government, 
public sector employees were asked to rate their level 
of satisfaction with the department they work at. 
The results revealed that NASA was the most popular 
department with a satisfaction rating of 95%.

One NASA employee, John Smith, commented on the findings, 
stating, "I'm not surprised that NASA came out on top. 
It's a great place to work with amazing people and 
incredible opportunities. I'm proud to be a part of 
such an innovative organization."The results were also welcomed by NASA's management team, 
with Director Tom Johnson stating, "We are thrilled to 
hear that our employees are satisfied with their work at NASA. 
We have a talented and dedicated team who work tirelessly 
to achieve our goals, and it's fantastic to see that their 
hard work is paying off."

The survey also revealed that the 
Social Security Administration had the lowest satisfaction 
rating, with only 45% of employees indicating they were 
satisfied with their job. The government has pledged to 
address the concerns raised by employees in the survey and 
work towards improving job satisfaction across all departments.
"""

提取 5 个主题

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)

输入

government survey, job satisfaction, NASA, Social Security Administration, employee concerns

当初给定了以下主题

topic_list = [
    "nasa", "local government", "engineering", 
    "employee satisfaction", "federal government"
]

心愿确认文本蕴含了哪些给定主题

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)

输入

nasa: 1
local government: 0
engineering: 0
employee satisfaction: 1
federal government: 1

转换

LLMs 十分善于将其输出转换为不同的格局,比方将一种语言翻译成另一种语言、纠正拼写和语法错误、转换格局(JSON、HTML 等)。上面是很多例子

翻译

  • 翻译
prompt = f"""
Translate the following English text to Spanish: \ 
```Hi, I would like to order a blender```
"""
response = get_completion(prompt)
print(response)

输入

Hola, me gustaría ordenar una licuadora.
  • 指出所用语言
prompt = f"""
Tell me which language this is: 
```Combien coûte le lampadaire?```
"""
response = get_completion(prompt)
print(response)

输入

This is French.
  • 同时翻译成多种语言
prompt = f"""
Translate the following  text to French and Spanish
and English pirate: \
```I want to order a basketball```
"""
response = get_completion(prompt)
print(response)

输入

French pirate: ```Je veux commander un ballon de basket```
Spanish pirate: ```Quiero pedir una pelota de baloncesto```
English pirate: ```I want to order a basketball```
  • 能够通过通知模型谈话者和听众的关系而扭转翻译
prompt = f"""
Translate the following text to Spanish in both the \
formal and informal forms: 
'Would you like to order a pillow?'
"""
response = get_completion(prompt)
print(response)

输入

Formal: ¿Le gustaría ordenar una almohada?
Informal: ¿Te gustaría ordenar una almohada?
  • 设想一下,您在一家大型跨国电子商务公司负责 IT。用户正在用他们所有的母语向您发送无关 IT 问题的音讯。您的员工来自世界各地,只说他们的母语。你须要一个万能翻译器!
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")

语气转换

  • 将语句转换成商业邮件的语气
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)

输入

Dear Sir/Madam,

I am writing to bring to your attention a standing lamp that I believe may be of interest to you. Please find attached the specifications for your review.

Thank you for your time and consideration.

Sincerely,

Joe

格局转换

  • 将 JSON 转换为 HTML
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}
"""
response = get_completion(prompt)
print(response)
from IPython.display import display, Markdown, Latex, HTML, JSON
display(HTML(response))

输入

拼写和语法问题查看

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)
text = f"""
Got this for my daughter for her birthday cuz she keeps taking \
mine from my room.  Yes, adults also like pandas too.  She takes \
it everywhere with her, and it's super soft and cute.  One of the \
ears is a bit lower than the other, and I don't think that was \
designed to be asymmetrical. It's a bit small for what I paid for it \
though. I think there might be other options that are bigger for \
the same price.  It arrived a day earlier than expected, so I got \
to play with it myself before I gave it to my daughter.
"""prompt = f"proofread and correct this review: ```{text}```"
response = get_completion(prompt)
print(response)

输入

I got this for my daughter's birthday because she keeps taking mine from my room. Yes, adults also like pandas too. She takes it everywhere with her, and it's super soft and cute. However, one of the ears is a bit lower than the other, and I don't think that was designed to be asymmetrical. Additionally, it's a bit small for what I paid for it. I think there might be other options that are bigger for the same price. On the positive side, it arrived a day earlier than expected, so I got to play with it myself before I gave it to my daughter.

通过 redlines 来查看批改

from redlines import Redlines

diff = Redlines(text,response)
display(Markdown(diff.output_markdown))

尝试生成 APA 格调和面向多种指标用户的语句

prompt = f"""
proofread and correct this review. Make it more compelling.
Ensure it follows APA style guide and targets an advanced reader.
Output in markdown format.
Text: ```{text}```
"""
response = get_completion(prompt)
display(Markdown(response))

输入

Title: A Soft and Cute Panda Plush Toy for All Ages
Introduction: As a parent, finding the perfect gift for your child’s birthday can be a daunting task. However, I stumbled upon a soft and cute panda plush toy that not only made my daughter happy but also brought joy to me as an adult. In this review, I will share my experience with this product and provide an honest assessment of its features.
Product Description: The panda plush toy is made of high-quality materials that make it super soft and cuddly. Its cute design is perfect for children and adults alike, making it a versatile gift option. The toy is small enough to carry around, making it an ideal companion for your child on their adventures.
Pros: The panda plush toy is incredibly soft and cute, making it an excellent gift for children and adults. Its small size makes it easy to carry around, and its design is perfect for snuggling. The toy arrived a day earlier than expected, which was a pleasant surprise.
Cons: One of the ears is a bit lower than the other, which makes the toy asymmetrical. Additionally, the toy is a bit small for its price, and there might be other options that are bigger for the same price.
Conclusion: Overall, the panda plush toy is an excellent gift option for children and adults who love cute and cuddly toys. Despite its small size and asymmetrical design, the toy’s softness and cuteness make up for its shortcomings. If you’re looking for a versatile gift option that will bring joy to your child and yourself, this panda plush toy is an excellent choice.

扩大

扩大是指将段文本(如一组阐明或主题列表)通过 LLMs 转化成更长的文本(如一封电子邮件或一篇对于某个主题的文章)

依据信息生成个性化电子邮件

咱们将编写一个自定义的电子邮件回复工具。依据客户的评论和情感,生成定制的回复

# given the sentiment from the lesson on "inferring",
# and the original customer message, customize the email
sentiment = "negative"

# review for a blender
review = f"""
So, they still had the 17 piece system on seasonal \
sale for around $49 in the month of November, about \
half off, but for some reason (call it price gouging) \
around the second week of December the prices all went \
up to about anywhere from between $70-$89 for the same \
system. And the 11 piece system went up around $10 or \
so in price also from the earlier sale price of $29. \
So it looks okay, but if you look at the base, the part \
where the blade locks into place doesn’t look as good \
as in previous editions from a few years ago, but I \
plan to be very gentle with it (example, I crush \
very hard items like beans, ice, rice, etc. in the \ 
blender first then pulverize them in the serving size \
I want in the blender then switch to the whipping \
blade for a finer flour, and use the cross cutting blade \
first when making smoothies, then use the flat blade \
if I need them finer/less pulpy). Special tip when making \
smoothies, finely cut and freeze the fruits and \
vegetables (if using spinach-lightly stew soften the \ 
spinach then freeze until ready for use-and if making \
sorbet, use a small to medium sized food processor) \ 
that you plan to use that way you can avoid adding so \
much ice if at all-when making your smoothie. \
After about a year, the motor was making a funny noise. \
I called customer service but the warranty expired \
already, so I had to buy another one. FYI: The overall \
quality has gone done in these types of products, so \
they are kind of counting on brand recognition and \
consumer loyalty to maintain sales. Got it in about \
two days.
"""
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)
print(response)

输入

Dear valued customer,

Thank you for taking the time to leave a review about our product. We are sorry to hear that you experienced a price increase and that the quality of the product did not meet your expectations. We apologize for any inconvenience this may have caused you.

If you have any further concerns or questions, please do not hesitate to reach out to our customer service team. They will be more than happy to assist you in any way they can.

Thank you again for your feedback. We appreciate your business and hope to have the opportunity to serve you better in the future.

Best regards,

AI customer agent

Temperature 参数

该参数容许咱们扭转模型响应的多样性。temperature 的范畴是 0 -1,数值越大,多样性越大。倡议设置为 0,这样能够构建一个牢靠和可预测的零碎。

聊天机器人

定义两个办法,应用 chatgpt 的模型,两个办法别离是繁多对话,以及音讯列表。这里能够留神到应用了新的对象ChatCompletion

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

角色

  • system:提供指导方针,有助于设置助手的行为和人设,并作为高层指令用于对话,而用户不会意识到零碎音讯。他为开发者提供了一种在不将申请自身作为对话的一部分的状况下疏导助手并领导其回复的形式
  • assistant:助手,chatgpt
  • user:用户

示例

音讯列表

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)

输入

{
  "content": "Your name is Isa!",
  "role": "assistant"
}
Your name is Isa!

<aside>
🥸 与语言模型的每次对话都是独立的交互,这意味着必须提供以后对话中所有相干的音讯,以供模型应用。如果心愿模型从先前的对话局部中提取或记住信息,必须在输出到模型的上下文中提供先前的信息。这就称为上下文。

</aside>

提供上下文

messages =  [{'role':'system', 'content':'You are friendly chatbot.'},
{'role':'user', 'content':'Hi, my name is Isa'},
{'role':'assistant', 'content': "Hi Isa! It's nice to meet you. \
Is there anything I can help you with today?"},
{'role':'user', 'content':'Yes, you can remind me, What is my name?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)

输入

Your name is Isa!

咱们发现,这里模型曾经晓得我叫什么名字了。因为模型在这个输出的信息列表中曾经领有了它所须要的所有上下文,所以它可能做出回应。

构建本人的机器人

咱们能够主动收集用户提醒和助手响应以构建 OrderBot。OrderBot 将在比萨餐厅承受订单。

在这个例子中,对话将被一直增加到上下文中,每次对话都会应用这个上下文。

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)

总结

LLMs 是一种十分弱小的技术,应用的时候要负责任哦,只构建对人们有踊跃影响的事物

本文由 mdnice 多平台公布

正文完
 0