
本文详解 YAML 配置文件中长字符串(尤其是含换行、特殊符号的提示词)的正确写法,重点解决因误用三重引号、转义混乱或缩进错误导致的解析失败问题。
本文详解 yaml 配置文件中长字符串(尤其是含换行、特殊符号的提示词)的正确写法,重点解决因误用三re引号、转义混乱或缩进错误导致的解析失败问题。
YAML 对多行字符串的支持非常灵活,但语法严格——常见错误(如 PROMPT_SUMMARY: """...""")并非 YAML 原生特性,而是混淆了 Python 的三重引号语法。YAML 中不存在 """ 字面量语法,连续双引号 """" 会被解析为两个独立标量(空字符串 + 未闭合字符串),直接触发 ParserError: expected
✅ 正确做法是根据是否需要保留原始换行选择两种标准块标量风格:
1. 使用 |(Literal Block Scalar)——保留所有换行与空白
适用于提示词、模板文本等需严格维持格式的场景。其核心规则:
- | 后必须紧跟换行;
- 后续内容顶格书写(即行首无缩进),或统一使用相同缩进量(YAML 会自动剥离公共前导空格);
- 不支持 \n 转义——\n 会被当作字面字符 "\n" 输出;
- 内部双引号、冒号等无需转义。
WORKFLOW:
EXTRACT_SUMMARIZATION:
PROMPT_SUMMARY: |
Extracting the timestamps of the goals scored by players in a football match using the commentator's description.
The structure of input is:
timestamp => text
timestamp => text
timestamp => text
timestamp => text
The output only consists of timestamps and does not include any text.
Example:
Input:
0:01 => [Applause]
0:04 => Welcome, ladies and gentlemen, to the match between Liverpool and Chelsea.
0:14 => Silva has scored, and the score is 1-0 in favor of Liverpool.
0:20 => So, there has been a foul committed by a Liverpool player.
0:25 => The referee has blown the whistle to end the first half.
0:30 => Chelsea has equalized through Ch.
0:45 => Tr has put Chelsea in the lead.
0:50 => So, the match has...
0:55 => ended, and the victory goes to Chelsea.
Output: 0:14, 0:30, 0:45
This is an incorrect format of output:
0:14 => Silva has scored, and the score is 1-0 in favor of Liverpool.
0:45 => Tr has put Chelsea in the lead.
This is another incorrect format of output:
0:01 => [Applause]
0:04 => 0:14 => 0:25 =>
Do it for the following text:
Input:
{}
Output:
SCALE_TIME_BEFORE: 6
SCALE_TIME_AFTER: 58
⚠️ 注意:| 后换行后第一行必须完全顶格(或统一缩进),否则 YAML 解析器将报 did not find expected
。若需缩进对齐,可改用 |-(strip)或 |+(keep)控制尾部换行,但初学者建议统一顶格书写。
2. 使用 >(Folded Block Scalar)——折叠换行为空格
适用于段落式文本,自动将换行转为空格,适合自然语言描述(如 PROMPT 字段):
ABSTRACT_SUMMARIZATION:
PROMPT: >-
Rewrite the following sentences to form a paragraph: {}
>- 表示“折叠并去除末尾换行”,输出中换行符被替换为空格,且末尾无额外换行。
❌ 常见错误规避清单
- 禁用 """ / ''':YAML 不支持三重引号,纯属 Python 语法迁移错误;
- 避免混合引号:如 """"abc" 是非法的,YAML 不支持字符串拼接;
- 慎用在线校验工具:许多工具(如 yaml-validator)基于过时解析器,可能给出误导性错误;推荐本地用 ruamel.yaml 或 yamllint 验证;
- 敏感配置勿上传:在线 YAML 校验器会上传内容,存在数据泄露风险;
- 缩进必须一致:YAML 依赖空格缩进(禁止 Tab),子级字段需严格对齐上级键的起始列。
最后提醒:YAML 文件扩展名应统一使用 .yaml(官方推荐),而非 .yml(虽被广泛接受,但非标准)。一个规范、可维护的配置文件,始于对基础语法的准确理解——尤其当承载 LLM 提示工程这类对格式零容忍的场景时,正确的 YAML 写法就是可靠性的第一道防线。











