0Pricing
AI Prompt Engineering · 课时

有效设定场景

学习“您是……”“鉴于……”“目标是……”等构建场景的技巧

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

有效的开场框架

提示词的第一句话最重要。它会设定模型的工作上下文,也就是模型理解后续所有内容时所采用的视角。

有效的开场框架包括:您是……、上下文是……、鉴于……以及目标是……。每种框架都会在实际任务开始前激活上下文的不同维度。

“您是……”框架

您是……框架会为模型分配一个角色。这会激活与该角色相关的词汇、推理方式和优先事项。

关键在于具体明确。“您是一名专家”很薄弱。“您是一名拥有 10 年经验、重视可读性而非炫技的资深 Python 工程师”则很有力。

当角色设定明确暗示了您所需要的特定思考和沟通方式时,角色设定框架的效果最好。

import anthropic

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

persona_prompts = [
    'You are a Socratic philosophy professor. Ask 3 probing questions about this claim: AI will replace programmers.',
    'You are a skeptical venture capitalist who has seen 500 pitches. Give brutal feedback on this pitch: We are building an AI writing assistant.',
    'You are a patient kindergarten teacher. Explain what a computer does in 3 sentences for 5-year-olds.'
]

for prompt in persona_prompts:
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=150,
        messages=[{'role': 'user', 'content': prompt}]
    )
    print(f'--- Persona ---')
    print(prompt[:80] + '...')
    print(response.content[0].text.strip())
    print()

系统消息中的“您是……”框架

放置角色设定框架最有效的位置是系统消息,而不是用户回合。系统消息中的角色设定会在整个对话期间持续生效——您无需重复说明。

精心设计的系统角色设定可以彻底改变人工智能助手在几十个后续问题中的回应方式。

import openai

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

# Persona set once in system; stays active for all turns
system_persona = (
    'You are Marcus, a senior software architect at a Fortune 500 company. '
    'You have 20 years of experience with distributed systems. '
    'Your communication style: direct, pragmatic, no buzzwords. '
    'You always ask about scale and failure modes before giving architecture advice. '
    'If a question lacks context, ask one clarifying question before answering.'
)

response = client.chat.completions.create(
    model='gpt-4o',
    messages=[
        {'role': 'system', 'content': system_persona},
        {'role': 'user', 'content': 'Should we use microservices for our new product?'}
    ]
)
print(response.choices[0].message.content)

“context 是……”框架

context 是……框架用于设置情境背景,而不指定角色设定。当您需要模型针对您的具体情境进行推理,而不是采用某种角色时,请使用此框架。

对于技术和分析任务,这种框架尤其有效:您希望模型以自身身份进行推理,同时充分了解您的限制条件。

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': (
            'The context is: we are a 5-person startup with $2M in seed funding. '
            'Our Python monolith handles 10,000 users and is starting to show performance issues. '
            'We have one backend engineer and cannot hire more for 6 months. '
            'We need to choose between refactoring the monolith vs migrating to microservices.\n\n'
            'Give a recommendation with 3 supporting reasons. Be direct.'
        )
    }]
)
print(response.content[0].text)

“鉴于……”框架

鉴于……框架会设置一个影响整个回应的前提或假设。当您需要确立模型在任务中必须视为事实的内容时,请使用此框架。

在假设性分析、条件式规划和基于情境的写作中,这种框架非常有用,因为您需要模型从特定的起点进行推理。

import openai

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

scenarios = [
    'Given that our user base will grow 10x in 6 months, what architecture changes should we make today?',
    'Given that we must launch in 2 weeks with the current team, which features should we cut from the MVP?',
    'Given that our API key was exposed publicly for 3 hours, what steps should we take in the next 24 hours?'
]

for scenario in scenarios:
    response = client.chat.completions.create(
        model='gpt-4o',
        max_tokens=120,
        messages=[{
            'role': 'user',
            'content': scenario + ' (Answer in 3 bullet points.)'
        }]
    )
    print(f'Scenario: {scenario[:60]}...')
    print(response.choices[0].message.content.strip())
    print()

“目标是……”框架

目标是……框架会说明输出的后续用途。它不同于任务指令——它解释了您为什么需要此输出,以及输出必须完成什么目标。

这种框架可以帮助模型做出更好的细微决策:采用多大程度的说服力、预先回应哪些异议,以及应包含或省略哪些细节。

import anthropic

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

goal_frames = [
    (
        'The goal is to get the reader to schedule a 30-minute demo call. '
        'Write a 100-word cold outreach email for our AI data pipeline tool '
        'targeting data engineers at e-commerce companies.'
    ),
    (
        'The goal is to help the reader pass a senior Python interview at a FAANG company. '
        'Explain Python decorators with one conceptual explanation and one practical code example.'
    )
]

for prompt in goal_frames:
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=200,
        messages=[{'role': 'user', 'content': prompt}]
    )
    print('--- Goal Frame ---')
    print(prompt[:80] + '...')
    print(response.content[0].text.strip())
    print()

组合使用开场框架

最有效的提示词会在任务指令之前组合使用多个开场框架。典型的高性能结构如下:

  1. 您是……[角色设定]
  2. context 是……[情境]
  3. 目标是……[后续目的]
  4. 鉴于……[关键假设或限制条件]
  5. [任务指令]

每个框架都会增加一层方向引导。组合使用时,模型几乎不需要自行猜测。

import openai

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

combined_frame_prompt = (
    'You are a senior product manager with 10 years of B2B SaaS experience.\n'
    'The context is: our team is debating whether to build a native mobile app '
    'or keep investing in our responsive web app.\n'
    'The goal is: to help our leadership team make a clear go/no-go decision at '
    'next week\'s board meeting.\n'
    'Given that: we have 3 engineers, $300k runway, and 85% of current users are on desktop.\n\n'
    'Write a 250-word recommendation memo with a clear position (build or wait) '
    'and 3 supporting arguments. End with one risk to monitor.'
)

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

为语气和表达风格设置框架

开场框架还可以设置语气和表达风格,甚至完全不使用“语气”这个词。描述角色设定和情境,会隐含地确定语言风格:

  • “您是一位亲切、耐心的导师,正在与一名学习困难的学生交谈” → 自动表现得亲切且善于鼓励
  • “您是一名直截了当的军事后勤官员” → 自动表现得直接而精准
  • “您是一名为《Wired》撰稿、风趣幽默的科技记者” → 自动表现得机智且易于理解
import anthropic

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

frames = [
    'You are a warm, patient mentor. Explain why learning to code is hard but worth it.',
    'You are a no-nonsense military logistics officer. Explain why learning to code is hard but worth it.',
    'You are a witty tech journalist writing for Wired. Explain why learning to code is hard but worth it.'
]

for frame in frames:
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=80,
        messages=[{'role': 'user', 'content': frame + ' (2 sentences only)'}]
    )
    print(f'Frame: {frame[:55]}...')
    print(response.content[0].text.strip())
    print()

为分析严谨性设置框架

当您需要严谨、批判性的分析,而不是热情的赞同,请使用能够明确激活怀疑或分析思维的框架开场:

  • “您是一名批判性审阅者,职责是找出缺陷……”
  • “请扮演魔鬼代言人,质疑以下内容……”
  • “请假设传统观点是错误的,并据此论证……”
  • “请为反对……的最弱论点构建最有力的论证……”
import openai

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

analytical_frames = [
    'You are a critical reviewer whose job is to find fatal flaws. Review this startup idea: a subscription box for AI prompt templates.',
    'Play devil\'s advocate. Challenge this claim: AI will make every knowledge worker 10x more productive.',
    'Steelman the weakest argument against remote work, then give the strongest counter-argument.'
]

for frame in analytical_frames:
    response = client.chat.completions.create(
        model='gpt-4o',
        max_tokens=120,
        messages=[{'role': 'user', 'content': frame + ' (3 sentences max)'}]
    )
    print(f'Frame type: analytical/critical')
    print(f'Prompt: {frame[:60]}...')
    print(response.choices[0].message.content.strip())
    print()

何时不使用 NOT 角色框架

角色设定框架并不总是合适的工具。以下情况请避免使用:

  • 您需要提取客观数据——角色设定会引入偏差
  • 您正在处理结构化数据——角色设定会造成干扰
  • 任务纯粹是机械性的——不涉及推理
  • 您希望获得模型真实的评估——角色设定会影响观点

对于“将此 CSV 转换为 JSON”或“统计这段文字中的句子数量”这类任务,不需要框架——只需给出指令。

import anthropic

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

# Persona frame is unhelpful here — just adds tokens
prompt_with_unnecessary_frame = (
    'You are an expert data processing specialist with years of experience. '
    'Convert the following to JSON: Name: Alice, Age: 30, City: London'
)

# Clean, direct instruction
prompt_direct = (
    'Convert to a JSON object with keys name, age, city:\n'
    'Name: Alice, Age: 30, City: London'
)

for label, prompt in [('WITH UNNECESSARY FRAME', prompt_with_unnecessary_frame), ('DIRECT', prompt_direct)]:
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=50,
        messages=[{'role': 'user', 'content': prompt}]
    )
    print(f'[{label}]')
    print(response.content[0].text.strip())
    print()

测试您的框架

了解哪些框架适合您的使用场景,最好的方法是进行 A/B 测试:任务相同,开场框架不同,然后比较输出。

请测试以下维度:

  • 不使用框架与使用角色设定框架的对比
  • 模糊的角色设定与具体的角色设定的对比
  • 仅使用情境框架与同时使用情境框架和目标框架的对比
  • 使用一个框架与组合使用多个框架的对比

请记录在您的工作中,每类任务使用哪些框架能够产生最佳输出。

import openai

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

task = 'Explain the pros and cons of using TypeScript over JavaScript.'

frames = {
    'No frame':       task,
    'Persona frame':  f'You are a TypeScript advocate who also knows JavaScript deeply. {task}',
    'Goal frame':     f'The goal is to help a JavaScript developer decide if switching to TypeScript is worth it. {task}',
    'Combined frame': f'You are a pragmatic senior engineer. The goal is to help a JavaScript developer decide. {task} Give a balanced view in 3 bullet points.'
}

for label, prompt in frames.items():
    response = client.chat.completions.create(
        model='gpt-4o', max_tokens=80,
        messages=[{'role': 'user', 'content': prompt}]
    )
    print(f'[{label}]: {response.choices[0].message.content.strip()[:120]}...')
    print()

知识检查

一名开发者希望人工智能对其初创企业路演演示文稿给出批判性、尖锐的反馈——不需要鼓励,不需要平衡,只要纯粹的对抗性批评。哪种开场框架最能实现这一点?

设置情境——回顾

开场框架会在模型阅读任务指令之前为其提供方向。最有效的四种框架是:

  • “您是……”:指定具有特定专业知识、沟通风格和优先事项的角色设定
  • “context 是……”:设置情境背景,而不指定角色设定
  • “鉴于……”:确立模型必须视为事实的前提或限制条件
  • “目标是……”:定义输出的后续用途

对于复杂任务,请组合使用多个框架。对于纯机械性任务,不要使用框架。请测试不同的框架变体,找出最适合您使用场景的方案。

常见问题解答

「有效设定场景」课时是免费的吗?

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

「有效设定场景」这节课中我会学到什么?

学习“您是……”“鉴于……”“目标是……”等构建场景的技巧 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

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

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

「有效设定场景」课时需要多长时间?

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

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

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

此课程中的所有课时

  1. 理解人工智能提示中的上下文
  2. 提供背景信息
  3. 有效设定场景
  4. 上下文长度与相关性
← 返回 AI Prompt Engineering