ai-patterns-tool-use-patterns
LLMの機能呼び出し、ツール連携、自律エージェントのワークフローにおいて、特定のサービスに依存せず汎用的に利用できるパターンを適用し、業務効率化や新たな価値創造を支援するSkill。
📜 元の英語説明(参考)
Provider-agnostic patterns for LLM function calling, tool loops, and agentic workflows
🇯🇵 日本人クリエイター向け解説
LLMの機能呼び出し、ツール連携、自律エージェントのワークフローにおいて、特定のサービスに依存せず汎用的に利用できるパターンを適用し、業務効率化や新たな価値創造を支援するSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o ai-patterns-tool-use-patterns.zip https://jpskill.com/download/10213.zip && unzip -o ai-patterns-tool-use-patterns.zip && rm ai-patterns-tool-use-patterns.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/10213.zip -OutFile "$d\ai-patterns-tool-use-patterns.zip"; Expand-Archive "$d\ai-patterns-tool-use-patterns.zip" -DestinationPath $d -Force; ri "$d\ai-patterns-tool-use-patterns.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
ai-patterns-tool-use-patterns.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
ai-patterns-tool-use-patternsフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
ツール利用パターン
クイックガイド: ツール利用(関数呼び出し)により、LLMは外部関数を呼び出すことができます。普遍的なパターンは、ツールスキーマ(パラメータのJSON Schema)を定義 -> ツールとメッセージをLLMに送信 -> レスポンスで
tool_useを検出 -> ローカルで実行 -> 結果をLLMに返す -> モデルがテキストで応答するまで繰り返す、です。すべてのループを最大ステップ数で保護し、実行前にすべてのツール入力を検証し、モデルが回復できるように構造化されたエラーを返してください。ツール選択制御(auto、required、none、特定のツール)を使用して、モデルの動作を誘導します。
<critical_requirements>
重要: この Skill を使用する前に
すべてのコードは、CLAUDE.md のプロジェクト規約に従う必要があります (kebab-case、名前付きエクスポート、インポート順序、
import type、名前付き定数)
(すべてのツールループを最大ステップ数で保護する必要があります -- 無制限のループは、無限のAPI呼び出しと制御不能なコストのリスクがあります)
(実行前にすべてのツール入力引数を検証する必要があります -- LLMによって生成された引数は信頼できない入力です)
(ツールの実行が失敗した場合は、構造化されたエラーメッセージをモデルに返す必要があります -- エラーを黙って無視したり、空の結果を返したりしないでください)
(ツールパラメータの定義にはJSON Schemaを使用する必要があります -- すべての主要プロバイダーがこの形式を必要とします)
(ツール定義をトークンコストとして扱う必要があります -- すべてのツールスキーマはAPI呼び出しごとに送信されるため、説明は簡潔かつ正確に保ってください)
</critical_requirements>
自動検出: tool use, function calling, tool_calls, tool_use, tool call loop, agent loop, tool definition, tool schema, toolChoice, tool_choice, parallel tool calls, human-in-the-loop, tool approval, agentic workflow, multi-step agent, tool result, tool error
使用する場面:
- あらゆるプロバイダーでLLMのツール呼び出し/関数呼び出しを実装する場合
- タスクが完了するまでツールを反復的に呼び出すエージェントループを構築する場合
- 並列ツール呼び出し(1つのレスポンスで複数のツール)を処理する場合
- モデルが回復できるように、ツールエラーをモデルに報告する場合
- ツール選択を制御する場合(auto、required、none、特定のツール)
- 危険なツールの実行前に人間の承認ゲートを追加する場合
- ツール呼び出しを含むレスポンスをストリーミングする場合
カバーする主要なパターン:
- ツール定義スキーマ(パラメータ、説明のJSON Schema)
- コアとなるツール呼び出しループ(送信 -> 検出 -> 実行 -> 返却 -> 再送信)
- 並列ツール呼び出し(1つのレスポンスで複数の呼び出しを処理)
- エラー処理(ツール障害をモデルに報告)
- ツール選択制御(auto、required、none、特定のツール)
- 会話状態を持つマルチステップエージェントワークフロー
- ヒューマンインザループ承認パターン
- TypeScriptでの型安全なツール定義
- セキュリティ(入力検証、サンドボックス化、最小特権)
- ツール呼び出しによるストリーミング
使用しない場面:
- ツール呼び出しなしの単純なテキスト生成 -- ツールは不要
- 構造化された出力/JSON抽出 -- 代わりにプロバイダーの構造化された出力機能を使用
- プロバイダー固有のSDKパターン -- SDK固有のAPIにはプロバイダーのSDK skillを使用
詳細なリソース:
- examples/core.md -- ツールの定義、ツール呼び出しループ、エラー処理、型安全なツール
- examples/advanced.md -- 並列ツール呼び出し、マルチステップエージェント、ヒューマンインザループ、ストリーミング、セキュリティ
- reference.md -- 意思決定フレームワーク、プロバイダー比較、アンチパターンチェックリスト
<philosophy>
哲学
ツール利用は、LLMをテキストジェネレーターからエージェントに変えるメカニズムです。モデルはコードを実行したり、データベースをクエリしたり、APIを呼び出したりすることはできません。構造化されたツール呼び出しを発行することで、あなたのコードにそうするように 要求 できるだけです。あなたのコードが実行者であり、モデルがプランナーです。
コア原則:
- モデルが計画し、あなたが実行する -- LLMは構造化された引数を持つツール呼び出しリクエストを発行します。あなたのコードは検証、実行、および結果の返却を行います。モデルに任意のコードを直接実行させないでください。
- エージェントはループである -- 単純な天気ボットから複雑なコーディングアシスタントまで、すべてのエージェントは同じループに従います:LLMが決定 -> システムが実行 -> 結果がフィードバック -> 繰り返し。複雑さは、ループ自体ではなく、ツールと状態から生まれます。
- ツールはスキーマである -- ツール定義は、どのような関数が存在するか、どのようなパラメータを取るか、いつ使用するかをモデルに伝えるJSON Schemaです。より良い説明は、より良いツールの選択と引数の品質を生み出します。
- エラーは情報である -- ツールが失敗した場合は、構造化されたエラーメッセージをモデルに返します。モデルは、異なる引数で再試行したり、別のツールを選択したり、ユーザーに失敗を説明したりすることで、多くの場合回復できます。
- 多層防御 -- LLMによって生成された引数は信頼できない入力です。スキーマを検証し、型を強制し、引数の範囲を制限し、実行をサンドボックス化し、危険な操作には承認を要求します。
ツール呼び出しを使用する場面:
- タスクが、モデルが持っていない現実世界のデータ(天気、データベース、API)を必要とする場合
- タスクが副作用(メールの送信、レコードの作成、ファイル操作)を必要とする場合
- タスクが中間データルックアップによる多段階推論を必要とする場合
- タスクがモデルが確実に実行できない計算(数学、コード実行)を必要とする場合
ツール呼び出しを使用しない場面:
- モデルがトレーニングデータのみから回答できる場合
- 構造化されたJSON出力のみが必要な場合(代わりに構造化された出力機能を使用)
- 「ツール」が関数を装ったプロンプトエンジニアリングにすぎない場合
- 決定論的な動作が必要な場合(ツール呼び出しはモデルの決定から非決定論を追加します)
</philosophy>
<patterns>
コアパターン
パターン1:ツール定義スキーマ
すべてのツール定義には、名前、説明、およびパラメータスキーマの3つの部分があります。説明は最も重要な部分です -- モデルがツールを呼び出す決定と、引数をどのように構築するかを導きます。
// プロバイダーに依存しないツール定義の形状
interface ToolDefinition {
name: string; // ^[a-zA-Z0-9_-]{1,64}$
description: string; // このツールをいつ、なぜ使用するか
parameters: JsonSchema; // JSO
(原文がここで切り詰められています) 📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
Tool Use Patterns
Quick Guide: Tool use (function calling) lets LLMs invoke external functions. The universal pattern is: define tool schemas (JSON Schema for parameters) -> send tools + message to LLM -> detect tool_use in response -> execute locally -> return result to LLM -> repeat until the model responds with text. Guard every loop with a max-step limit, validate all tool inputs before execution, and return structured errors so the model can recover. Use tool choice control (
auto,required,none, specific tool) to steer model behavior.
<critical_requirements>
CRITICAL: Before Using This Skill
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
import type, named constants)
(You MUST guard every tool loop with a maximum step limit -- unbounded loops risk infinite API calls and runaway costs)
(You MUST validate all tool input arguments before execution -- LLM-generated arguments are untrusted input)
(You MUST return structured error messages to the model when tool execution fails -- never silently swallow errors or return empty results)
(You MUST use JSON Schema for tool parameter definitions -- all major providers require this format)
(You MUST treat tool definitions as token cost -- every tool schema is sent on every API call, so keep descriptions concise but precise)
</critical_requirements>
Auto-detection: tool use, function calling, tool_calls, tool_use, tool call loop, agent loop, tool definition, tool schema, toolChoice, tool_choice, parallel tool calls, human-in-the-loop, tool approval, agentic workflow, multi-step agent, tool result, tool error
When to use:
- Implementing LLM tool calling / function calling in any provider
- Building agent loops that call tools iteratively until a task is complete
- Handling parallel tool calls (multiple tools in one response)
- Reporting tool errors back to the model for recovery
- Controlling tool selection (auto, required, none, force specific)
- Adding human approval gates before dangerous tool execution
- Streaming responses that include tool calls
Key patterns covered:
- Tool definition schemas (JSON Schema for parameters, descriptions)
- The core tool call loop (send -> detect -> execute -> return -> re-send)
- Parallel tool calls (handling multiple calls in one response)
- Error handling (reporting tool failures back to the model)
- Tool choice control (auto, required, none, specific tool)
- Multi-step agent workflows with conversation state
- Human-in-the-loop approval patterns
- Type-safe tool definitions in TypeScript
- Security (input validation, sandboxing, least privilege)
- Streaming with tool calls
When NOT to use:
- Simple text generation without tool calling -- no tools needed
- Structured output / JSON extraction -- use your provider's structured output feature instead
- Provider-specific SDK patterns -- use your provider's SDK skill for SDK-specific APIs
Detailed Resources:
- examples/core.md -- Tool definitions, the tool call loop, error handling, type-safe tools
- examples/advanced.md -- Parallel tool calls, multi-step agents, human-in-the-loop, streaming, security
- reference.md -- Decision frameworks, provider comparison, anti-pattern checklist
<philosophy>
Philosophy
Tool use is the mechanism that turns LLMs from text generators into agents. The model cannot execute code, query databases, or call APIs -- it can only request that your code does so by emitting structured tool calls. Your code is the executor; the model is the planner.
Core principles:
- The model plans, you execute -- The LLM emits tool call requests with structured arguments. Your code validates, executes, and returns results. Never let the model execute arbitrary code directly.
- Agents are loops -- Every agent, from a simple weather bot to a complex coding assistant, follows the same loop: LLM decides -> system executes -> results feed back -> repeat. Complexity comes from the tools and state, not the loop itself.
- Tools are schemas -- A tool definition is a JSON Schema that tells the model what function exists, what parameters it takes, and when to use it. Better descriptions produce better tool selection and argument quality.
- Errors are information -- When a tool fails, return a structured error message to the model. The model can often recover by retrying with different arguments, choosing a different tool, or explaining the failure to the user.
- Defense in depth -- LLM-generated arguments are untrusted input. Validate schemas, enforce types, limit argument ranges, sandbox execution, and require approval for dangerous operations.
When to use tool calling:
- The task requires real-world data the model doesn't have (weather, database, APIs)
- The task requires side effects (sending email, creating records, file operations)
- The task requires multi-step reasoning with intermediate data lookups
- The task requires computation the model can't do reliably (math, code execution)
When NOT to use tool calling:
- The model can answer from its training data alone
- You only need structured JSON output (use structured output features instead)
- The "tool" is just prompt engineering disguised as a function
- You want deterministic behavior (tool calling adds non-determinism from model decisions)
</philosophy>
<patterns>
Core Patterns
Pattern 1: Tool Definition Schema
Every tool definition has three parts: a name, a description, and a parameter schema. The description is the most important part -- it guides the model's decision to call the tool and how it constructs arguments.
// Provider-agnostic tool definition shape
interface ToolDefinition {
name: string; // ^[a-zA-Z0-9_-]{1,64}$
description: string; // When and why to use this tool
parameters: JsonSchema; // JSON Schema for input arguments
}
Good Tool Definition
// Good: precise description, constrained parameters, .describe() on each property
const VALID_UNITS = ["celsius", "fahrenheit"] as const;
const getWeatherTool: ToolDefinition = {
name: "get_current_weather",
description:
"Get the current weather conditions for a specific city. " +
"Returns temperature, humidity, and conditions. " +
"Use this when the user asks about current weather, NOT forecasts.",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "City name and optional country code, e.g. 'London, UK'",
},
unit: {
type: "string",
enum: VALID_UNITS,
description: "Temperature unit. Defaults to celsius if not specified.",
},
},
required: ["location"],
},
};
Why good: Description explains what the tool returns, when to use it, and when NOT to use it. Parameters have descriptions and constraints (enum). Named constant for valid values.
Bad Tool Definition
// Bad: vague description, no parameter descriptions, no constraints
const weatherTool: ToolDefinition = {
name: "weather",
description: "Gets weather", // BAD: too vague
parameters: {
type: "object",
properties: {
loc: { type: "string" }, // BAD: no description, cryptic name
u: { type: "string" }, // BAD: no enum constraint
},
},
};
Why bad: Vague description causes incorrect tool selection, no parameter descriptions cause malformed arguments, no enum constraint causes invalid values, cryptic parameter names confuse the model
Pattern 2: The Core Tool Call Loop
The fundamental pattern for tool use. Send a message with tool definitions, check if the response contains tool calls, execute them, return results, and let the model generate a final response. See examples/core.md for the complete implementation.
const MAX_TOOL_STEPS = 10;
for (let step = 0; step < MAX_TOOL_STEPS; step++) {
const response = await callLLM({ messages, tools });
if (!response.toolCalls?.length) return response.text;
messages.push({ role: "assistant", toolCalls: response.toolCalls });
for (const tc of response.toolCalls) {
messages.push({
role: "tool",
toolCallId: tc.id,
content: JSON.stringify(await executeTool(tc)),
});
}
}
Key points: Always use a bounded for loop with a named constant (MAX_TOOL_STEPS) -- never while (true). Always append the assistant message (with tool calls) before tool results. Include graceful termination when the step limit is reached.
Pattern 3: Tool Execution with Error Handling
When a tool fails, return a structured error to the model instead of crashing. The model can often recover by retrying, choosing a different approach, or explaining the failure. See examples/core.md for the complete validation pipeline.
// Four-step validation: tool exists -> JSON parses -> schema validates -> execution succeeds
async function executeTool(toolCall: ToolCall): Promise<ToolResult> {
const handler = toolRegistry[toolCall.name];
if (!handler)
return { success: false, error: `Unknown tool: "${toolCall.name}"` };
const validated = handler.schema.safeParse(toolCall.arguments);
if (!validated.success)
return { success: false, error: `Invalid args: ${validated.error}` };
try {
return { success: true, data: await handler.execute(validated.data) };
} catch (error) {
return {
success: false,
error: `Tool failed: ${error instanceof Error ? error.message : "Unknown"}`,
};
}
}
Key points: Always validate tool existence, parse JSON arguments, validate against schema, and catch execution errors. Return structured { success, data?, error? } results so the model can recover. Never crash the loop on tool errors.
Pattern 4: Tool Choice Control
Control whether and how the model uses tools. All major providers support four modes.
type ToolChoice =
| "auto" // Model decides whether to call tools (default)
| "required" // Model MUST call at least one tool
| "none" // Model MUST NOT call any tools
| { name: string }; // Model MUST call this specific tool
When to Use Each Mode
// auto (default) -- let the model decide
const response = await callLLM({
messages,
tools,
toolChoice: "auto",
});
// required -- force tool use (e.g., first step of an agent must act)
const response = await callLLM({
messages,
tools,
toolChoice: "required",
});
// none -- disable tools (e.g., final response must be text only)
const response = await callLLM({
messages,
tools,
toolChoice: "none",
});
// specific tool -- force a particular tool (e.g., classification step)
const response = await callLLM({
messages,
tools,
toolChoice: { name: "classify_intent" },
});
Decision guidance:
| Mode | Use When |
|---|---|
auto |
General-purpose agent -- model decides based on context |
required |
Agent's first step must always call a tool (e.g., data lookup) |
none |
Final response generation -- no more tool calls allowed |
{ name } |
Pipeline step that must use a specific tool (e.g., extract, classify) |
When to use: When you need to constrain or guarantee tool behavior at specific points in a workflow
Pattern 5: Type-Safe Tool Definitions in TypeScript
Use a typed registry pattern with Zod schemas to get compile-time safety for tool definitions and runtime validation for execution. See examples/core.md for the complete ToolRegistry class implementation.
import { z } from "zod";
// Define tool with schema + execute function -- TypeScript infers argument types
function defineTool<T extends z.ZodType>(config: {
name: string;
description: string;
schema: T;
execute: (args: z.infer<T>) => Promise<unknown>;
}) {
return config;
}
When to use: Any TypeScript project implementing tool calling -- Zod validates at runtime, TypeScript catches schema/handler mismatches at compile time
</patterns>
<decision_framework>
Decision Framework
Do You Need Tool Calling?
Does the task require information the model doesn't have?
+-- YES -> Tool calling (fetch data from APIs, databases, files)
+-- NO -> Does the task require side effects?
+-- YES -> Tool calling (send email, create record, execute code)
+-- NO -> Do you need structured JSON output?
+-- YES -> Use structured output features (NOT tool calling)
+-- NO -> Plain text generation, no tools needed
Which Loop Pattern?
How many tools might the model call?
+-- Single tool call per request
| +-- Simple request-response with one tool execution
| +-- No loop needed, just one round-trip
+-- Multiple sequential tool calls
| +-- Use the bounded tool call loop (Pattern 2)
| +-- Set MAX_TOOL_STEPS based on task complexity
+-- Multiple parallel tool calls in one response
| +-- Execute all tool calls concurrently (Promise.all)
| +-- Then return all results and loop
+-- Complex multi-step agent
+-- Use the bounded loop with conversation state
+-- Add human-in-the-loop for dangerous operations
+-- Consider per-step tool filtering
How to Handle Tool Errors?
Tool execution failed. What to do?
+-- Return structured error to the model
| +-- Include error message and context
| +-- Model can retry, choose alternative, or explain failure
+-- NEVER: silently return empty result
+-- NEVER: crash the loop
+-- NEVER: retry automatically without telling the model
(the model should decide whether to retry)
</decision_framework>
<red_flags>
RED FLAGS
High Priority Issues:
- Unbounded tool loop (
while (true)) without a step counter -- risks infinite API calls and runaway costs - Executing tool arguments without validation -- LLM-generated arguments are untrusted input, treat like user input
- Swallowing tool errors silently (returning
nullor{}) -- the model cannot recover from failures it doesn't know about - Allowing arbitrary code execution from tool arguments without sandboxing -- prompt injection can escalate to code execution
- Tool descriptions that say "Gets data" -- vague descriptions cause wrong tool selection and malformed arguments
Medium Priority Issues:
- Sending all tools on every API call when only a subset is relevant -- wastes tokens and confuses the model
- Not including the assistant message (with tool calls) in conversation history before tool results -- breaks the message sequence
- Using
tool_choice: "required"without a fallback for when no tool makes sense -- forces meaningless tool calls - Returning raw database rows or full API responses as tool results -- overwhelms context with irrelevant data; summarize or truncate
- Not logging tool calls and results -- impossible to debug agent behavior in production
Common Mistakes:
- Forgetting that tool call arguments arrive as a JSON string, not a parsed object -- always
JSON.parse()before use - Assuming the model will always call tools when tools are available -- with
automode, it may respond with text directly - Treating tool calling as structured output -- they solve different problems (actions vs data extraction)
- Putting business logic in tool descriptions instead of tool implementations -- descriptions guide selection, not execution
Gotchas & Edge Cases:
- Tool definitions consume tokens on every API call -- 10 tools with detailed schemas can use 1000+ tokens per request
- Parallel tool calls may arrive in any order -- never assume execution order matches definition order
- Some models hallucinate tool names or arguments that don't match any definition -- always validate the tool name exists in your registry
- Streaming responses with tool calls require accumulating partial JSON chunks before parsing -- the arguments arrive incrementally, not all at once
- Returning very large tool results (>4000 tokens) can push the conversation past context limits -- truncate or summarize large results
- The model maintains full conversation context including all tool calls and results -- long agent runs accumulate significant token usage
- Different providers use different message formats for tool results (
role: "tool"vs content blocks) -- abstract this in your callLLM wrapper
</red_flags>
<critical_reminders>
CRITICAL REMINDERS
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
import type, named constants)
(You MUST guard every tool loop with a maximum step limit -- unbounded loops risk infinite API calls and runaway costs)
(You MUST validate all tool input arguments before execution -- LLM-generated arguments are untrusted input)
(You MUST return structured error messages to the model when tool execution fails -- never silently swallow errors or return empty results)
(You MUST use JSON Schema for tool parameter definitions -- all major providers require this format)
(You MUST treat tool definitions as token cost -- every tool schema is sent on every API call, so keep descriptions concise but precise)
Failure to follow these rules will produce agents that run up API costs in infinite loops, execute unvalidated input, or silently fail without the model being able to recover.
</critical_reminders>