
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-beginners 的第 5 课日文版 translations/ja/05-advanced-prompts/README.md为核心主体系统讲解在基础提示工程之上的七种高级提示技术以及如何通过温度等参数控制 LLM 输出的多样性与确定性。读完本文你将掌握零样本、少样本、思维链、生成知识、最小到最大、自我完善、产婆式提示等技术的适用场景与构造方法并能在实际开发中通过调整温度获得可预测或富有创意的模型输出同时了解本课程配套的 Python 与 JavaScript 实战作业。从基础到高级提示工程的两步流程在进入高级技术之前先回顾前一课第 4 课提示工程基础的核心结论提示工程Prompt Engineering是通过提供更有用的指令或上下文引导模型生成更相关响应的过程。写好一个提示词包含两个步骤构造提示词提供相关上下文与优化逐步改进提示词。在 04-prompt-engineering-fundamentals/README.md 中我们学习了提示词由指令、主要内容和辅助内容构成并认识了零样本、少样本等基础形态。第 5 课的任务是把尝试各种提示词提升为理解为什么某个提示词优于另一个并掌握一套适用于任何 LLM 的基础技术框架。本章的学习目标有两条应用能改善提示词结果的提示工程技巧执行既可以是多样化的、也可以是确定性的提示词调用。从一个基础提示词看起上下文与输出限制以一个最简单的提示词为例生成 10 个地理相关问题。这个看似简单的提示词实际上已经应用了两种提示技术上下文Context明确了主题是地理输出限制Limiting the output把问题数量限制为不超过 10 个。但它仍可能无法满足你的预期原因在于主题过于宽泛Big topic你无法确定问题是关于国家、首都还是河流格式Format如果你希望问题以某种特定格式呈现这个提示词完全没有约束。可见构造提示词时有大量细节需要考虑。而生成式 AI 的能力远不止于此接下来我们逐个深入七种基本提示技术。七种高级提示技术详解首先需要建立的一个认知是提示是 LLM 的涌现emergent属性——它不是模型内置的功能而是我们在使用模型过程中发现并总结出来的能力。基于这一前提以下是可应用于任意 LLM 的七种基本技术。1. 零样本提示Zero-shot prompting这是最基础的提示形式单个提示词完全依赖模型训练数据生成响应。提示「代数是什么」响应「代数是数学的一个分支研究数学符号以及操作这些符号的规则。」2. 少样本提示Few-shot prompting通过随请求一起提供 1 个或多个示例来引导模型。示例为模型提供期望输出的上下文、格式或风格帮助它理解具体任务并生成更准确、更相关的响应。提示「请以莎士比亚风格写一首诗。以下是几首莎士比亚十四行诗示例 十四行诗 18我能否将你比作夏日你比它更可爱、更温婉…… 十四行诗 116别让我承认两颗真心的结合有任何障碍。爱不是爱若它随境遇而变…… 十四行诗 132我爱你的眼睛它们仿佛在怜悯我明知你的心正以轻蔑折磨着我…… 现在请写一首关于月亮之美的十四行诗。」响应「夜空之中月亮轻柔闪耀银色的光芒温柔地洒下它的优雅……」示例的作用是给模型示范让模型从示例中推断出所需输出的内容、格式或风格。3. 思维链Chain-of-thought思维链的核心思想是带领模型走完一系列步骤教会它如何正确地做某事。看一个不使用思维链的例子提示「爱丽丝有 5 个苹果扔掉了 3 个给了鲍勃 2 个鲍勃又还回 1 个。爱丽丝现在有几个苹果」响应5模型回答 5 是错误的——正确答案是 1计算式5 − 3 − 2 1 1。如何教会模型正确计算思维链的应用步骤是给模型一个类似的例子展示计算过程示范如何正确计算再给出原始提示词。构造出的新提示词如下提示「丽莎有 7 个苹果扔掉了 1 个给了巴特 4 个巴特又还回 1 个 7 − 1 6 6 − 4 2 2 1 3 爱丽丝有 5 个苹果扔掉了 3 个给了鲍勃 2 个鲍勃又还回 1 个。爱丽丝现在有几个苹果」响应1注意我们写下了包含另一个示例、完整计算过程与原始问题的明显更长的提示词最终得到了正确答案 1。思维链因此是非常强大的技术。4. 生成知识Generated knowledge很多时候我们希望使用自己公司的数据来构造提示词一部分内容来自公司数据另一部分是真正关心的提示内容。典型做法是模板化在模板中用{{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将上述提示词交给 LLM会得到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模型把需求之外的人寿保险也加进了方案且总价超出预算。这提示我们需要优化提示词明确允许什么。经过**试错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.这个例子的要点在于即使使用生成知识这种基础技术多数情况下仍需优化提示词才能获得期望结果。在本课程仓库中这种模板 变量的思路也在工具层得到了印证共享模块 shared/python/api_utils.py 中的create_openai_client与create_azure_openai_client从环境变量如OPENAI_API_KEY、AZURE_OPENAI_ENDPOINT读取配置并创建客户端正是把运行时会变化的参数从代码中抽离、由外部数据注入的工程化实践。5. 最小到最大Least-to-most最小到最大的思想是把大问题分解为若干子问题引导 LLM 逐步攻克大问题。以数据科学为例提示如何分 5 步完成数据科学AI 助手的回答收集数据清洗数据分析数据绘制数据呈现数据与思维链相似它要求把问题拆解为一连串步骤并按顺序执行。6. 自我完善Self-refine批评结果对于生成式 AI 与 LLM不能无条件信任输出。LLM 只是在给出下一个最可能出现的词而不是正确的词。因此让模型自我批评是很好的做法。工作流程如下用初始提示词请 LLM 解决问题LLM 给出回答你批评该回答并请 AI 改进LLM 再次回答这次会考虑批评意见并提出改进方案。该过程可以无限次重复。示例提示「创建一个包含 products 和 customers 路由的 Python 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 的回答显著改进了初始建议的代码。7. 产婆式提示Maieutic prompting产婆式提示与自我完善类似但更侧重于让模型解释自己。其目标是减少 LLM 输出中的矛盾确保它得出正确的答案。工作流如下请 LLM 回答一个问题针对答案的每一部分请 LLM 更深入地解释如果出现矛盾丢弃矛盾的部分。重复第 2、3 步直到遍历所有部分并对答案满意为止。示例提示如何分 5 步制定缓解大流行的危机计划 LLM 回答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 本质上是非确定性的同一个提示词每次运行都可能得到不同结果。试着运行下面这个提示词「生成一个 Python Web API 的代码」第一次运行可能得到# 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()再次运行同一提示词会得到略有不同的响应——例如生成一个图书 API#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是 0 到 1 之间的数值0 最确定1 最多样默认值是0.7。把温度设为 0.1 后两次运行同一提示词「生成一个 Python Web API 的代码」#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()两次输出之间只有微小的差异。现在反过来把温度设为 0.9 再试# 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()温度 0.9 下的第二次尝试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可以看到温度越高两次运行结果的差异越大。除了温度之外还可以调整 top-k、top-p、repetition penalty、length penalty、diversity penalty 等参数来影响输出的多样性但这些超出了本课程的范围。从工程实现的角度看温度参数需要在使用 API 时显式传入。本课程仓库的工具模块 shared/python/api_utils.py 提供了create_openai_client读取OPENAI_API_KEY和create_azure_openai_client基于AZURE_OPENAI_ENDPOINT与AZURE_OPENAI_API_KEY构造指向endpoint/openai/v1/的客户端等封装配合 00-course-setup/02-setup-local.md 中的本地环境配置步骤即可在代码中按需传入temperature等采样参数实现同一应用、不同确定性策略的切换。良好实践除了上述技术向 LLM 发起提示时还应遵循以下良好实践明确上下文Specify context上下文很重要领域、主题等描述得越具体结果越好限制输出Limit the output如果需要特定数量的条目或特定长度请明确指定同时说明什么与怎么做Specify both what and how例如创建一个包含 products 和 customers 路由的 Python Web API并拆分成 3 个文件使用模板Use templates常用公司数据丰富提示词模板中可以包含用真实数据替换的变量正确拼写Spell correctly正确拼写能获得更好的响应。随着不断使用提示词你会逐渐形成自己的风格并能把上述技术组合出适合具体场景的方案。实战作业用自我完善技术改进代码以下是使用 Flask 构建简单 API 的 Python 代码即本课作业的起点见 05-advanced-prompts/python/aoai-assignment.pyfrom 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()请使用 GitHub Copilot 或 ChatGPT 等 AI 助手应用自我完善技术改进这段代码。作业提示构造改进请求的提示词时最好限制改进的数量也可以要求按特定方向改进例如架构、性能、安全等。本仓库给出了一个完整的参考答案 05-advanced-prompts/python/aoai-solution.py。该解答正是自我完善技术的落地结果在文件头部记录了 AI 提出的三条改进建议输入校验、敏感信息改用环境变量、实现错误处理随后实现了对应的改进——用flask-wtf与wtforms做输入校验、通过os.environ.get(FLASK_SECRET_KEY, os.urandom(32))从环境变量加载密钥、用app.errorhandler(400)提供错误响应、用escape()与render_template_string防止 XSS。此外仓库还提供了 JavaScript 版本的对照作业 05-advanced-prompts/javascript/assignment.js 与解答 05-advanced-prompts/javascript/solution.js后者记录了转换为 ES 模块移除未使用的 req 参数改用 HTTPS 与输入校验等两轮自我完善迭代展示了同一种技术在 Node.js/Express 技术栈上的迁移方式。知识检查为什么使用思维链chain-of-thought提示请指出 1 个正确答案和 2 个错误答案为了教会 LLM 如何解决问题。B为了教会 LLM 在代码中找出错误。C为了让 LLM 想出不同的解决方案。答案A选项 1因为思维链正是通过提供一系列步骤以及相似的问题及其解决方式向 LLM 展示如何解决问题。挑战把自我完善应用到自己的程序在作业中你已经使用了自我完善技术。现在请选择任意一个你自己构建的程序思考想对它应用哪些改进然后使用自我完善技术应用这些建议的变更。结果是变好了还是变坏了继续学习完成本课后你可以进入第 6 课把提示工程的知识应用到实际应用中构建文本生成应用。整个课程共 21 课覆盖从提示工程、检索增强生成RAG到微调与 AI Agent 的完整知识体系仓库根目录的 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),仅供参考