AI Prompt Engineering · 课时

提供背景信息

了解何时以及如何加入领域知识、限制条件和项目细节

第 2 / 4 课13 个步骤

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

背景信息为何重要

背景信息会向模型提供它无法自行知道的事实:您的具体项目详情、团队的限制、已有成果,以及利益相关者的期望。

没有背景信息时,模型会针对一个想象中的普通情况生成内容。有了背景信息后,它生成的内容才会针对您的实际情况。

何时加入领域知识

在以下情况下,请将领域知识加入提示词:

  • 该主题在不同行业中有多种解释
  • 您正在使用专业术语
  • 正确答案取决于特定领域的规范或法规
  • 模型可能给出通用答案,而您需要特定领域的答案

不要粘贴整本教材——请概括与您的具体问题最相关的 2 至 3 条领域事实。

import anthropic

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

domain_knowledge = (
    'Domain: algorithmic trading at a regulated broker-dealer in the US. '
    'Relevant rules: SEC Rule 15c3-5 (Market Access Rule) requires pre-trade risk checks. '
    'Latency budget: all risk checks must complete in under 100 microseconds. '
    'Stack: C++ for the matching engine, Python for strategy logic.'
)

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=300,
    messages=[{
        'role': 'user',
        'content': (
            f'{domain_knowledge}\n\n'
            f'Question: How should we implement position limit checks for our order router?'
        )
    }]
)
print(response.content[0].text)

加入项目详情

项目详情会告诉模型您工作的具体背景。重要的项目详情包括:

  • 项目是什么,以及当前处于哪个阶段(MVP/扩张阶段/成熟阶段)
  • 技术栈和架构
  • 团队规模和技能水平
  • 时间安排和截止期限带来的压力
  • 会影响当前问题的近期变更或事件
import openai

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

project_context = (
    'Project: a mobile recipe app (React Native, Node.js backend, MongoDB). '
    'Stage: pre-launch, 2 weeks to go live. '
    'Team: 2 frontend devs, 1 backend dev, no dedicated QA. '
    'Current issue: app search is slow (3-5 seconds) with 50,000 recipes in the DB. '
    'Constraint: no time for a full re-architecture before launch.'
)

response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{
        'role': 'user',
        'content': (
            f'{project_context}\n\n'
            f'Suggest 3 quick wins to improve search speed before launch. '
            f'Each suggestion: what to do (1 sentence), estimated effort (hours), '
            f'expected improvement.'
        )
    }]
)
print(response.choices[0].message.content)

分享已有成果

分享已有成果可以让模型在您已经完成的工作基础上继续,而不是从头开始。以下情况下,请加入已有成果:

  • 需要续写或扩展文档或代码
  • 需要批评和改进建议
  • 需要匹配风格(匹配现有内容的语气和格式)
  • 需要检查一致性(新内容是否符合现有结构)
import anthropic

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

existing_intro = (
    'At Northlight Labs, we build AI tools that work the way humans think — '
    'not the other way around. Founded in 2022 by two ex-Google researchers, '
    'we have helped 500 companies ship smarter products without hiring ML teams.'
)

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=200,
    messages=[{
        'role': 'user',
        'content': (
            'Here is our existing company intro paragraph:\n\n'
            f'{existing_intro}\n\n'
            'Write a second paragraph (matching this exact tone and style) '
            'that describes our flagship product: an API that lets developers '
            'add natural language search to any database with 3 lines of code. '
            'Keep it under 60 words.'
        )
    }]
)
print(response.content[0].text)

提前说明约束

约束是模型必须遵守的规则。提前说明约束,可以防止模型建议一些完全合理、却恰好无法在您当前情况下实现的想法。

应包含的约束类型:

  • 技术方面:“Python 3.11,不得使用第三方库”
  • 预算方面:“0 美元——只能使用开源方案”
  • 时间方面:“必须在 2 小时的开发周期内完成”
  • 监管方面:“日志中不得包含个人身份信息”
  • 组织方面:“不能更改数据库架构”
import openai

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

response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{
        'role': 'user',
        'content': (
            'We need to add rate limiting to our REST API.\n\n'
            'Constraints:\n'
            '- Python 3.11 FastAPI application\n'
            '- No external dependencies beyond what is already installed (requests, pydantic, uvicorn)\n'
            '- Must work as a single process (no Redis, no shared state between workers)\n'
            '- Rate limit: 100 requests per minute per IP address\n'
            '- If limit exceeded, return HTTP 429 with Retry-After header\n\n'
            'Show me a complete implementation.'
        )
    }]
)
print(response.choices[0].message.content)

利益相关者信息

利益相关者信息会告诉模型,在您的情况下还有哪些人很重要。利益相关者会影响需要强调的风险、需要回应的异议,以及成功的标准。

  • “我的受众包括一位对人工智能投资持怀疑态度的 CFO”
  • “这会在发布前由我们的法务团队审核”
  • “最终用户有无障碍使用需求——必须兼容屏幕阅读器”
  • “我们的 CTO 更喜欢简单的解决方案,而不是巧妙但复杂的方案”
import anthropic

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

stakeholder_context = (
    'This proposal will be reviewed by:\n'
    '1. CTO: cares about technical risk and maintainability, skeptical of microservices\n'
    '2. CFO: cares about cost, wants to see clear ROI numbers\n'
    '3. VP Engineering: cares about developer experience and team morale\n'
    'The CTO has veto power.'
)

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=400,
    messages=[{
        'role': 'user',
        'content': (
            f'{stakeholder_context}\n\n'
            f'Write a 3-paragraph executive summary for a proposal to migrate '
            f'our monolith to a modular monolith (not microservices). '
            f'Address each stakeholder\'s top concern in a separate paragraph.'
        )
    }]
)
print(response.content[0].text)

按时间顺序组织的方法

面对复杂情况时,按时间顺序组织的方法会将背景信息整理成事件时间线。这有助于模型理解因果关系和当前状态。

格式:

  • 情况之前是什么样的
  • 发生了什么变化或事件
  • 当前状态是什么
  • 根据这一过程,您需要获得什么帮助
import openai

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

chronological_background = (
    'Timeline:\n'
    '- 6 months ago: We launched v1 of our API with a flat pricing model ($99/month).\n'
    '- 3 months ago: Power users (top 10%) started consuming 80% of compute.\n'
    '- 1 month ago: We introduced usage-based pricing — power users complained loudly.\n'
    '- Current: 12% of power users have churned; new signups are up 15%.\n'
    '- Goal: Keep power users without losing the new-signup growth.\n'
)

response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{
        'role': 'user',
        'content': (
            f'{chronological_background}\n\n'
            f'Suggest 3 pricing model adjustments that could address both groups. '
            f'For each: describe the change, who it benefits, and the revenue risk.'
        )
    }]
)
print(response.choices[0].message.content)

使用自己的数据作为背景

背景信息最强大的用途之一,是将您自己的数据——指标、日志、输出结果或研究资料——直接注入提示词,让模型能够根据您的具体数据进行推理。

请始终以整洁、易读的格式粘贴数据。表格和结构化列表的效果最好。原始文本堆积在一起时,模型更难解析。

import anthropic

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

metrics_data = (
    'Weekly active users (WAU) last 8 weeks:\n'
    'Week 1: 1,200  |  Week 2: 1,350  |  Week 3: 1,290  |  Week 4: 1,400\n'
    'Week 5: 1,380  |  Week 6: 1,220  |  Week 7: 1,100  |  Week 8: 980\n'
    'Note: We launched a pricing change in Week 5.'
)

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=300,
    messages=[{
        'role': 'user',
        'content': (
            f'{metrics_data}\n\n'
            f'Analyze the trend, identify where decline began, '
            f'and suggest 2 hypotheses for the cause. '
            f'Be specific — reference the exact weeks in your analysis.'
        )
    }]
)
print(response.content[0].text)

不应作为背景包含的内容(NOT)

背景信息是有成本的:会消耗令牌。只包含会直接影响答案的内容。

通常不必要的背景信息:

  • 公司创立故事(除非品牌语气很重要)
  • 团队组织架构图(除非决策权限很重要)
  • 早于决策时间范围的历史背景
  • 您并未使用的技术(NOT)
  • 与当前问题无关、已经解决的问题

如果拿不准:先加入一次,查看输出是否有所改善,然后在后续运行中删减。

# Contrast: bloated vs lean background
bloated_background = (
    'Our company was founded in 2018 by Alice and Bob. '
    'We have 45 employees across 3 offices. We use Jira for project management. '
    'We had a product refresh in 2020. Our CTO came from Amazon. '
    'We use Slack, Notion, and Linear. '
    'We once tried Kubernetes but moved back to Docker Compose. '
    'Question: How should we handle database connection pooling in FastAPI?'
)

lean_background = (
    'Stack: FastAPI, PostgreSQL, deployed on a single 8-core server. '
    'Load: ~200 concurrent users peak. '
    'Current issue: seeing "too many connections" errors under load. '
    'Question: How should we handle database connection pooling?'
)

print('Bloated background:', len(bloated_background.split()), 'words')
print('Lean background:', len(lean_background.split()), 'words')
print('Reduction:', round((1 - len(lean_background.split())/len(bloated_background.split()))*100), '%')

以易读的格式整理背景信息

背景信息的格式会影响模型处理这些信息的效果。最佳做法:

  • 使用带标签的部分:Stack:、Constraints:、Goal:
  • 使用项目符号列表列出并列项目
  • 将最重要的信息放在最前面
  • 使用空行或清晰的标记,将背景信息与任务分开
  • 使用一致的术语——不要用两个名称称呼同一事物
import openai

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

# Well-formatted background
formatted_background = (
    '=== BACKGROUND ===\n'
    'Project: real-time chat API\n'
    'Stack: Python FastAPI, WebSockets, Redis pub/sub, PostgreSQL\n'
    'Scale: 10,000 concurrent connections target\n'
    'Constraints: single server for now, no Kubernetes\n'
    'Current problem: messages are occasionally delivered out of order\n'
    '=== TASK ===\n'
    'Explain the root cause of out-of-order message delivery in WebSocket pub/sub '
    'and suggest the simplest fix for our stack.'
)

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

在系统消息中复用背景信息

如果您正在构建人工智能应用,并且所有对话都适用相同的背景信息,请将其放入系统消息,而不是在每次用户发言中重复。

这样效率更高,还能确保所有交互中的上下文保持一致,无需用户反复说明。

import anthropic

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

# System message carries reusable background for every user turn
system_background = (
    'You are an AI assistant embedded in Northlight Labs\' internal developer portal. '
    'Background: our stack is Python 3.11, FastAPI, PostgreSQL 15, Redis 7, Docker. '
    'We follow Google Python style guide. All code examples must include type hints. '
    'We do not use ORM — raw SQL with psycopg3. '
    'Our API follows REST conventions with snake_case JSON fields.'
)

# Now every user turn gets this background automatically
response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=300,
    system=system_background,
    messages=[
        {'role': 'user', 'content': 'Show me how to insert a row into the users table.'}
    ]
)
print(response.content[0].text)

知识检查

一名产品经理希望人工智能帮助撰写一封功能公告邮件。他们提供了公司的创立年份、员工人数、办公地点,然后直接给出任务。缺少哪类背景信息,最能改善输出?

提供背景信息——回顾

好的背景信息,是泛泛的建议与真正适合您实际情况的建议之间的差别。关键原则:

  • 加入会影响您所在领域正确答案的领域知识
  • 分享项目详情:技术栈、阶段、团队规模、近期变更
  • 需要续写或匹配风格时,加入已有成果
  • 提前说明约束,避免得到无用的建议
  • 加入利益相关者信息,让模型回应正确的关注点
  • 对于复杂的情境背景,使用按时间顺序组织的方法
  • 保持背景信息精简——只加入会影响答案的内容
免费开始

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

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

课程
53
课程
199

常见问题解答

「提供背景信息」课时是免费的吗?

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

「提供背景信息」这节课中我会学到什么?

了解何时以及如何加入领域知识、限制条件和项目细节 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

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

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

「提供背景信息」课时需要多长时间?

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

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

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

此课程中的所有课时

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