Claude tool and error handling
A tool request is not permission
A client tool lets the model request a named function that the application controls. Claude tool definitions describe name, purpose and input_schema. When stop_reason is tool_use, inspect every tool_use content block: id, name and input. Preserve the assistant content in conversation history, then append a user message containing corresponding tool_result blocks; the tool_use_id links each result to its request. Put results before other user text in that message. Preserve required thinking or other blocks unchanged when the selected API mode requires them. This is different from Responses function_call_output and call_id. Server tools and pause_turn follow different continuation rules. This lesson handles only client-side tools and does not send any result to a provider.
Deny unknown names and invalid arguments
The local function receives normalized call dictionaries extracted from tool_use blocks and an application-owned SKU allowlist. It requires unique nonempty IDs and tests name, argument shape and permitted SKU before creating a result. Denied calls still receive a linked error result. This illustrates correlation and authorization without executing any real function. The first printed result is an approved synthetic lookup; the second is a denied write request. Input keys are assumed present; a real boundary must also validate the entire incoming message and enforce size limits. Never let a model specify an arbitrary function, shell command, network destination or data scope. A production dispatcher also needs caller identity, resource permissions, bounded calls, deadlines, cancellation and human approval for consequential writes.
def mock_tool_results(calls, allowed_skus): # No external tools: return only synthetic read-only fixture values. ids = [c["id"] for c in calls] if any(not isinstance(i, str) or not i for i in ids) or len(set(ids)) != len(ids): raise ValueError("unique nonempty call IDs required") results = [] for c in calls: args = c["input"] ok = (c["name"] == "lookup_stock" and isinstance(args, dict) and set(args) == {"sku"} and isinstance(args["sku"], str) and args["sku"] in allowed_skus) results.append({"type": "tool_result", "tool_use_id": c["id"], "is_error": not ok, "content": "In stock" if ok else "Denied"}) return results
calls = [{"id": "call_a", "name": "lookup_stock", "input": {"sku": "A"}}, {"id": "call_b", "name": "delete_stock", "input": {"sku": "A"}}]for result in mock_tool_results(calls, {"A"}): print(result["tool_use_id"], result["content"], result["is_error"])Separate retryable transport errors from content failures
Use provider-specific error details and typed SDK exceptions. Authentication, permission and invalid requests usually need correction, not retries. Temporary rate limits, connection errors and overload (including HTTP 529) may warrant bounded retry with jitter and a total deadline; quota and account restrictions need different handling. Check SDK automatic retry behavior to avoid multiplying attempts. Never retry a side effect blindly after a timeout; provider work or cost may already have occurred. A tool error is represented as a linked error result; it is not automatically a transport failure. A refusal or malformed output goes to review. A pause_turn is a provider continuation case, not a generic client retry. Record request IDs and sanitized error categories, not full sensitive prompts. Keep a strict turn and spend budget; unknown usage is not zero.
Account for cache creation and cache reads
Prompt caching can reuse a matching input prefix rather than reuse a generated answer. The documented ephemeral cache mechanism and automatic or explicit cache settings depend on model, platform, prefix length and lifetime; check applicable constraints. A cache miss or expired prefix can incur creation or ordinary input usage. Claude usage can distinguish input_tokens, cache_creation_input_tokens, cache_read_input_tokens and output_tokens. For the applicable usage breakdown, add disjoint input categories to get total input; do not bill the cached categories twice. The example uses four hypothetical whole-dollar rates per million tokens, not actual Anthropic prices. The first calculation is 1,500 microdollars, the second is 1,600. Cache creation can cost more than ordinary input and different lifetimes can have different prices. Use the official rate table for the exact model and feature, including fractional rates and extra fees. Retention and cache eligibility vary with model and data arrangement; caching is not proof of zero retention.
def estimate_microdollars(tokens, rates): # Four disjoint usage categories; invented whole USD/million rates. if len(tokens) != 4 or len(rates) != 4: raise ValueError("four categories required") if any(type(x) is not int or x < 0 for x in [*tokens, *rates]): raise ValueError("nonnegative integers required") return sum(t * r for t, r in zip(tokens, rates))
# Ordinary input, cache creation, cache read, output.print(estimate_microdollars([100, 200, 300, 50], [2, 3, 1, 8]))print(estimate_microdollars([600, 0, 0, 50], [2, 3, 1, 8]))Build a bounded read-only adapter
Use the project fixtures to test one allowed lookup, invalid SKU, unknown tool, duplicate IDs and multiple results. Verify one result per valid unique call ID, preserve input order, and stop before sending a malformed batch. Compare known usage with the illustrative rate table and mark missing fields unknown unless the documented schema defines a default. Before any authorized live use verify installed SDK version, model access, pricing, retention, privacy, deadline, spend, approved data and policy. This chapter makes no live calls and executes no external tools. The next chapter introduces the Gemini API as another distinct integration contract.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Claude tool and error handling quiz
Apply the provider-specific offline integration contract.
Which field links a Claude tool result to its call?
What should happen to an unknown tool in the mock?
What can you conclude about remote work after a client timeout?
Which cache category represents tokens read from an existing cached prefix?
At invented rates [2,3,1,8], what is the microdollar cost for [10,20,30,5] tokens?