第六章 处理输入-链式

链式提示是将复杂任务分解为多个简单Prompt的策略。在本章中,我们将学习如何通过使用链式 Prompt 将复杂任务拆分为一系列简单的子任务。你可能会想,如果我们可以通过思维链推理一次性完成,那为什么要将任务拆分为多个 Prompt 呢?

主要是因为链式提示它具有以下优点:

  1. 分解复杂度,每个 Prompt 仅处理一个具体子任务,避免过于宽泛的要求,提高成功率。这类似于分阶段烹饪,而不是试图一次完成全部。

  2. 降低计算成本。过长的 Prompt 使用更多 tokens ,增加成本。拆分 Prompt 可以避免不必要的计算。

  3. 更容易测试和调试。可以逐步分析每个环节的性能。

  4. 融入外部工具。不同 Prompt 可以调用 API 、数据库等外部资源。

  5. 更灵活的工作流程。根据不同情况可以进行不同操作。

综上,链式提示通过将复杂任务进行科学拆分,实现了更高效、可靠的提示设计。它使语言模型集中处理单一子任务,减少认知负荷,同时保留了多步骤任务的能力。随着经验增长,开发者可以逐渐掌握运用链式提示的精髓。

一、 提取产品和类别

我们所拆解的第一个子任务是,要求 LLM 从用户查询中提取产品和类别。

  1. from tool import get_completion_from_messages
  2. delimiter = "####"
  3. system_message = f"""
  4. 您将获得客户服务查询。
  5. 客户服务查询将使用{delimiter}字符作为分隔符。
  6. 请仅输出一个可解析的Python列表,列表每一个元素是一个JSON对象,每个对象具有以下格式:
  7. 'category': <包括以下几个类别:Computers and Laptops、Smartphones and Accessories、Televisions and Home Theater Systems、Gaming Consoles and Accessories、Audio Equipment、Cameras and Camcorders>,
  8. 以及
  9. 'products': <必须是下面的允许产品列表中找到的产品列表>
  10. 类别和产品必须在客户服务查询中找到。
  11. 如果提到了某个产品,它必须与允许产品列表中的正确类别关联。
  12. 如果未找到任何产品或类别,则输出一个空列表。
  13. 除了列表外,不要输出其他任何信息!
  14. 允许的产品:
  15. Computers and Laptops category:
  16. TechPro Ultrabook
  17. BlueWave Gaming Laptop
  18. PowerLite Convertible
  19. TechPro Desktop
  20. BlueWave Chromebook
  21. Smartphones and Accessories category:
  22. SmartX ProPhone
  23. MobiTech PowerCase
  24. SmartX MiniPhone
  25. MobiTech Wireless Charger
  26. SmartX EarBuds
  27. Televisions and Home Theater Systems category:
  28. CineView 4K TV
  29. SoundMax Home Theater
  30. CineView 8K TV
  31. SoundMax Soundbar
  32. CineView OLED TV
  33. Gaming Consoles and Accessories category:
  34. GameSphere X
  35. ProGamer Controller
  36. GameSphere Y
  37. ProGamer Racing Wheel
  38. GameSphere VR Headset
  39. Audio Equipment category:
  40. AudioPhonic Noise-Canceling Headphones
  41. WaveSound Bluetooth Speaker
  42. AudioPhonic True Wireless Earbuds
  43. WaveSound Soundbar
  44. AudioPhonic Turntable
  45. Cameras and Camcorders category:
  46. FotoSnap DSLR Camera
  47. ActionCam 4K
  48. FotoSnap Mirrorless Camera
  49. ZoomMaster Camcorder
  50. FotoSnap Instant Camera
  51. 只输出对象列表,不包含其他内容。
  52. """
  53. user_message_1 = f"""
  54. 请告诉我关于 smartx pro phone 和 the fotosnap camera 的信息。
  55. 另外,请告诉我关于你们的tvs的情况。 """
  56. messages = [{'role':'system', 'content': system_message},
  57. {'role':'user', 'content': f"{delimiter}{user_message_1}{delimiter}"}]
  58. category_and_product_response_1 = get_completion_from_messages(messages)
  59. print(category_and_product_response_1)
  1. [{'category': 'Smartphones and Accessories', 'products': ['SmartX ProPhone']}, {'category': 'Cameras and Camcorders', 'products': ['FotoSnap DSLR Camera', 'FotoSnap Mirrorless Camera', 'FotoSnap Instant Camera']}, {'category': 'Televisions and Home Theater Systems', 'products': ['CineView 4K TV', 'CineView 8K TV', 'CineView OLED TV', 'SoundMax Home Theater', 'SoundMax Soundbar']}]

可以看到,输出是一个对象列表,每个对象都有一个类别和一些产品。如 “SmartX ProPhone” 和 “Fotosnap DSLR Camera” 、”CineView 4K TV”。

我们再来看一个例子。

  1. user_message_2 = f"""我的路由器不工作了"""
  2. messages = [{'role':'system','content': system_message},
  3. {'role':'user','content': f"{delimiter}{user_message_2}{delimiter}"}]
  4. response = get_completion_from_messages(messages)
  5. print(response)
  1. []

二、检索详细信息

我们提供大量的产品信息作为示例,要求模型提取产品和对应的详细信息。限于篇幅,我们产品信息存储在 products.json 中。

首先,让我们通过 Python 代码读取产品信息。

  1. import json
  2. # 读取产品信息
  3. with open("products_zh.json", "r") as file:
  4. products = json.load(file)

接下来,定义 get_product_by_name 函数,是我们能够根据产品名称获取产品:

  1. def get_product_by_name(name):
  2. """
  3. 根据产品名称获取产品
  4. 参数:
  5. name: 产品名称
  6. """
  7. return products.get(name, None)
  8. def get_products_by_category(category):
  9. """
  10. 根据类别获取产品
  11. 参数:
  12. category: 产品类别
  13. """
  14. return [product for product in products.values() if product["类别"] == category]

调用 get_product_by_name 函数,输入产品名称 “TechPro Ultrabook”:

  1. get_product_by_name("TechPro Ultrabook")
  1. {'名称': 'TechPro 超极本',
  2. '类别': '电脑和笔记本',
  3. '品牌': 'TechPro',
  4. '型号': 'TP-UB100',
  5. '保修期': '1 year',
  6. '评分': 4.5,
  7. '特色': ['13.3-inch display', '8GB RAM', '256GB SSD', 'Intel Core i5 处理器'],
  8. '描述': '一款时尚轻便的超极本,适合日常使用。',
  9. '价格': 799.99}

接下来,我们再看一个例子,调用 get_product_by_name 函数,输入产品名称 “电脑和笔记本”:

  1. get_products_by_category("电脑和笔记本")
  1. [{'名称': 'TechPro 超极本',
  2. '类别': '电脑和笔记本',
  3. '品牌': 'TechPro',
  4. '型号': 'TP-UB100',
  5. '保修期': '1 year',
  6. '评分': 4.5,
  7. '特色': ['13.3-inch display', '8GB RAM', '256GB SSD', 'Intel Core i5 处理器'],
  8. '描述': '一款时尚轻便的超极本,适合日常使用。',
  9. '价格': 799.99},
  10. {'名称': 'BlueWave 游戏本',
  11. '类别': '电脑和笔记本',
  12. '品牌': 'BlueWave',
  13. '型号': 'BW-GL200',
  14. '保修期': '2 years',
  15. '评分': 4.7,
  16. '特色': ['15.6-inch display',
  17. '16GB RAM',
  18. '512GB SSD',
  19. 'NVIDIA GeForce RTX 3060'],
  20. '描述': '一款高性能的游戏笔记本电脑,提供沉浸式体验。',
  21. '价格': 1199.99},
  22. {'名称': 'PowerLite Convertible',
  23. '类别': '电脑和笔记本',
  24. '品牌': 'PowerLite',
  25. '型号': 'PL-CV300',
  26. '保修期': '1 year',
  27. '评分': 4.3,
  28. '特色': ['14-inch touchscreen', '8GB RAM', '256GB SSD', '360-degree hinge'],
  29. '描述': '一款多功能的可转换笔记本电脑,具有灵敏的触摸屏。',
  30. '价格': 699.99},
  31. {'名称': 'TechPro Desktop',
  32. '类别': '电脑和笔记本',
  33. '品牌': 'TechPro',
  34. '型号': 'TP-DT500',
  35. '保修期': '1 year',
  36. '评分': 4.4,
  37. '特色': ['Intel Core i7 processor',
  38. '16GB RAM',
  39. '1TB HDD',
  40. 'NVIDIA GeForce GTX 1660'],
  41. '描述': '一款功能强大的台式电脑,适用于工作和娱乐。',
  42. '价格': 999.99},
  43. {'名称': 'BlueWave Chromebook',
  44. '类别': '电脑和笔记本',
  45. '品牌': 'BlueWave',
  46. '型号': 'BW-CB100',
  47. '保修期': '1 year',
  48. '评分': 4.1,
  49. '特色': ['11.6-inch display', '4GB RAM', '32GB eMMC', 'Chrome OS'],
  50. '描述': '一款紧凑而价格实惠的Chromebook,适用于日常任务。',
  51. '价格': 249.99}]

三、生成查询答案

3.1 解析输入字符串

定义一个 read_string_to_list 函数,将输入的字符串转换为 Python 列表

  1. def read_string_to_list(input_string):
  2. """
  3. 将输入的字符串转换为 Python 列表。
  4. 参数:
  5. input_string: 输入的字符串,应为有效的 JSON 格式。
  6. 返回:
  7. list 或 None: 如果输入字符串有效,则返回对应的 Python 列表,否则返回 None。
  8. """
  9. if input_string is None:
  10. return None
  11. try:
  12. # 将输入字符串中的单引号替换为双引号,以满足 JSON 格式的要求
  13. input_string = input_string.replace("'", "\"")
  14. data = json.loads(input_string)
  15. return data
  16. except json.JSONDecodeError:
  17. print("Error: Invalid JSON string")
  18. return None
  19. category_and_product_list = read_string_to_list(category_and_product_response_1)
  20. print(category_and_product_list)
  1. [{'category': 'Smartphones and Accessories', 'products': ['SmartX ProPhone']}, {'category': 'Cameras and Camcorders', 'products': ['FotoSnap DSLR Camera', 'FotoSnap Mirrorless Camera', 'FotoSnap Instant Camera']}, {'category': 'Televisions and Home Theater Systems', 'products': ['CineView 4K TV', 'CineView 8K TV', 'CineView OLED TV', 'SoundMax Home Theater', 'SoundMax Soundbar']}]

3.2 进行检索

定义函数 generate_output_string 函数,根据输入的数据列表生成包含产品或类别信息的字符串:

  1. def generate_output_string(data_list):
  2. """
  3. 根据输入的数据列表生成包含产品或类别信息的字符串。
  4. 参数:
  5. data_list: 包含字典的列表,每个字典都应包含 "products" 或 "category" 的键。
  6. 返回:
  7. output_string: 包含产品或类别信息的字符串。
  8. """
  9. output_string = ""
  10. if data_list is None:
  11. return output_string
  12. for data in data_list:
  13. try:
  14. if "products" in data and data["products"]:
  15. products_list = data["products"]
  16. for product_name in products_list:
  17. product = get_product_by_name(product_name)
  18. if product:
  19. output_string += json.dumps(product, indent=4, ensure_ascii=False) + "\n"
  20. else:
  21. print(f"Error: Product '{product_name}' not found")
  22. elif "category" in data:
  23. category_name = data["category"]
  24. category_products = get_products_by_category(category_name)
  25. for product in category_products:
  26. output_string += json.dumps(product, indent=4, ensure_ascii=False) + "\n"
  27. else:
  28. print("Error: Invalid object format")
  29. except Exception as e:
  30. print(f"Error: {e}")
  31. return output_string
  32. product_information_for_user_message_1 = generate_output_string(category_and_product_list)
  33. print(product_information_for_user_message_1)
  1. {
  2. "名称": "SmartX ProPhone",
  3. "类别": "智能手机和配件",
  4. "品牌": "SmartX",
  5. "型号": "SX-PP10",
  6. "保修期": "1 year",
  7. "评分": 4.6,
  8. "特色": [
  9. "6.1-inch display",
  10. "128GB storage",
  11. "12MP dual camera",
  12. "5G"
  13. ],
  14. "描述": "一款拥有先进摄像功能的强大智能手机。",
  15. "价格": 899.99
  16. }
  17. {
  18. "名称": "FotoSnap DSLR Camera",
  19. "类别": "相机和摄像机",
  20. "品牌": "FotoSnap",
  21. "型号": "FS-DSLR200",
  22. "保修期": "1 year",
  23. "评分": 4.7,
  24. "特色": [
  25. "24.2MP sensor",
  26. "1080p video",
  27. "3-inch LCD",
  28. "Interchangeable lenses"
  29. ],
  30. "描述": "使用这款多功能的单反相机,捕捉惊艳的照片和视频。",
  31. "价格": 599.99
  32. }
  33. {
  34. "名称": "FotoSnap Mirrorless Camera",
  35. "类别": "相机和摄像机",
  36. "品牌": "FotoSnap",
  37. "型号": "FS-ML100",
  38. "保修期": "1 year",
  39. "评分": 4.6,
  40. "特色": [
  41. "20.1MP sensor",
  42. "4K video",
  43. "3-inch touchscreen",
  44. "Interchangeable lenses"
  45. ],
  46. "描述": "一款具有先进功能的小巧轻便的无反相机。",
  47. "价格": 799.99
  48. }
  49. {
  50. "名称": "FotoSnap Instant Camera",
  51. "类别": "相机和摄像机",
  52. "品牌": "FotoSnap",
  53. "型号": "FS-IC10",
  54. "保修期": "1 year",
  55. "评分": 4.1,
  56. "特色": [
  57. "Instant prints",
  58. "Built-in flash",
  59. "Selfie mirror",
  60. "Battery-powered"
  61. ],
  62. "描述": "使用这款有趣且便携的即时相机,创造瞬间回忆。",
  63. "价格": 69.99
  64. }
  65. {
  66. "名称": "CineView 4K TV",
  67. "类别": "电视和家庭影院系统",
  68. "品牌": "CineView",
  69. "型号": "CV-4K55",
  70. "保修期": "2 years",
  71. "评分": 4.8,
  72. "特色": [
  73. "55-inch display",
  74. "4K resolution",
  75. "HDR",
  76. "Smart TV"
  77. ],
  78. "描述": "一款色彩鲜艳、智能功能丰富的惊艳4K电视。",
  79. "价格": 599.99
  80. }
  81. {
  82. "名称": "CineView 8K TV",
  83. "类别": "电视和家庭影院系统",
  84. "品牌": "CineView",
  85. "型号": "CV-8K65",
  86. "保修期": "2 years",
  87. "评分": 4.9,
  88. "特色": [
  89. "65-inch display",
  90. "8K resolution",
  91. "HDR",
  92. "Smart TV"
  93. ],
  94. "描述": "通过这款惊艳的8K电视,体验未来。",
  95. "价格": 2999.99
  96. }
  97. {
  98. "名称": "CineView OLED TV",
  99. "类别": "电视和家庭影院系统",
  100. "品牌": "CineView",
  101. "型号": "CV-OLED55",
  102. "保修期": "2 years",
  103. "评分": 4.7,
  104. "特色": [
  105. "55-inch display",
  106. "4K resolution",
  107. "HDR",
  108. "Smart TV"
  109. ],
  110. "描述": "通过这款OLED电视,体验真正的五彩斑斓。",
  111. "价格": 1499.99
  112. }
  113. {
  114. "名称": "SoundMax Home Theater",
  115. "类别": "电视和家庭影院系统",
  116. "品牌": "SoundMax",
  117. "型号": "SM-HT100",
  118. "保修期": "1 year",
  119. "评分": 4.4,
  120. "特色": [
  121. "5.1 channel",
  122. "1000W output",
  123. "Wireless subwoofer",
  124. "Bluetooth"
  125. ],
  126. "描述": "一款强大的家庭影院系统,提供沉浸式音频体验。",
  127. "价格": 399.99
  128. }
  129. {
  130. "名称": "SoundMax Soundbar",
  131. "类别": "电视和家庭影院系统",
  132. "品牌": "SoundMax",
  133. "型号": "SM-SB50",
  134. "保修期": "1 year",
  135. "评分": 4.3,
  136. "特色": [
  137. "2.1 channel",
  138. "300W output",
  139. "Wireless subwoofer",
  140. "Bluetooth"
  141. ],
  142. "描述": "使用这款时尚而功能强大的声音,升级您电视的音频体验。",
  143. "价格": 199.99
  144. }

3.3 生成用户查询的答案

  1. system_message = f"""
  2. 您是一家大型电子商店的客服助理。
  3. 请以友好和乐于助人的口吻回答问题,并尽量简洁明了。
  4. 请确保向用户提出相关的后续问题。
  5. """
  6. user_message_1 = f"""
  7. 请告诉我关于 smartx pro phone 和 the fotosnap camera 的信息。
  8. 另外,请告诉我关于你们的tvs的情况。
  9. """
  10. messages = [{'role':'system','content': system_message},
  11. {'role':'user','content': user_message_1},
  12. {'role':'assistant',
  13. 'content': f"""相关产品信息:\n\
  14. {product_information_for_user_message_1}"""}]
  15. final_response = get_completion_from_messages(messages)
  16. print(final_response)
  1. 关于SmartX ProPhoneFotoSnap相机的信息如下:
  2. SmartX ProPhone是一款由SmartX品牌推出的智能手机。它拥有6.1英寸的显示屏,128GB的存储空间,12MP的双摄像头和5G网络支持。这款手机的特点是先进的摄像功能。它的价格是899.99美元。
  3. FotoSnap相机有多个型号可供选择。其中包括DSLR相机、无反相机和即时相机。DSLR相机具有24.2MP的传感器、1080p视频拍摄、3英寸的LCD屏幕和可更换镜头。无反相机具有20.1MP的传感器、4K视频拍摄、3英寸的触摸屏和可更换镜头。即时相机具有即时打印功能、内置闪光灯、自拍镜和电池供电。这些相机的价格分别为599.99美元、799.99美元和69.99美元。
  4. 关于我们的电视产品,我们有CineViewSoundMax品牌的电视和家庭影院系统可供选择。CineView电视有不同的型号,包括4K分辨率和8K分辨率的电视,以及OLED电视。这些电视都具有HDR和智能电视功能。价格从599.99美元到2999.99美元不等。SoundMax品牌提供家庭影院系统和声音棒。家庭影院系统具有5.1声道、1000W输出、无线低音炮和蓝牙功能,价格为399.99美元。声音棒具有2.1声道、300W输出、无线低音炮和蓝牙功能,价格为199.99美元。
  5. 请问您对以上产品中的哪个感

在这个例子中,我们只添加了一个特定函数或函数的调用,以通过产品名称获取产品描述或通过类别名称获取类别产品。但是,模型实际上擅长决定何时使用各种不同的工具,并可以正确地使用它们。这就是 ChatGPT 插件背后的思想。我们告诉模型它可以访问哪些工具以及它们的作用,它会在需要从特定来源获取信息或想要采取其他适当的操作时选择使用它们。在这个例子中,我们只能通过精确的产品和类别名称匹配查找信息,但还有更高级的信息检索技术。检索信息的最有效方法之一是使用自然语言处理技术,例如命名实体识别和关系提取。

另一方法是使用文本嵌入(Embedding)来获取信息。嵌入可以用于实现对大型语料库的高效知识检索,以查找与给定查询相关的信息。使用文本嵌入的一个关键优势是它们可以实现模糊或语义搜索,这使您能够在不使用精确关键字的情况下找到相关信息。因此,在此例子中,我们不一定需要产品的确切名称,而可以使用更一般的查询如 “手机” 进行搜索。

四、总结

在设计提示链时,我们并不需要也不建议将所有可能相关信息一次性全加载到模型中,而是采取动态、按需提供信息的策略,原因如下:

  1. 过多无关信息会使模型处理上下文时更加困惑。尤其是低级模型,处理大量数据会表现衰减。

  2. 模型本身对上下文长度有限制,无法一次加载过多信息。

  3. 包含过多信息容易导致模型过拟合,处理新查询时效果较差。

  4. 动态加载信息可以降低计算成本。

  5. 允许模型主动决定何时需要更多信息,可以增强其推理能力。

  6. 我们可以使用更智能的检索机制,而不仅是精确匹配,例如文本 Embedding 实现语义搜索。

因此,合理设计提示链的信息提供策略,既考虑模型的能力限制,也兼顾提升其主动学习能力,是提示工程中需要着重考虑的点。希望这些经验可以帮助大家设计出运行高效且智能的提示链系统。

在下一章中我们将讨论如何评估语言模型的输出。

五、英文版

1.1 提取产品和类别

  1. delimiter = "####"
  2. system_message = f"""
  3. You will be provided with customer service queries. \
  4. The customer service query will be delimited with \
  5. {delimiter} characters.
  6. Output a Python list of objects, where each object has \
  7. the following format:
  8. 'category': <one of Computers and Laptops, \
  9. Smartphones and Accessories, \
  10. Televisions and Home Theater Systems, \
  11. Gaming Consoles and Accessories,
  12. Audio Equipment, Cameras and Camcorders>,
  13. and
  14. 'products': <products must be found in the customer service query. And products that must \
  15. be found in the allowed products below. If no products are found, output an empty list.
  16. >
  17. Where the categories and products must be found in \
  18. the customer service query.
  19. If a product is mentioned, it must be associated with \
  20. the correct category in the allowed products list below.
  21. If no products or categories are found, output an \
  22. empty list.
  23. Allowed products:
  24. Products under Computers and Laptops category:
  25. TechPro Ultrabook
  26. BlueWave Gaming Laptop
  27. PowerLite Convertible
  28. TechPro Desktop
  29. BlueWave Chromebook
  30. Products under Smartphones and Accessories category:
  31. SmartX ProPhone
  32. MobiTech PowerCase
  33. SmartX MiniPhone
  34. MobiTech Wireless Charger
  35. SmartX EarBuds
  36. Products under Televisions and Home Theater Systems category:
  37. CineView 4K TV
  38. SoundMax Home Theater
  39. CineView 8K TV
  40. SoundMax Soundbar
  41. CineView OLED TV
  42. Products under Gaming Consoles and Accessories category:
  43. GameSphere X
  44. ProGamer Controller
  45. GameSphere Y
  46. ProGamer Racing Wheel
  47. GameSphere VR Headset
  48. Products under Audio Equipment category:
  49. AudioPhonic Noise-Canceling Headphones
  50. WaveSound Bluetooth Speaker
  51. AudioPhonic True Wireless Earbuds
  52. WaveSound Soundbar
  53. AudioPhonic Turntable
  54. Products under Cameras and Camcorders category:
  55. FotoSnap DSLR Camera
  56. ActionCam 4K
  57. FotoSnap Mirrorless Camera
  58. ZoomMaster Camcorder
  59. FotoSnap Instant Camera
  60. Only output the list of objects, with nothing else.
  61. """
  62. user_message_1 = f"""
  63. tell me about the smartx pro phone and \
  64. the fotosnap camera, the dslr one. \
  65. Also tell me about your tvs """
  66. messages = [
  67. {'role':'system',
  68. 'content': system_message},
  69. {'role':'user',
  70. 'content': f"{delimiter}{user_message_1}{delimiter}"},
  71. ]
  72. category_and_product_response_1 = get_completion_from_messages(messages)
  73. category_and_product_response_1
  1. "[{'category': 'Smartphones and Accessories', 'products': ['SmartX ProPhone']}, {'category': 'Cameras and Camcorders', 'products': ['FotoSnap DSLR Camera']}, {'category': 'Televisions and Home Theater Systems', 'products': []}]"
  1. user_message_2 = f"""
  2. my router isn't working"""
  3. messages = [
  4. {'role':'system',
  5. 'content': system_message},
  6. {'role':'user',
  7. 'content': f"{delimiter}{user_message_2}{delimiter}"},
  8. ]
  9. response = get_completion_from_messages(messages)
  10. print(response)
  1. []

2.1 检索详细信息

  1. with open("products.json", "r") as file:
  2. products = josn.load(file)
  1. def get_product_by_name(name):
  2. return products.get(name, None)
  3. def get_products_by_category(category):
  4. return [product for product in products.values() if product["category"] == category]
  1. get_product_by_name("TechPro Ultrabook")
  1. {'name': 'TechPro Ultrabook',
  2. 'category': 'Computers and Laptops',
  3. 'brand': 'TechPro',
  4. 'model_number': 'TP-UB100',
  5. 'warranty': '1 year',
  6. 'rating': 4.5,
  7. 'features': ['13.3-inch display',
  8. '8GB RAM',
  9. '256GB SSD',
  10. 'Intel Core i5 processor'],
  11. 'description': 'A sleek and lightweight ultrabook for everyday use.',
  12. 'price': 799.99}
  1. get_products_by_category("Computers and Laptops")
  1. [{'name': 'TechPro Ultrabook',
  2. 'category': 'Computers and Laptops',
  3. 'brand': 'TechPro',
  4. 'model_number': 'TP-UB100',
  5. 'warranty': '1 year',
  6. 'rating': 4.5,
  7. 'features': ['13.3-inch display',
  8. '8GB RAM',
  9. '256GB SSD',
  10. 'Intel Core i5 processor'],
  11. 'description': 'A sleek and lightweight ultrabook for everyday use.',
  12. 'price': 799.99},
  13. {'name': 'BlueWave Gaming Laptop',
  14. 'category': 'Computers and Laptops',
  15. 'brand': 'BlueWave',
  16. 'model_number': 'BW-GL200',
  17. 'warranty': '2 years',
  18. 'rating': 4.7,
  19. 'features': ['15.6-inch display',
  20. '16GB RAM',
  21. '512GB SSD',
  22. 'NVIDIA GeForce RTX 3060'],
  23. 'description': 'A high-performance gaming laptop for an immersive experience.',
  24. 'price': 1199.99},
  25. {'name': 'PowerLite Convertible',
  26. 'category': 'Computers and Laptops',
  27. 'brand': 'PowerLite',
  28. 'model_number': 'PL-CV300',
  29. 'warranty': '1 year',
  30. 'rating': 4.3,
  31. 'features': ['14-inch touchscreen',
  32. '8GB RAM',
  33. '256GB SSD',
  34. '360-degree hinge'],
  35. 'description': 'A versatile convertible laptop with a responsive touchscreen.',
  36. 'price': 699.99},
  37. {'name': 'TechPro Desktop',
  38. 'category': 'Computers and Laptops',
  39. 'brand': 'TechPro',
  40. 'model_number': 'TP-DT500',
  41. 'warranty': '1 year',
  42. 'rating': 4.4,
  43. 'features': ['Intel Core i7 processor',
  44. '16GB RAM',
  45. '1TB HDD',
  46. 'NVIDIA GeForce GTX 1660'],
  47. 'description': 'A powerful desktop computer for work and play.',
  48. 'price': 999.99},
  49. {'name': 'BlueWave Chromebook',
  50. 'category': 'Computers and Laptops',
  51. 'brand': 'BlueWave',
  52. 'model_number': 'BW-CB100',
  53. 'warranty': '1 year',
  54. 'rating': 4.1,
  55. 'features': ['11.6-inch display', '4GB RAM', '32GB eMMC', 'Chrome OS'],
  56. 'description': 'A compact and affordable Chromebook for everyday tasks.',
  57. 'price': 249.99}]

3.1 解析输入字符串

  1. def read_string_to_list(input_string):
  2. """
  3. 将输入的字符串转换为 Python 列表。
  4. 参数:
  5. input_string: 输入的字符串,应为有效的 JSON 格式。
  6. 返回:
  7. list 或 None: 如果输入字符串有效,则返回对应的 Python 列表,否则返回 None。
  8. """
  9. if input_string is None:
  10. return None
  11. try:
  12. # 将输入字符串中的单引号替换为双引号,以满足 JSON 格式的要求
  13. input_string = input_string.replace("'", "\"")
  14. data = json.loads(input_string)
  15. return data
  16. except json.JSONDecodeError:
  17. print("Error: Invalid JSON string")
  18. return None
  1. category_and_product_list = read_string_to_list(category_and_product_response_1)
  2. category_and_product_list
  1. [{'category': 'Smartphones and Accessories', 'products': ['SmartX ProPhone']}, {'category': 'Cameras and Camcorders', 'products': ['FotoSnap DSLR Camera']}, {'category': 'Televisions and Home Theater Systems', 'products': []}]

3.2 进行检索

  1. def generate_output_string(data_list):
  2. """
  3. 根据输入的数据列表生成包含产品或类别信息的字符串。
  4. 参数:
  5. data_list: 包含字典的列表,每个字典都应包含 "products" 或 "category" 的键。
  6. 返回:
  7. output_string: 包含产品或类别信息的字符串。
  8. """
  9. output_string = ""
  10. if data_list is None:
  11. return output_string
  12. for data in data_list:
  13. try:
  14. if "products" in data and data["products"]:
  15. products_list = data["products"]
  16. for product_name in products_list:
  17. product = get_product_by_name(product_name)
  18. if product:
  19. output_string += json.dumps(product, indent=4, ensure_ascii=False) + "\n"
  20. else:
  21. print(f"Error: Product '{product_name}' not found")
  22. elif "category" in data:
  23. category_name = data["category"]
  24. category_products = get_products_by_category(category_name)
  25. for product in category_products:
  26. output_string += json.dumps(product, indent=4, ensure_ascii=False) + "\n"
  27. else:
  28. print("Error: Invalid object format")
  29. except Exception as e:
  30. print(f"Error: {e}")
  31. return output_string
  1. product_information_for_user_message_1 = generate_output_string(category_and_product_list)
  2. print(product_information_for_user_message_1)
  1. {
  2. "name": "SmartX ProPhone",
  3. "category": "Smartphones and Accessories",
  4. "brand": "SmartX",
  5. "model_number": "SX-PP10",
  6. "warranty": "1 year",
  7. "rating": 4.6,
  8. "features": [
  9. "6.1-inch display",
  10. "128GB storage",
  11. "12MP dual camera",
  12. "5G"
  13. ],
  14. "description": "A powerful smartphone with advanced camera features.",
  15. "price": 899.99
  16. }
  17. {
  18. "name": "FotoSnap DSLR Camera",
  19. "category": "Cameras and Camcorders",
  20. "brand": "FotoSnap",
  21. "model_number": "FS-DSLR200",
  22. "warranty": "1 year",
  23. "rating": 4.7,
  24. "features": [
  25. "24.2MP sensor",
  26. "1080p video",
  27. "3-inch LCD",
  28. "Interchangeable lenses"
  29. ],
  30. "description": "Capture stunning photos and videos with this versatile DSLR camera.",
  31. "price": 599.99
  32. }
  33. {
  34. "name": "CineView 4K TV",
  35. "category": "Televisions and Home Theater Systems",
  36. "brand": "CineView",
  37. "model_number": "CV-4K55",
  38. "warranty": "2 years",
  39. "rating": 4.8,
  40. "features": [
  41. "55-inch display",
  42. "4K resolution",
  43. "HDR",
  44. "Smart TV"
  45. ],
  46. "description": "A stunning 4K TV with vibrant colors and smart features.",
  47. "price": 599.99
  48. }
  49. {
  50. "name": "SoundMax Home Theater",
  51. "category": "Televisions and Home Theater Systems",
  52. "brand": "SoundMax",
  53. "model_number": "SM-HT100",
  54. "warranty": "1 year",
  55. "rating": 4.4,
  56. "features": [
  57. "5.1 channel",
  58. "1000W output",
  59. "Wireless subwoofer",
  60. "Bluetooth"
  61. ],
  62. "description": "A powerful home theater system for an immersive audio experience.",
  63. "price": 399.99
  64. }
  65. {
  66. "name": "CineView 8K TV",
  67. "category": "Televisions and Home Theater Systems",
  68. "brand": "CineView",
  69. "model_number": "CV-8K65",
  70. "warranty": "2 years",
  71. "rating": 4.9,
  72. "features": [
  73. "65-inch display",
  74. "8K resolution",
  75. "HDR",
  76. "Smart TV"
  77. ],
  78. "description": "Experience the future of television with this stunning 8K TV.",
  79. "price": 2999.99
  80. }
  81. {
  82. "name": "SoundMax Soundbar",
  83. "category": "Televisions and Home Theater Systems",
  84. "brand": "SoundMax",
  85. "model_number": "SM-SB50",
  86. "warranty": "1 year",
  87. "rating": 4.3,
  88. "features": [
  89. "2.1 channel",
  90. "300W output",
  91. "Wireless subwoofer",
  92. "Bluetooth"
  93. ],
  94. "description": "Upgrade your TV's audio with this sleek and powerful soundbar.",
  95. "price": 199.99
  96. }
  97. {
  98. "name": "CineView OLED TV",
  99. "category": "Televisions and Home Theater Systems",
  100. "brand": "CineView",
  101. "model_number": "CV-OLED55",
  102. "warranty": "2 years",
  103. "rating": 4.7,
  104. "features": [
  105. "55-inch display",
  106. "4K resolution",
  107. "HDR",
  108. "Smart TV"
  109. ],
  110. "description": "Experience true blacks and vibrant colors with this OLED TV.",
  111. "price": 1499.99
  112. }

3.3 生成用户查询的答案

  1. system_message = f"""
  2. You are a customer service assistant for a \
  3. large electronic store. \
  4. Respond in a friendly and helpful tone, \
  5. with very concise answers. \
  6. Make sure to ask the user relevant follow up questions.
  7. """
  8. user_message_1 = f"""
  9. tell me about the smartx pro phone and \
  10. the fotosnap camera, the dslr one. \
  11. Also tell me about your tvs"""
  12. messages = [{'role':'system','content': system_message},
  13. {'role':'user','content': user_message_1},
  14. {'role':'assistant',
  15. 'content': f"""Relevant product information:\n\
  16. {product_information_for_user_message_1}"""}]
  17. final_response = get_completion_from_messages(messages)
  18. print(final_response)
  1. The SmartX ProPhone is a powerful smartphone with a 6.1-inch display, 128GB storage, a 12MP dual camera, and 5G capability. It is priced at $899.99 and comes with a 1-year warranty.
  2. The FotoSnap DSLR Camera is a versatile camera with a 24.2MP sensor, 1080p video recording, a 3-inch LCD screen, and interchangeable lenses. It is priced at $599.99 and also comes with a 1-year warranty.
  3. As for our TVs, we have a range of options. The CineView 4K TV is a 55-inch TV with 4K resolution, HDR, and smart TV features. It is priced at $599.99 and comes with a 2-year warranty.
  4. We also have the CineView 8K TV, which is a 65-inch TV with 8K resolution, HDR, and smart TV features. It is priced at $2999.99 and also comes with a 2-year warranty.
  5. Lastly, we have the CineView OLED TV, which is a 55-inch TV with 4K resolution, HDR, and smart TV features. It is priced at $1499.99 and comes with a 2-year warranty.
  6. Is there anything specific you would like to know about these products?