
generative-ai-for-beginners 第 5 课高级提示词工程实战 —— 从零样本到思维链的七种技术及输出控制【免费下载链接】generative-ai-for-beginners21 Lessons, Get Started Building with Generative AI项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai-for-beginners本课是 generative-ai-for-beginners21 课时生成式 AI 入门课程的第 5 课。承接前课「提示词工程 用更有效的指令或上下文引导模型给出更相关的回答」这一基本认识本文深入讲解对任意 LLM 均可套用的提示词构建技术并通过大量真实示例演示为什么一个提示词优于另一个、如何把提示词拆解为「构造 优化」两步以及如何用 temperature 等参数把输出从「随机发散」调向「确定可控」。学完本篇你将能独立应用七大提示技术零样本、少样本、思维链、生成知识、最小到最大、自我改进、产婆术式提示并能区分与配置「多样」与「确定」两种输出形态。为什么写提示词要先理解技术而不是只靠直觉回顾前一章的核心结论提示词工程是「通过提供更有用的指令或上下文引导模型走向更相关回答」的过程。它包含两个步骤构造提示词提供相关上下文与优化提示词逐步改进。本课的目标是让你从「试各种提示」进步到「理解为什么 A 提示比 B 提示好」。课程配套的作业代码也体现了同样的思路初始提示词只描述目标如aoai-assignment.py中「用 Flask 写一个 API」随后通过追加批判性提示词不断逼近想要的工程化质量见 aoai-assignment.py 与 aoai-solution.py 的对比。优化提示词本身就是一个可重复的迭代工程。从一个简单提示词看「构造」的组成以一个基础提示词为例生成 10 个关于地理的问题。Generate 10 questions on geography.它看似简单实际已经同时应用了两种提示技巧上下文Context明确指出主题是「地理」限制输出Limiting the output要求不超过 10 个问题。简单提示词的局限你可能得到想要的结果也可能得不到。问题会生成出来但「地理」是个巨大的主题失败通常源于两点主题过大你无法预知问题是关于国家、首都还是河流格式未指定如果希望问题按特定格式呈现这类提示完全无法表达。可见创建提示词时需要考虑的因素非常多。生成式 AI 远不止能回答这类简单请求它可以服务多种角色与行业——下面进入七大基础技术。提示词的七大基础技术首先要理解一个关键前提提示prompting是 LLM 的「涌现emergent」属性——它并非模型内置的功能而是我们使用模型时发现的能力。在此基础上有如下七种可反复组合使用的基础技术。技术一句话含义适用场景零样本 Zero-shot单条提示完全依赖模型训练数据作答入门、开放式问题少样本 Few-shot提示中附带 1 个或多个示例希望固定格式 / 风格 / 任务思维链 Chain-of-thought引导模型把问题拆成步骤算术、逻辑、多步推理生成知识 Generated knowledge在提示中注入外部事实或公司数据需要结合自有数据的业务最小到最大 Least-to-most把大问题拆成有序子问题逐个完成复杂任务规划自我改进 Self-refine先作答再批判、再按批判改进代码质量、内容打磨产婆术式 Maieutic让模型逐步解释自己剔除不一致部分校验答案正确性零样本提示Zero-shot prompting最基础的提示形式只有一条提示模型仅凭训练数据作答。这也是大多数人初次接触 LLM 时用的方式。提示“什么是代数”回答“代数是数学的一个分支研究数学符号以及操纵这些符号的规则。”少样本提示Few-shot prompting在一条提示中附带若干「任务相关示例」用示例为模型提供期望输出的上下文、格式或风格帮助它生成更精确、更相关的回答。提示“请以莎士比亚风格写一首诗。这里有几首十四行诗示例第 18 首Shall I compare thee to a summers day? Thou art more lovely and more temperate...第 116 首Let me not to the marriage of true minds Admit impediments. Love is not love Which alters when it alteration finds...第 132 首Thine eyes I love, and they, as pitying me, Knowing thy heart torment me with disdain,...现在请写一首关于月亮之美的十四行诗。”回答“Upon the sky, the moon doth softly gleam, In silvry light that casts its gentle grace,...”示例越贴近目标任务输出越符合预期——这是本课作业与课程后续各例反复验证的基本规律。思维链提示Chain-of-thought prompting思维链的目标是「带 LLM 走完一系列步骤」让模型真正理解如何做。先看一个不用思维链的失败例子提示“Alice 有 5 个苹果扔掉 3 个给 Bob 2 个Bob 又还回 1 个Alice 还剩几个苹果”回答5错误正确答案是 15 − 3 − 2 1 1那么如何教会模型算对应用思维链需要三步给 LLM 一个类似的示例展示计算过程与正确算法再给出原始问题。提示“Lisa 有 7 个苹果扔掉 1 个给 Bart 4 个Bart 还回 1 个7 − 1 66 − 4 22 1 3Alice 有 5 个苹果扔掉 3 个给 Bob 2 个Bob 还回 1 个Alice 还剩几个苹果”回答1注意我们写下了明显更长的提示——多一个示例、一段计算、最后才是原始问题——才得到正确答案 1。这也直观回答了本课「知识检测」的问题为什么用思维链因为它通过「一系列步骤 相似问题及其解法」向 LLM 示范如何解题而非教它找代码 bug也并非让它给出不同方案。生成知识提示Generated knowledge prompting很多业务场景下我们希望提示词里「一部分来自公司自有数据、另一部分才是真正关心的请求」。下面是一份保险行业的提示模板其中{{variable}}是可被公司 API 的真实数据替换的变量{{company}}: {{company_name}} {{products}}: {{products_list}} Please suggest an insurance given the following budget and requirements: Budget: {{budget}} Requirements: {{requirements}}变量替换后实际发给模型的提示长这样Insurance company: ACME Insurance Insurance products (cost per month): - Car, cheap, 500 USD - Car, expensive, 1100 USD - Home, cheap, 600 USD - Home, expensive, 1200 USD - Life, cheap, 100 USD Please suggest an insurance given the following budget and requirements: Budget: $1000 Requirements: Car, Home, and Life insurance模型输出Given the budget and requirements, we suggest the following insurance package from ACME Insurance: - Car, cheap, 500 USD - Home, cheap, 600 USD - Life, cheap, 100 USD Total cost: $1,200 USD它推荐了需求里没有的 Life 险且总价超出预算——说明必须继续优化提示把允许范围说清楚。经过若干次试错trial and error后改进为Insurance company: ACME Insurance Insurance products (cost per month): - type: Car, cheap, cost: 500 USD - type: Car, expensive, cost: 1100 USD - type: Home, cheap, cost: 600 USD - type: Home, expensive, cost: 1200 USD - type: Life, cheap, cost: 100 USD Please suggest an insurance given the following budget and requirements: Budget: $1000 restrict choice to types: Car, Home注意为产品标注type与cost键并使用restrict限制这一关键词能帮助模型真正理解边界。此时输出变为Given the budget and requirements, we suggest the Car, Cheap insurance product which costs 500 USD per month.本示例的关键启示是即便只用了「生成知识」这一基础技术多数情况下仍需一轮轮优化提示才能得到理想结果。这也解释了课程目录中提示词工程的「构造 优化」双步骤为何缺一不可。最小到最大提示Least-to-most prompting核心思想是把大问题拆解为若干子问题引导 LLM 一步步「征服」它。适合数据科学这类流程化任务提示如何用 5 步完成数据科学助手回答收集数据Collect data清洗数据Clean data分析数据Analyze data绘图数据Plot data呈现数据Present data自我改进提示Self-refine prompting生成式 AI 的输出「不可盲信」——LLM 给出的只是「下一个最可能出现的词」不一定是正确的词。因此好的做法是让模型自我批判。流程如下给出初始提示请 LLM 解题LLM 作答你批判该回答请 AI 改进LLM 综合批判再次作答并给出它想出的新方案。该过程可按需无限重复。示例提示“用 Python 创建一个带 products 与 customers 路由的 Web API”AI 初始回答import flask app Flask(__name__) app.route(/products) def products(): return Products app.route(/customers) def customers(): return Customers提示“针对上面的代码提出 3 条改进建议”AI 回答Sure, here are three suggestions to improve the code: Import the correct module: The first line should import Flask instead of flask. The correct import statement should be from flask import Flask. Add a main function: Add a if __name__ __main__: block to the end of the file to run the application when the file is executed. Use f-strings: Use f-strings to format the return statements in the route functions. For example, return Products can be changed to return fThis is the {request.path} page.from flask import Flask, request app Flask(__name__) app.route(/products) def products(): return fThis is the {request.path} page app.route(/customers) def customers(): return fThis is the {request.path} page if __name__ __main__: app.run()可见得益于对第一版答案的批判AI 的第二版代码质量明显提升。本课作业正是这套流程作业初始代码见 python/aoai-assignment.py在 python/aoai-solution.py 中可以看到经自我改进后加入的输入校验flask-wtf 表单校验、密钥环境变量化os.environ.get(FLASK_SECRET_KEY, ...)、统一错误处理app.errorhandler(400)与 XSS 转义escape()等改进JavaScript 版对练习与两次迭代解答则见 javascript/assignment.js 与 javascript/solution.js——后者还示范了把批判方向收敛到「更安全more secure」后模型如何自行引入 express-validator 校验、HTTPS 与证书路径安全约束。产婆术式提示Maieutic prompting与自我改进相似但更强调「让模型解释自己」目的是减少输出中的不一致从而确认答案正确。工作流为请 LLM 回答一个问题对回答的每一部分请 LLM 更深入解释若发现不一致丢弃不一致的部分。重复 2、3 直至检查完全部部分并满意为止。示例提示“如何用 5 步制定缓解大流行的危机计划”1. Identify the risks 1. Identify the stakeholders 1. Identify the resources 1. Identify the actions 1. Identify the communication channels模型给出了 5 步但它正确吗逐层追问提示请更详细解释第一步一场大流行中具体有哪些风险The risks are the following: - Loss of life - Loss of business - Loss of reputation - Loss of customers - Loss of employees继续验证第一个风险是否自洽提示在一场大流行中最大的风险是什么为什么The biggest risk is loss of life because its the most important thing to protect.提示在一场大流行中最大的两个风险是什么The two biggest risks are loss of life and loss of business.此时模型保持一致「生命」与「业务」始终位列前二可以带着较高的置信度进入下一步。但仍需牢记永远不要盲信 LLM务必核验输出。让输出「千变万化」还是「稳如磐石」理解非确定性LLM 天然是**非确定性nondeterministic**的同样的提示多次运行结果会不同。比如反复执行「为 Python Web API 生成代码」第一次给出带/api路由的 Flask 骨架# Import necessary modules import flask from flask import request, jsonify # Create a Flask app app flask.Flask(__name__) # Create a route for the API app.route(/api, methods[GET]) def api(): # Get the data from the request data request.args # Process the data result process_data(data) # Return the result as JSON return jsonify(result) # Function to process the data def process_data(data): # Do something with the data result data 1 # Return the result return result # Run the app if __name__ __main__: app.run()再次运行同一提示却可能得到「Books API」这样完全不同的实现带书籍数据与/api/v1/resources/books/all等路由#import necessary packages import flask from flask import request, jsonify #create the Flask application app flask.Flask(__name__) app.config[DEBUG] True #create a list of books books [ {id: 0, title: A Fire Upon the Deep, author: Vernor Vinge, first_sentence: The coldsleep itself was dreamless., year_published: 1992}, {id: 1, title: The Ones Who Walk Away From Omelas, author: Ursula K. Le Guin, first_sentence: With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea., published: 1973}, {id: 2, title: Dhalgren, author: Samuel R. Delany, first_sentence: to wound the autumnal city., published: 1975} ] #create an endpoint for the API app.route(/, methods[GET]) def home(): return h1Books API/h1 pA prototype API for retrieving books./p #create an endpoint to return all books app.route(/api/v1/resources/books/all, methods[GET]) def api_all(): return jsonify(books) #create an endpoint to return a single book app.route(/api/v1/resources/books, methods[GET]) def api_id(): #check if an ID was provided as part of the URL #if ID is provided, assign it to a variable #if no ID is provided, display an error if id in request.args: id int(request.args[id]) else: return Error: No id field provided. Please specify an id. #create an empty list for our results results [] #loop through the data and match results that fit the requested ID #IDs are unique, but other fields might return many results for book in books: if book[id] id: results.append(book) #use the jsonify function from Flask to convert our list of #Python dictionaries to the JSON format return jsonify(results) app.run()输出的多样性是不是问题取决于你的目标需要某个特定回答时它是问题如果只是要「生成任意 3 个地理问题」这种发散内容就完全不是问题。用 temperature 调整多样性若要输出更可预测更确定核心手段是temperature 参数。课程定义它为 0~1 之间的值0 最确定、1 最多样默认值为 0.7。把同一提示“为 Python Web API 生成代码”在 temperature0.1 下运行两次得到的两份代码仅在命名与个别逻辑上略有差异如api_endpoint/api_call、data 1与固定 success 字典结构高度一致#import necessary libraries import flask from flask import request, jsonify #create an instance of the Flask class app flask.Flask(__name__) #create an endpoint for the API app.route(/api/v1/endpoint, methods[GET]) def api_endpoint(): #get the request data data request.get_json() #process the data result process_data(data) #return the result return jsonify(result) #function to process the data def process_data(data): #process the data result {result: success} #return the result return result #run the Flask app if __name__ __main__: app.run()#import necessary libraries import flask from flask import request, jsonify #create a Flask app app flask.Flask(__name__) #create a route for the API app.route(/api, methods[GET]) def api_call(): #get the data from the request data request.get_json() #process the data result process_data(data) #return the result return jsonify(result) #define the process_data function def process_data(data): #do something with the data result data 1 #return the result return result #run the app if __name__ __main__: app.run()把 temperature 调到 0.9 再运行两次两次输出却天差地别——第一次仍是单路由骨架第二次直接变成带DEBUGTrue与 Books 数据的完整 API# Import necessary libraries import flask from flask import request, jsonify # Create a Flask app app flask.Flask(__name__) # Create a route for the API app.route(/api, methods[GET]) def api_call(): # Get the data from the request data request.args # Process the data result process_data(data) # Return the result return jsonify(result) # Function to process the data def process_data(data): # Do something with the data result data 1 # Return the result return result # Run the app if __name__ __main__: app.run()import flask from flask import request, jsonify # create the Flask app app flask.Flask(__name__) app.config[DEBUG] True # create some test data books [ {id: 0, title: A Fire Upon The Deep, author: Vernor Vinge, first_sentence: The coldsleep itself was dreamless., year_published: 1992}, {id: 1, title: The Ones Who Walk Away From Omelas, author: Ursula K. Le Guin, first_sentence: With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea., published: 1973}, {id: 2, title: Dhalgren, author: Samuel R. Delany, first_sentence: to wound the autumnal city., published: 1975} ] # create an endpoint app.route(/, methods[GET]) def home(): return h1Welcome to our book API!/h1 app.route(/api/v1/resources/books可以看到两组结果的差异“不可能更大了”。课程后续章节如 06-text-generation-apps 的代码正是这样实际配置 temperature 的。例如 python/oai-app-recipe.py 在「生成菜谱」阶段使用temperature0.1、max_output_tokens600在需要稳定汇总的「生成购物清单」阶段进一步降到temperature0python/githubmodels-app.py 则把temperature1.与top_p1.显式传入client.complete(...)。从这些真实调用可以看出需要创意产出时温度设高需要确定、可复现的结果如购物清单、结算、分类时温度压低甚至设 0。说明除 temperature 外还有更多可调参数会影响输出如 top-k、top-p、重复惩罚repetition penalty、长度惩罚length penalty与多样性惩罚diversity penalty但超出本课范围。编写高质量提示词的实践建议除上述技术外与 LLM 打交道时还应养成以下习惯指明上下文。上下文很重要领域、主题等限定越具体越好限制输出。想要指定数量的条目或指定长度就明说同时说明「做什么」与「怎么做」。例如“用 Python 创建一个带 products 与 customers 路由的 Web API并拆分为 3 个文件”善用模板。用公司数据增强提示词时采用带{{variable}}的模板替换成真实数据即可拼写正确。LLM 有时也能给出正确答案但拼写规范往往换来更好的回答。作业把自我改进用在自己的代码上本课作业提供了一段极简 Flask API 代码请你用 Copilot、ChatGPT 等 AI 助手对这段代码应用「自我改进」技术from flask import Flask, request app Flask(__name__) app.route(/) def hello(): name request.args.get(name, World) return fHello, {name}! if __name__ __main__: app.run()建议参考 python/aoai-solution.py 与 javascript/solution.js 中示范的提示措辞——把批判方向限定在某一具体维度如架构、性能、安全且限制改进数量得到的反馈往往更聚焦、更可用。例如 Python 解答版就是围绕「输入校验、密钥不进代码、统一错误处理」三条安全建议完成了迭代。知识检测问为什么要使用思维链chain-of-thought提示在下列选项中找出 1 个正确与 2 个错误答案。教会 LLM 如何解决一类问题。教会 LLM 在代码中查找错误。指示 LLM 给出各种不同方案。答案1。因为思维链的本质是「用一系列步骤 相似问题及其解法」向 LLM 示范如何解题——而不是教它查错或让它发散出不同答案。挑战你已在作业中用过自我改进技术请任取一个你写过的程序思考你希望施加哪些改进再用「自我改进」技术把提议的改动落到代码上最后判断结果是变好还是变差。这正是本课「构造—批判—再构造」循环的日常化练习。本课结束即可进入第 6 课把提示词工程知识用于构建文本生成应用其中菜谱应用、历史对话机器人与学习伙伴等示例会带你实际运行带 temperature 配置的完整生成应用。翻译说明本仓库文档的多语言版本由机器翻译维护本文以课程英文原版 05-advanced-prompts/README.md 为事实基准并参考波斯语译本的结构整理成文涉及代码的部分均已对照仓库源码核实。【免费下载链接】generative-ai-for-beginners21 Lessons, Get Started Building with Generative AI项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai-for-beginners创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考