正在学习

6.2 Configuring API Keys and Rate Limits

Requirements:

pip install anthropic

Usage:

export ANTHROPIC_API_KEY="your_api_key_here"

python claude_config.py

import os

import time

from anthropic import Anthropic, APIError, RateLimitError

def get_api_client() -> Anthropic:

"""Load the API key securely from environment variables."""

api_key = os.getenv("ANTHROPIC_API_KEY")

if not api_key:

raise RuntimeError("Missing ANTHROPIC_API_KEY environment variable.")

return Anthropic(api_key=api_key)

def ask_claude(prompt: str, retries: int = 3, delay: float = 2.0) -> str:

"""Send a prompt to Claude with basic rate-limit handling."""

client = get_api_client()

for attempt in range(1, retries + 1):

try:

message = client.messages.create(

model="claude-3-5-sonnet-20240620",

max_tokens=300,

messages=[{"role": "user", "content": prompt}]

)

return message.content[0].text

except RateLimitError:

print(f"[WARN] Rate limit hit. Waiting {delay:.1f}s before retry {attempt}/{retries}...")

time.sleep(delay)

delay *= 2 # Exponential backoff

except APIError as e:

raise RuntimeError(f"API error occurred: {e}")

raise RuntimeError("Request failed after maximum retry attempts.")

if name == "main":

response = ask_claude("Explain the purpose of environment variables in Python.")

print("\nClaude says:\n")

print(response)

How it works:

  • The script reads your API key from an environment variable (ANTHROPIC_API_KEY) rather than storing it in code.
  • If the key is missing, it raises a clear error message.
  • The ask_claude function implements retry logic that detects when you hit a rate limit and waits before resending.
  • Exponential backoff (delay *= 2) prevents hammering the API and aligns with Anthropic’s best practices.

You can test this setup by intentionally sending multiple rapid requests in a loop. Claude will respond consistently until the rate threshold is reached, after which the retry mechanism gracefully pauses and resumes without crashing.

Clarification Table

Configuration Element Purpose Where It’s Stored or Used Best Practice
ANTHROPIC_API_KEY Authenticates API requests Environment variable (local or CI/CD) Never commit to source code or public repos
RateLimitError Signals excessive request frequency Returned by Anthropic API Catch and handle with exponential backoff
max_tokens Limits Claude’s output per request Passed to client.messages.create() Set per use case to control cost
Retry logic Automatically retries failed requests Application-level loop Combine with backoff and capped retries
Environment loader Securely loads secrets os.getenv() Centralize in configuration utilities

Configuring API keys and handling rate limits isn’t glamorous, but it’s the backbone of stable integration. Secure your key in environment variables, confirm it loads dynamically, and always expect temporary throttling during high-traffic moments. When you pair robust authentication with smart retry logic, your Claude-powered workflows stay reliable even under heavy use.

In the next section, we’ll extend this foundation by customizing Claude’s behavior through system prompts and configuration profiles, enabling fine-tuned personalities and domain-specific responses that match your project’s goals.

6.3 Working with Git and Version Control

When you start using Claude Code in a collaborative environment, version control becomes essential. Git isn’t just a safety net—it’s the foundation for disciplined, traceable, and reversible AI-assisted development. Claude can analyze diffs, summarize commits, explain merge conflicts, or even generate clean commit messages that match your team’s conventions. The combination of Claude and Git transforms the usual commit–push–review cycle into an intelligent feedback loop, where every change is verified and optimized before it ever reaches production.

Concept Development

Claude Code’s greatest strength when paired with Git is its ability to contextualize change. Rather than treating your code as static, Claude understands the flow between versions—what changed, why it changed, and whether the change aligns with your intent.

With this awareness, Claude can:

  • Summarize commits by analyzing staged changes before you commit.
  • Explain diffs between branches or PRs in plain English.
  • Propose commit messages following your repository’s conventions (e.g., Conventional Commits or Semantic Versioning).
  • Resolve merge conflicts by reasoning about both branches’ logic, not just textually merging.
  • Perform pre-commit reviews, identifying stylistic or structural issues before you push.

By integrating Claude into your Git workflow, you effectively get a reasoning layer sitting on top of version control—helping you make better, cleaner, and faster commits.

Hands-On Example

Below is a practical, runnable example showing how to combine Git commands with Claude Code in a local development setup. The goal is to review and summarize changes before committing.

Example: Claude-Assisted Commit Summary


# git_claude_commit.py

练习题

What is the primary purpose of using an environment variable like in the script?

A. To store the API key directly in the code for easy access
B. To authenticate API requests securely without committing the key to source code
C. To increase the rate limit of API requests
D. To make the API key visible to all users of the system

What happens when the script hits a rate limit while sending requests to the Anthropic API?

A. The script crashes immediately
B. The script continues sending requests without any delay
C. The script waits for a specified delay and retries the request with exponential backoff
D. The script ignores the rate limit and sends more requests

Which of the following are best practices for handling API keys and rate limits according to the text? (Select all that apply)

A. Store API keys in environment variables for local development
B. Commit API keys directly to source code for easier access
C. Implement retry logic with exponential backoff for rate-limited requests
D. Ignore rate limits and send requests as fast as possible
E. Use environment loaders like to securely load secrets

The script raises a clear error message if the environment variable is missing.

The retry logic in the script uses ___ backoff to prevent hammering the API and align with Anthropic’s best practices.

Explain why it is important to handle rate limits gracefully in API requests.

Which configuration element limits the output of Claude’s responses per request?

A.
B.
C.
D.

The script uses a centralized environment loader like to securely load secrets.

Which of the following are benefits of using version control with Claude Code? (Select all that apply)

A. It provides a safety net for code changes
B. It enables disciplined and traceable development
C. It allows Claude to analyze diffs and summarize commits
D. It increases the cost of API usage
E. It makes code changes irreversible

Describe how Claude Code can assist with merge conflicts in a collaborative environment.

When implementing retry logic for rate limits in Claude API calls, which of the following is a best practice to prevent hammering the API?

A. Use a fixed delay between retries
B. Implement exponential backoff
C. Retry immediately after each failure
D. Disable retries for rate limit errors

Which of the following are recommended practices for secure API key handling in Claude Code integration?

A. Store API keys in source code
B. Use environment variables for local development
C. Commit API keys to public repositories
D. Never commit API keys to source code or public repos
E. Load API keys dynamically in scripts

Claude Code's ability to summarize commits by analyzing staged changes is an example of its contextual understanding of code changes across versions when paired with Git.

When configuring API key and rate limit handling in Claude Code, the three essential steps are: securely store your API key, ___ it dynamically in your scripts, and wrap API calls with rate-limit handling logic.

登录后解锁笔记、知识点解析、AI 问答

立即登录