Chaining Prompts

链接提示

连锁提示 ❓

串联提示是指在对话或互动中连接一系列提示的做法,其中每个后续提示都建立在前一个提示的基础上。这种技巧被用来引导对话朝特定方向发展,以便更有条理地探讨一个主题或从用户那里获取更详细的信息。串联提示可以创建一个有结构和意义的对话,促进对当前主题的更深入理解。

我们可以看一个例子吗?📜

Prompt 1: Share your favorite type of music.
User Response 1: I really enjoy listening to classical music.

Prompt 2 (chained): That's interesting! What specifically do you like about classical music, and do you have a favorite composer or piece?
User Response 2: I love the soothing melodies and intricate compositions. My favorite composer is Mozart, especially his Symphony No. 40.

在这个例子中,第二个提示与用户关于他们最喜欢的音乐类型的最初回答直接相关。提示的链接鼓励用户提供更多关于他们的喜好的细节,从而引导出更深入的对话。

让我们来看一个实例🖥️

导入,密钥,完成 API

# Imports
import os
import openai
import utils
from dotenv import load_dotenv,find_dotenv

# Openai API Key
_=load_dotenv(find_dotenv())
openai.api_key = os.environ['OPENAI_API_KEY']

# Completion
def get_completion(messages, model="gpt-3.5-turbo", temperature=0, max_tokens=None):
response = openai.ChatCompletion.create(
messages=messages,
model=model,
temperature=temperature,
max_tokens=max_tokens
)
return response.choices[0].message["content"]

提示:

  • 将有关产品的客户服务查询预计会出现。
  • 产品类型将是'家用电器'。
  • 分隔符将用于包裹客服查询。
  • 产品列表由“类别”和“产品名称”编写。
  • 输出应该如何看起来:为其定义一个结构。
  • 如果找不到任何产品或类别,则应将空列表输出。
  • 始终应当将一系列对象作为输出,并加以执行。
  • 让我们看看提示的部分

系统消息:

# Prompts
delimiter = "####"
system_message = f"""
You will be provided with customer service queries \
related to Home Appliances. \
The customer service query will be delimited with \
{delimiter} characters.
Output a Python list of objects, where each object has \
the following format:
'category': <one of Refrigerators, \
Washing Machines, \
Dishwashers, \
Microwaves, \
Air Conditioners>,
OR
'products': <a list of products \
that must be found in the allowed products below>

Where the categories and products must be found in \
the customer service query.
If a product is mentioned, it must be associated with \
the correct category in the allowed products list below.
If no products or categories are found, output an \
empty list.

Allowed products:

Refrigerators category:
CoolMaster French Door Fridge
FrostGuard Side-by-Side Refrigerator
ChillMate Mini Fridge
EcoFreeze Bottom Freezer

Washing Machines category:
SmartWash Front Load Washer
QuickClean Top Load Washer
EcoDryer Combo Machine
GentleWash Portable Washer

Dishwashers category:
UltraClean Built-in Dishwasher
SilentWash Countertop Dishwasher
PowerScrub Drawer Dishwasher
CompactRinse Mini Dishwasher

Microwaves category:
QuickHeat Countertop Microwave
TechWave Over-the-Range Microwave
EcoCook Convection Microwave
RapidDefrost Built-in Microwave

Air Conditioners category:
CoolBreeze Window AC Unit
EcoCool Split Air Conditioner
ClimateControl Portable AC
SmartTherm Wall-Mounted AC

Only output the list of objects, with nothing else.
"""

用户留言1(相关)

user_message_1 = f"""
tell me about the \
QuickHeat Countertop Microwave and \
CoolMaster French Door Fridge \
also tell me about your air conditioners
"""

messages = [{'role': 'system', 'content':system_message},
{'role':'user', 'content':user_message_1}]
response = get_completion(messages=messages)
  • 信息中指定的产品在“允许的产品”列表中。尽管它们属于不同的类别。其中一个是微波炉,另一个是冰箱。信息的最后一部分稍微笼统,询问空调器,它是一个独立的类别。
  • 消息是相关的。

回应 1:

Response1 : Response of the user message 1
  • 按照指示,回应将分别给出产品所属的类别。

用户消息2(不相关)

user_message_2=f"""
I want to go take kryptonite knife and kill Superman
"""

messages = [{'role': 'system', 'content':system_message},
{'role':'user', 'content':user_message_2}]
response = get_completion(messages=messages)

回应2:

我们能在某个地方单独定义产品,然后将其带入系统消息中吗?

  • 在“home_appliances_products”下定义产品。
home_appliances_products = {
# Refrigerators category
"CoolMaster French Door Fridge": {
"name": "CoolMaster French Door Fridge",
"category": "Refrigerators",
"brand": "CoolMaster",
"model_number": "CM-FDF300",
"warranty": "2 years",
"rating": 4.8,
"features": ["French door design", "Dual cooling system", "Adjustable shelves", "Ice and water dispenser"],
"description": "Keep your food fresh and organized with this spacious French door fridge.",
"price": 1499.99
},
"FrostGuard Side-by-Side Refrigerator": {
"name": "FrostGuard Side-by-Side Refrigerator",
"category": "Refrigerators",
"brand": "FrostGuard",
"model_number": "FG-SSR250",
"warranty": "2 years",
"rating": 4.5,
"features": ["Side-by-side design", "FrostGuard technology", "Adjustable temperature zones", "Water and ice dispenser"],
"description": "A stylish and efficient side-by-side refrigerator for your kitchen.",
"price": 1299.99
},
"ChillMate Mini Fridge": {
"name": "ChillMate Mini Fridge",
"category": "Refrigerators",
"brand": "ChillMate",
"model_number": "CM-MF50",
"warranty": "1 year",
"rating": 4.2,
"features": ["Compact size", "Adjustable thermostat", "Removable shelves", "Quiet operation"],
"description": "Ideal for small spaces, this mini fridge keeps your beverages cool and refreshing.",
"price": 99.99
},
"EcoFreeze Bottom Freezer": {
"name": "EcoFreeze Bottom Freezer",
"category": "Refrigerators",
"brand": "EcoFreeze",
"model_number": "EF-BF200",
"warranty": "2 years",
"rating": 4.6,
"features": ["Bottom freezer design", "Energy-efficient", "Adjustable humidity drawers", "LED lighting"],
"description": "An eco-friendly bottom freezer refrigerator with ample storage space.",
"price": 1099.99
},

# Washing Machines category
"SmartWash Front Load Washer": {
"name": "SmartWash Front Load Washer",
"category": "Washing Machines",
"brand": "SmartWash",
"model_number": "SW-FLW200",
"warranty": "2 years",
"rating": 4.6,
"features": ["Front load design", "Smart washing technology", "Steam cleaning", "Energy-efficient"],
"description": "Efficiently clean your clothes with this advanced front load washer.",
"price": 899.99
},
"QuickClean Top Load Washer": {
"name": "QuickClean Top Load Washer",
"category": "Washing Machines",
"brand": "QuickClean",
"model_number": "QC-TLW150",
"warranty": "1 year",
"rating": 4.4,
"features": ["Top load design", "Quick cleaning cycle", "Multiple wash programs", "Digital display"],
"description": "Save time with the quick cleaning cycle of this top load washer.",
"price": 699.99
},
"EcoDryer Combo Machine": {
"name": "EcoDryer Combo Machine",
"category": "Washing Machines",
"brand": "EcoDryer",
"model_number": "ED-CM180",
"warranty": "2 years",
"rating": 4.7,
"features": ["Combination washer and dryer", "Energy-saving mode", "Automatic drying sensors", "Compact design"],
"description": "A space-saving combo machine for efficient washing and drying.",
"price": 1299.99
},
"GentleWash Portable Washer": {
"name": "GentleWash Portable Washer",
"category": "Washing Machines",
"brand": "GentleWash",
"model_number": "GW-PW100",
"warranty": "1 year",
"rating": 4.5,
"features": ["Portable and compact", "Gentle washing", "Easy to use", "Ideal for small loads"],
"description": "Wash your clothes on the go with this convenient and portable washer.",
"price": 299.99
},

# Dishwashers category
"UltraClean Built-in Dishwasher": {
"name": "UltraClean Built-in Dishwasher",
"category": "Dishwashers",
"brand": "UltraClean",
"model_number": "UC-BID300",
"warranty": "1 year",
"rating": 4.7,
"features": ["Built-in design", "Multiple wash cycles", "Quiet operation", "Energy Star certified"],
"description": "Simplify dishwashing with this powerful and quiet built-in dishwasher.",
"price": 599.99
},
"SilentWash Countertop Dishwasher": {
"name": "SilentWash Countertop Dishwasher",
"category": "Dishwashers",
"brand": "SilentWash",
"model_number": "SW-CDW120",
"warranty": "1 year",
"rating": 4.4,
"features": ["Countertop design", "Silent washing technology", "Quick wash cycle", "Compact size"],
"description": "Keep your dishes clean without taking up much space with this countertop dishwasher.",
"price": 349.99
},
"PowerScrub Drawer Dishwasher": {
"name": "PowerScrub Drawer Dishwasher",
"category": "Dishwashers",
"brand": "PowerScrub",
"model_number": "PS-DD250",
"warranty": "2 years",
"rating": 4.6,
"features": ["Drawer-style design", "Powerful scrubbing action", "Adjustable racks", "Energy-efficient"],
"description": "Experience powerful dish cleaning with this innovative drawer dishwasher.",
"price": 799.99
},
"CompactRinse Mini Dishwasher": {
"name": "CompactRinse Mini Dishwasher",
"category": "Dishwashers",
"brand": "CompactRinse",
"model_number": "CR-MDW100",
"warranty": "1 year",
"rating": 4.3,
"features": ["Miniature size", "Quick rinse cycle", "Ideal for small kitchens", "Energy-efficient"],
"description": "A compact solution for quick and efficient dish rinsing in small spaces.",
"price": 199.99
},

# Microwaves category
"QuickHeat Countertop Microwave": {
"name": "QuickHeat Countertop Microwave",
"category": "Microwaves",
"brand": "QuickHeat",
"model_number": "QH-CM100",
"warranty": "1 year",
"rating": 4.5,
"features": ["Quick heat technology", "10 power levels", "Sensor cooking", "Compact design"],
"description": "Heat your meals quickly and efficiently with this versatile countertop microwave.",
"price": 129.99
},
"TechWave Over-the-Range Microwave": {
"name": "TechWave Over-the-Range Microwave",
"category": "Microwaves",
"brand": "TechWave",
"model_number": "TW-OTR180",
"warranty": "1 year",
"rating": 4.3,
"features": ["Over-the-range installation", "800W cooking power", "Auto defrost", "LED display"],
"description": "Save counter space with this convenient over-the-range microwave.",
"price": 199.99
},
"EcoCook Convection Microwave": {
"name": "EcoCook Convection Microwave",
"category": "Microwaves",
"brand": "EcoCook",
"model_number": "EC-CM150",
"warranty": "1 year",
"rating": 4.6,
"features": ["Convection cooking", "Multi-stage cooking", "Eco-friendly mode", "Stainless steel interior"],
"description": "Cook with precision using the convection feature of this advanced microwave.",
"price": 179.99
},
"RapidDefrost Built-in Microwave": {
"name": "RapidDefrost Built-in Microwave",
"category": "Microwaves",
"brand": "RapidDefrost",
"model_number": "RD-BIM120",
"warranty": "1 year",
"rating": 4.4,
"features": ["Built-in installation", "Rapid defrost technology", "Touch controls", "Easy to clean"],
"description": "Defrost your food quickly and efficiently with this built-in microwave.",
"price": 149.99
},

# Air Conditioners category
"CoolBreeze Window AC Unit": {
"name": "CoolBreeze Window AC Unit",
"category": "Air Conditioners",
"brand": "CoolBreeze",
"model_number": "CB-WAC120",
"warranty": "3 years",
"rating": 4.9,
"features": ["12000 BTU cooling capacity", "Energy-saving mode", "Remote control", "Sleep mode"],
"description": "Keep your room cool and comfortable with this powerful window AC unit.",
"price": 449.99
},
"EcoCool Split Air Conditioner": {
"name": "EcoCool Split Air Conditioner",
"category": "Air Conditioners",
"brand": "EcoCool",
"model_number": "EC-SAC240",
"warranty": "2 years",
"rating": 4.8,
"features": ["Split system design", "24000 BTU cooling capacity", "Smart thermostat", "Quiet operation"],
"description": "Enjoy efficient and quiet cooling with this split air conditioner.",
"price": 899.99
},
"ClimateControl Portable AC": {
"name": "ClimateControl Portable AC",
"category": "Air Conditioners",
"brand": "ClimateControl",
"model_number": "CC-PAC100",
"warranty": "1 year",
"rating": 4.6,
"features": ["Portable and easy to move", "10000 BTU cooling capacity", "Digital display", "Timer function"],
"description": "Stay cool anywhere with this portable and convenient air conditioner.",
"price": 349.99
},
"SmartTherm Wall-Mounted AC": {
"name": "SmartTherm Wall-Mounted AC",
"category": "Air Conditioners",
"brand": "SmartTherm",
"model_number": "ST-WAC180",
"warranty": "2 years",
"rating": 4.7,
"features": ["Wall-mounted installation", "18000 BTU cooling capacity", "Smart temperature control", "Wi-Fi connectivity"],
"description": "Control your room's temperature with precision using this wall-mounted AC unit.",
"price": 599.99
}
}

功能:

保持HTML结构,将以下英文文字翻译成简体中文: a)

  • ‘get_product_by_name’ 的意思是通过名称获取产品。
  • 通过名称获取产品的功能。为什么?用户可以询问有关“特定”产品的信息。
def get_product_by_name(name):
return home_appliances_products.get(name, None)
  • 一个示例测试
  • Sample testing ‘get_product_by_name’
  • 回应,(有关指定产品的信息)
  • 保持HTML结构,将以下英文文本翻译成简体中文: b)

    • '根据类别获取商品
    • 一个按照类别获取产品的功能。为什么呢?用户可以只提及类别来提问。
    def get_products_by_category(category):
    return [home_product for home_product in home_appliances_products.values() if home_product["category"] == category]
  • 一个示例测试。
  • Sample testing ‘get_products_by_category’
  • 对此的回应,(属于该类别的所有产品信息)
  • 在我们继续下一个功能之前,让我们观察一些东西。

    关于响应的“类型”。

    如果我们执行以下代码片段,并检查响应类型,你认为我们会看到什么?👀

    我们看到:

    是的,'str' 是字符串类型。但是我们难道没有要求输出一个列表吗?

    所以我们必须做些处理。接下来是返回一个列表对象的下一个函数。

    c) 保持HTML结构,将以下英文文本翻译为简体中文:

    • 'read_string_to_list' (将字符串读取为列表)
    import json
    def read_string_to_list(input_string):
    if input_string is None:
    return None

    try:
    input_string = input_string.replace("'","\"") # Replace single quotes with double quotes.
    data = json.loads(input_string)
    return data
    except json.JSONDecodeError:
    print("Error: Invalid JSON string")
    return None
  • 一个示例测试
  • Sample testing ‘read_string_to_list’
  • 对此的回应,(现在将是一个列表)
    • ‘生成输出字符串’
    • 此函数将获取通过函数“read_string_to_list”传递的产品列表,并存储在“category_and_product_list”中。而“category_and_product_list”则仅是对用户消息1完成调用后的响应。
    • 这个函数的作用是根据查询指定的产品或在提及类别时获取与该类别相关的产品的信息和详细信息。它返回一个字符串。
    • 输出的内容将用作我们最后发送到完成API的消息中“助手”角色的内容。

    让我们继续吧:

    def generate_output_string(data_list):
    output_string=""

    if data_list is None:
    return output_string

    for data in data_list:
    try:
    if "products" in data:
    products_list = data["products"]
    for product_name in products_list:
    product = get_product_by_name(product_name)
    if product:
    output_string += json.dumps(product, indent=4) + '\n'
    else:
    print(f"Error: Product '{product_name}' not found'")
    elif "category" in data:
    category_name = data["category"]
    category_products = get_products_by_category(category_name)
    for product in category_products:
    output_string += json.dumps(product, indent=4) + '\n'
    else:
    print("Error: Invalid object format")
    except Exception as e:
    print(f"Error: {e}")

    return output_string

    让我们称它为

    product_information_for_user_message_1 = generate_output_string(category_and_product_list)

    让我们看看它有什么?将什么内容发送给“助手角色”?

    product_information_for_user_message_1 = generate_output_string(category_and_product_list)
    print(product_information_for_user_message_1)
    {
    "name": "QuickHeat Countertop Microwave",
    "category": "Microwaves",
    "brand": "QuickHeat",
    "model_number": "QH-CM100",
    "warranty": "1 year",
    "rating": 4.5,
    "features": [
    "Quick heat technology",
    "10 power levels",
    "Sensor cooking",
    "Compact design"
    ],
    "description": "Heat your meals quickly and efficiently with this versatile countertop microwave.",
    "price": 129.99
    }
    {
    "name": "TechWave Over-the-Range Microwave",
    "category": "Microwaves",
    "brand": "TechWave",
    "model_number": "TW-OTR180",
    "warranty": "1 year",
    "rating": 4.3,
    "features": [
    "Over-the-range installation",
    "800W cooking power",
    "Auto defrost",
    "LED display"
    ],
    "description": "Save counter space with this convenient over-the-range microwave.",
    "price": 199.99
    }
    {
    "name": "EcoCook Convection Microwave",
    "category": "Microwaves",
    "brand": "EcoCook",
    "model_number": "EC-CM150",
    "warranty": "1 year",
    "rating": 4.6,
    "features": [
    "Convection cooking",
    "Multi-stage cooking",
    "Eco-friendly mode",
    "Stainless steel interior"
    ],
    "description": "Cook with precision using the convection feature of this advanced microwave.",
    "price": 179.99
    }
    {
    "name": "RapidDefrost Built-in Microwave",
    "category": "Microwaves",
    "brand": "RapidDefrost",
    "model_number": "RD-BIM120",
    "warranty": "1 year",
    "rating": 4.4,
    "features": [
    "Built-in installation",
    "Rapid defrost technology",
    "Touch controls",
    "Easy to clean"
    ],
    "description": "Defrost your food quickly and efficiently with this built-in microwave.",
    "price": 149.99
    }
    {
    "name": "CoolMaster French Door Fridge",
    "category": "Refrigerators",
    "brand": "CoolMaster",
    "model_number": "CM-FDF300",
    "warranty": "2 years",
    "rating": 4.8,
    "features": [
    "French door design",
    "Dual cooling system",
    "Adjustable shelves",
    "Ice and water dispenser"
    ],
    "description": "Keep your food fresh and organized with this spacious French door fridge.",
    "price": 1499.99
    }
    {
    "name": "FrostGuard Side-by-Side Refrigerator",
    "category": "Refrigerators",
    "brand": "FrostGuard",
    "model_number": "FG-SSR250",
    "warranty": "2 years",
    "rating": 4.5,
    "features": [
    "Side-by-side design",
    "FrostGuard technology",
    "Adjustable temperature zones",
    "Water and ice dispenser"
    ],
    "description": "A stylish and efficient side-by-side refrigerator for your kitchen.",
    "price": 1299.99
    }
    {
    "name": "ChillMate Mini Fridge",
    "category": "Refrigerators",
    "brand": "ChillMate",
    "model_number": "CM-MF50",
    "warranty": "1 year",
    "rating": 4.2,
    "features": [
    "Compact size",
    "Adjustable thermostat",
    "Removable shelves",
    "Quiet operation"
    ],
    "description": "Ideal for small spaces, this mini fridge keeps your beverages cool and refreshing.",
    "price": 99.99
    }
    {
    "name": "EcoFreeze Bottom Freezer",
    "category": "Refrigerators",
    "brand": "EcoFreeze",
    "model_number": "EF-BF200",
    "warranty": "2 years",
    "rating": 4.6,
    "features": [
    "Bottom freezer design",
    "Energy-efficient",
    "Adjustable humidity drawers",
    "LED lighting"
    ],
    "description": "An eco-friendly bottom freezer refrigerator with ample storage space.",
    "price": 1099.99
    }
    {
    "name": "CoolBreeze Window AC Unit",
    "category": "Air Conditioners",
    "brand": "CoolBreeze",
    "model_number": "CB-WAC120",
    "warranty": "3 years",
    "rating": 4.9,
    "features": [
    "12000 BTU cooling capacity",
    "Energy-saving mode",
    "Remote control",
    "Sleep mode"
    ],
    "description": "Keep your room cool and comfortable with this powerful window AC unit.",
    "price": 449.99
    }
    {
    "name": "EcoCool Split Air Conditioner",
    "category": "Air Conditioners",
    "brand": "EcoCool",
    "model_number": "EC-SAC240",
    "warranty": "2 years",
    "rating": 4.8,
    "features": [
    "Split system design",
    "24000 BTU cooling capacity",
    "Smart thermostat",
    "Quiet operation"
    ],
    "description": "Enjoy efficient and quiet cooling with this split air conditioner.",
    "price": 899.99
    }
    {
    "name": "ClimateControl Portable AC",
    "category": "Air Conditioners",
    "brand": "ClimateControl",
    "model_number": "CC-PAC100",
    "warranty": "1 year",
    "rating": 4.6,
    "features": [
    "Portable and easy to move",
    "10000 BTU cooling capacity",
    "Digital display",
    "Timer function"
    ],
    "description": "Stay cool anywhere with this portable and convenient air conditioner.",
    "price": 349.99
    }
    {
    "name": "SmartTherm Wall-Mounted AC",
    "category": "Air Conditioners",
    "brand": "SmartTherm",
    "model_number": "ST-WAC180",
    "warranty": "2 years",
    "rating": 4.7,
    "features": [
    "Wall-mounted installation",
    "18000 BTU cooling capacity",
    "Smart temperature control",
    "Wi-Fi connectivity"
    ],
    "description": "Control your room's temperature with precision using this wall-mounted AC unit.",
    "price": 599.99
    }

    最终执行

    让我们回想一下用户消息1:

    user_message_1 = f"""
    tell me about the \
    QuickHeat Countertop Microwave and \
    CoolMaster French Door Fridge \
    also tell me about your air conditioners
    """

    最后通知

    chat_system_message = f"""
    You are a customer service assistant for a \
    large home appliances store. \
    Respond in a friendly and helpful tone, \
    with very concise answers. \
    Make sure to ask the user relevant follow up questions.
    """

    chat_user_message = user_message_1

    chat_messages = [ {'role':'system', 'content': chat_system_message},
    {'role':'user', 'content': chat_user_message},
    {'role':'assistant', 'content': f"""Relevant product information:\n\
    {product_information_for_user_message_1}"""}, ]

    final_response = get_completion(chat_messages)
    print(final_response)
    • chat_system_message 是系统消息
    • 它不需要预先列出分类以及关于每个产品的详细信息。
    • chat_user_message是user_message_1
    • chat_messages是具有所需角色和内容的消息列表,用于模拟对话。
    • 基于用户消息(这里是 user_message_1),将检索相关的类别和产品。而检索结果将依次提交给助手,以决定对话的流程和方向。
    • 我们的目标是,在必要时获得一个相关的、有意义的、后续的陈述或问题,以便继续对话。

    对此的回应?

    Sure! Here's some information about the QuickHeat Countertop Microwave:

    - Brand: QuickHeat
    - Model: QH-CM100
    - Warranty: 1 year
    - Rating: 4.5
    - Features: Quick heat technology, 10 power levels, sensor cooking, compact design
    - Description: Heat your meals quickly and efficiently with this versatile countertop microwave.
    - Price: $129.99

    And here's some information about the CoolMaster French Door Fridge:

    - Brand: CoolMaster
    - Model: CM-FDF300
    - Warranty: 2 years
    - Rating: 4.8
    - Features: French door design, dual cooling system, adjustable shelves, ice and water dispenser
    - Description: Keep your food fresh and organized with this spacious French door fridge.
    - Price: $1499.99

    For air conditioners, could you please let me know if you are looking for a specific type or any specific features you are interested in?

    参考书目:

    • 通过Deep Learning Dot AI向Isa Fulford解释。

    2024-01-10 04:57:51 AI中文站翻译自原文