PromptWizard:微软开源 AI 提示词自动化优化框架,能够迭代优化提示指令和上下文示例,提升 LLMs 特定任务的表现

❤️ 如果你也关注 AI 的发展现状,且对 AI 应用开发非常感兴趣,我会每日跟你分享最新的 AI 资讯和开源应用,也会不定期分享自己的想法和开源实例,欢迎关注我哦!

🥦 微信公众号|搜一搜:蚝油菜花 🥦


🚀 快速阅读

  1. 功能:自动化优化提示词,提升 LLMs 在特定任务中的表现。
  2. 机制:通过反馈驱动的批评和合成过程,迭代优化提示指令和示例。
  3. 应用:适用于情感分析、智能教育助手、医疗诊断支持等多个领域。

正文(附运行示例)

PromptWizard 是什么

在这里插入图片描述

PromptWizard 是微软推出的自动化提示优化框架,旨在改进大型语言模型(LLMs)在特定任务中的表现。该框架基于自我演变和自我适应机制,通过反馈驱动的批评和合成过程,在探索和利用之间找到平衡,迭代地优化提示指令和上下文示例,从而提高模型的准确性和效率,减少 API 调用和令牌使用,降低成本。

PromptWizard 在多个任务和数据集上展现了卓越的性能,即使在训练数据有限或使用较小模型的情况下也能保持高效。

PromptWizard 的主要功能

  • 自动化提示优化:自动优化 LLMs 的提示,提高特定任务的性能。
  • 自我演变和自我适应:框架能自我演变和适应,生成更好的任务特定提示。
  • 反馈驱动的批评和合成:基于反馈机制,不断改进提示和示例。
  • 迭代细化:框架迭代地细化提示指令和上下文示例,提升模型输出的质量。

PromptWizard 的技术原理

  • 问题表述:用问题描述和初始提示指令开始,为后续优化提供基础。
  • 迭代细化提示指令:通过变异、评分、批评和合成组件,生成更具体和有效的指令。
  • 识别多样化示例:从训练数据中选择正例和负例,优化提示。
  • 顺序优化:同时优化提示指令和少量示例,基于迭代反馈循环进行。
  • 自我生成的推理和验证:自动为每个示例生成详细的推理链,验证示例的一致性和相关性。
  • 任务意图和专家角色的整合:将任务意图和专家角色整合到提示中,提高模型性能和解释性。

如何运行 PromptWizard

安装

  1. 克隆仓库:
git clone https://github.com/microsoft/PromptWizard
cd PromptWizard
  1. 创建并激活虚拟环境:
  • 在 Windows 上:
python -m venv venv
venv\Scripts\activate
  • 在 macOS/Linux 上:
python -m venv venv
source venv/bin/activate
  1. 安装包:
pip install -e .

快速开始

PromptWizard 提供了三种主要的使用场景:

  1. 优化提示而不使用示例
  2. 生成合成示例并使用它们优化提示
  3. 使用训练数据优化提示
运行 PromptWizard 的示例

以下是使用 PromptWizard 优化提示的简单示例:

  1. 设置环境变量
from dotenv import load_dotenv
load_dotenv(override=True)
  1. 导入依赖
import sys
sys.path.insert(0, "../../")
import promptwizard
from promptwizard.glue.promptopt.instantiate import GluePromptOpt
from promptwizard.glue.promptopt.techniques.common_logic import DatasetSpecificProcessing
from promptwizard.glue.common.utils.file import save_jsonlist
from typing import Any
from tqdm import tqdm
from re import compile, findall
import os
from datasets import load_dataset
import yaml
  1. 更新 YAML 文件
def update_yaml_file(file_path, config_dict):
    with open(file_path, 'r') as file:
        data = yaml.safe_load(file)
    for field, value in config_dict.items():
        data[field] = value
    with open(file_path, 'w') as file:
        yaml.dump(data, file, default_flow_style=False)
    print("YAML file updated successfully!")
  1. 设置路径
path_to_config = "configs"
promptopt_config_path = os.path.join(path_to_config, "promptopt_config.yaml")
setup_config_path = os.path.join(path_to_config, "setup_config.yaml")
  1. 优化提示的三种情景
情景 1:无训练数据,且不想在最终提示中使用上下文示例
file_path = 'configs/promptopt_config.yaml'
config_dict = {
    "task_description": "You are a mathematics expert. You will be given a mathematics problem which you need to solve",
    "base_instruction": "Lets think step by step.",
    "mutation_rounds": 5
}
update_yaml_file(file_path, config_dict)

gp = GluePromptOpt(promptopt_config_path, setup_config_path, dataset_jsonl=None, data_processor=None)
best_prompt, expert_profile = gp.get_best_prompt(use_examples=False, run_without_train_examples=True, generate_synthetic_examples=False)
情景 2:无训练数据,但在最终提示中使用上下文示例
  • 步骤 1:生成合成数据
file_path = 'configs/promptopt_config.yaml'
config_dict = {
    "num_train_examples": 20
}
update_yaml_file(file_path, config_dict)

gp = GluePromptOpt(promptopt_config_path, setup_config_path, dataset_jsonl=None, data_processor=None)
best_prompt, expert_profile = gp.get_best_prompt(use_examples=False, run_without_train_examples=False, generate_synthetic_examples=True)
  • 步骤 2:使用合成数据优化提示
class GSM8k(DatasetSpecificProcessing):
    def dataset_to_jsonl(self, dataset_jsonl: str, **kwargs: Any) -> None:
        def extract_answer_from_output(completion):
            ans_re = compile(r"#### (-?[0-9\.,]+)")
            self.INVALID_ANS = "[invalid]"
            match = ans_re.search(completion)
            if match:
                match_str = match.group(1).strip()
                match_str = match_str.replace(",", "")
                return match_str
            else:
                return self.INVALID_ANS

        examples_set = []
        for _, sample in tqdm(enumerate(kwargs["dataset"]), desc="Evaluating samples"):
            example = {
                DatasetSpecificProcessing.QUESTION_LITERAL: sample['question'],
                DatasetSpecificProcessing.ANSWER_WITH_REASON_LITERAL: sample['answer'],
                DatasetSpecificProcessing.FINAL_ANSWER_LITERAL: extract_answer_from_output(sample["answer"])
            }
            examples_set.append(example)

        save_jsonlist(dataset_jsonl, examples_set, "w")

    def extract_final_answer(self, answer: str):
        if not answer:
            return self.INVALID_ANS

        model_pred = answer.lower()
        preds = model_pred.split(self.ANSWER_START.lower())
        answer_flag = True if len(preds) > 1 else False

        pred = preds[-1].replace(",", "")
        pred = [s for s in findall(r'-?\d+\.?\d*', pred)]

        if len(pred) == 0:
            return self.INVALID_ANS

        if answer_flag:
            pred = pred[0]
        else:
            pred = pred[-1]

        if pred[-1] == ".":
            pred = pred[:-1]
        return pred

gsm8k_processor = GSM8k()

file_path = 'configs/promptopt_config.yaml'
config_dict = {
    "task_description": "You are a mathematics expert. You will be given a mathematics problem which you need to solve",
    "base_instruction": "Lets think step by step.",
    "mutation_rounds": 2,
    "few_shot_count": 5,
    "generate_reasoning": True,
    "mutate_refine_iterations": 3,
    "seen_set_size": 20
}
update_yaml_file(file_path, config_dict)

gp = GluePromptOpt(promptopt_config_path, setup_config_path, dataset_jsonl="train_synthetic.jsonl", data_processor=gsm8k_processor)
best_prompt, expert_profile = gp.get_best_prompt(use_examples=True, run_without_train_examples=False, generate_synthetic_examples=False)
情景 3:有训练数据,并在最终提示中使用上下文示例
if not os.path.exists("data"):
    os.mkdir("data")

dataset = load_dataset("openai/gsm8k", "main")
num_samples = 0
for dataset_type in ['train', 'test']:
    data_list = []
    for data in dataset[dataset_type]:
        data_list.append({"question": data['question'], "answer": data['answer']})
        if num_samples == 100 and dataset_type == 'train':
            break
        num_samples += 1
    gsm8k_processor.dataset_to_jsonl(f"data/{dataset_type}.jsonl", dataset=data_list)

file_path = 'configs/promptopt_config.yaml'
config_dict = {
    "task_description": "You are a mathematics expert. You will be given a mathematics problem which you need to solve",
    "base_instruction": "Lets think step by step.",
    "mutation_rounds": 2,
    "few_shot_count": 5,
    "generate_reasoning": True,
    "mutate_refine_iterations": 3,
    "seen_set_size": 20
}
update_yaml_file(file_path, config_dict)

gp = GluePromptOpt(promptopt_config_path, setup_config_path, dataset_jsonl=os.path.join("data", "train.jsonl"), data_processor=gsm8k_processor)
best_prompt, expert_profile = gp.get_best_prompt(use_examples=True, run_without_train_examples=False, generate_synthetic_examples=False)

资源


❤️ 如果你也关注 AI 的发展现状,且对 AI 应用开发非常感兴趣,我会每日跟你分享最新的 AI 资讯和开源应用,也会不定期分享自己的想法和开源实例,欢迎关注我哦!

🥦 微信公众号|搜一搜:蚝油菜花 🥦

<think>嗯,用户想了解关于LangChain的信息,包括介绍、教程使用案例。首先,我需要整理LangChain的基本概念。根据引用[3],LangChain是一个开源的应用开发框架,允许将大模型与各种工具结合,实现文档问答、网页解析、表格查询等功能。支持PythonTypeScript,但Python更全面。 接下来,教程部分。引用[1]提到进阶教程,比如自定义模型,而引用[2]介绍了链的类型,如LLMChain、RefineChainMapReduceChain。需要分入门进阶两部分,说明链检索器的作用。 使用案例方面,结合引用中的例子,可以列举文档问答、网页解析、表格查询以及智能客服数据分析等场景。要确保每个案例都有具体说明,比如用代码示例展示LLMChain的使用。 用户可能还关心如何开始使用LangChain,所以需要给出安装步骤基础代码示例。同时,注意遵循系统指令,数学公式用$...$,独立公式用$$...$$,但这里可能用不上太多数学内容,主要是代码块结构。 需要检查是否有遗漏的信息,比如框架支持的模型类型或者与其他工具的整合。此外,用户的问题可能隐含对实际应用的需求,所以案例部分要具体,帮助用户理解如何应用到实际项目中。 最后,生成相关问题时要覆盖概念、教程、案例对比分析,确保问题能引导用户深入学习。比如,询问核心组件、应用案例或与其他框架的区别。确保引用标记正确,例如引用[1]、[2]、[3]在适当的位置。</think>### LangChain 介绍 LangChain 是一个开源的应用开发框架,支持将大语言模型(LLM)与外部工具(如文档、数据库、API)结合,实现问答、数据分析、自动化任务等复杂功能。其核心目标是通过“链”(Chain)机制管理任务流程,提升模型与工具协作的效率[^3]。目前主要支持 Python TypeScript,其中 Python 生态更为完善。 --- ### LangChain 核心组件 1. **模型(Model)** 支持集成多种大语言模型(如 GPT、Claude 等),通过统一接口调用。用户可自定义模型参数,例如温度(控制随机性)最大生成长度[^1]。 2. **链(Chain)** - **LLMChain**:基础链,用于单步任务(如生成文本摘要)。 - **RefineChain**:多步任务链,通过迭代优化输出结果。 - **MapReduceChain**:并行处理链,适用于大规模数据分块处理[^2]。 3. **检索器(Retriever)** 从外部数据源(如文档、数据库)中提取相关信息,增强模型输入的上下文准确性。例如,结合向量数据库实现语义搜索[^2]。 --- ### LangChain 基础教程 #### 1. 安装与基础使用 ```python pip install langchain from langchain.llms import OpenAI # 初始化模型 llm = OpenAI(temperature=0.9, model_name="gpt-3.5-turbo") response = llm("如何解释量子力学?") print(response) ``` #### 2. 构建简单任务链(LLMChain) ```python from langchain.prompts import PromptTemplate from langchain.chains import LLMChain template = "用一句话解释{concept}" prompt = PromptTemplate(input_variables=["concept"], template=template) chain = LLMChain(llm=llm, prompt=prompt) print(chain.run("区块链")) ``` --- ### LangChain 应用案例 1. **文档问答系统** 结合检索器从 PDF 或网页中提取内容,生成精确回答: ```python from langchain.document_loaders import WebBaseLoader from langchain.indexes import VectorstoreIndexCreator loader = WebBaseLoader("https://example.com/article") index = VectorstoreIndexCreator().from_loaders([loader]) query = "文章的主要观点是什么?" answer = index.query(query) ``` 2. **自动化数据分析** 解析 CSV 文件并生成统计结论: ```python from langchain.agents import create_csv_agent agent = create_csv_agent(llm, "data.csv") agent.run("计算销售额的月增长率") ``` --- ### 与其他框架对比 | 框架 | 特点 | 适用场景 | |-------------|-------------------------------|------------------------| | LangChain | 强调任务工具集成 | 复杂流程自动化 | | LlamaIndex | 专注检索增强生成(RAG) | 文档问答 | | HuggingFace | 提供预训练模型库 | 模型微调直接调用 | ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值