正在学习
5.6 Best Practices and Cost Considerations
A lightweight, runnable helper to estimate prompt/response costs.
from dataclasses import dataclass
@dataclass
class Pricing:
Prices per 1000 tokens (adjust these to your plan)
input_per_1k: float
output_per_1k: float
def rough_token_count(text: str) -> int:
"""
Very rough token approximation: number of whitespace-delimited chunks.
This intentionally errs a bit to stay dependency-free and runnable.
"""
return max(1, len(text.strip().split()))
def estimate_cost(prompt: str, expected_response_words: int, pricing: Pricing):
in_tokens = rough_token_count(prompt)
out_tokens = expected_response_words # rough proxy
cost = (in_tokens / 1000) * pricing.input_per_1k + (out_tokens / 1000) * pricing.output_per_1k
return in_tokens, out_tokens, round(cost, 4)
if name == "main":
Example values — update to your plan and task
pricing = Pricing(input_per_1k=3.0, output_per_1k=15.0)
prompt = (
"You are Claude Code. Summarize this project spec in 150 words, "
"then generate a single FastAPI endpoint with docstring and Pydantic model."
)
in_tokens, out_tokens, cost = estimate_cost(prompt, expected_response_words=250, pricing=pricing)
print(f"Estimated input tokens: {in_tokens}")
print(f"Estimated output tokens: {out_tokens}")
print(f"Estimated cost (USD): ${cost}")
Run this script to sanity-check the budget before a long session. The exact tokenization differs in production, but even a rough estimate encourages better scoping and prevents accidental overuse of context.
Part 2: Prompt Slimmer with Reusable Summary
This second script shows how a reusable, compact summary can replace repeating full context every turn. It demonstrates how to keep a short “session anchor” and inject only task-specific deltas, which often yields better reasoning at lower cost.
prompt_planner.py
Shows how to reuse a compact session summary instead of pasting large context repeatedly.
BASE_SUMMARY = (
"Project: FastAPI service for product catalog. "
"Stack: FastAPI, SQLModel, SQLite. "
"Non-functional: JSON-only responses, Pydantic validation, 100% typed."
)
def make_prompt(task_instruction: str, limit_words: int = 160) -> str:
"""
Build a compact, high-signal prompt that reuses BASE_SUMMARY and adds only the current task.
"""
return (
f"{BASE_SUMMARY} "
f"Task: {task_instruction} "
f"Constraints: Keep answer under {limit_words} words where possible; "
f"return only the final Python code if the task is code."
)
if name == "main":
p1 = make_prompt("Create POST /products with validation and 201 response.")
p2 = make_prompt("Add GET /products/{id} with 404 handling and type-hinted return.")
print("Prompt 1:\n", p1, "\n")
print("Prompt 2:\n", p2, "\n")
Using a short, evergreen summary prevents you from pasting the entire spec on every turn. It also steers Claude toward consistent outputs by restating the same constraints succinctly.
Clarification Table
| Practice | What You Do | Why It Saves Cost | Side Benefit |
|---|---|---|---|
| Choose the right model tier | Match model capability to task complexity | Avoid overpaying for deep reasoning when you only need quick fixes | Better latency for small tasks |
| Reuse a compact session summary | Keep a 2–4 sentence anchor and add only the delta | Reduces repeated input tokens across turns | More consistent answers |
| Scope outputs precisely | Ask for “final Python code only” or “≤150 words” | Limits unnecessary generation | Easier to review and paste into code |
| Batch narrow tasks | Combine similar small requests in one structured prompt | Amortizes system/setup tokens | More coherent results |
| Trim raw context | Include only relevant files or snippets | Lowers input size without losing signal | Improves focus and accuracy |
| Favor structured formats | Request JSON tables or single files | Reduces verbose prose | Faster integration into pipelines |
| Cache intermediate artifacts | Keep model-generated summaries/tests for reuse | Prevents regenerating the same content | Stable team conventions |
Cost control with Claude Code is a product of clarity and structure. Right-size the model to the task, anchor the session with a compact summary, and constrain outputs to what you actually need. Simple local tools like the cost estimator and prompt planner make budgets visible and nudge you toward leaner prompts that still deliver complete, correct results. With these practices in place, you get predictable spend, faster iterations, and the same high-quality outcomes that make Claude an effective pair-programming partner. In the next section, you will apply these habits to a full optimization checklist that scales from individual prompts to project-wide workflows.
6.1 Claude Code in VS Code, Zed, and the Terminal
Claude Code is designed to fit naturally into a developer’s daily workflow. Whether you’re coding in VS Code, writing in Zed, or running commands directly from the terminal, integration makes AI assistance immediate and frictionless. The goal isn’t to replace your editor’s capabilities but to augment them — letting Claude assist with reasoning, refactoring, debugging, and documentation right where you work.
This section walks you through setting up Claude Code in each of these environments, explains how to use it efficiently, and demonstrates practical examples that show its value in real-time coding scenarios.
Concept Development
Integrating Claude Code effectively means aligning it with your workflow’s rhythm. Each environment—VS Code, Zed, and the terminal—offers different strengths.
- VS Code Integration focuses on convenience and visibility. Claude sits in your sidebar or command palette, helping you analyze files, generate code snippets, or run inline refactors without context switching.
- Zed Integration emphasizes minimalism and responsiveness. Zed’s architecture allows instant AI feedback with minimal overhead, perfect for developers who prefer a lightweight yet powerful interface.
- Terminal Integration is ideal for quick one-offs, scripting tasks, and automation. You can query Claude directly from the command line using natural language or structured prompts, treating it like an intelligent command assistant.
Claude Code’s underlying behavior is consistent across all environments: it reads the open file or terminal input, interprets your command in natural language, and provides immediate, context-aware output — whether that’s code, explanation, or analysis.
Hands-On Example: VS Code Integration
Let’s start with the most common setup: integrating Claude Code into Visual Studio Code.
Installation and Setup
Claude’s VS Code extension (available through the Anthropic marketplace or manual download) requires:
- A Claude API key from your Anthropic account.
- A compatible model (such as Claude 3.5 or Claude 3.7 Code). Once installed, open the Command Palette (Ctrl + Shift + P or Cmd + Shift + P) and search for “Claude: Connect Account”. Paste your API key, and the extension is ready.
Basic Usage Example
Open a Python file and highlight a function. Right-click and choose:
Claude → Explain this code
Claude generates a contextual explanation inline:
This function process_orders aggregates daily sales data by category,
applies discounts, and exports the results to CSV. It uses a generator
for memory efficiency.
Now try a modification prompt:
Claude → Refactor for better readability
Claude will rewrite the function with improved variable names, docstrings, and consistent formatting.
Finally, use the integrated “chat panel” to discuss the file:
Developer: “Claude, how can I cache API responses here?” Claude: “Wrap your API call in functools.lru_cache or persist results to a JSON file between runs. Here’s an example...”
The result is an ongoing collaboration that feels like pair programming — without ever leaving VS Code.
Zed Integration
Zed is built for speed, and its Claude Code integration is equally lightweight. Configuration is done via your settings.json or through the command palette.
Setup Steps
- Open Zed’s settings with Ctrl +, or Cmd +,.
- Add your Claude API key under the "ai" section:
{
"ai": {
"provider": "claude",
"api_key": "your_api_key_here",
"model": "claude-3.5-code"
}
}
Example Usage
Open a file and type Cmd + I (or your assigned shortcut) to trigger an AI command. For example:
“Add type hints to all functions in this file.”
Claude responds inline, showing a diff preview of proposed changes. Press Enter to apply or Esc to cancel.
Zed’s Claude integration shines in rapid iteration — for instance, you can have it summarize diffs, suggest renaming strategies, or review multiple files simultaneously with contextual awareness.
Terminal Integration
Claude Code’s command-line interface allows developers to use natural language commands for automation and scripting. With tools like claude-cli or anthropic-client, you can query Claude directly without leaving your shell session.
Installation
Install via pip or npm (depending on your setup):
pip install anthropic-cli
Authenticate by running:
claude login
and paste your API key.
Example Usage
Let’s say you want to debug a failing script quickly:
cat process_data.py | claude explain
Claude reads the entire script and returns:
This script processes log files into structured JSON but fails when
the input path is invalid. The likely issue is that 'os.path.exists'
is not imported. Add 'import os' at the top.
For a more advanced case, you can feed Claude both the code and the error:
claude ask "Why is this function raising a TypeError?" < logs/error_trace.txt
Claude analyzes the traceback and suggests the fix directly in terminal output.
You can even generate new scripts interactively:
claude generate "Write a Python script that monitors disk usage and logs alerts above 90%."
Claude returns the full script, ready to be saved and executed.
Clarification Table
| Environment | Setup Complexity | Primary Use Case | Best Feature | Ideal User |
|---|---|---|---|---|
| VS Code | Moderate (extension + API key) | Full-featured IDE assistance | Inline code editing, refactor suggestions | Developers who want tight integration |
| Zed | Minimal (JSON configuration) | Lightweight AI collaboration | Instant diff previews, minimal UI lag | Power users who prefer speed and simplicity |
| Terminal (CLI) | Simple (install + login) | Quick fixes, automation, scripting | Pipe input/output with natural queries | DevOps engineers, backend developers, automation experts |
Integrating Claude Code into your daily development environment unlocks a new level of productivity. In VS Code, it feels like an intelligent assistant at your fingertips. In Zed, it acts as a fast, responsive companion that never breaks flow. And in the terminal, it becomes a natural-language automation layer — letting you debug, generate, and optimize on demand.
The key is to integrate Claude where you already think and build, not as an external tool but as a collaborative partner.
In the next section we’ll explore how to tailor Claude’s behavior with project-specific prompts, reusable system instructions, and environment variables to make your coding experience uniquely efficient and personalized.
练习题
What is the primary purpose of the Pricing class in the given code?
How does the rough_token_count function estimate the number of tokens in a text?
Which of the following are components of the cost estimation formula in the estimate_cost function?
input_per_1k and output_per_1k valuesThe estimate_cost function returns the exact cost of an API call based on precise tokenization.
In the make_prompt function, the ___ variable is used to limit the number of words in the task instructions.
Explain the purpose of reusing a compact session summary in the make_prompt function.
What is the benefit of using a generator in the filter_even_numbers_stream function compared to a list comprehension?
Which of the following practices from the Cost-Saving Practices Clarification Table help reduce unnecessary generation?
The BASE_SUMMARY in the make_prompt function is intended to be modified frequently to reflect the latest project details.
The ___ function in the provided code is used to approximate the number of tokens in a text for cost estimation purposes.
When estimating costs using the estimate_cost function, which two factors primarily determine the total cost?
Which practices from the Cost-Saving Practices Clarification Table (kp_6_1_5) can be directly applied when using the make_prompt function (kp_6_1_4)? Select all that apply.
The rough_token_count function (kp_6_1_2) provides an exact count of tokens as defined by Claude Code's tokenization model.
To reduce costs when using Claude Code, you should ___ the context by including only relevant information and avoiding repetition across turns.
Explain how the make_prompt function (kp_6_1_4) supports the cost-saving practice of 'Reuse a compact session summary' (kp_6_1_5).
登录后解锁笔记、知识点解析、AI 问答
立即登录