理解人工智能提示中的上下文
了解背景信息如何影响模型的响应方向
理解人工智能提示中的上下文 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。
上下文:模型的背景说明
上下文是能够帮助模型给出相关、准确且恰当匹配的回答的背景信息。
没有上下文,模型就只能猜测您是谁、需要什么、从事哪个领域,以及适合什么详细程度。这些猜测基于统计意义上最常见的理解,而不是您的实际情况。
没有上下文时会发生什么
请比较下面两个关于同一主题的请求:
没有上下文:“我该如何处理数据库问题?”
模型不知道您使用的是哪种数据库、具体问题是什么,也不知道在您的情境中“处理”意味着什么。
有上下文:“我们在 AWS RDS 上运行 PostgreSQL 15。昨天进行架构迁移后,我们的查询响应时间从 20ms 飙升到了 800ms。这次迁移新增了 3 个索引。我应该先调查什么?”
第二个问题包含了领域、技术、时间线、症状和最近发生的变更——这些信息足以帮助模型给出有用的回答。
import anthropic
client = anthropic.Anthropic(api_key='sk-ant-your-key-here')
no_context = 'What should I do about the database issue?'
with_context = (
'We are running PostgreSQL 15 on AWS RDS. '
'Query response time spiked from 20ms to 800ms after a schema migration yesterday. '
'The migration added 3 new indexes on the orders table (500M rows). '
'No other infrastructure changes were made. '
'What should I investigate first to diagnose the slowdown?'
)
for label, prompt in [('NO CONTEXT', no_context), ('WITH CONTEXT', with_context)]:
response = client.messages.create(
model='claude-opus-4-5',
max_tokens=200,
messages=[{'role': 'user', 'content': prompt}]
)
print(f'--- {label} ---')
print(response.content[0].text[:300])
print()上下文的四种类型
每条提示词都可以从最多四种上下文中受益:
- 领域上下文——您正在从事的领域或行业
- 受众上下文——谁会使用或阅读输出
- 目标上下文——您最终想要实现什么
- 约束上下文——存在哪些限制(时间、预算、技术栈和规则)
并非每条提示词都需要这四种上下文,但了解这些类别有助于您找出缺失的信息。
import openai
client = openai.OpenAI(api_key='sk-your-key-here')
# Prompt with all 4 context types explicitly labelled
response = client.chat.completions.create(
model='gpt-4o',
messages=[{
'role': 'user',
'content': (
'Domain context: B2B SaaS, fintech, invoice reconciliation.\n'
'Audience context: mid-market CFOs with basic Excel skills, no coding.\n'
'Goal context: write a one-pager that convinces them to book a demo.\n'
'Constraint context: max 300 words, no technical jargon, no pricing mentioned.\n\n'
'Task: Write the one-pager.'
)
}]
)
print(response.choices[0].message.content)领域上下文
领域上下文会告诉模型您正在处理的领域、行业或主题。它会确定词汇、默认知识水平以及需要关注的相关问题。
同一个问题在不同领域可能完全不同。“如何妥善处理错误?”在软件工程中指异常处理;在客户服务中指降低冲突的技巧;在医学中则指差错未遂事件报告。
import anthropic
client = anthropic.Anthropic(api_key='sk-ant-your-key-here')
# Same question, different domain context
domains = [
('Software Engineering', 'We build Python microservices.'),
('Customer Service', 'We run a 50-agent call center for an e-commerce brand.'),
('Surgical Team', 'We are a hospital OR team implementing WHO checklists.'),
]
for domain, context in domains:
response = client.messages.create(
model='claude-opus-4-5',
max_tokens=80,
messages=[{
'role': 'user',
'content': f'Context: {context}\n\nQuestion: How do I handle errors gracefully? (1 sentence answer)'
}]
)
print(f'[{domain}]: {response.content[0].text.strip()}')
print()受众上下文
受众上下文会告诉模型谁将阅读、听取或使用输出内容。这会决定:
- 词汇难度和默认知识水平
- 所需的解释深度
- 语气(正式还是对话式)
- 应使用的类比
- 应省略的内容(过于基础或过于高级)
受众会影响一切。同一个概念,向幼儿园孩子和博士生解释时,呈现方式应该完全不同。
import openai
client = openai.OpenAI(api_key='sk-your-key-here')
audiences = [
'a 10-year-old who loves video games',
'a first-year computer science university student',
'a senior software architect with 15 years of experience'
]
for audience in audiences:
response = client.chat.completions.create(
model='gpt-4o',
max_tokens=80,
messages=[{
'role': 'user',
'content': f'Explain recursion in 2 sentences for {audience}.'
}]
)
print(f'Audience: {audience}')
print(response.choices[0].message.content.strip())
print()目标上下文
目标上下文说明输出内容最终要用于什么。这与任务本身不同——它指的是后续用途。
- 任务:“撰写产品介绍”
- 目标:“这将用于 PPC 落地页,以转化从未听说过我们的陌生流量”
当模型了解目标后,就能更好地决定应包含哪些内容、采用多强的说服方式,以及读者可能会提出哪些问题。
import anthropic
client = anthropic.Anthropic(api_key='sk-ant-your-key-here')
goals = [
'Internal documentation for our own engineering team',
'A sales one-pager to send cold prospects who know nothing about our product',
'A support article for existing customers who are confused about the feature'
]
for goal in goals:
response = client.messages.create(
model='claude-opus-4-5',
max_tokens=100,
messages=[{
'role': 'user',
'content': (
f'Goal: {goal}\n\n'
f'Task: Write 2 sentences about our new AI-powered search feature '
f'that finds relevant documents from a knowledge base.'
)
}]
)
print(f'Goal: {goal}')
print(response.content[0].text.strip())
print()约束上下文
约束上下文描述输出内容必须遵守的限制:
- 技术方面:“必须在没有互联网连接的情况下运行”,“只能使用 Python 3.9,不得使用第三方库”
- 预算方面:“只能使用免费层”,“解决方案的成本必须低于每月 50 美元”
- 监管方面:“符合 HIPAA”,“适用 GDPR——提示词中不得包含用户数据”
- 组织方面:“上线前必须获得法务批准”,“我们不能更改数据库架构”
约束上下文可以防止模型建议在您的实际情况下无法实现的解决方案。
import openai
client = openai.OpenAI(api_key='sk-your-key-here')
response = client.chat.completions.create(
model='gpt-4o',
messages=[{
'role': 'user',
'content': (
'Suggest 3 ways to cache API responses in a Python backend.\n\n'
'Constraint context:\n'
'- Python 3.11, stdlib only (no Redis, no Memcached, no third-party libraries)\n'
'- The backend is a single process (no distributed cache needed)\n'
'- Cache must expire after 5 minutes automatically\n'
'- Solution must work on a server without internet access'
)
}]
)
print(response.choices[0].message.content)缺少上下文时模型会自行猜测
这里有一个关键的思维模型:每一项缺失的上下文,都是模型替您做出的一个决定,而且不会告诉您。
缺少领域信息 → 模型会为该主题选择最常见的领域
缺少受众信息 → 模型会面向最常见的读者来撰写
缺少目标信息 → 模型会选择最明显的目标
缺少约束信息 → 模型会忽略所有限制
这些未被说明的选择,就是您经常得到略显不合适的答案的原因——答案在技术上正确,却不适合您的实际情况。
import anthropic
client = anthropic.Anthropic(api_key='sk-ant-your-key-here')
# Demonstrate: same question, very different useful answers with context
without_context = 'How should I structure my data?'
with_full_context = (
'Domain: mobile gaming backend, 10M daily active users.\n'
'Technology: Python FastAPI + PostgreSQL + Redis.\n'
'Goal: store player inventory items (weapon skins, power-ups) with fast reads.\n'
'Constraint: reads happen 50x more than writes; schema changes are expensive.\n\n'
'How should I structure my data? Give 2 options with tradeoffs.'
)
response = client.messages.create(
model='claude-opus-4-5',
max_tokens=300,
messages=[{'role': 'user', 'content': with_full_context}]
)
print(response.content[0].text)各类上下文最重要的场景
并非每个提示词都需要包含四类上下文,但某些任务类别尤其受益于特定类型的上下文:
- 技术任务:领域上下文和约束上下文最为关键
- 写作任务:受众上下文和目标上下文带来的改善最大
- 解释说明:仅受众上下文就能显著提升输出质量
- 决策支持:约束上下文可以避免无用的建议
- 创意任务:目标上下文和领域上下文可以确定正确的创作框架
import openai
client = openai.OpenAI(api_key='sk-your-key-here')
# Context selection for a creative task
response = client.chat.completions.create(
model='gpt-4o',
messages=[{
'role': 'user',
'content': (
'Domain: luxury skincare brand (eco-conscious, premium, women 35-55).\n'
'Goal: Valentine\'s Day campaign headline — will run on Instagram and in email.\n'
'Constraint: must not mention price, discount, or sale. Max 8 words.\n\n'
'Generate 5 headline options.'
)
}]
)
print(response.choices[0].message.content)上下文与提示词污染
上下文并非越多越好。无关的上下文会污染提示词,还可能使模型困惑,导致回答偏离主题。
保持上下文简洁的规则:
- 只包含会直接影响输出的信息
- 有两句话的摘要就够时,不要粘贴整份文档
- 删除相互矛盾的上下文
- 如果不确定某项上下文是否相关,请先省略;只有当输出质量受到影响时,再将其加入
import anthropic
client = anthropic.Anthropic(api_key='sk-ant-your-key-here')
# Polluted context (too much irrelevant info)
polluted = (
'I started my company in 2019. We have 12 employees. We use Slack. '
'Our office is in Berlin. We had a good Q3. Our CEO is named Thomas. '
'We have a dog-friendly office. We use Python for our backend. '
'Last year we moved to a new CRM. We sponsor a local football team.\n\n'
'Write a 2-sentence company bio for our website.'
)
# Clean context (only relevant info)
clean = (
'Company: B2B SaaS, Berlin, founded 2019, 12 employees. '
'Product: Python-based CRM for mid-market sales teams.\n\n'
'Write a 2-sentence company bio for our website.'
)
for label, prompt in [('POLLUTED', polluted), ('CLEAN', clean)]:
response = client.messages.create(
model='claude-opus-4-5',
max_tokens=100,
messages=[{'role': 'user', 'content': prompt}]
)
print(f'--- {label} ---')
print(response.content[0].text.strip())
print()将上下文作为标准做法
最有效的提示词撰写者会把上下文当作标准模板部分,放在每条任务指令之前。
一个简单的模板:
Context: [domain, technology, role, situation] Audience: [who reads/uses the output] Goal: [what this will accomplish] Constraints: [what must/must not be included] Task: [the actual instruction]
在每次编写提示词前填写这个模板只需 30 秒,却能避免数小时的反复改写。
# Standard context template implementation
def build_prompt(context, audience, goal, constraints, task):
sections = []
if context: sections.append(f'Context: {context}')
if audience: sections.append(f'Audience: {audience}')
if goal: sections.append(f'Goal: {goal}')
if constraints: sections.append(f'Constraints: {constraints}')
sections.append(f'Task: {task}')
return '\n'.join(sections)
prompt = build_prompt(
context='Python open-source project, MIT license, 2,000 GitHub stars',
audience='New contributors who know Python but are unfamiliar with our codebase',
goal='Help them submit their first pull request within 30 minutes of reading',
constraints='Max 400 words. No command-line flags beyond git basics. No Docker.',
task='Write a Getting Started contributing guide.'
)
print(prompt)知识检查
一名开发者向人工智能提问:“请帮我优化查询。”人工智能给出了通用的 SQL 优化建议,但这些建议并不适用于该开发者的环境。缺失的哪类上下文最为关键(MOST)?
人工智能提示词中的上下文——回顾
上下文是模型提供有用且有针对性的回答,而不是泛泛回答所需的背景信息。上下文分为四类:
- 领域上下文:领域、行业、技术栈
- 受众上下文:谁会阅读输出内容,以及他们的背景和专业程度
- 目标上下文:输出内容最终要用于什么
- 约束上下文:必须遵守哪些限制
每一项缺失的上下文,都是模型替您默默做出的一个决定。使用上下文模板,在每个重要提示词之前系统地加入关键信息。
常见问题解答
「理解人工智能提示中的上下文」课时是免费的吗?
是的 — 「理解人工智能提示中的上下文」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。
「理解人工智能提示中的上下文」这节课中我会学到什么?
了解背景信息如何影响模型的响应方向 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Prompt Engineering 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「理解人工智能提示中的上下文」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Prompt Engineering 课中编写并运行代码吗?
能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。