
元提示技术:用 LLM 优化 LLM 的 Prompt
Meta-Prompting 原理 Meta-Prompting 的核心思想:用 LLM 来优化 LLM 的 prompt。这是一种"元"层面的优化——不在 prompt 内部做文章,而是让模型自己去寻找更好的 prompt。 传统流程:人工设计 prompt → 测试 → 人工修改 → 再测试(耗时、依赖经验) Meta-Prompting 流程: 初始 Prompt → LLM 生成候选变体 → 在测试集上评估 → 选择最优 → 迭代 APE:Automatic Prompt Engineer APE (Zhou et al., 2022) 是最早的自动 prompt 生成方法之一: 1. 给 LLM 少量输入-输出示例 2. 让 LLM 推断可能的 instruction (prompt) 3. 在验证集上评估每个候选 prompt 4. 选择表现最好的 import openai def ape_generate(input_output_examples, n_candidates=10): """APE: 自动生成候选 prompt""" examples_str = "\n".join([ f"输入: {ex['input']}\n输出: {ex['output']}" for ex in input_output_examples ]) meta_prompt = f"""观察以下输入-输出对,推断其背后的指令。 {examples_str} 请生成 {n_candidates} 条可能的指令,使模型能根据该指令从输入得到输出。 每条指令独占一行,以数字编号。指令应简洁、准确、可泛化。""" resp = openai.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": meta_prompt}], temperature=0.9, ) return resp.choices[0].message.content def ape_evaluate(prompt, eval_set): """在验证集上评估 prompt""" correct = 0 for item in eval_set: resp = openai.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": f"{prompt}\n\n输入: {item['input']}"}], temperature=0.0, ) if resp.choices[0].message.content.strip() == item['output'].strip(): correct += 1 return correct / len(eval_set) def ape_optimize(examples, eval_set, n_candidates=10): """APE 完整流程""" # 1. 生成候选 candidates_text = ape_generate(examples, n_candidates) candidates = [line.split('. ', 1)[1] for line in candidates_text.strip().split('\n') if '. ' in line] # 2. 评估 scores = [(c, ape_evaluate(c, eval_set)) for c in candidates] scores.sort(key=lambda x: x[1], reverse=True) return scores[0] # (best_prompt, score) OPRO:优化 by PROgression OPRO (Yang et al., 2023) 将 prompt 优化建模为优化问题,用 LLM 作为优化器: ...