正在学习

Hands-On Example: Token Estimation Comparison

Simulated Claude API call (mock)

def call_claude(prompt: str) -> str:

"""Simulate Claude API call with artificial delay."""

print("Calling Claude API...")

time.sleep(1.5) # simulate latency

return f"Generated code for: {prompt[:30]}..."

# Cache storage
```python
CACHE_FILE = "claude_cache.json"

def load_cache():
    try:
        with open(CACHE_FILE, "r") as f:
            return json.load(f)
    except FileNotFoundError:
        return {}

def save_cache(cache):
    with open(CACHE_FILE, "w") as f:
        json.dump(cache, f, indent=4)

def get_cached_response(prompt: str):
    """Return cached result if available; otherwise query Claude and store."""
    cache = load_cache()
    prompt_hash = hashlib.sha256(prompt.encode()).hexdigest()
    if prompt_hash in cache:
        print("Cache hit — returning stored response.")
        return cache[prompt_hash]
    print("Cache miss — querying Claude.")
    response = call_claude(prompt)
    cache[prompt_hash] = response
    save_cache(cache)
    return response

练习题

What is the purpose of the time.sleep(1.5) line in the call_claude function?

A. To simulate network latency
B. To generate a random response
C. To hash the prompt string
D. To load the cache file

What is the value of CACHE_FILE in the code?

A. cache.json
B. claude_cache.json
C. data.json
D. temp_cache.json

Which of the following are true about the load_cache function?

A. It attempts to open and read the cache file
B. It returns an empty dictionary if the file doesn't exist
C. It saves the cache to disk
D. It uses a try-except block to handle FileNotFoundError

The save_cache function writes the cache dictionary to disk in JSON format with indentation for readability.

The get_cached_response function uses ___ to generate a unique key for each prompt.

Explain what happens when get_cached_response is called with a prompt that has never been used before.

What does the call_claude function return when called with the prompt 'Generate a Python function'? (Assume this is the first call)

A. Generated code for: Generate a Python function...
B. Generated code for: Generate a Python func...
C. An empty string
D. A hash value of the prompt

The cache system will return different responses for the same prompt if called multiple times.

Which knowledge points are involved in understanding how the caching system reduces API costs?

A. Simulating Claude API Call with Artificial Delay
B. Cache File Definition
C. Getting Cached Response Function
D. Token Estimation for Cost Control

How would you modify the caching system to implement a maximum cache size limit?

When implementing the get_cached_response function, which of the following best describes the relationship between caching and token cost optimization?

A. Caching increases token costs by storing redundant data
B. Caching reduces token costs by reusing previous responses
C. Caching has no impact on token costs
D. Caching only affects input token costs, not output

The time.sleep(1.5) in the call_claude function affects token costs directly by increasing the number of tokens processed.

To minimize costs when using Claude's API, you should ___ previous responses instead of making new API calls for identical prompts.

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

立即登录