什么是提示链
了解按顺序执行提示并传递信息的概念
什么是提示链 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。
单个提示词的上限
单个提示词能完成很多工作,但也有局限。需要多个专门化子任务、超长上下文或迭代式优化的复杂任务,往往超出单个提示词能够可靠完成的范围。
达到单个提示词上限的迹象:
- 模型在多步骤任务中跳过步骤
- 长任务的后续部分质量下降
- 输出过长,无法放入一个上下文窗口
- 任务的不同部分需要不同的专业知识或语气
什么是提示词链式调用
提示词链式调用是按顺序执行的过程,其中每个提示词的输出都会成为下一个提示词的输入。与其让一个大型提示词试图完成所有工作,不如将任务拆分为专门化的步骤。
第 1 步 → 输出 → 第 2 步 → 输出 → 第 3 步 → 最终结果
每个步骤都可以独立优化、使用不同的模型,或应用不同的约束。
一个简单的链式调用示例
以撰写一篇博客文章为例。与其使用一个提示词,不如将三个提示词串联起来:
import anthropic
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
def call(prompt):
r = client.messages.create(
model='claude-opus-4-5',
max_tokens=1000,
messages=[{'role': 'user', 'content': prompt}]
)
return r.content[0].text
# Step 1: Generate outline
outline = call('Create a 5-point outline for a blog post about prompt engineering for beginners.')
# Step 2: Expand outline into draft
draft = call(f'Write a full blog post based on this outline:\n\n{outline}')
# Step 3: Edit for clarity
final = call(f'Edit this blog post for clarity and conciseness. Remove jargon:\n\n{draft}')
print(final[:500])链式调用的适用场景:任务复杂度
当一个提示词难以高质量处理任务时,链式调用尤其有效。将复杂任务拆分为专门化步骤,可以让每个步骤专注于完成自己的小范围工作。
示例:大规模分析客户反馈
- 第 1 步:提取提到的所有问题(提取)
- 第 2 步:将每个问题分类(分类)
- 第 3 步:根据频率和严重程度确定优先级(排序)
- 第 4 步:撰写执行摘要(综合)
每个步骤都使用针对其子任务优化的专注型提示词。
链式调用的适用场景:通过专门化提升质量
对于特定的子任务,专门化提示词的表现优于通用提示词。链式调用让您可以为每个阶段使用合适的提示词风格:
# Each step uses a prompt optimized for its role
step1_prompt_template = '''
<task>Extract all named entities from the text below. Return JSON:
{"people": [], "companies": [], "locations": []}</task>
<text>{text}</text>
'''
step2_prompt_template = '''
<task>For each company in the list below, classify it as:
startup, enterprise, government, or nonprofit.
Return JSON: [{"company": str, "type": str}]</task>
<companies>{companies}</companies>
'''
# Each prompt is simpler, more focused, and easier to debug
# than a single prompt trying to do both tasks at once.
print('Specialized prompts per step.')链式调用的适用场景:上下文窗口限制
即使上下文窗口很大(100K+ 个词元),由于中间丢失效应,一次性处理非常长的文档也会导致质量下降。链式调用提供了一种解决方案:
- 第 1 步:独立处理每个文本块 → 为每个文本块生成摘要或提取结果
- 第 2 步:合并各文本块的输出 → 综合出最终答案
这种 map-归约模式是处理长文档的基本链式调用策略。
def map_reduce_summarize(document, chunk_size=3000):
chunks = [document[i:i+chunk_size] for i in range(0, len(document), chunk_size)]
# Map: summarize each chunk
summaries = []
for i, chunk in enumerate(chunks):
summary = call(f'Summarize this section of a document in 3 bullet points:\n\n{chunk}')
summaries.append(summary)
# Reduce: synthesize all summaries
combined = '\n\n'.join(f'Section {i+1}:\n{s}' for i, s in enumerate(summaries))
final = call(f'Combine these section summaries into a single executive summary:\n\n{combined}')
return final同步链与并行链
链并不总是线性的。当某些步骤彼此独立时,可以并行运行:
import concurrent.futures
def parallel_step(topics):
# Each topic can be researched in parallel — they do not depend on each other
def research_topic(topic):
return call(f'List 5 key facts about: {topic}')
with concurrent.futures.ThreadPoolExecutor() as executor:
results = list(executor.map(research_topic, topics))
# Then synthesize in a sequential step
combined = '\n\n'.join(f'{t}:\n{r}' for t, r in zip(topics, results))
synthesis = call(f'Write a comparative analysis of these topics:\n\n{combined}')
return synthesis
print('Parallel steps can reduce total latency.')链与智能体
提示词链和 AI 智能体彼此相关,但并不相同:
- 链:预先定义的确定性流程。步骤顺序固定。更易于测试、调试和预测。
- 智能体:动态流程。模型根据输出决定下一步。更加灵活,但更难控制和调试。
对于大多数生产环境用例,请从链开始。只有当任务确实是开放式任务、且无法预先确定链的结构时,才使用智能体。
链中的成本考量
链中的每个步骤都是一次独立的 API call,并有相应成本。请在设计链时考虑成本:
- 简单步骤(提取、分类)使用更便宜或更小的模型
- 将昂贵的模型(GPT-4o、Claude Opus)留给需要高水平推理的步骤
- 缓存中间结果,避免对相同输入重复运行昂贵的步骤
- 快速失败——将每个步骤的输出传递给下一步之前先进行验证
import anthropic
import functools
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
@functools.lru_cache(maxsize=128)
def cached_call(prompt, model='claude-haiku-4-5'):
r = client.messages.create(
model=model,
max_tokens=500,
messages=[{'role': 'user', 'content': prompt}]
)
return r.content[0].text
# Cheap model for extraction, expensive for synthesis
def smart_chain(text):
entities = cached_call(f'Extract entities from: {text}', model='claude-haiku-4-5')
synthesis = cached_call(f'Analyze these entities: {entities}', model='claude-opus-4-5')
return synthesis记录您的链
记录完善的链更易于维护。使用简单的结构描述每个步骤:
chain_spec = {
'name': 'Blog Post Generator',
'steps': [
{
'id': 'step_1',
'name': 'Outline Generation',
'model': 'claude-haiku-4-5',
'input': 'topic (string)',
'output': 'outline (string, 5 bullet points)',
'prompt_template': 'outline_prompt.txt'
},
{
'id': 'step_2',
'name': 'Draft Writing',
'model': 'claude-opus-4-5',
'input': 'outline from step_1',
'output': 'draft (string, ~800 words)',
'prompt_template': 'draft_prompt.txt'
},
{
'id': 'step_3',
'name': 'Editorial Polish',
'model': 'claude-haiku-4-5',
'input': 'draft from step_2',
'output': 'final post (string)',
'prompt_template': 'polish_prompt.txt'
}
]
}
print('Chain documented with step specs.')真实案例:竞争分析链
用于竞争分析的实用三步链:
def competitive_analysis_chain(competitor_list, product_description):
# Step 1: Research each competitor (parallel)
def research(competitor):
return call(f'List key features, pricing model, and target market for: {competitor}')
with concurrent.futures.ThreadPoolExecutor() as ex:
research_results = dict(zip(competitor_list, ex.map(research, competitor_list)))
# Step 2: Compare against our product
comparison_input = '\n\n'.join(f'{k}:\n{v}' for k, v in research_results.items())
comparison = call(f'Compare these competitors against our product:\nOur product: {product_description}\n\nCompetitors:\n{comparison_input}')
# Step 3: Strategic recommendations
recommendations = call(f'Based on this competitive analysis, provide 3 strategic recommendations:\n\n{comparison}')
return recommendations快速检查
哪种情形更适合使用提示词链式调用,而不是单个提示词?
提示词链式调用——要点回顾
提示词链式调用是生产环境 AI 系统的基础:
- 按顺序执行,每个输出都会作为输入传递给下一个提示词
- 支持专门化——每个步骤都使用针对其小范围子任务优化的提示词
- 通过 map-归约模式解决上下文窗口限制
- 彼此独立的步骤可以并行运行,以降低延迟
- 比完全由智能体驱动的系统更易预测和调试
- 通过在简单步骤中使用更便宜的模型、在复杂推理中使用更昂贵的模型来优化成本
- 始终记录您的链,包括步骤标识、输入/输出规范和模型分配
用 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 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「什么是提示链」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Prompt Engineering 课中编写并运行代码吗?
能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。