0Pricing
Claude Architect · 课时

何时使用代理

代理、简单提示词与固定流程之间的选择。

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

本课时的部分内容尚未翻译,以英文显示。

Three Ways to Solve a Task

Before you build anything with Claude, you make one key decision: how much autonomy does the task need? There are three patterns:

  • Simple prompt — one request, one reply.
  • Fixed pipeline — a known sequence of steps you wire up yourself.
  • Agent — the model decides which tools to call and when, looping until the work is done.

Picking the right one is an architecture decision. Over-build and you add cost and failure points; under-build and the task can't complete. This lesson teaches you to choose well.

The Simple Prompt

A simple prompt is a single API call: you send a system message plus messages, and you get one answer back. No tools, no loop.

Use it when the task is self-contained: rewriting text, summarizing a paragraph, classifying a sentence, answering a question from given context. If everything the model needs is already in the prompt, you don't need anything more.

Remember: the model keeps no state. Each call is independent — you must resend the full messages history yourself if you want continuity.

import anthropic

client = anthropic.Anthropic()

resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=512,
    system="You rewrite text to be clear and concise.",
    messages=[
        {"role": "user", "content": "Rewrite: 'The meeting, which was long, ended.'"}
    ],
)
print(resp.content[0].text)

The Fixed Pipeline

A fixed pipeline chains several steps in a known order. You — the architect — decide the sequence in code. Step 1 feeds step 2, which feeds step 3.

This is also called prompt chaining. Use it when the steps are known and sequential: extract fields, then validate them, then format a report. The model never chooses the path — you did, in advance.

Pipelines are predictable and easy to debug because the control flow is fixed. The trade-off is rigidity: they can't adapt when a task needs different steps depending on what they find.

# Fixed pipeline: each step's output feeds the next
extracted = extract_fields(document)        # step 1
validated = validate(extracted)             # step 2
report    = format_report(validated)        # step 3
# The sequence is hard-coded. The model never picks the path.

The Agent

An agent hands control flow to the model. You give Claude a goal and a set of tools, and the model decides which tool to call, inspects the result, and decides what to do next — looping until the goal is met.

The defining feature: decisions are model-driven, not hard-coded. You don't know in advance how many steps it will take or which tools it will use.

Use an agent when the path is open-ended: investigating a bug, researching a topic across sources, resolving a customer issue that might need a lookup, a refund, or an escalation depending on what's found.

resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    system="You are a support agent. Resolve the customer's issue.",
    tools=[get_customer, lookup_order, process_refund, escalate_to_human],
    messages=conversation,
)
# The model chooses which tool(s) to call based on the situation.

The Agentic Loop

An agent runs a loop driven by the response's stop_reason:

  • Send the request.
  • Inspect stop_reason.
  • If it is tool_use, run the requested tool(s), append the results to the message history, and send again.
  • Repeat until stop_reason is end_turn.

You terminate on the stop reason — the API's own signal that the turn is complete. This is the heart of every agent.

while True:
    resp = client.messages.create(model=MODEL, max_tokens=1024,
                                  system=SYSTEM, tools=TOOLS,
                                  messages=messages)
    messages.append({"role": "assistant", "content": resp.content})

    if resp.stop_reason == "end_turn":
        break                       # task complete
    if resp.stop_reason == "tool_use":
        results = run_tools(resp.content)
        messages.append({"role": "user", "content": results})

Never Parse Text for 'Done'

A common and dangerous mistake: ending the loop by scanning the model's reply for words like "done" or "finished". The model might say "done" mid-thought, or never say it at all. This is a classic anti-pattern.

Always terminate on the stop_reason — end_turn means complete. The stop reason is a structured, reliable signal; free text is not.

Iteration caps (a maximum loop count) are a safety net to prevent runaway loops — never the primary stop mechanism. The real stop is always the stop reason.

# ANTI-PATTERN: do not do this
if "done" in resp.content[0].text.lower():
    break

# CORRECT: rely on the structured stop reason
if resp.stop_reason == "end_turn":
    break

Decision Rule: Is the Path Known?

Here is the single question that decides agent vs pipeline:

Do you know the steps in advance?

  • Yes, fixed and sequential → use a fixed pipeline (prompt chaining). It is cheaper, faster, and easier to debug.
  • No, open-ended investigation → use an agent with adaptive decomposition.

If a task needs no external data or actions at all and fits in one call, you don't even need a pipeline — a simple prompt is enough. Always reach for the simplest pattern that does the job.

Decisions vs Guarantees

Agents are powerful because the model decides — but model decisions are probabilistic (roughly 90% reliable), not certain. So a second rule applies:

Let the model decide; reserve hard code for guarantees.

When a wrong action has financial, legal, or safety consequences — like a large refund — you do not rely on a prompt. You enforce the rule deterministically with a hook or a programmatic precondition. Prompts guide; hooks guarantee.

So an agent is the right shape and critical rules are still enforced in code around it. The two are not in conflict.

# Prompt guidance is ~90% reliable — fine for routine routing.
# A hook is 100% deterministic — use it for critical rules:
#   block process_refund when amount > 500
#   block process_refund until get_customer returns a verified ID
# Outgoing-call hooks reject policy-violating actions before they run.

When a Pipeline Beats an Agent

Don't reach for an agent just because it feels modern. A fixed pipeline wins when:

  • The sequence of steps is known and stable.
  • You want predictable cost and latency (no open-ended looping).
  • You need control flow that is easy to test and debug.

Example: structured data extraction where you always extract, then validate, then format. The path never changes, so hard-coding it is the correct, robust choice. Adding agent autonomy here only adds nondeterminism and cost for no benefit.

When an Agent Is the Right Call

Choose an agent when the work is genuinely open-ended and the path depends on what is discovered along the way:

  • Bug investigation — grep entry points, read files, follow usages; you can't script the route in advance.
  • Multi-source research — a coordinator decomposes the question and delegates to subagents.
  • Customer support — one issue needs a lookup, another a refund, another an escalation.

In all of these, the next step depends on the last result. That dependency is exactly what an agentic loop handles and a fixed pipeline cannot.

system=("You are a debugging agent. Investigate the failing test "
        "and find the root cause.")
tools=[glob_tool, grep_tool, read_tool, bash_tool]
# The model adapts: Grep entry points -> Read files -> Grep usages
# -> Read consumers. The route is decided at runtime, not by you.

A Practical Checklist

Run any new task through this quick checklist:

  • One self-contained call? → simple prompt.
  • Known, fixed sequence of steps? → fixed pipeline.
  • Open-ended, path depends on results? → agent.
  • Critical rule (money / legal / safety)? → enforce it with a hook, whichever pattern you chose.

Default to the simplest pattern that works. Add autonomy only when the task truly needs it — and add deterministic enforcement wherever a mistake would be costly. That balance is what separates an architect from a tinkerer.

Quick Check

Test your decision-making on a realistic scenario.

Recap: Choosing Your Pattern

Key takeaways:

  • Simple prompt — self-contained, one call, no state (resend full history yourself).
  • Fixed pipeline — known, sequential steps; predictable, cheap, easy to debug.
  • Agent — open-ended path the model decides at runtime via the agentic loop.
  • The loop terminates on stop_reason == end_turn, never by parsing text; iteration caps are only a safety net.
  • Model decisions are probabilistic; enforce critical money/legal/safety rules with hooks or programmatic preconditions for deterministic guarantees.
  • Default to the simplest pattern that does the job.

Master this choice and the rest of agent architecture builds cleanly on top of it.

常见问题解答

「何时使用代理」课时是免费的吗?

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

「何时使用代理」这节课中我会学到什么?

代理、简单提示词与固定流程之间的选择。 你通过在浏览器中直接运行的动手代码来练习 Claude Architect,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Claude Architect 需要有经验吗?

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

「何时使用代理」课时需要多长时间?

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

我能在这节 Claude Architect 课中编写并运行代码吗?

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

此课程中的所有课时

  1. 什么让系统具备代理性
  2. 模型驱动决策与硬编码决策
  3. 何时使用代理
  4. 代理循环概览
← 返回 Claude Architect