ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Generative AI for Beginners 第 5 课:掌握高级提示词(Advanced Prompts)七大技巧与输出控制实战

Generative AI for Beginners 第 5 课:掌握高级提示词(Advanced Prompts)七大技巧与输出控制实战 Generative AI for Beginners 第 5 课掌握高级提示词Advanced Prompts七大技巧与输出控制实战【免费下载链接】generative-ai-for-beginners21 Lessons, Get Started Building with Generative AI项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai-for-beginners本文对应本仓库 21 课课程体系中的第 5 课关联文档为 translations/hr/05-advanced-prompts/README.md英文原版见 05-advanced-prompts/README.md。在上一课《提示词工程基础》见 04-prompt-engineering-fundamentals/README.md中我们学习了提示词Prompt是生成式 AI 应用的编程接口提示词工程是设计并优化输入以引导模型产生稳定、高质量输出的过程。本课将把会写提示词升级为理解为什么某个提示词比另一个更好系统掌握7 种可应用于任何 LLM 的基础提示词技术并学会通过temperature 等采样参数在多样输出与确定性输出之间精确调节最终配合仓库中可运行的 Python/JavaScript 作业完成一次完整的自我精炼self-refine实战。一、先回顾提示词工程的两个步骤第 4 课给出了提示词工程的定义提示词工程Prompt Engineering是通过提供更有用的指令或上下文引导模型给出更相关回答的过程。在此基础上写提示词其实包含两个步骤构造Constructing通过提供相关上下文来构建提示词优化Optimizing逐步改进提示词逼近理想结果。第 4 课还解释了为什么提示词工程如此重要LLM 的响应是随机的stochastic——同一个提示词在不同模型、甚至同一模型的多次调用中可能产生不同结果模型可能编造fabrication不存在的事实不同模型的能力存在差异。这三类挑战正是本课技巧要解决的问题。二、从一个简单提示词看起简单提示词的局限先看一个最基础的提示词生成 10 个关于地理的问题。Generate 10 questions on geography.这个看似简单的提示词其实已经隐含了两种提示词技术上下文Context你指定了主题是地理限制输出Limiting the output你要求最多 10 个问题。然而你可能仍然得不到满意的结果原因在于主题过宽Big topic你不知道生成的问题是关于国家、首都还是河流格式不受控Format如果希望问题以特定格式如 JSON、列表、选择题呈现这个提示词完全没有约束。这说明创建提示词时有大量因素需要考量。接下来进入本课核心——7 种可复用的高级提示词技术。需要先明确一个前提提示词能力是 LLM 的涌现属性emergent property——它不是模型内置的显式功能而是我们在使用模型过程中发现的规律。三、七大高级提示词技术1. Zero-shot 提示词零样本提示这是最基础的形式单个提示词完全依靠 LLM 的训练数据作答不给任何示例。它往往是你刚接触 LLM 时就在使用的方式。提示词什么是代数What is Algebra?回答代数是数学的一个分支研究数学符号以及操作这些符号的规则。2. Few-shot 提示词少样本提示Few-shot 通过在请求中附带一个或多个示例来引导模型。它本质上仍是单个提示词但注入了与任务相关的额外数据为 LLM 提供输出所需的上下文、格式或风格帮助模型理解具体任务并生成更准确、更相关的回答。提示词写一首莎士比亚风格的诗。这里有几个莎士比亚十四行诗的例子 Sonnet 18Shall I compare thee to a summers day? Thou art more lovely and more temperate... Sonnet 116Let me not to the marriage of true minds Admit impediments. Love is not love Which alters when it alteration finds... Sonnet 132Thine 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,...注意示例不仅是答案参考更是风格与格式的锚点。示例越贴近目标输出模型的模仿越到位。3. Chain-of-thought 提示词思维链思维链的精髓是带领 LLM 一步一步推理让它真正学会怎么做而非直接猜答案。看一个经典的反例提示词Alice 有 5 个苹果扔掉了 3 个给了 Bob 2 个Bob 又还回来 1 个Alice 现在有几个苹果回答5回答 5 是错误的——正确计算是 5 − 3 − 2 1 1。模型跳过了过程直接猜了一个高频答案。应用思维链只需要三步给 LLM 一个相似的例题展示计算过程及正确算法再给出原始问题。实践如下提示词Lisa 有 7 个苹果扔掉了 1 个给了 Bart 4 个Bart 又还回来 1 个 7 − 1 6 6 − 4 2 2 1 3 Alice 有 5 个苹果扔掉了 3 个给了 Bob 2 个Bob 又还回来 1 个Alice 现在有几个苹果回答1可以看到我们写出了明显更长的提示词——包含另一个例题、逐步计算再回到原始问题——最终得到正确答案 1。思维链是极其强大的技术它的价值在于把隐式的推理显式化为模型可循的步骤。4. Generated knowledge 提示词生成知识 / 企业数据注入很多时候我们希望提示词注入自己公司的数据一部分来自企业另一部分才是真正关心的问题。这时使用**模板template**是标准做法——模板中用{{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 insuranceLLM 的输出是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人寿保险而这超出了预算$1000 预算却报出 $1200 总价。这说明提示词对允许范围的表述不够清晰需要优化。经过试错trial and error我们改进了提示词——为每条产品显式标注type与cost并使用restrict限制关键字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这次得到了符合预期的输出Given the budget and requirements, we suggest the Car, Cheap insurance product which costs 500 USD per month.本案例的启示即使使用了生成知识这样的基础技巧大多数情况下仍需对提示词进行迭代优化才能得到理想结果。添加type/cost字段、使用restrict这类语义明确的关键词都能帮助 LLM 更准确地理解意图。5. Least-to-most 提示词从简到繁 / 问题分解该技术的思想是把大问题拆解为若干子问题引导 LLM 逐个击破从而攻克复杂任务。例如在数据科学场景中提示词如何分 5 步完成数据科学AI 助手的回答收集数据Collect data清洗数据Clean data分析数据Analyze data绘制数据Plot data呈现数据Present data它与思维链相似但更强调先列出子问题清单、再按序执行的结构化拆解。6. Self-refine 提示词自我精炼先批判再改进生成式 AI 的输出不能无条件信任——LLM 只是在告诉你下一句最可能说什么而非什么是对的。因此一个好习惯是让 LLM 自我批判这就是 self-refine 技术。工作流程如下初始提示词让 LLM 解决一个问题LLM 给出回答你批判该回答并要求 AI 改进LLM 再次回答——这次它会考虑你的批评并给出改进方案。该过程可无限重复。示例提示词创建一个带 products 和 customers 路由的 Python Web APIAI 第一版回答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 的第二次回答正是因为对第一次回答进行了批判而显著提升——修正了导入语句、补充了入口函数、引入了 f-string 格式化。7. Maieutic 提示词助产式提示让模型解释自己Maieutic 与 self-refine 类似但更侧重于要求 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此时为了确认 LLM 的正确性要求它进一步解释第一个风险并期望与上面答案一致提示词疫情中最大的风险是什么为什么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永远要验证输出。四、控制输出的多样性理解 temperature 参数LLM 天生非确定LLM 本质上是**非确定性nondeterministic**的同一个提示词每次运行都会得到略有不同的结果。试运行生成一个 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()再次运行同一提示词输出变成了一个Books 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 调节确定性如果希望输出更可预测更确定最直接的参数是temperature取值范围0 到 10 最确定每次几乎相同1 最多样默认值为 0.7。实验一temperature 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()两次输出只有微小差异路由名、函数名、注释略有不同整体结构高度一致——这正是低温度 高确定性的体现。实验二temperature 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()第二次运行节选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两次结果差异巨大第二次甚至演化出了完整的 Books API 与书籍数据列表。可见高温度下输出的多样性能达到极致。补充说明除 temperature 外还有更多可调节输出多样性的参数如top-k、top-p、重复惩罚repetition penalty、长度惩罚length penalty、多样性惩罚diversity penalty但它们超出了本课程的教学范围。如果你想在自己动手的代码里直观感受 temperature 的效果可以对照第 6 课 构建文本生成应用 中基于openai库的示例在请求参数中显式传入temperature字段。五、提示词的良好实践Good Practices除了上述 7 种技术还有一些跨场景适用的实践经验明确指定上下文Specify context上下文至关重要能指定的领域domain、主题topic等越具体越好限制输出Limit the output想要特定数量的条目或特定长度时明确写出来同时说明做什么与怎么做Specify both what and how例如创建一个带 products 和 customers 路由的 Python Web API并拆分为 3 个文件——既指定目标也指定组织方式使用模板Use templates需要把公司数据注入提示词时用带变量的模板{{variable}}在运行时替换为真实数据拼写正确Spell correctlyLLM 也许能容忍拼写错误并给出正确回答但拼写正确的提示词通常能获得更好的回答。六、实战作业用 self-refine 改进一个 Flask API仓库为本课提供了完整的作业代码与解决方案。作业起点是一个极简的 Flask API见 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 助手运用本课学到的self-refine 技术改进上述代码。技巧提示构造请求改进的提示词时最好限制改进条数也可以要求按特定方向改进例如架构architecture、性能performance、安全性security等。仓库参考解法05-advanced-prompts/python/aoai-solution.py展示了一条典型的 self-refine 迭代链路先让 AI 提出 3 条改进建议再要求以安全为导向重构。最终代码把建议落到了实处import os from flask import Flask, render_template_string from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired, Length, Email from markupsafe import escape app Flask(__name__) # SECURITY: Load secret key from environment variable instead of hardcoding app.config[SECRET_KEY] os.environ.get(FLASK_SECRET_KEY, os.urandom(32)) class HelloForm(FlaskForm): name StringField(Name, validators[DataRequired(), Length(min3)]) email StringField(Email, validators[DataRequired(), Email()]) submit SubmitField(Submit) # Form template with proper CSRF protection and escaping FORM_TEMPLATE !DOCTYPE html html headtitleHello Form/title/head body form methodPOST {{ form.hidden_tag() }} p{{ form.name.label }} {{ form.name(size32) }} {% for error in form.name.errors %}span stylecolor: red;[{{ error }}]/span{% endfor %}/p p{{ form.email.label }} {{ form.email(size32) }} {% for error in form.email.errors %}span stylecolor: red;[{{ error }}]/span{% endfor %}/p p{{ form.submit() }}/p /form /body /html app.route(/, methods[GET, POST]) def hello(): form HelloForm() if form.validate_on_submit(): # SECURITY: Use escape() to prevent XSS attacks safe_name escape(form.name.data) safe_email escape(form.email.data) return fHello, {safe_name} ({safe_email})! # SECURITY: Use Flasks render_template_string for proper escaping return render_template_string(FORM_TEMPLATE, formform) app.errorhandler(400) def bad_request(error): return Bad request, 400 if __name__ __main__: app.run()对照起点代码可以清楚看到 self-refine 引入的改进维度输入校验flask-wtf WTForms 验证器防止恶意输入、密钥安全从环境变量加载SECRET_KEY避免硬编码泄露、错误处理app.errorhandler(400)返回有意义的错误信息、XSS 防护escape()转义与render_template_string自动转义。如果使用 JavaScript 技术栈仓库还提供了 Express 版本起点见 05-advanced-prompts/javascript/assignment.js解法见 05-advanced-prompts/javascript/solution.js。JS 解法同样演示了两轮 self-refine——第一轮聚焦代码质量ES 模块化、去掉未使用参数、改进日志信息第二轮聚焦安全环境变量、express-validator 输入校验、HTTPS 与证书加载与 Python 解法的迭代思路完全一致。七、知识检查为什么使用思维链问为什么要使用 chain-of-thought思维链提示从以下选项中选出 1 个正确答案和 2 个错误答案教会 LLM 如何解决问题B教会 LLM 在代码中查找错误C指示 LLM 提出不同的解决方案。答正确答案是1。因为思维链的核心是通过提供一系列步骤、相似的问题及它们的解法向 LLM 展示如何解决问题——而非让它找 bug 或发散创意。八、挑战与下一步你刚刚在作业中使用了 self-refine 技术。现在做个延伸挑战任取一个你自己构建过的程序先思考你希望对其施加哪些改进然后用 self-refine 技术让 AI 助手实施这些改进最后评估结果——是变好了还是变差了完成本课后第 6 课将把提示词工程知识落地为真实的文本生成应用——在那里你写的每一个提示词、调校的每一个 temperature 值都会变成可运行的代码。【免费下载链接】generative-ai-for-beginners21 Lessons, Get Started Building with Generative AI项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai-for-beginners创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表