正在学习
3.2 Step-by-Step and Chain-of-Thought Techniques
Input model
class FactorialInput(BaseModel):
number: int
def calculate_factorial(n: int) -> int:
"""Compute factorial recursively with validation."""
if n < 0:
raise ValueError("Number must be non-negative")
if n in (0, 1):
return 1
return n * calculate_factorial(n - 1)
@app.post("/factorial")
async def factorial_endpoint(input_data: FactorialInput):
"""API endpoint to compute factorials safely."""
try:
result = calculate_factorial(input_data.number)
return {"input": input_data.number, "factorial": result}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception:
raise HTTPException(status_code=500, detail="Unexpected error occurred")
This example is complete and fully runnable with FastAPI. It includes validation, exception handling, and explanatory comments. The quality of the code directly stems from Claude’s step-by-step reasoning before writing the implementation.
If you run this API locally using `uvicorn main:app --reload` and send a JSON request such as `{"number": 5}`, the endpoint will return `{"input": 5, "factorial": 120}`.
Clarification Table
| Prompt Element | Purpose | Example Instruction | Effect on Output |
| --- | --- | --- | --- |
| Reasoning Phase | Encourages Claude to think before coding | “Outline your steps first.” | Produces structured and documented code |
| Implementation Phase | Separates logic from execution | “Then write the complete implementation.” | Generates cleaner and more reliable output |
| Validation Step | Forces Claude to check assumptions | “Include input validation and error handling.” | Prevents logical and runtime errors |
| Explanation | Reinforces comprehension | “Add comments explaining each section.” | Improves readability and maintainability |
This framework ensures every generated solution is deliberate and technically sound. Instead of treating Claude like an instruction follower, you’re training it to reason like a teammate.
Step-by-step and chain-of-thought prompting is how you make Claude Code think before it acts. It strengthens logical flow, reduces guesswork, and increases reliability across projects. By asking Claude to reason first, implement next, and validate at the end, you transform it into a deliberate engineering collaborator rather than an automated generator.
The next section builds on this concept by teaching you how to handle long contexts and multi-file prompts, so Claude can reason across entire projects and maintain coherence in large-scale applications.
## 3.3 Handling Long Contexts and Multi-File Prompts
As your projects grow, so does the number of files, functions, and dependencies that Claude Code must understand. Small snippets are easy for any coding assistant to handle, but real-world development rarely fits inside a few hundred lines. This is where Claude Code’s long-context capability becomes a true advantage. With support for extremely large token windows, Claude can read, understand, and reason across entire projects — multiple files, documentation, and configurations — all within a single session. When prompted correctly, Claude behaves like a developer who has read your entire repository and can give detailed, consistent feedback across every module. Learning to use long contexts effectively allows you to manage complex codebases with precision and maintain full architectural awareness throughout your interaction.
Concept Development
A context window defines how much information Claude can “see” at once — including your prompt, previous exchanges, and the code it’s analyzing. The larger the window, the more context Claude can retain when reasoning. In models like Claude 3 Opus, this extends to hundreds of thousands of tokens, meaning you can include several files, test data, and system documentation in one conversation.
However, providing Claude with too much unstructured data can dilute its focus. Like any experienced engineer, Claude needs a guided briefing to know which files are important and what to look for. Effective long-context prompting is about focus, hierarchy, and relevance. Instead of dumping code, you structure the context in a way that mirrors human reasoning — from the foundation (models and utilities) to higher layers (controllers, routes, and APIs).
When working with multi-file prompts, your goal is to help Claude retain relationships between files. You can do this by marking file boundaries clearly, summarizing intent before each file, and ending with a specific request. Think of yourself as a technical lead handing an assistant a stack of code — you wouldn’t say “read this,” you’d say “start with models.py, then see how it’s used in main.py, and tell me how they interact.” That same discipline applies to Claude.
Hands-On Example
练习题
What happens when a negative number is passed to the calculate_factorial function?
A. It returns 1
B. It raises a ValueError with the message 'Number must be non-negative'
C. It calculates the factorial of the absolute value of the number
D. It returns 0
What is the base case for the recursive factorial calculation in the calculate_factorial function?
A.
B. or
C.
D.
Which HTTP status codes are raised in the factorial_endpoint function for different error scenarios?
A. 200 for success
B. 400 for invalid input
C. 500 for unexpected errors
D. 404 for not found
E. 401 for unauthorized access
The calculate_factorial function uses an iterative approach to calculate the factorial.
The factorial_endpoint function returns a JSON response with both the input number and its factorial on success.
The calculate_factorial function raises a ValueError if the input number is ___.
The factorial_endpoint function uses the calculate_factorial function to compute the factorial of the input ___.
Explain the purpose of the validation step in the calculate_factorial function.
What is the expected output of the factorial_endpoint function when a valid input is provided?
Which of the following is a characteristic of Claude 3.5 Sonnet that makes it suitable for the factorial API task?
A. Very low cost
B. Enhanced reasoning and context coherence
C. Best for rapid, inexpensive tasks
D. Limited to short-form completion
How does combining the knowledge of Claude 3.5 Sonnet's characteristics with the factorial API implementation improve the overall solution?
When implementing a FastAPI endpoint for factorial calculation, which of the following is NOT a valid reason for including input validation?
A. To ensure the input is a non-negative integer
B. To prevent the calculation of factorials for very large numbers that could cause performance issues
C. To make the code look more complex and professional
D. To handle edge cases like or explicitly
Which of the following are essential components when defining a FastAPI endpoint for factorial calculation? (Select all that apply)
A. A model to define the input structure
B. A recursive function to calculate the factorial
C. A try-except block to handle potential errors
D. A loop to iterate through all possible inputs
The FactorialInput model is necessary to ensure that the input to the factorial endpoint is a valid integer.
In the FastAPI factorial endpoint, the ___ block is used to catch and handle specific errors like invalid input.
登录后解锁笔记、知识点解析、AI 问答
立即登录