本页目录

📗 第 4 章 · Prompt evaluation

所属课程:课程 004 Building with the the AI API
官方章节名:Prompt evaluation
课时数:8
CCAR-F 主命中领域:D3 20%
归档日期:2026-10-15


📋 本章课时清单

本章序 全课序 类型 课时 lesson ID 直链 精译
1 16 🎬 视频 Prompt evaluation 287731 直链 ✅ 已精译
2 17 🎬 视频 A typical eval workflow 287736 直链 ✅ 已精译
3 18 🎬 视频 Generating test datasets 287739 直链 ✅ 已精译
4 19 🎬 视频 Running the eval 287743 直链 ✅ 已精译
5 20 🎬 视频 Model based grading 287742 直链 ✅ 已精译
6 21 🎬 视频 Code based grading 287737 直链 ✅ 已精译
7 22 🎬 视频 Exercise on prompt evals 287738 直链 ⏸ 不补
8 23 📝 测验 Quiz on prompt evaluation 289118 直链 ⏸ 不补

🎯 本章考点提示

D3(20%)主战场之一,8 课时。本课独有高价值章:官方系统讲评估工作流——测试集生成、model-based grading、code-based grading。

⭐ CCAR-F 五领域里没有单独的「评估」域,但「把评估做成验收标准」是架构题高频问法,本章是唯一系统讲它的地方。


📖 逐课精译

课时 1 · Prompt evaluation

类型:🎬 视频 | lesson ID:287731 | 官方直链

🎯 本课学习目标(据官方段落反推)

  1. 能一句话区分 prompt engineering 与 prompt evaluation:一个管「怎么写」,一个管「怎么测」。
  2. 能复述 engineering 的三类技法,以及 evaluation 的三种自动化手段。
  3. 能完整说出写完提示词后的三条路,并讲清每条的代价与风险。
  4. 能解释为什么工程师(包括讲师本人)会掉进测试陷阱:低估真实用户的边界情况。
  5. 能说出 Option 3 的四项收益与一项代价,以及它的最终目标。

一、开场:写好提示词只是开始

官方原句:When working with the AI, writing a good prompt is just the beginning. To build reliable AI applications, you need to understand two critical concepts: prompt engineering and prompt evaluation. Prompt engineering gives you techniques for writing better prompts, while prompt evaluation helps you measure how well those prompts actually work.

精译:使用 the AI 时,写出一个好的提示词只是开始。要构建可靠的 AI 应用,你需要理解两个关键概念:提示词工程与提示词评估。提示词工程给你写出更好提示词的技法,而提示词评估帮你度量这些提示词实际效果如何。

⭐ 一句定调:just the beginning——整个第 4 章的立论前提就在这四个字里。考题若问「写好提示词之后还缺什么」,答案是评估。🔗 课程 002 第 8 课 Diligence(勤勉)——4D 框架里的 D,讲的正是对输出负责、做验证,与本章呼应。


二、⭐⭐ 两个概念的分工(Prompt Engineering vs Prompt Evaluation)

官方原句:Prompt engineering is your toolkit for crafting effective prompts. It includes techniques like:

  • Multishot prompting
  • Structuring with XML tags
  • Many other best practices**

These techniques help the AI understand exactly what you're asking for and how you want it to respond.

精译:提示词工程是你精心编写有效提示词的工具箱。它包含的技法例如:多样例提示(Multishot prompting)、用 XML 标签做结构化、以及许多其他最佳实践。这些技法帮助 the AI 准确理解你到底在要什么,以及你希望它怎么回应。

官方原句:Prompt evaluation takes a different approach. Instead of focusing on how to write prompts, it's about measuring their effectiveness through automated testing. You can:

  • Test against expected answers
  • Compare different versions of the same prompt
  • Review outputs for errors

精译:提示词评估走的是另一条路。它不关注怎么写提示词,而是通过自动化测试来度量提示词的有效性。你可以:对照预期答案进行测试、比较同一提示词的不同版本、检查输出中的错误。

维度 Prompt Engineering Prompt Evaluation
关注点 怎么写(how to write) 怎么测(how well it works)
形态 工具箱 / 技法 自动化测试
具体手段 Multishot、XML 标签、最佳实践 对照预期答案、版本对比、查错
产出 一个提示词 一个分数 / 一组指标

⭐⭐ 两个术语细节(D3 易混点): 1. 官方用 Multishot prompting,不是常见的 few-shot。两者同义,但考试按官方用词认,看到 Multishot 要能对上 few-shot。 2. XML tags 本课只是点名,系统讲法在第 5 章《Prompt engineering techniques》。本课属于先埋点、后展开。


三、⭐⭐ 写完提示词后的三条路(Three Paths After Writing a Prompt)

官方原句:Once you've drafted a prompt, you typically face three options for what to do next:

选项 官方描述 官方给的评价 风险
Option 1 Test the prompt once and decide it's good enough carries a significant risk of breaking in production when users provide unexpected inputs** 最高
Option 2 Test a few times and tweak it to handle a corner case or two** better than option 1,但 users will often provide very unexpected outputs you haven't considered 中
Option 3 Run the prompt through an evaluation pipeline to score it, then iterate based on objective metrics** requires more work and cost,但 gives you **much more confidence 最低

精译:

  • 选项 1:只测一次就认为够用了。当用户给出意外输入时,这在生产环境出问题的风险相当大。
  • 选项 2:测几次,再针对一两个边界情况修修补补。比选项 1 好,但用户常常会给出你根本没考虑过的、非常意外的输出。
  • 选项 3:把提示词送入评估流水线打分,然后依据客观指标迭代。这条路需要更多工作量与成本,但能让你对提示词的可靠性有高得多的信心。

⭐⭐ 本课第一号考点(D3/D5): Option 3 的代价是「更多工作与成本」,不是「效果不好」。 考题若问「为什么很多团队不做评估」,标准答案是前期投入大(时间 + 测试基础设施),而不是「评估没用」。官方对三条路的定性里,Option 3 是唯一被推荐的。


四、⭐⭐ 为什么多数工程师掉进测试陷阱(Why Most Engineers Fall Into Testing Traps)

官方原句:Options 1 and 2 are common traps that all engineers fall into, myself included. It's natural to write a prompt for a serious application and not test it thoroughly enough. We tend to underestimate how many edge cases real users will encounter.

精译:选项 1 和 2 是所有工程师都会掉进去的常见陷阱,包括我自己。为一个正经应用写好提示词却没有测试得足够彻底,这是人之常情。我们往往低估真实用户会碰到多少边界情况。

官方原句:The reality is that when you deploy a prompt to production, users will interact with it in ways you never anticipated. What seemed like a solid prompt during your limited testing can quickly break down when faced with the full variety of real-world inputs.

精译:现实是,当你把一个提示词部署到生产环境,用户会以你从未预料到的方式与它交互。在你有限的测试中看起来很扎实的提示词,一旦面对真实世界输入的全部分多样性,可能很快就崩掉。

⭐⭐ 两句原话要能认出来(D5): 1. all engineers fall into, myself included——讲师自承。这句的作用是排除「只有新手才犯错」的误解:陷阱是行业性的。 2. never anticipated / full variety of real-world inputs——官方对风险的定量描述是「你有限的测试 vs 真实输入的全部多样性」。考题问「为什么有限的测试不够」,答案是测试覆盖远小于真实输入的分布。


五、⭐⭐ 评估优先(The Evaluation-First Approach)

官方原句:Option 3 represents a more systematic approach to prompt development. By running your prompt through an evaluation pipeline, you get objective metrics about its performance across a broader range of test cases. This data-driven approach lets you:

  • Identify weaknesses before they become production issues
  • Compare different prompt versions objectively
  • Iterate with confidence based on measurable improvements
  • Build more reliable AI applications

精译:选项 3 代表一种更系统化的提示词开发方式。通过评估流水线,你能得到提示词在更广的测试用例范围上表现的客观指标。这种数据驱动的方式让你能够:

  • 在弱点变成生产事故之前就识别出来
  • 客观地比较提示词的不同版本
  • 基于可度量的改进、带着信心去迭代
  • 构建更可靠的 AI 应用

官方原句:While this approach requires more upfront investment in time and testing infrastructure, it pays dividends in the reliability and robustness of your final application. The goal is to catch problems during development rather than after your users encounter them.

精译:虽然这种方式需要在时间与测试基础设施上做更多前期投入,但它会在最终应用的可靠性与健壮性上带来回报。其目标是在开发阶段就发现问题,而不是等用户碰到之后。

⭐⭐ 本课第二号考点(D3/D5): * 四项收益(枚举题高频):提前识别弱点 → 客观比较版本 → 基于可度量改进迭代 → 构建更可靠应用。 * 一个代价:upfront investment(时间 + 测试基础设施)。 * 最终目标(一句话):catch problems during development rather than after your users encounter them——即左移(shift left)。这是本章最重要的一句话结论,几乎可直接当简答题答案。


六、⭐ Key Takeaways(本课官方无独立 Key Takeaways 段,据正文反推)

  1. 写好提示词只是开始;engineering 管怎么写,evaluation 管怎么测。
  2. 写完提示词有三条路,只有 Option 3(评估流水线)被官方推荐;它的代价是成本,不是效果。
  3. 选项 1、2 是全行业通病,根因是低估真实用户的边界情况。
  4. 评估优先带来客观指标 + 数据驱动,四项收益记住。
  5. 终极目标是开发期发现问题,而非等用户碰到。

🔤 本课新生词(临时小表 · 已回灌 30-单词表/04- 第 4 章分组)

星 词汇 音标 本课义 备注
⭐⭐ prompt engineering — 提示词工程(怎么写的工具箱) 本课两概念之一
⭐⭐ prompt evaluation — 提示词评估(怎么测的度量) 本课两概念之一
⭐⭐ reliable (adj.) / reliability (n.) /rɪˈlaɪəbl/ /rɪˌlaɪəˈbɪləti/ 可靠的 / 可靠性 全章目标词
⭐ toolkit (n.) /ˈtuːlkɪt/ 工具箱 your toolkit for crafting
⭐ craft (v.) / crafting /kræft/ 精心编写
⭐⭐ effective (adj.) / effectiveness (n.) /ɪˈfektɪv/ 有效的 / 有效性 measuring their effectiveness
⭐⭐ multishot prompting — 多样例提示(官方用词,≈ few-shot) ⚠️ 官方不说 few-shot
⭐⭐ XML tags — XML 标签(结构化组织) 第 5 章展开
⭐ best practices — 最佳实践
⭐⭐ measure (v.) /ˈmeʒər/ 度量、衡量 evaluation 的核心动作
⭐⭐ automated testing — 自动化测试 evaluation 的实现形态
⭐ expected answers — 预期答案(测试基准)
⭐ compare (v.) /kəmˈper/ 比较(同一提示词的不同版本)
⭐ review (v.) /rɪˈvjuː/ 检查、复核 review outputs for errors
⭐ draft (v.) /dræft/ 起草 once you've drafted a prompt
⭐⭐ significant risk — 重大风险 Option 1 的定性
⭐⭐ break in production — 在生产环境出问题
⭐⭐ corner case / edge case — 边界情况 / 极端案例 Option 2 只覆盖一两个
⭐⭐ evaluation pipeline — 评估流水线 Option 3 的载体
⭐⭐ iterate (v.) / iteration (n.) /ˈɪtəreɪt/ 迭代 iterate based on objective metrics
⭐⭐ objective metrics — 客观指标 ↔ 主观印象
⭐⭐ trap (n.) / testing traps — 陷阱 all engineers fall into
⭐ fall into (v. phr.) — 落入、掉进
⭐ thoroughly (adv.) /ˈθɜːroʊli/ 彻底地 not test it thoroughly enough
⭐⭐ underestimate (v.) /ˌʌndərˈestɪmeɪt/ 低估 陷阱根因
⭐ deploy (v.) / deployment (n.) /dɪˈplɔɪ/ 部署(上线)
⭐⭐ anticipate (v.) /ænˈtɪsɪpeɪt/ 预料 ways you never anticipated
⭐⭐ break down (v. phr.) — 崩溃、失效 can quickly break down
⭐⭐ systematic (adj.) /ˌsɪstəˈmætɪk/ 系统化的 Option 3 的定性
⭐⭐ data-driven (adj.) — 数据驱动的 ↔ 拍脑袋
⭐ weakness (n.) / weaknesses (n. pl.) /ˈwiːknəs/ 弱点 identify weaknesses
⭐⭐ measurable (adj.) /ˈmeʒərəbl/ 可度量的 measurable improvements
⭐⭐ upfront (adj.) /ˌʌpˈfrʌnt/ 前期的、预先的 upfront investment
⭐⭐ pay dividends — 带来回报、产生效益 官方收尾比喻
⭐⭐ robustness (n.) / robust (adj.) /roʊˈbʌstnəs/ 健壮性、鲁棒性

课时 2 · A typical eval workflow

类型:🎬 视频 | lesson ID:287736 | 官方直链

🎯 本课学习目标(据官方段落反推)

  1. 能按序说出评估工作流的五个步骤,并说出每步的输入输出。
  2. 能解释「先小规模起步、再按需扩展」的思想,以及为什么本课用三题这种小数据集。
  3. 能说明评估数据集应该装什么(代表生产场景的样本输入),以及它怎么被插进提示词模板。
  4. 能复述grader(评分器)的工作方式与 1–10 打分,并会算平均分。
  5. 能说出本工作流的核心收益:数值化比较版本、用掉拍脑袋、确认改动是改进而非只是不同。

一、开场:五步工作流总览

官方原句:A typical prompt evaluation workflow follows five key steps that help you systematically improve your prompts through objective measurement. While there are many different ways to assemble these workflows and various open source and paid tools available, understanding the core process helps you start small and scale up as needed.

精译:一个典型的提示词评估工作流遵循五个关键步骤,帮助你通过客观度量来系统化地改进提示词。虽然组装这些工作流的方式多种多样,也有各种开源与付费工具可用,但理解核心流程能让你从小处起步,按需扩展。

⭐ 两个前置观点(D3): 1. 工具很多(开源/付费),但先懂核心流程——本课刻意不绑定任何具体工具,讲的是方法论骨架。 2. start small and scale up——所以本课例子只有三个问题。考题若问「为什么官方示例用这么小的数据集」,答案是起步阶段重在理解流程,规模可随需扩展(真实评估可能成千上万条)。


二、⭐⭐ 五步工作流(The Five Steps)

Step 1 · Draft a Prompt(起草提示词)

官方原句:Start by writing an initial prompt that you want to improve.

prompt = f"""
Please answer the user's question:

{question}
"""

精译:先写一个你想改进的初始提示词。这个基础提示词将作为我们测试与改进的基线(baseline)。

⭐ 注意 {question} 是占位符:提示词是模板,question 会在后续步骤里被数据集里的样本插值(interpolate)进去。这与课时 6/8 里 chat() 的 system/temperature 参数一样,都是「参数 → 行为」的 D3 映射题素材。


Step 2 · Create an Eval Dataset(创建评估数据集)

官方原句:Your evaluation dataset contains sample inputs that represent the types of questions or requests your prompt will handle in production. The dataset should include questions that will be interpolated into your prompt template.

精译:评估数据集包含样本输入,代表你的提示词在生产环境中将要处理的那类问题或请求。数据集里的问题会被插值进你的提示词模板。

官方示例三题: * "What's 2+2?" * "How do I make oatmeal?" * "How far away is the Moon?"

官方原句:In real-world evaluations, you might have tens, hundreds, or even thousands of records. You can assemble these datasets by hand or use the AI to generate them for you.

精译:在真实评估中,你可能有几十、几百甚至上千条记录。这些数据集可以手工组装,也可以让 the AI 替你生成。

⭐⭐ 三个必记点(D3): 1. 数据集的本质:代表生产环境的输入分布——不是随便找的问题,而是「真实用户会问的那类」。这直接呼应课时 1 的 full variety of real-world inputs。 2. 规模:真实评估可达成百上千条(官方给了 tens, hundreds, or even thousands 三个量级)。 3. 两种来源:手工(by hand)或 AI 生成(the AI to generate)——后者正是下一课《Generating test datasets》的主题,先埋点。


Step 3 · Feed Through the AI(送入 the AI)

官方原句:Take each question from your dataset and merge it with your prompt template to create complete prompts. Then send each one to the AI to get responses.

精译:把数据集里的每个问题与你的提示词模板合并,生成完整提示词,再逐个发给 the AI 获取响应。

官方示例:第一个问题合并后变成—— Please answer the user's question: What's 2+2?

三种问题分别得到:数学题 2 + 2 = 4、燕麦做法、月球距离。注意:这一步不评分,只是收集原始输出。


Step 4 · Feed Through a Grader(送入评分器)

官方原句:The grader evaluates the quality of the AI's responses by examining both the original question and the AI's answer. This step provides objective scoring, typically on a scale from 1 to 10, where 10 represents a perfect answer and lower scores indicate room for improvement.

精译:评分器通过同时检查原始问题和 the AI 的回答来评估输出质量。这一步提供客观打分,通常是 1 到 10 分:10 分代表完美答案,低分表示有改进空间。

官方示例打分: * 数学题:10(完美) * 燕麦题:4(需改进) * 月球题:9(很好)

平均分:(10 + 4 + 9) ÷ 3 = 7.66

⭐⭐ 本课第一号考点(D1/D3): grader 的输入是「原始问题 + the AI 回答」两者——不是只看输出。这句常被考题偷换为「grader 只检查模型输出」,判错。打分区间是 1–10(注意:不是 0–1,也不是 0–100)。


Step 5 · Change Prompt and Repeat(改提示词并重跑)

官方原句:Now that you have a baseline score, you can modify your prompt and run the entire process again to see if your changes improve performance.

精译:现在你有了基线分数,就可以修改提示词并重跑整个流程,看你的改动是否提升了表现。

官方改进示例(加一句指导): ```python prompt = f""" Please answer the user's question:

{question}

Answer the question with ample detail """ ```

用同一流程重跑后,平均分可能从 7.66 升到 8.7,说明新增的指令确实帮助 the AI 给出了更好的回答。

⭐⭐ 两个关键词(D3): 1. baseline score——Step 5 的一切都建立在第一步先测出基线之上。没有基线,「改进」无从谈起。 2. 同一流程重跑——关键在控制变量:只改提示词,数据集与 grader 不变,分数变化才能归因于提示词改动。


三、⭐⭐ Prompt Scoring(打分带来的核心收益)

官方原句:The key benefit of this workflow is getting objective measurements of prompt performance. You can:

  • Compare different prompt versions numerically
  • Use the version with the best score**
  • Continue iterating to find even better approaches

精译:这个工作流最关键的好处是获得提示词表现的客观度量。你可以:用数值比较不同的提示词版本、采用得分最高的版本、持续迭代寻找更好的方案。

官方原句:This systematic approach removes guesswork from prompt engineering and gives you confidence that your changes are actually improvements rather than just different variations.

精译:这种系统化方法去掉了提示词工程里的「拍脑袋」(guesswork),并给你信心:你的改动是真正的改进,而非仅仅是不同的变化。

⭐⭐ 本课第二号考点(D3/D5): * 三个收益:数值化比较版本 → 采用最优版 → 持续迭代。 * 一句话定性:removes guesswork + improvements rather than just different variations。这是「为什么要用数值打分」的标准答案——主观感觉分不清「改进」和「只是变了」。


四、⭐ 五步速记(Key Takeaways · 反推)

步 名称 输入 输出
1 Draft a Prompt — 初始提示词(模板)
2 Create an Eval Dataset 生产输入分布 样本问题集
3 Feed Through the AI 问题 × 模板 每题的原始回答
4 Feed Through a Grader 问题 + 回答 1–10 分,平均分
5 Change Prompt and Repeat 基线分 新版本 + 新分

一句话:模板 → 数据集 → 生成 → 打分 → 改模板重跑。与课时 1 的 Option 3(evaluation pipeline)直接衔接——本课就是 Option 3 的具体五步实现。


🔤 本课新生词(临时小表 · 已回灌 30-单词表/04- 第 4 章分组)

星 词汇 音标 本课义 备注
⭐⭐ workflow (n.) /ˈwɜːrkfloʊ/ 工作流、流程 五步评估流程
⭐⭐ baseline (n.) / baseline score /ˈbeɪslaɪn/ 基线(分) Step 1/5 的关键
⭐⭐ dataset (n.) / eval dataset /ˈdeɪtəset/ 数据集(评估集) Step 2 的产物
⭐⭐ sample inputs — 样本输入 代表生产输入分布
⭐⭐ interpolate (v.) / interpolated /ɪnˈtɜːrpəleɪt/ 插值、插入(进模板) {question} 占位
⭐⭐ grader (n.) /ˈɡreɪdər/ 评分器 Step 4 的核心
⭐⭐ objective scoring — 客观打分 1–10 分
⭐ scale (n.) / scale from 1 to 10 /skeɪl/ 刻度、量表 打分区间
⭐ perfect answer — 完美答案(= 10 分)
⭐ room for improvement — 改进空间 低分的含义
⭐ average score — 平均分 (10+4+9)÷3=7.66
⭐⭐ assemble (v.) / assembled /əˈsembl/ 组装、汇集 组装工作流/数据集
⭐⭐ by hand — 手工(做) ↔ AI 生成
⭐⭐ merge (v.) /mɜːrdʒ/ 合并 问题 × 模板
⭐⭐ feed through (v. phr.) — 送入、经过(某流程) feed through the AI/grader
⭐⭐ modify (v.) /ˈmɑːdɪfaɪ/ 修改 Step 5 的动作
⭐⭐ repeat (v.) /rɪˈpiːt/ 重跑、重复 控制变量的重跑
⭐ numerically (adv.) /nuːˈmerɪkli/ 用数值、以数字方式 compare numerically
⭐⭐ remove guesswork — 去掉「拍脑袋」 核心收益
⭐⭐ confidence (n.) /ˈkɑːnfɪdəns/ 信心 gives you confidence
⭐⭐ variation (n.) /ˌveriˈeɪʃn/ 变化、变体 improvements rather than just different variations
⭐ open source / paid tools — 开源 / 付费工具 本课不绑定工具
⭐⭐ start small and scale up — 小处起步、按需扩展 官方方法论
⭐ ample (adj.) / ample detail /ˈæmpl/ 充足的、充分的 改进提示词示例

课时 3 · Generating test datasets

类型:🎬 视频 | lesson ID:287739 | 官方直链

🎯 本课学习目标(据官方段落反推)

  1. 能说出评估数据集的结构(JSON 对象数组,含 task 属性)与两种来源(手工 / AI 生成)。
  2. 能说明为什么生成测试数据时优先用更快的模型(如 Haiku)。
  3. 能复述数据集生成函数的写法,以及它如何复用课时 11 的预填 + 停止序列技巧来解析 JSON。
  4. 能说出数据集生成的约束条件(单函数 / 单 JSON / 单 regex、不写大量代码)。
  5. 能写出把数据集落盘的代码(json.dump),以及这样做的好处。

一、开场:先定目标,再生成测试数据

官方原句:Building a custom prompt evaluation workflow starts with creating a solid prompt and then generating test data to see how well it performs.

精译:构建自定义的提示词评估工作流,始于创建扎实的提示词,然后生成测试数据来看它表现如何。

⭐ 承上启下:本课接的是课时 2 的 Step 2(Create an Eval Dataset)——把「用 the AI 生成数据集」这个埋点具体化。


二、⭐⭐ 设定目标(Setting Up the Goal)

官方原句:Our prompt needs to assist users in writing three specific types of output for AWS use cases:

  • Python code
  • JSON configuration files
  • Regular expressions

精译:我们的提示词需要帮助用户为 AWS 用例写出三类特定输出:Python 代码、JSON 配置文件、正则表达式(Regular expressions)。

官方原句:The key requirement is that when a user requests help with a task, we return clean output in one of these formats without any extra explanations, headers, or footers.

精译:关键需求是——当用户请求帮助时,我们返回其中一种格式的干净输出,不带任何额外的解释、页眉或页脚。

官方示例提示词(版本 1): python prompt = f""" Please provide a solution to the following task: {task} """

⭐⭐ 与课时 11《Structured data》的强呼应(D3):这个需求完全复用了课时 11 的判据——clean output without explanations。课时 11 讲的是「怎么让输出干净」,本课是「为评估这种干净输出而生成测试数据」。headers, or footers 在这里是非代码输出的代称,指模型爱加的解释性框架。


三、⭐⭐ 评估数据集的结构与来源(Creating an Evaluation Dataset)

官方原句:An evaluation dataset contains inputs that we'll feed into our prompt. For each combination of prompt and input, we'll run the prompt and analyze the results.

精译:评估数据集包含我们要送入提示词的输入。对「提示词 × 输入」的每个组合,我们运行提示词并分析结果。

官方原句:Our dataset will be an array of JSON objects, where each object contains a "task" property describing what we want the AI to accomplish. We can either create this dataset by hand or generate it automatically using the AI.

精译:我们的数据集将是一个 JSON 对象数组,每个对象包含一个 task 属性,描述我们想让 the AI 完成什么。我们可以手工创建,也可以用 the AI 自动生成。

官方原句:Since we're generating test data, this is a perfect opportunity to use a faster model like Haiku instead of the full the AI model.

精译:因为我们是在生成测试数据,这是使用 Haiku 这类更快模型的绝佳时机,而不是用完整版 the AI 模型。

⭐⭐ 三个必记点(D1/D3): 1. 数据结构:[{ "task": "..." }, ...]——JSON 对象数组,键名是 task。 2. 两种来源:by hand 或 generate it automatically using the AI(呼应课时 2 Step 2)。 3. ⭐⭐ 模型选型(本课最实用考点):生成测试数据这种非关键、量大的任务,适合用更快更便宜的模型(Haiku)。这是 D1「按任务复杂度选模型」的经典实例——测试数据质量要求低于最终输出,不必烧大模型。这与课时 2 的 Provider 选型、课时 8 的 appropriate(选型匹配)是一条线。


四、⭐⭐ 用代码生成测试数据(Generating Test Data with Code)

先备好辅助函数(helper functions)——add_user_message / add_assistant_message / chat:

def add_user_message(messages, text):
    user_message = {"role": "user", "content": text}
    messages.append(user_message)

def add_assistant_message(messages, text):
    assistant_message = {"role": "assistant", "content": text}
    messages.append(assistant_message)

def chat(messages, system=None, temperature=1.0, stop_sequences=[]):
    params = {
        "model": model,
        "max_tokens": 1000,
        "messages": messages,
        "temperature": temperature
    }
    if system:
        params["system"] = system
    if stop_sequences:
        params["stop_sequences"] = stop_sequences

    response = client.messages.create(**params)
    return response.content[0].text

⭐ 签名进化(🔗 课时 6/8/10 的延续):chat() 到本课已累积到 四个可选参数——system、temperature、stop_sequences,且全部条件传入(if system: / if stop_sequences:)。这四条线正好把课时 6、8、11 的考点在一个函数里收拢,是很完整的 D3 参数映射题素材。

数据集生成函数 generate_dataset():

def generate_dataset():
    prompt = """
Generate an evaluation dataset for a prompt evaluation. The dataset will be used to evaluate prompts that generate Python, JSON, or Regex specifically for AWS-related tasks. Generate an array of JSON objects, each representing task that requires Python, JSON, or a Regex to complete.

Example output:
```json
[
  {
    "task": "Description of task",
  },
  ...additional
]
  • Focus on tasks that can be solved by writing a single Python function, a single JSON object, or a single regex
  • Focus on tasks that do not require writing much code

Please generate 3 objects. """

> ⭐ **数据集生成的约束条件(D3 易考)**:
> * **三类目标**:Python 函数 / JSON 对象 / 正则表达式,**AWS 相关**。
> * **两条约束**:`single`(单函数/单 JSON/单 regex)+ **不要大量代码**。
> * **数量**:示例里 `Please generate 3 objects`(呼应课时 2 的「小处起步」)。

**解析 JSON 返回**——复用课时 11 的组合技:

```python
    messages = []
    add_user_message(messages, prompt)
    add_assistant_message(messages, "```json")
    text = chat(messages, stop_sequences=["```"])
    return json.loads(text)

⭐⭐ 本课第一号考点(D4/D3): 这四行是整个本课最值得拆解的代码——它原封不动复用了课时 11《Structured data》的「预填 assistant 消息 + 停止序列」: 1. add_user_message 放生成指令; 2. add_assistant_message(messages, "```json") 预填,让模型续写 JSON; 3. chat(messages, stop_sequences=["```"]) 用闭合标记做停止序列,掐掉多余内容; 4. json.loads(text) 解析成 Python 对象。

两课合起来看:课时 11 是「手工拿到干净 JSON」的技法,本课是「把它自动化批量用在数据集生成上」——同一个组合技的两次应用。这是章节间串联的高价值点。


五、⭐ 运行并保存数据集(Testing & Saving the Dataset)

运行:

dataset = generate_dataset()
print(dataset)

应返回三个覆盖三类目标输出的测试用例(Python 函数 / JSON 配置 / 正则表达式)。

落盘:

with open('dataset.json', 'w') as f:
    json.dump(dataset, f, indent=2)

这会在与 notebook 同目录生成一个 dataset.json,里面是可复用的任务清单,供后续评估时反复加载。

⭐ 为什么要落盘(D1):数据集是可复用资产——生成一次、评估多次。落盘后每次评估跑同一份测试数据,才谈得上课时 2 的「控制变量、比较版本」。这也呼应课时 1 的 objective metrics:分数可比的前提是测试集稳定。


六、⭐ Key Takeaways(本课官方无独立 Key Takeaways 段,据正文反推)

  1. 数据集结构 = JSON 对象数组(task 键),来源 = 手工或 AI 生成。
  2. 生成测试数据这种非关键批量任务,优先用快而便宜的模型(Haiku)。
  3. generate_dataset() 通过 AI 自己造测试题,约束为单函数/单 JSON/单 regex、少代码、AWS 相关。
  4. 解析 JSON 复用课时 11 的预填 + 停止序列。
  5. 数据集落盘复用,是「控制变量、客观比较版本」的基石。

🔤 本课新生词(临时小表 · 已回灌 30-单词表/04- 第 4 章分组)

星 词汇 音标 本课义 备注
⭐⭐ regular expressions (n. pl.) / regex — 正则表达式 三类目标输出之一
⭐⭐ configuration file (n.) / JSON configuration — 配置文件(JSON) 三类目标输出之一
⭐ headers / footers (n. pl.) /ˈhedərz/ / /ˈfʊtərz/ 页眉 / 页脚 指非代码解释框架
⭐⭐ property (n.) / "task" property /ˈprɑːpərti/ 属性(JSON 键) 数据集对象结构
⭐⭐ array (n.) / array of JSON objects /əˈreɪ/ 数组 数据集 = 对象数组
⭐⭐ Haiku — Haiku(the AI 的快而小模型) 测试数据用快模型
⭐⭐ generate automatically — 自动生成 ↔ by hand
⭐ assist (v.) / assist users /əˈsɪst/ 协助、帮助
⭐ accomplish (v.) /əˈkɑːmplɪʃ/ 完成、达成 what we want the AI to accomplish
⭐ faster (adj.) / a faster model — 更快的(模型) 选型依据
⭐ solve (v.) /sɑːlv/ 解决 tasks that can be solved
⭐ single (adj.) /ˈsɪŋɡl/ 单个的、单一的 单函数/单 JSON/单 regex
⭐ focus on (v. phr.) — 聚焦于、专注于 数据集约束
⭐⭐ save (v.) / saving /seɪv/ 保存、落盘 json.dump
⭐⭐ load (v.) / load later /loʊd/ 加载 评估时复用
⭐ reusable (adj.) /ˌriːˈjuːzəbl/ 可复用的 ⚠️ 已在 §3 课时6 收录,此处为同词复现
⭐ foundation (n.) /faʊnˈdeɪʃn/ 基础、根基 官方收尾词
⭐ notebook (n.) /ˈnoʊtbʊk/ 笔记本(指 Jupyter notebook) 落盘位置

课时 4 · Running the eval

类型:🎬 视频 | lesson ID:287743 | 官方直链

🎯 本课学习目标(据官方段落反推)

  1. 能说出评估流水线的三个核心函数,以及各自单一职责。
  2. 能解释当前流水线里评分为何是硬编码的 10,以及它的定位。
  3. 能复述「第一次跑会慢」的原因(即使 Haiku 也要约 30 秒),并知道优化在后面章节。
  4. 能说出每条结果对象的三个字段(output / test_case / score)。
  5. 能判断「流水线已经完成的主体部分」与「缺的那块(grading)」分别是什么。

一、开场:把评估流水线真正搭起来

官方原句:Now that we have our evaluation dataset ready, it's time to build the core evaluation pipeline. This involves taking each test case, merging it with our prompt, feeding it to the AI, and then grading the results.

精译:既然评估数据集已就绪,是时候搭建核心评估流水线了。这涉及把每个测试用例与提示词合并、送入 the AI,然后评分结果。

官方原句:The evaluation process follows a clear workflow: we take our dataset of test cases, combine each one with our prompt template, send it to the AI for processing, and then evaluate the output using a grader system.

精译:评估流程遵循清晰的工作流:取测试用例数据集,逐一与提示词模板合并,发给 the AI 处理,再用评分器(grader)系统评估输出。

⭐ 承上启下:这是课时 2 五步工作流的 Step 3(Feed Through the AI)+ Step 4(Feed Through a Grader) 的代码实现。数据来自课时 3 生成的 dataset.json。


二、⭐⭐ 三个核心函数(Building the Core Functions)

官方原句:The evaluation pipeline consists of three main functions, each with a specific responsibility.

精译:评估流水线由三个主函数组成,各司其职。

① run_prompt(test_case)——职责:合并提示词与用例,交给 the AI

def run_prompt(test_case):
    """Merges the prompt and test case input, then returns the result"""
    prompt = f"""
Please solve the following task:

{test_case["task"]}
"""

    messages = []
    add_user_message(messages, prompt)
    output = chat(messages)
    return output

官方原句:Right now, we're keeping the prompt extremely simple. We're not including any formatting instructions, so the AI will likely return more verbose output than we need. We'll refine this later as we iterate on our prompt design.

精译:目前我们让提示词极其简单——不含任何格式指令,所以 the AI 很可能会返回比我们需要的更啰嗦的输出。我们稍后会在迭代提示词设计时精炼它。

⭐⭐ 本课第一号考点(D3/D4): run_prompt 只管「生成」,不管「评分」——职责分离的第一层。注意这里 test_case["task"] 正是课时 3 数据集里的那个 task 键,两课的数据契约是同一个。而「当前输出很 verbose、不含格式指令」是故意为之——为后续「改提示词 → 分数变化」的迭代留出改进空间(呼应课时 1 的 Option 3 与课时 2 的 baseline)。

② run_test_case(test_case)——职责:编排「跑一个用例 + 评分」

def run_test_case(test_case):
    """Calls run_prompt, then grades the result"""
    output = run_prompt(test_case)

    # TODO - Grading
    score = 10

    return {
        "output": output,
        "test_case": test_case,
        "score": score
    }

官方原句:For now, we're using a hardcoded score of 10. The grading logic is where we'll spend significant time in upcoming sections, but this placeholder lets us test the overall pipeline.

精译:目前我们用硬编码的 10 分。评分逻辑是我们接下来几节要花大量时间的地方,但这个占位能让我们先测通整体流水线。

⭐⭐ 本课第二号考点(D4): * score = 10 是硬编码占位(hardcoded placeholder),不是真实评分。它的价值是让流水线先跑通(先测「管线通畅」,再谈「评分正确」)。 * 返回结构是 {"output", "test_case", "score"} 三字段字典——这是后面所有版本都要保持的稳定契约。 * # TODO - Grading 是官方的「此处待填」标记,下一课(Model based grading)就填这里。

③ run_eval(dataset)——职责:统筹整个评估流程

def run_eval(dataset):
    """Loads the dataset and calls run_test_case with each case"""
    results = []

    for test_case in dataset:
        result = run_test_case(test_case)
        results.append(result)

    return results

官方原句:This function processes every test case in our dataset and collects all the results into a single list.

精译:这个函数处理数据集里的每一个测试用例,并把所有结果收集成一个列表。

⭐ 三函数的调用链(D1/D4 架构题): run_eval(dataset) → 循环 → run_test_case(test_case) → run_prompt(test_case) → chat() → 返回 即 统筹 → 编排 → 生成,一层套一层。考题若问「想只重跑某一条用例该调哪个」,答案是 run_test_case(不用重跑整个数据集)。


三、⭐ 运行评估(Running the Evaluation)

官方原句:To execute our evaluation pipeline, we load our dataset and run it through our functions:

with open("dataset.json", "r") as f:
    dataset = json.load(f)

results = run_eval(dataset)

官方原句:The first time you run this, expect it to take some time - even with the AI Haiku, it can take around 30 seconds to process a full dataset. We'll cover optimization techniques later.

精译:第一次跑的时候,预计要花一些时间——即便用 Haiku,处理整个数据集也可能要约 30 秒。优化技巧我们后面会讲。

⭐⭐ 本课第三号考点(D1): dataset.json 的加载直接复用课时 3 落盘的文件——生成一次、评估多次的闭环在此打通。而「约 30 秒」这条值得记:评估是批处理、非实时,所以延迟可接受、吞吐优先。这为后面课时 3 提过的「用 Haiku 提速」和课时 5/6 的 grader 优化埋了伏笔。


四、⭐ 查看结果(Examining the Results)

官方原句:The evaluation returns a structured JSON array where each object represents one test case result:

print(json.dumps(results, indent=2))

官方原句:Each result contains three key pieces of information:

  • output: The complete response from the AI
  • test_case: The original test case that was processed
  • score: The evaluation score (currently hardcoded)

精译:评估返回一个结构化 JSON 数组,每个对象代表一条测试用例的结果。每条结果包含三项关键信息:output(the AI 的完整响应)、test_case(被处理的原始测试用例)、score(评估分数,目前是硬编码的)。

⭐ indent=2 的作用:让 JSON 带缩进打印,便于人读。官方在课时 3 落盘时也用 json.dump(..., indent=2),是同一个可读性约定。

⭐ 三字段速记(D4):output(模型答了什么)、test_case(问了什么)、score(得几分)。注意这里 test_case 是整条原样塞回,不是只有 task——这保证了「结果能对回输入」,是后续分析/排错的根基。


五、⭐ 我们完成了什么(What We've Accomplished)

官方原句:At this point, we've successfully built the core evaluation pipeline. We can take our dataset, process it through the AI, and collect structured results. The major missing piece is the grading system - that hardcoded score of 10 needs to be replaced with actual evaluation logic.

精译:至此,我们已经成功搭建了核心评估流水线:能取数据集、经 the AI 处理、收集结构化结果。缺的那块大件是评分系统——那个硬编码的 10 分需要换成真正的评估逻辑。

官方原句:This pipeline represents the foundation of most AI evaluation systems. While it may seem simple, you've just built the majority of what an eval pipeline actually does. The complexity comes in the details - better prompts, sophisticated grading, and performance optimizations.

精译:这条流水线代表大多数 AI 评估系统的基础。虽然看起来简单,但你其实已经搭好了评估流水线实际工作的大半。复杂性在于细节——更好的提示词、更成熟的评分、以及性能优化。

官方原句:Next, we'll dive into the critical topic of graders, which will transform our hardcoded scores into meaningful evaluations of the AI's performance.

精译:接下来,我们将深入评分器这个关键主题,它会把硬编码的分数转变成对 the AI 表现的有意义的评估。

⭐⭐ 本课第四号考点(D1/D3 收束): * 已完成的:数据 → 生成 → 收集结构化结果(run_eval / run_test_case / run_prompt 三件套)。 * 缺的那块:评分逻辑(score = 10 待替换)。 * 一句话定性:官方说已搭好「大多数评估流水线实际工作」,复杂性在细节(提示词、评分、优化)——这句话直接预告了后续课程(课时 5/6 grading、以及各处 optimization)。


六、⭐ Key Takeaways(本课官方无独立 Key Takeaways 段,据正文反推)

  1. 三函数各司其职:run_prompt 生成、run_test_case 编排+评分、run_eval 统筹全数据集。
  2. score = 10 是硬编码占位,为的是先测通管线;真正评分是下一课的主题。
  3. 结果三字段稳定契约:output / test_case / score。
  4. 评估是批处理:首跑约 30 秒,延迟可接受,吞吐优先。
  5. 已搭好评估流水线的主体,缺的是评分系统与各类优化。

🔤 本课新生词(临时小表 · 已回灌 30-单词表/04- 第 4 章分组)

星 词汇 音标 本课义 备注
⭐⭐ pipeline (n.) /ˈpaɪplaɪn/ 流水线、管线 core evaluation pipeline
⭐⭐ test case (n.) — 测试用例 数据集里的单条
⭐⭐ orchestrate (v.) / orchestrates /ˈɔːrkɪstreɪt/ 编排、统筹 run_test_case 的职责
⭐⭐ coordinate (v.) /koʊˈɔːrdɪneɪt/ 协调、统筹 run_eval 的职责
⭐⭐ hardcoded (adj.) — 硬编码的 score = 10 占位
⭐⭐ placeholder (n.) /ˈpleɪshoʊldər/ 占位符、占位 先测通管线的过渡值
⭐ verbose (adj.) /vɜːrˈboʊs/ 啰嗦的、冗长的 无格式指令的默认输出
⭐⭐ refine (v.) /rɪˈfaɪn/ 精炼、改进 迭代提示词的动作
⭐⭐ merge (v.) /mɜːrdʒ/ 合并 run_prompt 的核心动作
⭐ individual (adj.) /ˌɪndɪˈvɪdʒuəl/ 单个的、个别的 individual prompts
⭐ responsibility (n.) /rɪˌspɑːnsəˈbɪləti/ 职责、责任 specific responsibility
⭐ overall (adj.) /ˌoʊvərˈɔːl/ 整体的 overall pipeline
⭐⭐ load (v.) /loʊd/ 加载 读 dataset.json
⭐⭐ optimization (n.) / optimize (v.) /ˌɑːptɪməˈzeɪʃn/ 优化 首跑约 30 秒的后续话题
⭐⭐ foundation (n.) /faʊnˈdeɪʃn/ 基础、根基 评估系统的基础
⭐ majority (n.) /məˈdʒɔːrəti/ 大部分、多数 the majority of what an eval pipeline does
⭐⭐ sophisticated (adj.) /səˈfɪstɪkeɪtɪd/ 成熟的、复杂的 sophisticated grading
⭐ transform (v.) /trænsˈfɔːrm/ 转变、转化 把硬编码分变成有意义评估
⭐ meaningful (adj.) /ˈmiːnɪŋfl/ 有意义的 meaningful evaluations

课时 5 · Model based grading

类型:🎬 视频 | lesson ID:287742 | 官方直链

🎯 本课学习目标(据官方段落反推)

  1. 能说出三种 grader(code / model / human)及各自特点。
  2. 能说出 code grader 的四类常见用途与唯一要求(返回可用信号)。
  3. 能说清 model grader 的机制(把输出再送一次 API)与它能评的五类维度。
  4. 能定义评估标准(criteria),并判断哪个标准该配哪种 grader。
  5. 能写出model grader 函数,并说出「评分之外要 strengths/weaknesses/reasoning」的关键洞察。

一、开场:grader 的定义与打分

官方原句:When building prompt evaluation workflows, grading systems provide objective signals about output quality. A grader takes model output and returns some kind of measurable feedback - typically a number between 1 and 10, where 10 represents high quality and 1 represents poor quality.

精译:构建提示词评估工作流时,评分系统为输出质量提供客观信号。grader 接收模型输出,返回某种可度量的反馈——通常是一个 1 到 10 之间的数字:10 代表高质量,1 代表低质量。

⭐ 承上启下:本课直接填课时 4 的 # TODO - Grading。注意打分区间的口径又出现了:1–10(与课时 2 一致),且10 高 1 低。


二、⭐⭐ 三种 grader(Types of Graders)

官方原句:There are three main approaches to grading model outputs:

  • Code graders - Programmatically evaluate outputs using custom logic**
  • Model graders - Use another AI model to assess the quality
  • Human graders - Have people manually review and score outputs

精译:给模型输出评分有三种主要方式:代码评分器(用自定义逻辑以编程方式评估输出)、模型评分器(用另一个 AI 模型评估质量)、人工评分器(由人手动审查并打分)。

类型 机制 特点 本课定位
Code grader 程序逻辑 快、确定、可自动化 适合格式/语法等硬校验
Model grader 再送一次 API 灵活、可评软性维度 本课主角
Human grader 人手审 最灵活但耗时繁琐 少用

三、⭐⭐ Code graders(代码评分器)

官方原句:Code graders let you implement any programmatic check you can imagine. Common uses include:

  • Checking output length**
  • Verifying output does/doesn't have certain words**
  • Syntax validation for JSON, Python, or regex
  • Readability scores

精译:代码评分器让你能实现任何你能想到的编程检查。常见用途包括:检查输出长度、验证输出是否包含/不包含某些词、对 JSON / Python / regex 做语法校验、可读性评分。

官方原句:The only requirement is that your code returns some usable signal - usually a number between 1 and 10.

精译:唯一要求是,你的代码返回某种可用的信号——通常是 1 到 10 之间的数字。

⭐ 本课第一号考点(D4):code grader 的本质是「自定义逻辑的硬校验」——长度、词、语法、可读性这类规则明确的检查。它快而确定,但评不了「好不好」「对不对」这类软性质量。⚠️ 本课只点名 code grader,具体实现是下一课(Code based grading)。


四、⭐⭐ Model graders(模型评分器)

官方原句:Model graders feed your original output into another API call for evaluation. This approach offers tremendous flexibility for assessing:

  • Response quality
  • Quality of instruction following**
  • Completeness
  • Helpfulness
  • Safety

精译:模型评分器把你的原始输出再次送进一次 API 调用来评估。这种方式为评估这些维度提供了极大的灵活性:回答质量、指令遵循度、完整性、有用性、安全性。

⭐⭐ 本课第二号考点(D1/D3): * 机制:feed your original output into another API call——输出被当作输入再评一次。这天然把「评估」也变成了一个模型调用,因此评估同样吃 token、同样有延迟(呼应课时 4 的「批处理、约 30 秒」)。 * 五类维度(枚举题):质量、指令遵循、完整性、有用性、安全性。前四个偏「能力」,safety 是唯一的硬性合规维度——它和课时 1 的「可靠性」、CCAR-F 里的治理红线是一类。


五、⭐ Human graders(人工评分器)

官方原句:Human graders provide the most flexibility but are time-consuming and tedious. They're useful for evaluating:

  • General response quality**
  • Comprehensiveness
  • Depth
  • Conciseness
  • Relevance

精译:人工评分器提供最大的灵活性,但耗时且繁琐。它们适合评估:总体回答质量、全面性、深度、简洁性、相关性。

⭐ 对比记忆(D3):human 评的五个词(quality / comprehensiveness / depth / conciseness / relevance)和 model 评的五个词(quality / instruction following / completeness / helpfulness / safety)有重叠但不完全相同——重叠的是「质量」一类,其余各偏各的。考题若问「哪个维度只能用人工评」,较稳妥的答法是深度、相关性这类需要主观判断的。


六、⭐⭐ 先定评估标准,再选 grader(Defining Evaluation Criteria)

官方原句:Before implementing any grader, you need clear evaluation criteria. For a code generation prompt, you might focus on:

  • Format - Should return only Python, JSON, or Regex without explanation**
  • Valid Syntax - Produced code should have valid syntax**
  • Task Following - Response should directly address the user's task with accurate code**

精译:在实现任何 grader 之前,你需要清晰的评估标准。对一个代码生成提示词,你可能会聚焦于:格式(应只返回 Python / JSON / Regex,不带解释)、语法有效(产出的代码语法有效)、任务遵循(响应应直接回应用户的任务,给出准确的代码)。

官方原句:The first two criteria work well with code graders, while task following is better suited for model graders due to their flexibility.

精译:前两条标准(格式、语法)很适合 code grader,而任务遵循由于需要灵活性,更适合 model grader。

⭐⭐ 本课第三号考点(D3/D4)——标准 ↔ grader 的匹配: * Format(只返回格式、不带解释)→ code grader(检查有没有多余文字,规则明确)。 * Valid Syntax(语法有效)→ code grader(JSON/Python/regex 的语法校验,下一课就是它)。 * Task Following(有没有真正答对任务、代码准不准确)→ model grader(需要理解语义,代码硬校验做不到)。

记忆口诀:硬规则配 code,软语义配 model。这条几乎可以原样当一道匹配题。


七、⭐⭐ 实现一个 model grader(Implementing a Model Grader)

官方原句:Here's how to build a model grader function:

def grade_by_model(test_case, output):
    # Create evaluation prompt
    eval_prompt = """
    You are an expert code reviewer. Evaluate this AI-generated solution.

    Task: {task}
    Solution: {solution}

    Provide your evaluation as a structured JSON object with:
    - "strengths": An array of 1-3 key strengths
    - "weaknesses": An array of 1-3 key areas for improvement
    - "reasoning": A concise explanation of your assessment
    - "score": A number between 1-10
    """

    messages = []
    add_user_message(messages, eval_prompt)
    add_assistant_message(messages, "```json")

    eval_text = chat(messages, stop_sequences=["```"])
    return json.loads(eval_text)

官方原句:The key insight is asking for strengths, weaknesses, and reasoning alongside the score. Without this context, models tend to default to middling scores around 6.

精译:关键洞察是——在要分数之外,同时要 strengths、weaknesses 和 reasoning。没有这些上下文,模型倾向于默认给出 6 分上下的中庸分数。

⭐⭐ 本课第一号考点(D3/D4): * grade_by_model 完整复用了课时 11 的组合技:add_assistant_message(messages, "```json") 预填 + stop_sequences=["```"] + json.loads。这是第三次出现这个组合(课时 11 手工、课时 3 数据集、本课评分)——官方几乎把它当章节间固定模板。 * 评估输出是结构化 JSON:strengths(1–3 条)、weaknesses(1–3 条)、reasoning、score(1–10)。 * ⭐⭐ 最关键洞察:不能只要 score——要带上 strengths / weaknesses / reasoning 作为上下文,否则模型会偷懒给 6 分(default to middling scores around 6)。这是本课最像简答题/判断题的点:题干「为什么 model grader 要同时要求 reasoning?」→ 答案「防止模型默认给中庸的 6 分」。


八、⭐⭐ 把评分接回工作流(Integrating Grading into Your Workflow)

更新 run_test_case,让它真正调用 grader:

def run_test_case(test_case):
    output = run_prompt(test_case)

    # Grade the output
    model_grade = grade_by_model(test_case, output)
    score = model_grade["score"]
    reasoning = model_grade["reasoning"]

    return {
        "output": output,
        "test_case": test_case,
        "score": score,
        "reasoning": reasoning
    }

⭐ 对比课时 4 的 run_test_case:结果从 3 字段变成了 4 字段——多了 reasoning。这正是课时 4 那句「稳定契约,后面版本会改」的实例:output / test_case / score 保留,新增 reasoning。score = 10 的硬编码占位在这里被真正的 model_grade["score"] 替换——课时 4 的 # TODO - Grading 就此填上。

计算平均分:

from statistics import mean

def run_eval(dataset):
    results = []

    for test_case in dataset:
        result = run_test_case(test_case)
        results.append(result)

    average_score = mean([result["score"] for result in results])
    print(f"Average score: {average_score}")

    return results

官方原句:This gives you an objective metric to track as you iterate on your prompt. While model graders can be somewhat capricious, they provide a consistent baseline for measuring improvements.

精译:这给了你一个客观指标,供你在迭代提示词时追踪。虽然 model grader 可能有些反复无常(capricious),但它为衡量改进提供了一个一致的基线。

⭐⭐ 本课第二号考点(D3/D5): * mean() 来自 statistics 标准库——官方示例明确 import 的是 from statistics import mean(不是 numpy 之类的第三方库)。 * model grader 的局限:somewhat capricious(反复无常)——同一条输出可能得不同分。这正好呼应课时 1 的「评估要客观」:正因为 grader 有波动,才更依赖多条用例取平均来平滑噪声。 * 它的价值定位:consistent baseline——即便有波动,它仍是可复现的基准线,用于追踪改进趋势而非追求单次绝对准确。


九、⭐ Key Takeaways(本课官方无独立 Key Takeaways 段,据正文反推)

  1. 三种 grader:code(硬规则)/ model(软语义)/ human(最灵活但耗时)。
  2. 先定评估标准,再配 grader:Format/语法 → code,Task Following → model。
  3. model grader = 把输出再送一次 API,能评质量/指令遵循/完整性/有用性/安全性。
  4. 关键洞察:评分要带 strengths / weaknesses / reasoning,否则模型默认给 6 分。
  5. 平均分用 statistics.mean;model grader 有波动(capricious),但提供一致的基线。

🔤 本课新生词(临时小表 · 已回灌 30-单词表/04- 第 4 章分组)

星 词汇 音标 本课义 备注
⭐⭐ grader (n.) /ˈɡreɪdər/ 评分器 已在 §4 课时2 收录
⭐⭐ objective signal — 客观信号 grader 的产出
⭐⭐ programmatically (adv.) /ˌproʊɡrəˈmætɪkli/ 以编程方式 code grader 的实现
⭐⭐ custom logic — 自定义逻辑 code grader 的引擎
⭐ syntax validation — 语法校验 code grader 用途之一
⭐ readability (n.) / readability scores /ˌriːdəˈbɪləti/ 可读性 code grader 用途之一
⭐ usable signal — 可用信号 code grader 唯一要求
⭐⭐ tremendous (adj.) /trəˈmendəs/ 极大的、巨大的 tremendous flexibility
⭐⭐ flexibility (n.) /ˌfleksəˈbɪləti/ 灵活性 model grader 的优势
⭐⭐ instruction following — 指令遵循(度) model 评分维度之一
⭐ completeness (n.) /kəmˈpliːtnəs/ 完整性 model 评分维度之一
⭐ helpfulness (n.) /ˈhelpflnəs/ 有用性 model 评分维度之一
⭐ safety (n.) /ˈseɪfti/ 安全性 model 评分维度之一
⭐⭐ time-consuming (adj.) / tedious — 耗时的 / 繁琐的 human grader 的代价
⭐ comprehensiveness (n.) /ˌkɑːmprɪˈhensɪvnəs/ 全面性 human 评分维度之一
⭐ conciseness (n.) /kənˈsaɪsnəs/ 简洁性 human 评分维度之一
⭐ relevance (n.) /ˈreləvəns/ 相关性 human 评分维度之一
⭐⭐ criteria (n. pl.) / criterion (n. sg.) /kraɪˈtɪriə/ 标准(复数) 先定标准再选 grader
⭐⭐ task following — 任务遵循(是否答对任务) 配 model grader
⭐⭐ directly address — 直接回应(任务) task following 的要求
⭐⭐ accurate (adj.) /ˈækjərət/ 准确的 accurate code
⭐⭐ strengths / weaknesses (n. pl.) — 优点 / 缺点 评分 JSON 结构
⭐⭐ reasoning (n.) /ˈriːznɪŋ/ 理由、推理(说明) 防默认 6 分的关键
⭐⭐ middling (adj.) /ˈmɪdlɪŋ/ 中等的、中庸的 default to middling scores around 6
⭐⭐ capricious (adj.) /kəˈprɪʃəs/ 反复无常的、任性的 model grader 的局限
⭐ consistent (adj.) /kənˈsɪstənt/ 一致的 consistent baseline
⭐ baseline (n.) /ˈbeɪslaɪn/ 基线 已在 §4 课时2 收录

课时 6 · Code based grading

类型:🎬 视频 | lesson ID:287737 | 官方直链

🎯 本课学习目标(据官方段落反推)

  1. 能说出代码评分(code-based grading)要校验的两大方面:格式与语法。
  2. 能写出三个语法校验函数(validate_json / validate_python / validate_regex),并说出各自返回 10 / 0 的分支。
  3. 能说出数据集为什么需要 format 字段,以及如何让生成提示词自动带上它。
  4. 能用更明确的指令(只返回代码、不加解释)和 prefilled 消息("```code")提升生成质量。
  5. 能把 model grader 分数与 code grader 分数取平均合并,并说出权重可调。

一、开场:为什么需要代码评分

官方原句:When evaluating AI models that generate code, you need more than just checking if the response makes sense. You also need to verify that the generated code actually has valid syntax and follows the correct format. This is where code-based grading comes in.

精译:评估会生成代码的 AI 模型时,你需要的不仅仅是检查回答是否合理。你还要验证生成的代码语法确实有效、且遵循了正确的格式。这正是代码评分(code-based grading)的用武之地。

⭐ 承上启下:课时 5 点名了 code grader,本课正面实现它。关键转折词是「more than just checking if it makes sense」——光靠「读起来对」不够,代码要机器能解析才算对。这是把「主观合理性」升级为「客观可执行性」的一课。


二、⭐⭐ 代码评分校验两大方面

官方原句:Code grading validates two key aspects of AI-generated responses:

  • Format - The response should return only the requested code type (Python, JSON, or Regex) without explanations**
  • Valid Syntax - The generated code should actually parse correctly as the intended language
  • Task Following - The response should directly address what was asked and be accurate**

The first two criteria are handled by the code grader, while task following is evaluated by the model grader. Together, they provide a comprehensive evaluation.

精译:代码评分校验 AI 生成响应的两大方面:格式(响应应只返回所请求的代码类型——Python、JSON 或 Regex——不带解释)、语法有效(生成的代码应能以目标语言正确解析)、任务遵循(响应应直接回应所问内容且准确)。前两条由 code grader 处理,而任务遵循由 model grader 评估。两者结合,提供全面的评估。

⭐⭐ 本课第一号考点(D3/D4)——三标准的分工: * 官方文案写了三个标准,但明确说「two key aspects」归 code grader——即 Format(只返回代码、无解释)和 Valid Syntax(能解析)。Task Following(任务遵循)交给 model grader。 * 这正是课时 5 §六 那张匹配表的正式落地:硬规则配 code,软语义配 model。本课把它讲透:code grader 只负责「机器能跑」,「答得对不对」仍由 model grader 兜底。 * 记忆点:code grader = 格式 + 语法(可机械校验);model grader = 任务遵循(需语义理解)。两者合起来才是全面评估(comprehensive evaluation)。


三、⭐⭐ 语法校验函数(Syntax Validation Functions)

官方原句:To check if generated code has valid syntax, you can create three helper functions that attempt to parse the output:

def validate_json(text):
    try:
        json.loads(text.strip())
        return 10
    except json.JSONDecodeError:
        return 0

def validate_python(text):
    try:
        ast.parse(text.strip())
        return 10
    except SyntaxError:
        return 0

def validate_regex(text):
    try:
        re.compile(text.strip())
        return 10
    except re.error:
        return 0

官方原句:Each function tries to parse the text as its respective format. If parsing succeeds, it returns a perfect score of 10. If it fails with an error, the syntax is invalid and returns 0.

精译:每个函数都尝试把文本按其对应格式解析。若解析成功,返回满分 10;若因错误失败,说明语法无效,返回 0。

⭐⭐ 本课第二号考点(D1/D4)——三个校验函数是高频原题: * validate_json:json.loads(text.strip()) → 成功 10,捕获 json.JSONDecodeError → 0。 * validate_python:ast.parse(text.strip())(注意用 ast 模块,不是 compile)→ 成功 10,捕获 SyntaxError → 0。 * validate_regex:re.compile(text.strip()) → 成功 10,捕获 re.error → 0。 * 统一范式:try: 解析 → return 10 / except 特定错误 → return 0。三个函数结构完全对称,只是解析器不同:json.loads / ast.parse / re.compile,对应错误类型 json.JSONDecodeError / SyntaxError / re.error。考题很可能给出某个函数挖空,考「用什么解析器、捕获什么异常」。 * 返回区间仍是 1–10 口径,但 code grader 更干脆:只有 10(满分)或 0(失败)两档,没有中间分。


四、⭐⭐ 数据集要带 format 字段

官方原句:For the code grader to know which validator to use, your test cases need to specify the expected output format:

{
    "task": "Create a Python function to validate an AWS IAM username",
    "format": "python"
}

官方原句:You can update your dataset generation prompt to automatically include this format field by adding it to the example output structure.

精译:为了让 code grader 知道该用哪个校验器,你的测试用例需要指明期望的输出格式。你可以在数据集生成提示词的示例输出结构里加上 format 字段,让它自动带上这一字段。

⭐⭐ 本课第三号考点(D3/D4): * format 字段是 code grader 的「路由开关」:validate_json / validate_python / validate_regex 哪个上场,由测试用例里的 format 决定("format": "python" → 走 validate_python)。 * 字段来源:不用手工给每条用例加,而是改数据集生成提示词的「示例输出结构」(example output structure)——这正是课时 3「用 JSON schema 约束数据集生成」的延续:给生成器看一个带 format 的样例,它就会照做。任务样例本身又呼应了AWS IAM 用户名校验(D5 安全治理语境)。 * 结构:{"task": ..., "format": ...}——任务 + 期望格式两字段。这比课时 3 的三字段(task / difficulty / expected)更精简,是评估专用的用例形状。


五、⭐ 用更明确的指令提升输出质量(Improving Prompt Clarity)

官方原句:To get better results from your AI model, make your prompt instructions more specific about the expected output format:

  • Respond only with Python, JSON, or a plain Regex**
  • Do not add any comments or commentary or explanation**

You can also use a pre-filled assistant message with code blocks to encourage the model to return just the raw code:

add_assistant_message(messages, "code") ```

This tells the AI to start generating code content without having to specify whether it's Python, JSON, or Regex ahead of time.

精译:要让 AI 模型得到更好的结果,把提示词里对期望输出格式的说明写得更具体:只回复 Python、JSON 或纯 Regex;不要加任何注释、评述或解释。你还可以用预填(pre-filled)的助手消息配合代码块,引导模型只返回原始代码:add_assistant_message(messages, "```code")。这告诉 AI 直接开始生成代码内容,而无需事先指定是 Python、JSON 还是 Regex。

⭐ 承前(D3/D4):这条又是课时 11 组合技的变体——add_assistant_message(messages, "```code") 预填一个代码围栏起始符。与课时 11 的 "```json"、课时 5 评分时的 "```json" 同源,只是把预填内容换成中性的 "```code"——好处是不用预先锁定具体语言,让模型自然延续代码块。注意这里预填符是 ```code(code 语言标注),stop_sequences 在课时 5 已用于终止,本课聚焦起始预填。

两条指令口诀:① 只给代码(限定语言集合)② 不给解释(禁注释/评述/说明)。


六、⭐⭐ 合并分数(Combining Scores)

官方原句:The final step is merging the model grader score with the code grader score. A simple approach is to take the average:

model_grade = grade_by_model(test_case, output)
model_score = model_grade["score"]
syntax_score = grade_syntax(output, test_case)

score = (model_score + syntax_score) / 2

官方原句:This gives equal weight to both content quality and technical correctness. You might adjust these weights based on what matters more for your specific use case.

精译:最后一步是把 model grader 分数和 code grader 分数合并。简单做法是取平均:score = (model_score + syntax_score) / 2。这给内容质量与技术正确性以同等权重。你还可以根据具体场景里哪个更重要来调整权重。

⭐⭐ 本课第四号考点(D3/D4): * 融合公式:(model_score + syntax_score) / 2——两分等权取平均。model_score 来自课时 5 的 grade_by_model(内容质量/任务遵循),syntax_score 来自本课的 grade_syntax(技术正确性)。 * 权重可调:equal weight 只是默认,官方明确「adjust these weights based on what matters more」——即换成 w*model + (1-w)*syntax 这类加权和。这是开放式简答题点:「为什么用平均?」→「在内容质量与技术正确性之间给相等权重,且可按场景调权」。 * 这里出现 grade_syntax(output, test_case) 这一调度函数(内部按 test_case["format"] 选对应 validator),官方未给完整实现,但第四节的 format 路由逻辑就是它的身体。


七、⭐ 测试你的实现(Testing Your Implementation)

官方原句:Once you've implemented code grading, run your evaluation to get a baseline score. The score itself isn't inherently good or bad - what matters is whether you can improve it by refining your prompts. This gives you a quantitative way to measure prompt engineering progress rather than relying on subjective assessment.

精译:实现代码评分后,运行你的评估拿到一个基线分数。分数本身没有绝对的好坏——重要的是你能不能通过改进提示词来提升它。这给了你一个量化衡量提示词工程进展的方式,而不是依赖主观判断。

⭐ 承前(D3):这句话几乎逐字呼应课时 1「评估 = 提示词的客观度量」和课时 5「model grader 提供 consistent baseline」。本课把基线(baseline)这个概念坐实:分数不是绝对好坏,而是相对改进的标尺——baseline → refine → improve 是提示词工程的迭代闭环(同课时 1 的 iterate)。下载区的 001_prompt_evals_fns.ipynb 正是这套函数的可运行 notebook(D1 实操)。


八、⭐ Key Takeaways(本课官方无独立 Key Takeaways 段,据正文反推)

  1. 代码评分校验两大方面:格式(只返回代码、无解释)+ 语法有效(能解析);任务遵循归 model grader。
  2. 三个校验函数同构:validate_json/validate_python/validate_regex → 解析成功 10、失败 0(json.loads/ast.parse/re.compile,对应 JSONDecodeError/SyntaxError/re.error)。
  3. 测试用例要带 format 字段,靠数据集生成提示词的示例输出结构自动带上。
  4. 提升质量:只给代码、不加解释 的明确指令 + prefill "```code"。
  5. 融合分数:(model_score + syntax_score) / 2,等权可调。

🔤 本课新生词(临时小表 · 已回灌 30-单词表/04- 第 4 章分组)

星 词汇 音标 本课义 备注
⭐⭐ code-based grading — 代码评分 本课核心
⭐⭐ syntax (n.) / valid syntax /ˈsɪntæks/ 语法 / 有效语法 code grader 校验之一
⭐⭐ parse (v.) / parsing /pɑːrs/ 解析 语法校验的动作
⭐ format (n.) /ˈfɔːrmæt/ 格式 数据集 format 字段
⭐⭐ intended (adj.) /ɪnˈtendɪd/ 预期的、目标(语言) as the intended language
⭐ helper function — 辅助函数 三个 validator 的定位
⭐ perfect score — 满分 解析成功 → 10
⭐⭐ attempt (v.) /əˈtempt/ 尝试 attempt to parse the output
⭐⭐ respective (adj.) /rɪˈspektɪv/ 各自的、分别的 its respective format
⭐⭐ specify (v.) /ˈspesɪfaɪ/ 指明、规定 测试用例指明格式
⭐⭐ route / which validator — 路由 / 用哪个校验器 format 决定 validator
⭐ example output structure — 示例输出结构 让生成器自动带 format
⭐⭐ pre-filled (adj.) — 预填的 pre-filled assistant message
⭐⭐ raw code — 原始代码 prefill "```code" 的目标
⭐ commentary (n.) /ˈkɑːmənteri/ 评述、解说 指令禁用之一
⭐⭐ combine (v.) /kəmˈbaɪn/ 合并 融合两个分数
⭐⭐ average (n./v.) /ˈævərɪdʒ/ 平均 (model+syntax)/2
⭐⭐ equal weight — 等权重 默认的融合方式
⭐ technical correctness — 技术正确性 code grader 代表的一极
⭐ adjust weights — 调整权重 可按场景调
⭐ quantitative (adj.) /ˈkwɑːntəteɪtɪv/ 定量的 量化的进展度量
⭐ subjective (adj.) /səbˈdʒektɪv/ 主观的 被替代的评估方式
⭐ refine (v.) /rɪˈfaɪn/ 改进、精炼 已在 §3 课时9 收录
⭐ baseline (n.) /ˈbeɪslaɪn/ 基线 已在 §4 课时2 收录

课时 7 · Exercise on prompt evals

类型:🎬 视频 | lesson ID:287738 | 官方直链

  • 精译状态:⏸ 不补(决定 2026-10-16)——练习课,官方无讲稿/字幕正文,仅动手任务,无可精译语料。
  • 建议复习指向:巩固课时 2《A typical eval workflow》的评估闭环(生成测试集 → 跑 eval → 看结果 → 迭代)与课时 5《Model based grading》/课时 6《Code based grading》两类判分的适用边界。自测即按课时 4《Running the eval》把一轮 eval 跑通。
  • 本章新生词:无(练习课不产生新语料;相关词已随课时 1–6 回灌)

课时 8 · Quiz on prompt evaluation

类型:📝 测验 | lesson ID:289118 | 官方直链

  • 精译状态:⏸ 不补(决定 2026-10-16)——章末测验,题目本身即考点,无讲稿语料,且需登录态取得。
  • 建议复习指向:本章 6 课正课已精译完毕,测验覆盖的考点分布为——D3 评估工作流与测试集构造(课时 1–3)/D3 两类 grading 的取舍(课时 5、6)/D3 用 eval 结果迭代提示词(课时 2、4)。做题前建议重点回看各课小结与 ⭐⭐ 标注。
  • 本章新生词:无(章末测验不产生新语料)

✅ 本章进度

  • [x] 抓取本章讲稿/字幕(用户提供,2026-10-16)
  • [x] 逐课精译(8 课时)—— 精译 6 课 ✅ + 不补 2 课 ⏸ = 8 课全覆盖(2026-10-16)
  • 已精译(6):课时 1–6
  • ⏸ 不补(2):课时 7 为练习课(无讲稿正文);课时 8 为章末测验(题目需登录态)
  • 说明:这 2 课官方均无可精译的讲稿/字幕语料,考点与生词已被相邻正课覆盖,故统一标注不补并各附复习指向
  • [x] 生词回灌 30-单词表/04-—— 已建「第 4 章」速查分组(140 条)
  • [x] ~~章节测验/练习(课时 8 Quiz)~~ —— ⏸ 不补(题目需登录态;复习指向见课时 8 条目)

🔗 关联

输入至少 2 个字符,检索全部课程与单词表