0Pricing
AI Prompt Engineering · 课时

什么是元提示词?

生成其他提示词的提示词:LLM 的递归能力。

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

元提示词的定义

元提示词是编写提示词,使其输出其他提示词的一种方法。元提示词不是直接解决任务,而是指示模型生成之后用于解决任务的指令。这是在常规提示词之上的一层抽象。

一阶提示词与元提示词

一阶提示词与元提示词的区别在于:一阶提示词生成任务输出(摘要、代码、分析);元提示词生成提示词、评估标准或系统指令,然后这些内容可以应用于实际任务。

import anthropic

client = anthropic.Anthropic(api_key='YOUR_API_KEY')

# FIRST-ORDER prompt (produces a task output directly)
first_order = 'Write a customer service response for a user whose order was delayed.'

# META-PROMPT (produces a prompt that can then solve similar tasks)
meta_prompt = (
    'Design a system prompt for a customer service AI agent '
    'that handles order delay complaints. The agent should '
    'be empathetic, solution-focused, and proactively offer '
    'compensation when appropriate. Output only the system prompt.'
)

response = client.messages.create(
    model='claude-opus-4-5', max_tokens=800,
    messages=[{'role': 'user', 'content': meta_prompt}]
)
generated_system_prompt = response.content[0].text
print('Generated system prompt:')
print(generated_system_prompt[:300], '...')

使用场景 1:生成系统提示词

元提示词最强大的用途之一,是为特定角色或应用生成系统提示词。您不必手动编写系统提示词,而是可以向模型提供使用场景的描述,让它生成相应的系统提示词。

META_SYSTEM_PROMPT_GENERATOR = '''You are a prompt engineer specializing in system prompts.
Given a description of an AI assistant role, generate a comprehensive system prompt.

The system prompt you generate must:
1. Define the assistant\'s persona and expertise
2. Specify its primary objectives
3. List behavioral rules (what it should and should not do)
4. Define output format preferences
5. Include appropriate disclaimers for the domain
6. Be between 200-400 words

Output only the system prompt — no explanation, no preamble.'''

def generate_system_prompt(role_description):
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=600,
        system=META_SYSTEM_PROMPT_GENERATOR,
        messages=[{'role': 'user', 'content':
            f'Generate a system prompt for: {role_description}'}]
    )
    return response.content[0].text

# Example: generate a system prompt for a coding tutor
result = generate_system_prompt(
    'A Python coding tutor for absolute beginners aged 12-16, '
    'who explains concepts using simple analogies and emojis'
)
print(result[:400], '...')

使用场景 2:创建评估标准

元提示词可以为任务生成评估量表。与其手动定义什么才算“优秀”,不如让模型针对给定目标生成评估标准。

META_CRITERIA_GENERATOR = '''You are an evaluation framework designer.
Given a task description, create a detailed evaluation rubric.

For each criterion:
- Name: concise label
- Weight: percentage (all weights sum to 100)
- Description: what to look for
- Scoring: 1-5 scale with what each score means

Output as a JSON array.'''

def generate_eval_criteria(task_description):
    import json
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=1000,
        system=META_CRITERIA_GENERATOR,
        messages=[{'role': 'user', 'content':
            f'Create evaluation criteria for: {task_description}'}]
    )
    return json.loads(response.content[0].text)

criteria = generate_eval_criteria(
    'AI-generated summaries of financial earnings reports'
)
for c in criteria[:3]:
    print(f'{c["name"]} ({c["weight"]}%): {c["description"][:50]}')

使用场景 3:提示词模板设计

元提示词可以为常见任务生成可重复使用的提示词模板。元提示词接收任务描述,并输出带有 {variable} 占位符的参数化模板。

META_TEMPLATE_DESIGNER = '''You are a prompt template engineer.
Given a task type, design a prompt template with {variable} placeholders.

Requirements:
- Identify all input variables and use {variable_name} syntax
- Include clear instruction structure
- Specify desired output format
- Add any necessary constraints or rules
- Output: JSON with keys: template (string), variables (list of variable descriptions)'''

def design_prompt_template(task_type):
    import json
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=800,
        system=META_TEMPLATE_DESIGNER,
        messages=[{'role': 'user', 'content':
            f'Design a prompt template for: {task_type}'}]
    )
    return json.loads(response.content[0].text)

template = design_prompt_template('extracting action items from meeting notes')
print('Template:', template['template'][:200], '...')
print('Variables:', template['variables'][:3])

用于生成角色设定的元提示词

元提示词可以生成多样化的人工智能角色定义。这对于角色扮演应用、聊天机器人配置,以及测试不同角色设定下的人工智能行为都很有用。

META_PERSONA_GENERATOR = '''Generate {num_personas} distinct AI assistant personas for the following application.
Each persona should have:
- Name
- Personality traits (3-5 adjectives)
- Communication style description
- Expertise areas
- Signature phrases or patterns
- Things this persona would never say

Make personas meaningfully different from each other.
Output as a JSON array.'''

def generate_personas(application, num_personas=3):
    import json
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=1500,
        messages=[{'role': 'user', 'content':
            META_PERSONA_GENERATOR.format(num_personas=num_personas) +
            f'\n\nApplication: {application}'}]
    )
    return json.loads(response.content[0].text)

personas = generate_personas('a fitness and wellness coaching app')
for p in personas:
    print(f'{p["name"]}: {p["personality_traits"]}')

元提示词链

元提示词在串联使用时最为强大:一个元提示词的输出会作为下一个元提示词的输入。这样就能创建提示词生成流水线,根据高层需求构建复杂的人工智能系统。

def meta_prompt_pipeline(application_description):
    print('Step 1: Generating system prompt...')
    system_prompt = generate_system_prompt(application_description)

    print('Step 2: Generating evaluation criteria...')
    criteria = generate_eval_criteria(
        f'Responses from an AI assistant that: {application_description}'
    )

    print('Step 3: Generating test cases...')
    test_cases_meta = (
        f'Generate 5 diverse test user messages for an AI assistant '
        f'that {application_description}. '
        f'Include edge cases and difficult requests. Return as JSON list.'
    )
    test_response = client.messages.create(
        model='claude-opus-4-5', max_tokens=800,
        messages=[{'role': 'user', 'content': test_cases_meta}]
    )
    import json
    test_cases = json.loads(test_response.content[0].text)

    return {
        'system_prompt': system_prompt,
        'eval_criteria': criteria,
        'test_cases': test_cases
    }

result = meta_prompt_pipeline('helps junior developers understand error messages')
print('Pipeline output keys:', list(result.keys()))

元提示词质量控制

生成的提示词在使用前需要经过验证。请进行质量检查:生成的提示词是否包含所有必需元素?是否避开了常见问题?同时使用自动化检查和人工审查环节。

def validate_generated_system_prompt(system_prompt):
    checks = {
        'Has persona definition': any(w in system_prompt.lower() for w in
            ['you are', 'your role', 'you\'re', 'act as']),
        'Has behavioral rules': any(w in system_prompt.lower() for w in
            ['do not', 'never', 'always', 'must', 'should']),
        'Has output format': any(w in system_prompt.lower() for w in
            ['format', 'output', 'structure', 'respond with']),
        'Length appropriate': 100 < len(system_prompt.split()) < 600,
        'No explicit profanity': True,  # add real check in production
        'Has domain scope': len(system_prompt) > 50
    }
    passed = sum(checks.values())
    print(f'Validation: {passed}/{len(checks)} checks passed')
    for check, result in checks.items():
        status = 'PASS' if result else 'FAIL'
        print(f'  [{status}] {check}')
    return all(checks.values())

# Validate a generated prompt
test_prompt = 'You are a helpful customer service assistant. Always be polite.'
validate_generated_system_prompt(test_prompt)

元提示词的局限性

元提示词功能强大,但也存在重要局限,实践者必须理解这些局限。生成的提示词在投入生产使用前需要经过人工审查。

meta_prompting_limitations = {
    'Quality variance': (
        'Generated prompts vary in quality. '
        'Always evaluate and iterate — do not use raw output in production.'
    ),
    'Domain knowledge gaps': (
        'The model may generate plausible-sounding prompts that '
        'miss critical domain-specific requirements. '
        'Domain experts must review generated criteria and rules.'
    ),
    'Hallucinated instructions': (
        'Generated prompts may include instructions that sound right '
        'but are incorrect (e.g., citing wrong regulations, wrong APIs). '
        'Verify all factual claims in generated prompts.'
    ),
    'Misalignment with intent': (
        'A generated system prompt may technically fulfill the meta-prompt '
        'but not capture the actual product requirements. '
        'User testing is still required.'
    ),
    'Compounding errors': (
        'In meta-prompt chains, errors in early stages compound. '
        'Validate outputs at each step before passing to the next.'
    )
}

for limitation, description in meta_prompting_limitations.items():
    print(f'{limitation}: {description[:80]}...')

用于提示词批评的元提示词

除了生成提示词,元提示词还可以批评现有提示词。请模型审查一个提示词并找出其薄弱之处——缺少约束、指令含义不明确,或缺少输出格式规范。

CRITIQUE_META_PROMPT = '''You are an expert prompt engineer.
Review the following prompt and identify weaknesses.

Prompt to review:
{prompt_to_review}

For each weakness:
1. Weakness: what is missing or unclear
2. Impact: what problems this causes in practice
3. Fix: exact suggested replacement text

Also provide:
- Overall quality score: 1-10
- Top 3 improvements ordered by impact

Be specific — quote the relevant part of the prompt.'''

def critique_existing_prompt(prompt_text):
    import anthropic
    client = anthropic.Anthropic(api_key='YOUR_API_KEY')
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=1000,
        messages=[{'role': 'user', 'content':
            CRITIQUE_META_PROMPT.format(prompt_to_review=prompt_text)}]
    )
    return response.content[0].text

# Example usage
weak_prompt = 'Summarize the article.'
critique = critique_existing_prompt(weak_prompt)
print(critique[:300], '...')

元提示词与手动提示词工程

元提示词和手动提示词工程各有优势。知道何时使用哪一种方法,与知道如何使用同样重要。

WHEN_TO_USE = {
    'Meta-prompting is better when': [
        'You need many prompt variants quickly (A/B testing)',
        'The use case is well-defined and the requirements are clear',
        'You need to scale prompt creation across many categories',
        'You want to explore the design space of possible prompts',
        'You have evaluation criteria to filter generated prompts'
    ],
    'Manual prompt engineering is better when': [
        'Deep domain expertise is required (medical, legal, safety-critical)',
        'The prompt controls a high-stakes production system',
        'Iterative refinement and human judgment are essential',
        'The requirements are nuanced and hard to express to a meta-prompt',
        'You need guaranteed correctness (not just plausible)'
    ]
}

for mode, reasons in WHEN_TO_USE.items():
    print(f'\n{mode}:')
    for r in reasons[:3]:
        print(f'  - {r}')

快速检查

元提示词区别于普通提示词的决定性特征是什么?

元提示词总结

元提示词为提示词工程增加了强大的抽象层:

  • 定义:以其他提示词作为输出的提示词
  • 使用场景:生成系统提示词、评估标准、模板设计、角色设定生成
  • 元提示词链:串联元提示词,构建完整的人工智能应用配置
  • 质量控制:投入生产使用前,始终验证生成的提示词
  • 局限性:领域知识不足、虚构指令,以及链式流程中的错误累积
  • 最适合:扩大提示词创建规模、探索设计空间、生成测试套件

常见问题解答

「什么是元提示词?」课时是免费的吗?

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

「什么是元提示词?」这节课中我会学到什么?

生成其他提示词的提示词:LLM 的递归能力。 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

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

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

「什么是元提示词?」课时需要多长时间?

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

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

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

此课程中的所有课时

  1. 什么是元提示词?
  2. 生成提示词的提示词
  3. 自我改进的提示词系统
  4. 自我改进中的评估与选择
← 返回 AI Prompt Engineering