大语言模型学习:提示词工程实战、优秀的提示工程案例

一、Prompt_APE-------自动化设计和优化提示词

为了实现这个策略,我们将遵循以下步骤:
第1步,提示生成(Prompt Generation):首先需要一个方法来生成一系列可能的提示。这可以通过向大模型提供一个关于任务或目标的描述,并要求它生成相关的提示来实现。
第2步,提示评分(Prompt Scoring):对于生成的每个提示,我们需要一个评分函数来评估其有效性。评分可以根据一系列标准进行,例如清晰度、具体性和引发所需响应的可能性。
第3步,精炼和迭代(Refinement and Iteration):根据评分,我们可以选择对提示进行精炼和迭代,以提高其质量和有效性。

一、官方原代码程序如下:


import random

def LLM_response(question):
    # 这里假设LLM_response是一个已经定义好的大模型响应函数
    # 实际上,这个函数会调用大模型API并返回响应
    pass

def generate_prompts(task_description, num_prompts=5):
    # 根据任务描述生成一系列提示
    prompts = [LLM_response(f"生成提示:基于任务'{task_description}'生成提示") for _ in range(num_prompts)]
    return prompts

def score_prompt(prompt, criteria):
    # 对提示进行评分,这里简化为随机评分
    # 实际中,可能需要更复杂的评分机制,可能包括调用LLM来评估提示的质量
    score = sum(prompt.count(criterion) for criterion in criteria) / len(criteria)
    return score

def refine_prompt(prompt, feedback):
    # 根据反馈精炼提示
    # 这里简化为在提示后添加反馈
    refined_prompt = prompt + " " + feedback
    return refined_prompt

# 假设我们有一个任务描述
task_description = "描述一个复杂的科学概念,使其易于理解。"
# 生成一系列提示
prompts = generate_prompts(task_description)
# 设定评分标准
scoring_criteria = ["清晰", "具体", "易于理解"]
# 对每个提示进行评分
scores = {prompt: score_prompt(prompt, scoring_criteria) for prompt in prompts}
# 根据评分选择最佳提示
best_prompt = max(scores, key=scores.get)
# 假设我们有关于最佳提示的反馈
feedback = "增加一个日常生活中的例子。"

# 精炼提示
refined_prompt = refine_prompt(best_prompt, feedback)

print("原始提示:", prompts)
print("最佳提示:", best_prompt)
print("精炼后的提示:", refined_prompt)

运行时报错:

这是由于第一个函数没有定义现有的大模型。这里我使用Qwen3-0.6B的模型进行部署,首先去modelscope下载模型(不会的见微调实战1、2),推荐使用SDK下载

#模型下载
from modelscope import snapshot_download
model_dir = snapshot_download('Qwen/Qwen3-0.6B')

二、修改代码程序

模型地址要换成你自己的地址,代码如下:

import random
from modelscope import AutoModelForCausalLM, AutoTokenizer

# 加载模型和分词器
model_name = "/home/user/.cache/modelscope/hub/models/Qwen/Qwen3-0.6B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype="auto",
    device_map="auto"
)


def LLM_response(user_input, history):
    """获取LLM的响应"""
    # 添加用户消息到历史
    history.append({"role": "user", "content": user_input})

    # 应用聊天模板
    text = tokenizer.apply_chat_template(
        history,
        tokenize=False,
        add_generation_prompt=True
    )

    # 准备模型输入
    model_inputs = tokenizer([text], return_tensors="pt").to(model.device)

    # 生成响应
    generated_ids = model.generate(
        **model_inputs,
        max_new_tokens=512,
        pad_token_id=tokenizer.eos_token_id,
        do_sample=True,
        temperature=0.7,
        top_p=0.9
    )

    # 解码响应
    response = tokenizer.decode(
    # 从生成的完整序列中截取新生成的部分:
    #   generated_ids[0]: 取batch中的第一个结果(shape=[1, seq_length]时的索引0)
    #   [model_inputs.input_ids.shape[1]: ]: 从输入序列长度之后开始截取(去掉输入部分)
        generated_ids[0][model_inputs.input_ids.shape[1]:],
    # 跳过特殊标记(如[CLS], [SEP], [PAD]等)
        skip_special_tokens=True
    ).strip()

    # 添加助手响应到历史
    history.append({"role": "assistant", "content": response})

    return response, history


def generate_prompts(task_description, num_prompts=5):
    """生成一系列提示"""
    prompts = []
    for _ in range(num_prompts):
        # 为每个提示创建新的初始历史
        initial_history = [
            {
                "role": "system",
                "content": "你是一个提示生成专家。请直接生成一个高质量的提示,不要包含任何思考过程或解释。"
            }
        ]
        response, _ = LLM_response(
            f"为以下任务生成一个高质量提示,只输出提示本身,不要包含任何思考或解释:\n任务: {task_description}",
            initial_history
        )

        # 清理响应 - 移除思考标签
        if "<think>" in response:
            response = response.split("</think>")[-1].strip()

        prompts.append(response)
    return prompts


# def score_prompt(prompt, criteria):
#     """对提示进行评分 - 使用更复杂的评分机制"""
#     # 检查提示是否包含思考标签(应该避免)
#     if "<think>" in prompt:
#         return 0  # 如果包含思考标签,评分为0
#
#     # 根据评分标准计算分数
#     score = 0
#     for criterion in criteria:
#         if criterion in prompt:
#             score += 1
#
#     # 添加额外评分因素
#     # 1. 提示长度(适中的长度更好)
#     ideal_length = 15
#     length_score = 1 - min(1, abs(len(prompt) - ideal_length) / ideal_length)
#
#     # 2. 具体性(包含具体例子或细节)
#     specificity_score = 1 if "例如" in prompt or "比如" in prompt else 0.5
#
#     # 综合评分
#     total_score = (score + length_score + specificity_score) / (len(criteria) + 2)
#     return round(total_score, 2)

def score_prompt(prompt, criteria):
    """改进后的提示评分机制"""
    # 0. 基础检查:如果提示包含思考标签,评分为0
    if "<think>" in prompt:
        return 0.0

    # 1. 核心特性评分(0-3分)
    core_score = 0
    # 使用更宽松的标准检查特性是否存在
    if any(word in prompt for word in ["清晰", "清楚", "简明"]):
        core_score += 1
    if any(word in prompt for word in ["具体", "详细", "明确"]):
        core_score += 1
    if any(word in prompt for word in ["易于理解", "简单", "通俗", "易懂"]):
        core_score += 1

    # 2. 长度评分(0-1分)
    prompt_length = len(prompt)
    if 30 <= prompt_length <= 100:  # 理想长度范围
        length_score = 1.0
    elif 20 <= prompt_length < 30 or 100 < prompt_length <= 150:
        length_score = 0.5
    else:
        length_score = 0.3

    # 3. 具体性评分(0-2分)
    specificity_score = 0
    if any(word in prompt for word in ["例如", "比如", "举例", "实际例子"]):
        specificity_score += 1
    if any(word in prompt for word in ["日常生活", "现实生活", "日常经验"]):
        specificity_score += 1

    # 4. 结构评分(0-1分)
    structure_score = 1.0 if any(word in prompt for word in ["步骤", "过程", "方法"]) else 0.5

    # 综合评分(满分7分,归一化为0-1范围)
    total_score = core_score + length_score + specificity_score + structure_score
    normalized_score = total_score / 7.0

    return round(normalized_score, 2)


def refine_prompt(prompt, feedback):
    """使用LLM精炼提示"""
    # 创建精炼用的对话历史
    refine_history = [
        {"role": "system", "content": "你是一个提示优化专家。请根据反馈改进以下提示。"},
        {"role": "user", "content": f"原始提示: {prompt}\n反馈: {feedback}\n请输出改进后的提示,不要包含任何解释或思考。"}
    ]

    # 获取精炼后的提示
    refined_response, _ = LLM_response("", refine_history)

    # 清理响应
    if "<think>" in refined_response:
        refined_response = refined_response.split("</think>")[-1].strip()

    return refined_response


# 主流程
if __name__ == "__main__":
    # 示例任务
    task_description = "描述一个复杂的科学概念,使其易于理解。"

    # 1. 生成提示
    print("生成提示中...")
    prompts = generate_prompts(task_description, num_prompts=3)
    print("\n生成的提示:")
    for i, prompt in enumerate(prompts, 1):
        print(f"{i}. {prompt}")

    # 2. 评分提示
    scoring_criteria = ["清晰", "具体", "易于理解"]
    print("\n评分提示中...")
    scores = {prompt: score_prompt(prompt, scoring_criteria) for prompt in prompts}

    print("\n提示评分:")
    for prompt, score in scores.items():
        print(f"- 评分 {score:.2f}: {prompt[:60]}{'...' if len(prompt) > 60 else ''}")

    # 3. 精炼最佳提示
    best_prompt = max(scores, key=scores.get)
    feedback = "增加一个日常生活中的例子。"

    print("\n精炼最佳提示中...")
    refined_prompt = refine_prompt(best_prompt, feedback)

    print("\n=== 最终结果 ===")
    print("最佳提示:", best_prompt)
    print("反馈:", feedback)
    print("精炼后的提示:", refined_prompt)

    # 4. 测试精炼后的提示
    print("\n测试精炼后的提示...")
    test_history = [
        {"role": "system", "content": "你是一个科学教育专家,擅长用简单语言解释复杂概念。"}
    ]

    # 使用精炼后的提示提问
    response, _ = LLM_response(refined_prompt, test_history)

    print("\n模型响应:")
    print(response)

    print("\n进入交互模式 (输入 '退出' 结束对话)" + "-" * 50)
    conversation_history = [
        {"role": "system", "content": "你是一个乐于助人的AI助手,用简洁的语言回答用户问题"}
    ]

    while True:
        user_input = input("\n用户: ")
        if user_input.lower() in ["退出", "exit", "quit"]:
            print("\n对话结束。")
            break

        response, conversation_history = LLM_response(user_input, conversation_history)
        print(f"\n助手: {response}")

        # 显示当前对话长度
        token_count = sum(len(tokenizer.encode(msg["content"])) for msg in conversation_history)
        print(f"[当前对话长度: {token_count} tokens]")

三、程序解读

运行后首先进入第一个函数生成3种提示词

prompts = generate_prompts(task_description, num_prompts=3)

然后进入第二个函数,根据自己设置的评分标准来对三种提示词分别打分

scoring_criteria = ["清晰", "具体", "易于理解"]
print("\n评分提示中...")
scores = {prompt: score_prompt(prompt, scoring_criteria) for prompt in prompts}
print("\n提示评分:")
for prompt, score in scores.items():
    print(f"- 评分 {score:.2f}: {prompt[:60]}{'...' if len(prompt) > 60 else ''}")

然后进入第三个函数,选取评分最高的提示,对提示进行精炼的同时,加入新的要求,比如“增加一个日常生活中的例子”

best_prompt = max(scores, key=scores.get)
feedback = "增加一个日常生活中的例子。"

最终输出最终结果

后面还进入了一个调用模型API的交互模式的函数,注意这里并没有将刚刚的过程加入history,只是进行了一个调用。

二、Prompt_Chains--------链式处理流程

使用Python编程语言实现一个名为"Chains"的链式处理流程,使用大型语言模型(LLMs)来处理复杂的任务。
为了实现这个策略,我们将遵循以下步骤:
每个链式组件执行特定的功能,并将输出作为下一个组件的输入。
我们将使用一个假设的LLM_response(question)函数来代表大模型的回答功能。这个函数将接收一个问题作为输入,并返回模型的回答。
第1步,使用chain_component_1函数处理输入数据并生成一个问题,
第2步,使用chain_component_2函数利用大型语言模型来回答这个问题。

一、官方原始代码

如下:




#######
'''
使用Python编程语言实现一个名为"Chains"的链式处理流程,使用大型语言模型(LLMs)来处理复杂的任务。
为了实现这个策略,我们将遵循以下步骤:
每个链式组件执行特定的功能,并将输出作为下一个组件的输入。
我们将使用一个假设的LLM_response(question)函数来代表大模型的回答功能。这个函数将接收一个问题作为输入,并返回模型的回答。
第1步,使用chain_component_1函数处理输入数据并生成一个问题,
第2步,使用chain_component_2函数利用大型语言模型来回答这个问题。
'''


def LLM_response(question):
    # 这个函数模拟了一个大型语言模型的回答功能。
    # 在实际应用中,这将是调用大型语言模型的接口。
    # 为了示例,我们简单地返回一个格式化的回答。
    return f"模型对'{question}'的回答是:这里会插入模型的回答。"

def chain_component_1(input_data):
    # 第一个链式组件,它将处理输入数据并生成一个问题。
    # 在实际应用中,这可能包括数据预处理、问题生成等步骤。
    question = f"请解释'{input_data}'的含义。"
    return question

def chain_component_2(input_data):
    # 第二个链式组件,它将使用大型语言模型来回答第一个组件生成的问题。
    response = LLM_response(input_data)
    return response

def chain_of_components(input_data):
    # 链式处理流程,将依次调用每个组件。
    question = chain_component_1(input_data)
    answer = chain_component_2(question)
    return answer

# 示例输入数据
example_input = "Chains"

# 运行链式处理流程
chain_result = chain_of_components(example_input)
chain_result

二、修改代码程序

将代码修改:

import random
from modelscope import AutoModelForCausalLM, AutoTokenizer

# 加载模型和分词器
model_name = "/home/user/.cache/modelscope/hub/models/Qwen/Qwen3-0.6B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype="auto",
    device_map="auto"
)

# def LLM_response(question):
#     # 这个函数模拟了一个大型语言模型的回答功能。
#     # 在实际应用中,这将是调用大型语言模型的接口。
#     # 为了示例,我们简单地返回一个格式化的回答。
#     return f"模型对'{question}'的回答是:这里会插入模型的回答。"

def LLM_response(user_input, history):
    """获取LLM的响应"""
    # 添加用户消息到历史
    history.append({"role": "user", "content": user_input})

    # 应用聊天模板
    text = tokenizer.apply_chat_template(
        history,
        tokenize=False,
        add_generation_prompt=True
    )

    # 准备模型输入
    model_inputs = tokenizer([text], return_tensors="pt").to(model.device)

    # 生成响应
    generated_ids = model.generate(
        **model_inputs,
        max_new_tokens=512,
        pad_token_id=tokenizer.eos_token_id,
        do_sample=True,
        temperature=0.7,
        top_p=0.9
    )

    # 解码响应
    response = tokenizer.decode(
    # 从生成的完整序列中截取新生成的部分:
    #   generated_ids[0]: 取batch中的第一个结果(shape=[1, seq_length]时的索引0)
    #   [model_inputs.input_ids.shape[1]: ]: 从输入序列长度之后开始截取(去掉输入部分)
        generated_ids[0][model_inputs.input_ids.shape[1]:],
    # 跳过特殊标记(如[CLS], [SEP], [PAD]等)
        skip_special_tokens=True
    ).strip()

    # 添加助手响应到历史
    history.append({"role": "assistant", "content": response})

    return response, history


def chain_component_1(input_data):
    # 第一个链式组件,它将处理输入数据并生成一个问题。
    # 在实际应用中,这可能包括数据预处理、问题生成等步骤。
    question = f"你是英文方面的专家,请解释'{input_data}'的含义。"
    print("-" * 50 + "chain_component_1"+ "-" * 50)
    print(question)
    return question

def chain_component_2(input_data):
    # 创建新的对话历史记录
    history = [
        {"role": "system", "content": "你是一个乐于助人的AI助手,用简洁的语言回答用户问题"}
    ]
    response, history = LLM_response(input_data, history)
    print("-" * 50 + "chain_component_2"+ "-" * 50)
    print(response)
    return response

def chain_of_components(input_data):
    # 链式处理流程,将依次调用每个组件。
    question = chain_component_1(input_data)
    answer = chain_component_2(question)
    print("-" * 50 + "chain_of_components"+ "-" * 50)
    print(answer)
    return answer

if __name__ == "__main__":

    # 示例输入数据
    example_input = "Chains"

    # 运行链式处理流程
    chain_result = chain_of_components(example_input)
    print("-" * 50 + "链式响应结果"+ "-" * 50)
    print(chain_result)

    conversation_history = [
        {"role": "system", "content": "你是一个乐于助人的AI助手,用简洁的语言回答用户问题"}
    ]

    while True:
        user_input = input("\n用户: ")
        if user_input.lower() in ["退出", "exit", "quit"]:
            print("\n对话结束。")
            break
        response, conversation_history = LLM_response(user_input, conversation_history)
        print(f"\n助手: {response}")

三、程序解读

这里是将提示工程转化为链式结构去处理,将复杂任务简单化处理。

在示例中,例如我们只输出了单词Chain,但是在第一层中设计了模板

question = f"你是英文方面的专家,请解释'{input_data}'的含义。"

因此会将问题转化为

简化了问题的输入。

在第二层中,也会进行一个历史信息的处理

history = [
    {"role": "system", "content": "你是一个乐于助人的AI助手,用简洁的语言回答用户问题"}
]
response, history = LLM_response(input_data, history)

从而进入第二层的提示/输出

最终的链式响应结果为:

三、Prompt_CoT--------逐步推理

以下是一个适用于多案例的通用CoT提示:
"请仔细思考问题,并逐步阐述你的推理过程。
首先,明确问题的核心点和关键信息。
其次,根据问题的特点,运用适当的逻辑和知识进行推理。
然后,在推理过程中,请务必清晰地表述每一个步骤,包括你的思考、假设、推断和结论。如果遇到复杂问题,可以尝试将其分解为若干个子问题,逐一解决。
最后,总结你的推理过程,给出答案。
在整个过程中,请保持逻辑严密、条理清晰,以确保推理的准确性和有效性。"
T1、零样本CoT实现:
我们将构建一个简单的函数,该函数接受一个问题作为输入。
该函数将指导模型通过一系列步骤来解决问题,并在每一步都要求模型展示其推理过程。

T2、手动CoT实现:
在这个变体中,我们需要提供一个或多个示例,其中包含解决特定类型问题的步骤。
函数将使用这些示例作为模板,来指导模型如何解决问题。

一、官方原始代码

from zhipuai import ZhipuAI
def ChatGLM4_API_Chat(question):
    api_key = "f2d95339d780f7124b95151be60695d1.q3VlDM1ArBt4DqKJ"  # 请替换为您的APIKey
    client = ZhipuAI(api_key=api_key)
    messages = [{"role": "user", "content": question}]
    response = client.chat.completions.create(
        model="glm-4",
        messages=messages,
    )
    # print(response)
    res = response.choices[0].message.content
    return res
# 使用示例:
question = "你好!你叫什么名字?"
answer = ChatGLM4_API_Chat(question)
print(answer)


def CoT_By_zero_shot_cot(question):
    """
    实现零样本Chain of Thought (CoT)。
    这个函数接受一个问题作为输入,并指导模型一步步进行思考。
    """
    # 第一步:理解问题
    step1 = "首先,让我们理解这个问题:" + question
    # 第二步:识别问题的关键元素
    step2 = "接下来,我们需要识别这个问题中的关键元素或术语。"
    # 第三步:制定解决问题的计划
    step3 = "现在,让我们根据识别的元素制定解决问题的计划。"
    # 第四步:执行计划并进行逐步推理
    step4 = "我们将执行计划并进行逐步推理。"
    # 第五步:根据推理得出结论
    step5 = "最后,我们将根据我们的逐步推理得出结论。"
    # 将所有步骤组合成一个CoT
    cot = "\n".join([step1, step2, step3, step4, step5])
    return cot

# 测试零样本CoT函数
test_question = "法国的首都是什么?"
CoT_prompt = CoT_By_zero_shot_cot(test_question)
print('CoT_By_zero_shot_cot \n',CoT_prompt)
answer = ChatGLM4_API_Chat(CoT_prompt)
print(answer)


def CoT_By_manual_cot(question, examples):
    """
    实现手动Chain of Thought (CoT)。
    这个函数接受一个问题和一个示例列表作为输入。
    它使用这些示例作为模板,指导模型如何通过一系列步骤来解决问题。
    """
    # 第一步:理解问题
    step1 = "首先,让我们理解这个问题:" + question
    # 第二步:识别问题的关键元素
    step2 = "接下来,我们需要识别这个问题中的关键元素或术语。"
    # 使用示例来指导推理过程
    reasoning_steps = []
    for example_question, example_solution in examples:
        reasoning_steps.append(f"对于一个类似的问题 '{example_question}',答案是 '{example_solution}'。")
    # 第三步:制定解决问题的计划
    step3 = "现在,让我们根据识别的元素和提供的示例制定解决问题的计划。"
    # 第四步:执行计划并进行逐步推理
    step4 = "我们将执行计划并进行逐步推理,由提供的示例指导。"
    # 第五步:根据推理得出结论
    step5 = "最后,我们将根据我们的逐步推理得出结论,由示例指导。"
    # 将所有步骤组合成一个CoT
    cot = "\n".join([step1, step2, *reasoning_steps, step3, step4, step5])
    return cot

# 准备一个示例,用于解决地理问题
example_question = "德国的首都是什么?"
example_solution = "德国的首都是柏林。"
examples = [(example_question, example_solution)]
# 测试手动CoT函数
CoT_prompt = CoT_By_manual_cot(test_question, examples)
print('CoT_By_manual_cot \n',CoT_prompt)
answer = ChatGLM4_API_Chat(CoT_prompt)
print(answer)

二、修改代码程序

这里依旧是用下载到本地的Qwen3-0.6B的模型来替换官方代码的程序

from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# 初始化模型和分词器(确保模型已下载到本地路径)
MODEL_PATH = "/home/user/.cache/modelscope/hub/models/Qwen/Qwen3-0.6B"  # 替换为你的实际模型路径

# 加载模型和分词器(首次运行会加载模型)
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
model = AutoModelForCausalLM.from_pretrained(
    MODEL_PATH,
    torch_dtype="auto",  # 自动选择数据类型
    device_map="auto"  # 自动选择设备(优先使用GPU)
)

def Qwen_local_Chat(question):
    # 构建符合Qwen格式的对话输入
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": question}
    ]

    # 应用聊天模板
    text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )
    # 编码输入文本
    inputs = tokenizer(text, return_tensors="pt").to(model.device)
    # 生成回复
    outputs = model.generate(
        **inputs,
        max_new_tokens=512,  # 生成的最大token数
        do_sample=True,  # 启用采样
        temperature=0.7,  # 控制随机性
        top_p=0.9  # 核采样参数
    )

    # 解码并提取回复(跳过输入部分)
    response = outputs[0][inputs.input_ids.shape[-1]:]
    return tokenizer.decode(response, skip_special_tokens=True)

# from zhipuai import ZhipuAI
# def ChatGLM4_API_Chat(question):
#     api_key = "f2d95339d780f7124b95151be60695d1.q3VlDM1ArBt4DqKJ"  # 请替换为您的APIKey
#     client = ZhipuAI(api_key=api_key)
#     messages = [{"role": "user", "content": question}]
#     response = client.chat.completions.create(
#         model="glm-4",
#         messages=messages,
#     )
#     # print(response)
#     res = response.choices[0].message.content
#     return res
# # 使用示例:
# question = "你好!你叫什么名字?"
# answer = ChatGLM4_API_Chat(question)
# print(answer)

def CoT_By_zero_shot_cot(question):
    """
    实现零样本Chain of Thought (CoT)。
    这个函数接受一个问题作为输入,并指导模型一步步进行思考。
    """
    # 第一步:理解问题
    step1 = "首先,让我们理解这个问题:" + question
    # 第二步:识别问题的关键元素
    step2 = "接下来,我们需要识别这个问题中的关键元素或术语。"
    # 第三步:制定解决问题的计划
    step3 = "现在,让我们根据识别的元素制定解决问题的计划。"
    # 第四步:执行计划并进行逐步推理
    step4 = "我们将执行计划并进行逐步推理。"
    # 第五步:根据推理得出结论
    step5 = "最后,我们将根据我们的逐步推理得出结论。"
    # 将所有步骤组合成一个CoT
    cot = "\n".join([step1, step2, step3, step4, step5])
    return cot

# 测试零样本CoT函数
test_question = "法国的首都是什么?"
CoT_prompt = CoT_By_zero_shot_cot(test_question)
print('CoT_By_zero_shot_cot \n',CoT_prompt)
answer = Qwen_local_Chat(CoT_prompt)
print(answer)

def CoT_By_manual_cot(question, examples):
    """
    实现手动Chain of Thought (CoT)。
    这个函数接受一个问题和一个示例列表作为输入。
    它使用这些示例作为模板,指导模型如何通过一系列步骤来解决问题。
    """
    # 第一步:理解问题
    step1 = "首先,让我们理解这个问题:" + question
    # 第二步:识别问题的关键元素
    step2 = "接下来,我们需要识别这个问题中的关键元素或术语。"
    # 使用示例来指导推理过程
    reasoning_steps = []
    for example_question, example_solution in examples:
        reasoning_steps.append(f"对于一个类似的问题 '{example_question}',答案是 '{example_solution}'。")
    # 第三步:制定解决问题的计划
    step3 = "现在,让我们根据识别的元素和提供的示例制定解决问题的计划。"
    # 第四步:执行计划并进行逐步推理
    step4 = "我们将执行计划并进行逐步推理,由提供的示例指导。"
    # 第五步:根据推理得出结论
    step5 = "最后,我们将根据我们的逐步推理得出结论,由示例指导。"
    # 将所有步骤组合成一个CoT
    cot = "\n".join([step1, step2, *reasoning_steps, step3, step4, step5])
    return cot

# 准备一个示例,用于解决地理问题
example_question = "德国的首都是什么?"
example_solution = "德国的首都是柏林。"
examples = [(example_question, example_solution)]
# 测试手动CoT函数
CoT_prompt = CoT_By_manual_cot(test_question, examples)
print('CoT_By_manual_cot \n',CoT_prompt)
answer = Qwen_local_Chat(CoT_prompt)
print(answer)

三、程序解读

函数零样本推理,直接没有示例进行推理ICL

def CoT_By_zero_shot_cot(question):

定义了模型推理时提示词需要经过的逻辑步骤

# 第一步:理解问题
step1 = "首先,让我们理解这个问题:" + question
# 第二步:识别问题的关键元素
step2 = "接下来,我们需要识别这个问题中的关键元素或术语。"
# 第三步:制定解决问题的计划
step3 = "现在,让我们根据识别的元素制定解决问题的计划。"
# 第四步:执行计划并进行逐步推理
step4 = "我们将执行计划并进行逐步推理。"
# 第五步:根据推理得出结论
step5 = "最后,我们将根据我们的逐步推理得出结论。"

函数进行少样本推理,基于示例去进行提示学习,也称为手动COT

def CoT_By_manual_cot(question, examples):

定义了一个推理流程的模板,以知道模型按照这种方式去推理

    # 第一步:理解问题
    step1 = "首先,让我们理解这个问题:" + question
    # 第二步:识别问题的关键元素
    step2 = "接下来,我们需要识别这个问题中的关键元素或术语。"
    # 使