目录

1、思维链提示设计

2、链式提示

2.1、构造知识库数据

2.2、构造输入提示词

3、检查结果有害性

4、检查结果相关性


语言模型需要进行详细的逐步推理才能回答特定问题。如果过于匆忙得出结论,很可能在推理链中出现错误。

通过引导语言模型逐步推理的方法,可以减少其匆忙错误,生成更准确可靠的响应。

1、思维链提示设计

通过在 Prompt 中设置系统消息,要求语言模型在给出最终结论之前,先明确各个推理步骤。

import requests
import json

class Llama3Test:

    url = "http://192.168.1.1:19327/v1/chat/completions"

    @staticmethod
    def test2():
        delimiter = "===="

        system_message = f"""请按照以下步骤回答客户的提问。客户的提问将以{delimiter}分隔。
                          步骤 1:{delimiter}首先确定用户是否正在询问有关特定产品或产品的问题。产品类别不计入范围。
                          步骤 2:{delimiter}如果用户询问特定产品,请确认产品是否在以下列表中。所有可用产品:
                          产品:TechPro 超极本
                          类别:计算机和笔记本电脑
                          品牌:TechPro
                          型号:TP-UB100
                          保修期:1 年
                          评分:4.5
                          特点:13.3 英寸显示屏,8GB RAM,256GB SSD,Intel Core i5 处理器
                          描述:一款适用于日常使用的时尚轻便的超极本。
                          价格:$799.99
                          产品:BlueWave 游戏笔记本电脑
                          类别:计算机和笔记本电脑
                          品牌:BlueWave
                          型号:BW-GL200
                          保修期:2 年
                          评分:4.7
                          特点:15.6 英寸显示屏,16GB RAM,512GB SSD,NVIDIA GeForce RTX 3060
                          描述:一款高性能的游戏笔记本电脑,提供沉浸式体验。
                          价格:$1199.99
                          步骤 3:{delimiter} 如果消息中包含上述列表中的产品,请列出用户在消息中做出的任何假设, 
                          例如笔记本电脑 X 比笔记本电脑 Y 大,或者笔记本电脑 Z 有 2 年保修期。
                          步骤 4:{delimiter} 如果用户做出了任何假设,请根据产品信息确定假设是否正确。
                          步骤 5:{delimiter} 如果用户有任何错误的假设,请先礼貌地纠正客户的错误假设(如果适用)。 
                          只提及或引用可用产品列表中的产品,因为这是商店销售的唯一五款产品。以友好的口吻回答客户。
                          使用以下格式回答问题:
                          步骤 1: {delimiter} <步骤 1 的推理>
                          步骤 2: {delimiter} <步骤 2 的推理>
                          步骤 3: {delimiter} <步骤 3 的推理>
                          步骤 4: {delimiter} <步骤 4 的推理>
                          回复客户: {delimiter} <回复客户的内容>
                          请确保每个步骤上面的回答问题中使用{delimiter}对步骤和步骤的推理进行分隔
                        """

        user_message = "BlueWave Chromebook 比 TechPro 超极本贵多少?"

        body = {
            "messages": [
                {"role": "system", "content": system_message},
                {"role": "user", "content": f"""{delimiter}{user_message}{delimiter}"""}
            ]
        }

        headers = {'Content-Type': 'application/json'}
        response = requests.post(Llama3Test.url, headers=headers, json=body)

        chat = response.json()
        choices = chat.get('choices', [])
        if choices:
            result = choices[-1]['message']['content']
            print(result)

            # 隐藏 推到过程,直接返回结果
            final_response = "对不起,我现在有点问题,请尝试问另外一个问题"
            if delimiter in result:
                arr = result.split(delimiter)
                final_response = arr[-1].strip()
            else:
                arr = result.split(":")
                final_response = arr[-1].strip()

            print(final_response)

if __name__ == "__main__":
    Llama3Test.test2()

步骤 1:客户正在询问两个不同品牌的笔记本电脑之间的价格差异。

步骤 2:我们可以从可用的产品列表中找到这两种笔记本电脑:

产品:TechPro 超极本
产品:BlueWave 游戏笔记本电脑

步骤 3:客户没有提出任何关于这些笔记本电脑的假设。

步骤 4:根据产品信息,我们可以比较它们的价格:

TechPro 超极本的价格为 $799.99,
BlueWave 游戏笔记本电脑的价格为 $1199.99。

因此,BlueWave 游戏笔记本电脑比 TechPro 超极本贵了 $399.99。

经测试:思维链方式可以有效的应对提示词注入问题

2、链式提示

链式提示是将复杂任务分解为多个简单Prompt的策略。

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

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

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

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

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

2.1、构造知识库数据

product_information = [
    {
        "价格": 899.99,
        "保修期": "1 year",
        "名称": "SmartX ProPhone",
        "品牌": "SmartX",
        "型号": "SX-PP10",
        "描述": "一款拥有先进摄像功能的强大智能手机。",
        "特色": [
            "6.1-inch display",
            "128GB storage",
            "12MP dual camera",
            "5G"
        ],
        "类别": "智能手机和配件",
        "评分": 4.6
    },
    {
        "价格": 599.99,
        "保修期": "1 year",
        "名称": "FotoSnap DSLR Camera",
        "品牌": "FotoSnap",
        "型号": "FS-DSLR200",
        "描述": "使用这款多功能的单反相机,捕捉惊艳的照片和视频。",
        "特色": [
            "24.2MP sensor",
            "1080p video",
            "3-inch LCD",
            "Interchangeable lenses"
        ],
        "类别": "相机和摄像机",
        "评分": 4.7
    },
    {
        "价格": 799.99,
        "保修期": "1 year",
        "名称": "FotoSnap Mirrorless Camera",
        "品牌": "FotoSnap",
        "型号": "FS-ML100",
        "描述": "一款具有先进功能的小巧轻便的无反相机。",
        "特色": [
            "20.1MP sensor",
            "4K video",
            "3-inch touchscreen",
            "Interchangeable lenses"
        ],
        "类别": "相机和摄像机",
        "评分": 4.6
    },
    {
        "价格": 69.99,
        "保修期": "1 year",
        "名称": "FotoSnap Instant Camera",
        "品牌": "FotoSnap",
        "型号": "FS-IC10",
        "描述": "使用这款有趣且便携的即时相机,创造瞬间回忆。",
        "特色": [
            "Instant prints",
            "Built-in flash",
            "Selfie mirror",
            "Battery-powered"
        ],
        "类别": "相机和摄像机",
        "评分": 4.1
    },
    {
        "价格": 599.99,
        "保修期": "2 years",
        "名称": "CineView 4K TV",
        "品牌": "CineView",
        "型号": "CV-4K55",
        "描述": "一款色彩鲜艳、智能功能丰富的惊艳4K电视。",
        "特色": [
            "55-inch display",
            "4K resolution",
            "HDR",
            "Smart TV"
        ],
        "类别": "电视和家庭影院系统",
        "评分": 4.8
    },
    {
        "价格": 2999.99,
        "保修期": "2 years",
        "名称": "CineView 8K TV",
        "品牌": "CineView",
        "型号": "CV-8K65",
        "描述": "通过这款惊艳的8K电视,体验未来。",
        "特色": [
            "65-inch display",
            "8K resolution",
            "HDR",
            "Smart TV"
        ],
        "类别": "电视和家庭影院系统",
        "评分": 4.9
    },
    {
        "价格": 1499.99,
        "保修期": "2 years",
        "名称": "CineView OLED TV",
        "品牌": "CineView",
        "型号": "CV-OLED55",
        "描述": "通过这款OLED电视,体验真正的五彩斑斓。",
        "特色": [
            "55-inch display",
            "4K resolution",
            "HDR",
            "Smart TV"
        ],
        "类别": "电视和家庭影院系统",
        "评分": 4.7
    },
    {
        "价格": 399.99,
        "保修期": "1 year",
        "名称": "SoundMax Home Theater",
        "品牌": "SoundMax",
        "型号": "SM-HT100",
        "描述": "一款强大的家庭影院系统,提供沉浸式音频体验。",
        "特色": [
            "5.1 channel",
            "1000W output",
            "Wireless subwoofer",
            "Bluetooth"
        ],
        "类别": "电视和家庭影院系统",
        "评分": 4.4
    },
    {
        "价格": 199.99,
        "保修期": "1 year",
        "名称": "SoundMax Soundbar",
        "品牌": "SoundMax",
        "型号": "SM-SB50",
        "描述": "使用这款时尚而功能强大的声音,升级您电视的音频体验。",
        "特色": [
            "2.1 channel",
            "300W output",
            "Wireless subwoofer",
            "Bluetooth"
        ],
        "类别": "电视和家庭影院系统",
        "评分": 4.3
    }
]

2.2、构造输入提示词

{
    "messages": [
        {
            "content": "您是一家大型电子商店的客服助理。请以友好和乐于助人的口吻回答问题,并尽量简洁明了。请确保向用户提出相关的后续问题。",
            "role": "system"
        },
        {             
            "content": "相关产品信息:" + product_information             
            "role": "assistant"         
        },
        {
            "content": "请告诉我关于 smartx pro phone 和 the fotosnap camera 的信息。另外,请告诉我关于你们的tvs的情况。",
            "role": "user"
        }
    ]
}

回答结果如下:

当然可以!我们这里有一些与你提到的产品相关的信息。

首先是 SmartX ProPhone,它是一款高性能的智能手机,具备以下特点:
名称:SmartX ProPhone
类别:智能手机和配件
品牌:SmartX
型号:SX-PP10
保修期:一年(1 year)
评分:4.6分(基于客户评价)
特色:
六英寸显示屏幕(6.1-inch display)
128GB存储空间(128GB storage)
双摄像头(12MP dual camera)
支持5G网络连接(5G)

接下来是 FotoSnap 相机系列,其中包括三种不同的型号:
名称:FotoSnap DSLR Camera
类别:相机和摄像机
品牌:FotoSnap
型号:FS-DSLR200
保修期:一年(1 year)
评分:4.7分(基于客户评价)
特色:
24兆像素传感器(24.2MP sensor)
1080p高清录制能力(1080p video)
三英寸液晶屏幕(3-inch LCD)
可更换镜头(Interchangeable lenses)

名称:FotoSnap Mirrorless Camera
类别:相机和摄像机
品牌:FotoSnap
型号:FS-ML100
保修期:一年(1 year)
评分:4.6分(基于客户评价)
特色:
20兆像素传感器(20.1MP sensor)
4K超高清录制能力(4K video)
三英寸触摸屏幕(3-inch touchscreen)
可更换镜头(Interchangeable lenses)

名称:FotoSnap Instant Camera
类别:相机和摄像机
品牌:FotoSnap
型号:FS-IC10
保修期:一年(1 year)
评分:4.1分(基于客户评价)
特色:
即时打印功能(Instant prints)
内置闪光灯(Built-in flash)
自拍镜子(Selfie mirror)
电池供电(Battery-powered)

至于我们的电视,我们有四个不同类型的产品:
名称:CineView 4K TV
类别:电视和家庭影院系统
品牌:CineView
型号:CV-4K55
保修期:两年(2 years)
评分:4.8分(

3、检查结果有害性

通过 OpenAI 提供的 Moderation API 来实现对有害内容的检查。

import openai
from tool import get_completion_from_messages

final_response_to_customer = f"""
SmartX ProPhone 有一个 6.1 英寸的显示屏,128GB 存储、\
1200 万像素的双摄像头,以及 5G。FotoSnap 单反相机\
有一个 2420 万像素的传感器,1080p 视频,3 英寸 LCD 和\
可更换的镜头。我们有各种电视,包括 CineView 4K 电视,\
55 英寸显示屏,4K 分辨率、HDR,以及智能电视功能。\
我们也有 SoundMax 家庭影院系统,具有 5.1 声道,\
1000W 输出,无线重低音扬声器和蓝牙。关于这些产品或\
我们提供的任何其他产品您是否有任何具体问题?
"""
# Moderation 是 OpenAI 的内容审核函数,旨在评估并检测文本内容中的潜在风险。
response = openai.Moderation.create(
    input=final_response_to_customer
)
moderation_output = response["results"][0]
print(moderation_output)

 

{
  "categories": {
    "harassment": false,
    "harassment/threatening": false,
    "hate": false,
    "hate/threatening": false,
    "self-harm": false,
    "self-harm/instructions": false,
    "self-harm/intent": false,
    "sexual": false,
    "sexual/minors": false,
    "violence": false,
    "violence/graphic": false
  },
  "category_scores": {
    "harassment": 4.2861907e-07,
    "harassment/threatening": 5.9538485e-09,
    "hate": 2.079682e-07,
    "hate/threatening": 5.6982725e-09,
    "self-harm": 2.3966843e-08,
    "self-harm/instructions": 1.5763412e-08,
    "self-harm/intent": 5.042827e-09,
    "sexual": 2.6989035e-06,
    "sexual/minors": 1.1349888e-06,
    "violence": 1.2788286e-06,
    "violence/graphic": 2.6259923e-07
  },
  "flagged": false
}

4、检查结果相关性

用于检查LLM输出的结果,是否满足客户问题,并验证助理引用的事实是否正确。

import openai
import json
import requests

url = "http://192.168.1.1:19327/v1/chat/completions"


# 这是一段电子产品相关的信息
system_message = f"""
您是一个助理,用于评估客服代理的回复是否充分回答了客户问题,\
并验证助理从产品信息中引用的所有事实是否正确。 
产品信息、用户和客服代理的信息将使用三个反引号(即 ```)\
进行分隔。 
请以 Y 或 N 的字符形式进行回复,不要包含标点符号:\
Y - 如果输出充分回答了问题并且回复正确地使用了产品信息\
N - 其他情况。

仅输出单个字母。
"""

#这是顾客的提问
customer_message = f"""
告诉我有关 smartx pro 手机\
和 fotosnap 相机(单反相机)的信息。\
还有您电视的信息。
"""
product_information = """{ "name": "SmartX ProPhone", "category": "Smartphones and Accessories", "brand": "SmartX", "model_number": "SX-PP10", "warranty": "1 year", "rating": 4.6, "features": [ "6.1-inch display", "128GB storage", "12MP dual camera", "5G" ], "description": "A powerful smartphone with advanced camera features.", "price": 899.99 } { "name": "FotoSnap DSLR Camera", "category": "Cameras and Camcorders", "brand": "FotoSnap", "model_number": "FS-DSLR200", "warranty": "1 year", "rating": 4.7, "features": [ "24.2MP sensor", "1080p video", "3-inch LCD", "Interchangeable lenses" ], "description": "Capture stunning photos and videos with this versatile DSLR camera.", "price": 599.99 } { "name": "CineView 4K TV", "category": "Televisions and Home Theater Systems", "brand": "CineView", "model_number": "CV-4K55", "warranty": "2 years", "rating": 4.8, "features": [ "55-inch display", "4K resolution", "HDR", "Smart TV" ], "description": "A stunning 4K TV with vibrant colors and smart features.", "price": 599.99 } { "name": "SoundMax Home Theater", "category": "Televisions and Home Theater Systems", "brand": "SoundMax", "model_number": "SM-HT100", "warranty": "1 year", "rating": 4.4, "features": [ "5.1 channel", "1000W output", "Wireless subwoofer", "Bluetooth" ], "description": "A powerful home theater system for an immersive audio experience.", "price": 399.99 } { "name": "CineView 8K TV", "category": "Televisions and Home Theater Systems", "brand": "CineView", "model_number": "CV-8K65", "warranty": "2 years", "rating": 4.9, "features": [ "65-inch display", "8K resolution", "HDR", "Smart TV" ], "description": "Experience the future of television with this stunning 8K TV.", "price": 2999.99 } { "name": "SoundMax Soundbar", "category": "Televisions and Home Theater Systems", "brand": "SoundMax", "model_number": "SM-SB50", "warranty": "1 year", "rating": 4.3, "features": [ "2.1 channel", "300W output", "Wireless subwoofer", "Bluetooth" ], "description": "Upgrade your TV's audio with this sleek and powerful soundbar.", "price": 199.99 } { "name": "CineView OLED TV", "category": "Televisions and Home Theater Systems", "brand": "CineView", "model_number": "CV-OLED55", "warranty": "2 years", "rating": 4.7, "features": [ "55-inch display", "4K resolution", "HDR", "Smart TV" ], "description": "Experience true blacks and vibrant colors with this OLED TV.", "price": 1499.99 }"""



final_response_to_customer = f"""
SmartX ProPhone 有一个 6.1 英寸的显示屏,128GB 存储、\
1200 万像素的双摄像头,以及 5G。FotoSnap 单反相机\
有一个 2420 万像素的传感器,1080p 视频,3 英寸 LCD 和\
可更换的镜头。我们有各种电视,包括 CineView 4K 电视,\
55 英寸显示屏,4K 分辨率、HDR,以及智能电视功能。\
我们也有 SoundMax 家庭影院系统,具有 5.1 声道,\
1000W 输出,无线重低音扬声器和蓝牙。关于这些产品或\
我们提供的任何其他产品您是否有任何具体问题?
"""

q_a_pair = f"""
顾客的信息: ```{customer_message}```
产品信息: ```{product_information}```
代理的回复: ```{final_response_to_customer}```

回复是否正确使用了检索的信息?
回复是否充分地回答了问题?

输出 Y 或 N
"""


body = {
    "messages": [
        {'role': 'system', 'content': system_message},
        {'role': 'user', 'content': q_a_pair}
    ]
}
body['max_tokens'] = 1

headers = {'Content-Type': 'application/json'}
response = requests.post(url, headers=headers, json=body)

chat = response.json()
choices = chat.get('choices', [])
if choices:
    result = choices[-1]['message']['content']
    print(result)

 Y

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐