正在学习
6.4 Managing Cost and Token Usage
Requirements: pip install anthropic
Usage:
export ANTHROPIC_API_KEY="your_api_key_here"
python token_tracker.py
import os
from anthropic import Anthropic
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
def send_prompt(prompt_text: str, model="claude-3-5-sonnet-20240620"):
"""Send a prompt to Claude and print token usage statistics."""
message = client.messages.create(
model=model,
max_tokens=300,
messages=[{"role": "user", "content": prompt_text}]
)
usage = message.usage # contains input/output token data
print("Claude’s Response:\n")
print(message.content[0].text)
print("\nToken Usage Summary:")
print(f" Input tokens: {usage.input_tokens}")
print(f" Output tokens: {usage.output_tokens}")
print(f" Total tokens: {usage.input_tokens + usage.output_tokens}")
if __name__ == "__main__":
prompt = "Explain the difference between synchronous and asynchronous programming in Python with short examples."
send_prompt(prompt)
Explanation:This script not only prints Claude’s response but also reports how many tokens were used for input, output, and total. You can experiment by sending different prompts to see how changes in prompt size and verbosity impact cost.
For instance:
- Adding detailed instructions or long code snippets drastically increasesinput tokens.
- Asking for “a concise summary” instead of “an in-depth analysis” cutsoutput tokensnearly in half.
Practical Optimization Example
Here’s a simple demonstration of how Claude’s output can be constrained to control token usage effectively:
prompt_long = (
"Explain asynchronous programming in detail with multiple examples "
"and comparisons to multithreading and multiprocessing."
)
prompt_short = (
"In 100 words, summarize how asynchronous programming differs from threading."
)
for prompt in [prompt_long, prompt_short]:
print("\nPrompt Length:", len(prompt.split()), "words")
send_prompt(prompt)
You’ll observe that the shorter, more focused prompt reduces both tokens and cost, while still delivering useful insights. This reinforces that clarity beats verbosity when working with AI models.
Clarification Table
| Aspect | Definition / Example | Impact on Token Usage | Optimization Strategy |
|---|---|---|---|
| Prompt Size | Input text length | Directly increases input token count | Keep context minimal; reuse summaries |
| Response Length | Output generated by Claude | Affects output tokens and cost | Use constraints like “limit to 150 words” |
| Model Type | e.g., Haiku vs. Sonnet vs. Opus | Determines token cost multiplier | Match model capability to task complexity |
| Conversation Depth | Number of turns in one session | Accumulates historical tokens | Truncate or summarize conversation memory |
| Redundant Context | Repeated instructions or unchanged code | Wastes input tokens | Store reference snippets externally |
| System Prompts | Persistent behavioral configuration | Small but cumulative overhead | Keep system instructions concise |
Managing token usage is a skill that balances clarity, brevity, and precision. By monitoring how many tokens your prompts consume, selecting the right model, and setting explicit output limits, you gain full control over performance and cost. Efficient developers treat tokens like compute cycles — everyone should have a purpose.
In the next section, we’ll explore Caching and Reuse Strategies, where you’ll learn how to store intermediate Claude responses and reuse them intelligently across sessions to save both time and budget while keeping context continuity intact.
6.5 Building a Productive Claude-Driven Workflow
A productive Claude-driven workflow is about designing an efficient rhythm between you, your tools, and Claude Code’s reasoning capabilities. The goal is not simply to use Claude for ad-hoc code generation but to integrate it as a structured part of your development loop—from brainstorming ideas and scaffolding code to debugging, refactoring, and testing. When developers approach Claude systematically, it becomes an intelligent extension of the team rather than a sporadic assistant. This section teaches you how to build that system: a repeatable, low-friction process that enhances creativity, ensures accuracy, and keeps momentum steady across projects.
Concept Development
The secret to productivity with Claude Code lies in workflow orchestration—structuring your interactions so that every exchange has context, purpose, and continuity. Instead of prompting in isolation, you use Claude as part of a consistent cycle:
- Intent Stage: You clarify what you want to achieve in natural language (a new feature, bug fix, or architectural change).
- Reasoning Stage: Claude outlines its plan or approach, allowing you to review its reasoning before code generation.
- Execution Stage: Claude produces complete, validated code with inline comments.
- Verification Stage: You test or run the code locally, feeding errors or test results back to Claude for refinement.
- Reflection Stage: Claude summarizes what changed and why, creating a knowledge artifact for future reference.
This cycle mirrors the human process of pair programming: planning, writing, testing, and learning iteratively. Once automated or repeated consistently, it forms a Claude loop—a feedback-driven development system that reduces friction and accelerates delivery.
A good workflow also distinguishes between temporary prompts (for exploratory tasks) and persistent system prompts (which define Claude’s long-term behavior for a given project). Keeping these separate prevents context drift and ensures that Claude behaves predictably no matter how long the session lasts.
Hands-On Example: A Continuous Claude Workflow
Let’s build a lightweight, Claude-assisted loop for developing and refining a simple Flask API. The loop will automate planning, generation, testing, and summarization.
claude_workflow.py
练习题
What is the primary goal of a productive Claude-driven workflow?
Which stage of workflow orchestration involves Claude outlining its plan or approach before code generation?
Which of the following are stages in workflow orchestration when using Claude? (Select all that apply)
The Claude loop is a one-time process that does not involve iteration.
The __________ Stage involves Claude summarizing what changed and why, creating a knowledge artifact for future reference.
Explain the purpose of distinguishing between temporary and persistent system prompts in a Claude-driven workflow.
Which of the following best describes the impact of prompt size on token usage?
Asking for a concise summary instead of an in-depth analysis reduces output tokens.
Using constraints like “limit to 150 words” helps control __________ token usage.
How does managing token usage require balancing clarity, brevity, and precision? Provide an example.
Which of the following are optimization strategies for managing token usage? (Select all that apply)
Which stage of workflow orchestration involves testing or running the code locally and feeding errors or test results back to Claude for refinement?
The Intent Stage is the first stage of workflow orchestration and involves clarifying what you want to achieve in natural language.
The __________ Stage involves Claude producing complete, validated code with inline comments.
Explain how the Claude loop accelerates delivery in a development workflow.
When optimizing token usage in a Claude-driven workflow, which of the following strategies is most effective for reducing output tokens while maintaining useful insights?
Which of the following are key elements of a productive Claude-driven workflow? (Select all that apply)
In a Claude-driven workflow, the Reflection Stage is primarily focused on Claude summarizing what changed and why, creating a knowledge artifact for future reference.
To prevent context drift in a Claude-driven workflow, it is important to distinguish between ___ and persistent system prompts.
Explain how the Intent Stage in a Claude-driven workflow contributes to the overall productivity of the development process.
登录后解锁笔记、知识点解析、AI 问答
立即登录