AI Prompt Engineering · 课时

纯文本与格式化输出

了解何时应请求整洁的纯文本,何时应请求丰富的 Markdown 输出

第 4 / 4 课13 个步骤

纯文本与格式化输出 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。

纯文本场景

标记语法格式功能强大,但并不总是合适的选择。许多实际应用需要整洁、未格式化的文本,在这些应用中,标记语法符号会作为普通字符显示,而不是呈现为格式。

了解何时请求纯文本,与了解如何请求丰富格式同样重要。

需要纯文本的情况

当您的环境无法呈现标记语法时,请使用纯文本输出:

  • 电子邮件文案:大多数电子邮件客户端会显示原始星号
  • SMS 和推送通知:不支持格式化
  • 语音输出:文本转语音会将“** 粗体 **”按字面读出
  • CRM 和帮助台字段:许多此类字段无法呈现标记语法
  • 应用程序接口数据处理:文本将被存储或进一步处理时
  • 旧版系统输入字段:仅支持纯文本
import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=200,
    messages=[{
        'role': 'user',
        'content': (
            'Write a 120-character push notification for a flash sale ending in 2 hours. '
            'Plain text only — no emojis, no markdown, no asterisks, no special characters. '
            'Must include: urgency, discount percentage (30%), and category (electronics). '
            'Output the notification text only — nothing else.'
        )
    }]
)
print(response.content[0].text)

明确请求纯文本

在许多场景中,人工智能模型默认会生成大量标记语法。要获得真正的纯文本,您必须明确说明这一要求,并且通常还要列出需要避免的具体符号(symbols):

  • “仅使用纯文本——不要使用标记格式”
  • “不要使用星号、井号或项目符号”
  • “不要使用标题、粗体或列表——仅使用连贯的散文段落”
  • “去除所有格式——输出内容应如同在记事本中撰写一样”
import openai

client = openai.OpenAI(api_key='sk-your-key-here')

# Without plain text instruction — likely gets markdown
default_prompt = 'Explain what a webhook is in 100 words.'

# With explicit plain text instruction
plain_prompt = (
    'Explain what a webhook is in 100 words. '
    'Output format: plain text only. No markdown. No asterisks. No headers. '
    'No bullet points. Just continuous prose paragraphs.'
)

for label, prompt in [('DEFAULT (likely markdown)', default_prompt), ('EXPLICIT PLAIN TEXT', plain_prompt)]:
    response = client.chat.completions.create(
        model='gpt-4o', max_tokens=150,
        messages=[{'role': 'user', 'content': prompt}]
    )
    print(f'--- {label} ---')
    print(response.choices[0].message.content)
    print()

电子邮件文案中的纯文本

电子邮件文案是最常见的纯文本使用场景之一。虽然某些电子邮件客户端支持 HTML 格式,但人工智能生成的电子邮件文案应以整洁的散文形式提供,使人工编辑可以直接将其粘贴到电子邮件客户端或 CRM 中,而无需清理。

请明确说明:“将电子邮件正文写成纯文本。不要使用标记语法。不要使用星号表示粗体。不要使用连字符表示列表。请使用编号句子或换行来代替 lists。”

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=300,
    messages=[{
        'role': 'user',
        'content': (
            'Write a 3-paragraph re-engagement email for inactive newsletter subscribers. '
            'Context: SaaS analytics tool, subscriber inactive for 60 days.\n'
            'Format requirements:\n'
            '- Plain text only — no asterisks, no pound signs, no bullet symbols\n'
            '- Paragraph 1: acknowledge absence, create curiosity\n'
            '- Paragraph 2: one new feature they missed\n'
            '- Paragraph 3: CTA with a direct link placeholder [LINK]\n'
            '- No subject line — body only'
        )
    }]
)
print(response.content[0].text)

整洁的散文段落

除了避免使用标记语法符号之外,“整洁的散文”还意味着将想法组织成连贯的句子,而不是零散的项目符号。

优秀的散文:

  • 使用过渡词连接想法(然而、此外、因此)
  • 改变句子长度以形成节奏
  • 将相关想法归入连贯的段落
  • 避免每个句子都以名词开头

请求:“使用整洁的散文段落——不要使用 lists 或标题,使用带有过渡词的连贯句子。”

import openai

client = openai.OpenAI(api_key='sk-your-key-here')

prose_prompt = (
    'Explain the advantages of using Docker for development environments. '
    'Write in 3 clean prose paragraphs. '
    'Requirements:\n'
    '- No bullet points or numbered lists\n'
    '- No markdown headers\n'
    '- Use transition words between sentences and paragraphs\n'
    '- Vary sentence length — mix short and long\n'
    '- 150 words total maximum'
)

response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{'role': 'user', 'content': prose_prompt}]
)
print(response.choices[0].message.content)

语音输出中的纯文本

文本转语音系统会按字面读出所有内容。如果人工智能的输出将被朗读:

  • 避免使用所有标记语法符号
  • 避免使用缩写(TTS 可能不会将其展开)
  • 在适当情况下将数字完整拼写出来
  • 使用逗号表示自然的停顿位置
  • 避免使用括号——TTS 通常会以不自然的方式读出括号
  • 拼写出特殊字符(将“@”读作“在”)
import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=200,
    messages=[{
        'role': 'user',
        'content': (
            'Write a 45-second spoken weather briefing for London today. '
            'Conditions: 12 degrees Celsius, light rain, wind 15 km/h from the southwest.\n'
            'Format for voice output:\n'
            '- No markdown symbols of any kind\n'
            '- No parentheses\n'
            '- No abbreviations (write "kilometres per hour" not "km/h")\n'
            '- Natural spoken rhythm — use commas for pause points\n'
            '- Write numbers as words when under ten'
        )
    }]
)
print(response.content[0].text)

从现有输出中去除标记语法

有时您会获得(get)一次人工智能调用生成的标记语法输出,但需要将其用于其他场景,因此必须进行清理。您可以专门进行第二次人工智能调用来去除格式:

“从以下文本中删除所有标记语法格式。将 **粗体** 替换为纯文本,删除 # 标题,将项目符号转换为编号句子,删除所有星号和井号。仅输出整洁的纯文本。”

import openai
import re

client = openai.OpenAI(api_key='sk-your-key-here')

markdown_text = (
    '## Key Benefits\n'
    '- **Faster deployment** with Docker containers\n'
    '- **Consistent environments** across dev and prod\n'
    '- Reduced *configuration drift* between machines\n'
    '### Getting Started\n'
    'Run docker-compose up to start all services.'
)

# Option 1: Ask AI to strip
response = client.chat.completions.create(
    model='gpt-4o',
    max_tokens=150,
    messages=[{
        'role': 'user',
        'content': (
            'Remove all markdown formatting from the text below. '
            'Keep all the information but strip: **, ##, ###, -, *, backticks. '
            'Convert bullet lists to flowing sentences. Output plain text only.\n\n'
            + markdown_text
        )
    }]
)
print('AI-stripped:', response.choices[0].message.content.strip())

# Option 2: Simple regex strip (for code-based pipelines)
import re
clean = re.sub(r'[#*]', '', markdown_text).strip()
print('Regex-stripped:', clean)

系统消息中的纯文本

对于始终向纯文本环境输出内容的人工智能助手,与其在每次用户消息中重复格式规则,不如在系统消息中一次性设置该规则。

对于能够提前确定呈现环境的生产应用,这是最整洁的方法。

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

# System message enforces plain text for all responses
plain_text_system = (
    'You are a helpful assistant embedded in a mobile push notification system. '
    'All your responses are displayed as plain text in mobile notifications. '
    'ALWAYS follow these formatting rules:\n'
    '- Never use markdown (no **, no #, no -, no backtick, no *, no _)\n'
    '- Never use bullet points or numbered lists\n'
    '- Write in 1-2 complete sentences only\n'
    '- Maximum 120 characters per response\n'
    '- No emojis'
)

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=64,
    system=plain_text_system,
    messages=[
        {'role': 'user', 'content': 'Notify user their order has shipped and will arrive in 2 days.'}
    ]
)
print(response.content[0].text)

格式选择框架

在请求任何输出格式之前,请使用以下快速决策框架:

  1. 输出将发送到哪里?网页界面、电子邮件、终端、语音或数据库
  2. 该环境是否会呈现标记语法?是 → 使用标记语法。否 → 使用纯文本。
  3. 人类会阅读它吗?是 → 组织内容以便快速浏览。否 → 针对解析进行优化。
  4. 代码会处理它吗?是 → 使用结构化数据格式或 CSV,不要使用散文。
  5. 内容会被朗读吗?是 → 使用适合语音的纯文本,不要使用缩写。
def choose_format(environment, human_reads, code_processes, voice_output):
    '''Simple formatting decision tree.'''
    if voice_output:
        return 'PLAIN TEXT — voice safe, spell out numbers and units'
    if code_processes:
        return 'JSON or CSV — machine-parseable, no prose'
    renders_markdown = environment in ['web', 'notion', 'github', 'vscode', 'obsidian']
    if renders_markdown and human_reads:
        return 'MARKDOWN — headers, bold, code blocks, lists'
    return 'PLAIN TEXT — clean prose paragraphs, no markdown symbols'

scenarios = [
    ('web',         True,  False, False),
    ('email',       True,  False, False),
    ('api_pipeline',False, True,  False),
    ('voice_app',   False, False, True),
    ('terminal',    True,  False, False),
]
for env, human, code, voice in scenarios:
    result = choose_format(env, human, code, voice)
    print(f'{env:<15} -> {result}')

结构化纯文本

纯文本不必是无结构的。您可以在不使用标记语法的情况下,通过以下方式创建(create)结构:

  • ALL CAPS SECTION LABELS(在任何位置都以相同方式呈现)
  • 在各部分之间换行
  • 使用编号句子:“1. 第一点。2. 第二点。”
  • 使用破折号进行分隔:“关键见解——行动前务必进行验证。”
  • 使用空格保持一致的缩进(用于终端输出)
import openai

client = openai.OpenAI(api_key='sk-your-key-here')

response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{
        'role': 'user',
        'content': (
            'Write a daily briefing for a developer — 3 sections: TASKS, BLOCKERS, NOTES. '
            'Format: plain text only. '
            'Use ALL CAPS section labels followed by a colon. '
            'Use a line break between sections. '
            'Number each item within a section. '
            'No markdown symbols of any kind. '
            'Use realistic placeholder content.'
        )
    }]
)
print(response.choices[0].message.content)

输出格式检测

在生产应用中,您可以通过程序检测输出环境,并自动注入适当的格式说明,因此无需在每个提示中手动指定格式。

这是多通道人工智能系统中的常见模式,此类系统会为网页、移动设备和应用程序接口使用者提供相同的内容。

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

def get_format_instruction(channel):
    formats = {
        'web':   'Use markdown formatting: headers, bold, bullet points, code blocks.',
        'email': 'Plain text only. No markdown symbols. Use line breaks between sections.',
        'sms':   'Plain text. Single paragraph. Max 160 characters.',
        'voice': 'Plain text. No symbols. Natural spoken sentences only. Spell out numbers.',
        'api':   'JSON output only. No prose.',
    }
    return formats.get(channel, 'Plain text only.')

def ask_with_channel(question, channel):
    fmt = get_format_instruction(channel)
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=100,
        system=f'Format instruction: {fmt}',
        messages=[{'role': 'user', 'content': question}]
    )
    return response.content[0].text

q = 'What are 3 benefits of regular code reviews?'
for ch in ['web', 'sms', 'voice']:
    print(f'[{ch.upper()}]:')
    print(ask_with_channel(q, ch)[:150])
    print()

知识检查

一名开发人员为客户服务构建了一个人工智能聊天机器人,该机器人会将回复传送到只能存储纯文本的旧版 CRM 中。人工智能不断输出带有 **(表示粗体)和 -(表示项目符号)的回复,而这些符号在 CRM 中会以原始字符显示。最可靠的解决方法是什么?

纯文本与格式化输出——回顾

正确格式的选择取决于输出环境。主要规则如下:

  • 当环境能够呈现标记语法时使用标记语法:网页界面、笔记工具、GitHub 和文档
  • 电子邮件文案、SMS、语音、CRM 和应用程序接口处理流水线使用纯文本
  • 当代码将处理输出时,使用结构化数据格式/CSV
  • 通过明确列出需要避免的内容来请求纯文本:不要使用星号、井号或项目符号
  • 为了确保应用行为一致,在系统消息中设置一次格式规则
  • 纯文本仍然可以通过 CAPS LABELS、换行和编号句子来保持结构
免费开始

用 AI 导师学习 AI Prompt Engineering — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
53
课程
199

常见问题解答

「纯文本与格式化输出」课时是免费的吗?

是的 — 「纯文本与格式化输出」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。

「纯文本与格式化输出」这节课中我会学到什么?

了解何时应请求整洁的纯文本,何时应请求丰富的 Markdown 输出 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Prompt Engineering 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「纯文本与格式化输出」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Prompt Engineering 课中编写并运行代码吗?

能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 请求列表与项目符号
  2. 请求表格与结构化数据
  3. 提示中的 Markdown 格式
  4. 纯文本与格式化输出
← 返回 AI Prompt Engineering