/llm-patterns:tool-usefrom llm-patterns
Use when an LLM needs to interact with external systems — calling APIs, querying databases, reading files, executing code, or performing actions with side effects. Apply when the LLM must go beyond text generation to retrieve live data, perform calculations, or trigger real-world operations. Covers tool definition, invocation patterns, safety boundaries, and error handling.
Ships in llm-patterns. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Tool Use turns the LLM into a controller that decides which function to call and with what arguments, while the actual execution happens in deterministic, testable code. The LLM is the Strategy selector; the tools are the strategies.
User query → LLM decides which tool(s) → Tool executes → Result returned to LLM → LLM synthesises answer
The LLM never executes code directly. It expresses intent through structured tool calls; your system executes them.
Tools are defined by their name, description, and input schema. The description is critical — it is how the model decides when to use the tool.
tools = [
{
"name": "get_order_status",
"description": "Look up the current status of a customer order by order ID. "
"Use this when the user asks about an order, shipment, or delivery.",
"input_schema": {
"type": "object",
"properties": {
"order_id": {
"type": "string",
"description": "The order ID, e.g. ORD-12345"
}
},
"required": ["order_id"]
}
},
{
"name": "calculate_shipping",
"description": "Calculate shipping cost for a given weight and destination. "
"Use this when the user asks about shipping costs or delivery fees.",
"input_schema": {
"type": "object",
"properties": {
"weight_kg": {"type": "number", "description": "Package weight in kilograms"},
"destination_country": {"type": "string", "description": "ISO 3166-1 alpha-2 country code"}
},
"required": ["weight_kg", "destination_country"]
}
}
]
Rules for tool definitions:
get_order_status, calculate_shipping, create_invoice — not order or shippingdescription for each parameterA single user query may require multiple tool calls, possibly in sequence.
def run_with_tools(user_message: str, tools: list[dict], max_rounds: int = 5) -> str:
messages = [{"role": "user", "content": user_message}]
for _ in range(max_rounds):
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
tools=tools,
messages=messages
)
# If the model wants to use a tool
if response.stop_reason == "tool_use":
tool_results = []
for block in response.content:
if block.type == "tool_use":
result = execute_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": str(result)
})
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
else:
# Model is done — return final text
return extract_text(response.content)
raise MaxRoundsExceeded("Tool use loop did not converge")
Tools have different risk profiles. Classify every tool and enforce appropriate safeguards.
| Category | Risk | Example | Safeguard |
|---|---|---|---|
| Read-only | Low | get_order_status, search_products | None needed — safe to call freely |
| Write | Medium | update_address, create_ticket | Confirm with user before executing |
| Destructive | High | cancel_order, delete_account | Require explicit confirmation + audit log |
| Financial | High | process_refund, charge_card | Confirmation + amount limits + audit |
TOOL_SAFETY = {
"get_order_status": "read",
"search_products": "read",
"update_address": "write",
"cancel_order": "destructive",
"process_refund": "financial",
}
def execute_tool(name: str, args: dict) -> ToolResult:
safety = TOOL_SAFETY[name]
if safety in ("destructive", "financial"):
if not user_confirmed(name, args):
return ToolResult(error="User did not confirm this action")
handler = TOOL_REGISTRY[name]
return handler(**args)
Rule: the LLM never bypasses safety classification. The system enforces the boundary, not the model.
Tool execution can fail. Return errors to the model so it can adapt — do not silently swallow them.
def execute_tool(name: str, args: dict) -> str:
try:
handler = TOOL_REGISTRY.get(name)
if handler is None:
return json.dumps({"error": f"Unknown tool: {name}"})
result = handler(**args)
return json.dumps({"result": result})
except ValidationError as e:
return json.dumps({"error": f"Invalid input: {e}"})
except NotFoundError as e:
return json.dumps({"error": f"Not found: {e}"})
except Exception as e:
logger.error(f"Tool {name} failed: {e}")
return json.dumps({"error": "An internal error occurred. Please try again."})
The model receives the error and can:
Complex queries may require multiple tools called in sequence, with the output of one feeding into the next.
# User: "How much would it cost to ship my order ORD-12345?"
# Step 1: LLM calls get_order_status(order_id="ORD-12345") → gets weight
# Step 2: LLM calls calculate_shipping(weight_kg=2.5, destination_country="DE") → gets cost
# Step 3: LLM synthesises: "Shipping your order (2.5 kg) to Germany would cost €8.50."
The LLM orchestrates the sequence — your system only executes individual tool calls. This is where the LLM's reasoning ability adds genuine value over hard-coded workflows.
What SKILL.md sets; muted values are Claude Code's defaults
10 skills in this plugin
/agent-loopUse when a task requires autonomous multi-step reasoning — the LLM must observe, decide, act, and iterate until a goal is met or a termination condition is reached. Apply when a single prompt cannot solve the task, the number of steps is not known in advance, and the next step depends on the result of the previous one. Covers ReAct, Plan-and-Execute, state management, termination, and guardrails for autonomous agents./evaluation-harnessUse when you cannot systematically measure whether your LLM feature is working correctly. Apply when testing is based on vibes rather than metrics, when you cannot detect regressions after prompt changes, or when production quality is unknown. Covers evaluation datasets, metrics, regression testing, LLM-as-judge, and production monitoring for non-deterministic systems./graceful-degradationUse when an LLM-powered feature must remain functional when the primary model is slow, down, over budget, or producing low-quality results. Apply when building any production AI feature that users depend on. Covers fallback chains, semantic routing, circuit breakers, cost management, and degradation levels./guardrailsUse when LLM inputs or outputs must be validated for safety, policy compliance, schema conformance, or content appropriateness before they reach users or downstream systems. Apply when LLM responses could contain harmful content, PII leakage, prompt injection, off-topic responses, or policy violations. Covers input validation, output validation, content filtering, and prompt injection defence./llm-pattern-selectionINVOKE THIS FIRST before designing any LLM-powered feature. Use when integrating an LLM as a component in a software system — not as a chat interface, but as a decision-making, data-processing, or logic-executing building block. Maps the friction you feel to the pattern that removes it./prompt-engineeringUse when prompts are ad-hoc strings scattered through code, hard to test, version, or maintain. Apply when building any LLM-powered feature to ensure prompts are treated as first-class engineering artifacts — versioned, tested, composable, and separated from application logic. Covers prompt structure, template patterns, few-shot design, chain-of-thought, and prompt chaining.npx claudepluginhub entelligentsia/skillforge --plugin llm-patternsOther plugins' skills for the same job