Files
skills/public/tool-use.html

691 lines
34 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>tool-use</title>
<meta name="color-scheme" content="dark">
<style>
/* Committed to one visual world: a dark instrument panel. No light variant —
the dot field and the hairline rules only read on black, and a naive
inversion would wash both out. Every colour is painted explicitly so the page
never borrows a host background. */
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
:root{
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
--font-zen-pixel-square:'Zen Pixel Square',monospace;
--mono:var(--font-zen-mono);
--sans:var(--font-zen-sans);
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
--r:999px; --r-soft:14px;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
/* The dot field. A halftone made of one repeating radial-gradient, faded out
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
/* No overflow clip here: the dot field is inset to the box already, and a clip
would cut off the copy-prompt menu. */
.hero{position:relative;border-bottom:1px solid var(--line)}
.hero::before{content:"";position:absolute;inset:0;
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
background-size:7px 7px;
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
pointer-events:none}
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
nav{border-bottom:1px solid var(--line)}
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
justify-content:space-between;align-items:center;gap:1rem}
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--ink);text-decoration:none;
display:inline-flex;align-items:center;gap:.6rem}
.brand i{font-style:normal;color:var(--faint)}
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--soft);text-decoration:none}
nav a.up:hover{color:var(--ink)}
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
h1 em{font-style:normal;color:var(--faint)}
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
line-height:1.2;font-weight:400}
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
.btn.solid:hover{background:#d8d8d4}
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
/* Copy-prompt selector. Each row copies the prompt for its own target. */
.copy{position:relative;display:inline-flex}
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
padding:.4rem;display:flex;flex-direction:column;
box-shadow:0 12px 32px rgba(0,0,0,.75)}
.menu[hidden]{display:none}
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
white-space:nowrap}
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
.mi:hover .mark{color:var(--ink)}
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
letter-spacing:.1em;text-transform:uppercase}
/* Works-with bar: one scrolling row, name and mark per agent. */
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
display:flex;align-items:center}
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
-webkit-overflow-scrolling:touch;
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
.bar::-webkit-scrollbar{display:none}
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
text-decoration:none;background:var(--ground)}
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
.agent .mark{width:.95rem;height:.95rem}
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
p{margin:0 0 1rem;max-width:70ch}
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
li{margin:.22rem 0}
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
text-decoration-color:var(--line-hi)}
a:hover{text-decoration-color:var(--ink)}
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
display:block;overflow-x:auto}
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
.curl{display:block;background:var(--panel);border:1px solid var(--line);
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
white-space:pre;line-height:1.9}
.curl b{color:var(--ink);font-weight:400}
.curl i{font-style:normal;color:var(--faint)}
/* index */
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
#q:focus{outline:none;border-color:var(--soft)}
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
text-transform:uppercase;margin:0 0 2rem}
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
padding-bottom:.45rem}
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
border-radius:var(--r-soft);text-decoration:none}
.row:hover{background:#0a0a0a}
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
color:var(--faint);font-size:.85rem}
footer a{color:var(--soft)}
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
margin:0 0 2rem;font-size:.85rem}
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
border-bottom:1px solid var(--line);padding-bottom:.4rem}
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
.fmap a:hover{text-decoration:underline}
.fmap div{color:var(--faint);line-height:1.5}
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
@media (max-width:640px){
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
.btns{gap:.5rem}
.btn{padding:.75rem 1.15rem;font-size:.68rem}
.copy,.copy .btn{width:100%;justify-content:center}
.menu{left:0;right:0;min-width:0}
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
.strip b{border-right:0;padding-right:0}
.bar{width:100%}
}
</style>
<link rel="alternate" type="text/markdown" href="/tool-use.md">
<link rel="icon" href="/favicon.svg">
<link rel="canonical" href="https://hanzoskills.com/tool-use">
</head>
<!-- Reading this with a machine? Every page here is also plain markdown.
This one: https://hanzoskills.com/tool-use.md
Index: https://hanzoskills.com/llms.txt
Corpus: https://hanzoskills.com/all.md
Append .md to any path for the markdown twin. -->
<body>
<nav><div class="in">
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
<a class="up" href="/">All skills</a>
</div></nav>
<div class="wrap">
<h1>tool-use</h1><p class="lede">For conceptual overview (tool definitions, tool choice, tips), see shared/tool-use-concepts.md(../../shared/tool-use-concepts.md).</p><h1>Tool Use — TypeScript</h1>
<p>For conceptual overview (tool definitions, tool choice, tips), see <a href="../../shared/tool-use-concepts.md">shared/tool-use-concepts.md</a>.</p>
<h2>Tool Runner (Recommended)</h2>
<p><strong>Beta:</strong> The tool runner is in beta in the TypeScript SDK.</p>
<p>Use <code>betaZodTool</code> with Zod schemas to define tools with a <code>run</code> function, then pass them to <code>client.beta.messages.toolRunner()</code>:</p>
<pre><code class="lang-typescript">import Anthropic from &quot;@anthropic-ai/sdk&quot;;
import { betaZodTool } from &quot;@anthropic-ai/sdk/helpers/beta/zod&quot;;
import { z } from &quot;zod&quot;;
const client = new Anthropic();
const getWeather = betaZodTool({
name: &quot;get_weather&quot;,
description: &quot;Get current weather for a location&quot;,
inputSchema: z.object({
location: z.string().describe(&quot;City and state, e.g., San Francisco, CA&quot;),
unit: z.enum([&quot;celsius&quot;, &quot;fahrenheit&quot;]).optional(),
}),
run: async (input) =&gt; {
// Your implementation here
return `72°F and sunny in ${input.location}`;
},
});
// The tool runner handles the agentic loop and returns the final message
const finalMessage = await client.beta.messages.toolRunner({
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
tools: [getWeather],
messages: [{ role: &quot;user&quot;, content: &quot;What&#x27;s the weather in Paris?&quot; }],
});
console.log(finalMessage.content);</code></pre>
<p>Zod is optional — <code>betaTool()</code> from <code>@anthropic-ai/sdk/helpers/beta/json-schema</code> accepts a raw JSON Schema <code>inputSchema</code> plus a <code>run</code> function if you don&#x27;t want a Zod dependency.</p>
<p><strong>Key benefits of the tool runner:</strong></p>
<ul><li>No manual loop — the SDK handles calling tools and feeding results back</li><li>Type-safe tool inputs via Zod schemas (or raw JSON Schema via <code>betaTool()</code>)</li><li>Tool schemas are generated automatically from Zod definitions</li><li>Iteration stops automatically when Claude has no more tool calls</li></ul>
<h3>Server tools with the tool runner</h3>
<p>The runner&#x27;s <code>tools</code> array accepts raw server-tool definitions (<code>web_search_20260209</code>, <code>web_fetch_20260209</code>, code execution) alongside runnable tools — pass the literal tool object; server tools run on Anthropic&#x27;s servers, so there is no <code>run</code> function.</p>
<p><strong>Caution — the runner does not auto-resume <code>pause_turn</code> (as of <code>@anthropic-ai/sdk</code> 0.110.0).</strong> A long-running server-tool turn can stop with <code>stop_reason: &quot;pause_turn&quot;</code>. The runner only continues after a client tool produces a result, so a paused turn ends the loop and is returned as the final message — no error, no warning, just a silently truncated answer. If you mix server tools into the runner, check <code>stop_reason</code> on every iteration and resume by pushing the paused assistant turn back:</p>
<pre><code class="lang-typescript">const params = {
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
tools: [getWeather, { type: &quot;web_search_20260209&quot;, name: &quot;web_search&quot;, max_uses: 5 }],
messages: [{ role: &quot;user&quot;, content: &quot;Compare this week&#x27;s forecasts for Paris across two sources&quot; }],
};
const runner = client.beta.messages.toolRunner(params);
// Non-streaming: each iteration yields a complete message
for await (const message of runner) {
if (message.stop_reason === &quot;pause_turn&quot;) {
runner.pushMessages({ role: &quot;assistant&quot;, content: message.content });
}
}
// Streaming alternative — construct the runner with `stream: true` (same
// params as above). Each iteration then yields a stream, not a message — a
// bare `message.stop_reason` check never fires. Resolve the stream first:
const streamingRunner = client.beta.messages.toolRunner({ ...params, stream: true });
for await (const stream of streamingRunner) {
const message = await stream.finalMessage();
if (message.stop_reason === &quot;pause_turn&quot;) {
streamingRunner.pushMessages({ role: &quot;assistant&quot;, content: message.content });
}
}</code></pre>
<p>Each pause–resume consumes a <code>max_iterations</code> tick, so a capped run can still end paused — check the final message&#x27;s <code>stop_reason</code> before trusting the result (after the loop, call <code>.done()</code> on the runner you iterated to get the final message). Alternatively, use the manual loop below, which handles <code>pause_turn</code> explicitly.</p>
<hr>
<h2>Manual Agentic Loop</h2>
<p>Prefer the tool runner above. Drop to a manual loop only when you need control the runner does not expose (e.g., a custom transport, request shapes the SDK cannot build, or avoiding a beta dependency — the runner is beta, and it supports per-token streaming via <code>stream: true</code>). Human-in-the-loop approval does <em>not</em> require a manual loop — gate inside the tool&#x27;s <code>run()</code> function (return a &quot;user declined&quot; result) or inspect pending <code>tool_use</code> blocks and call <code>setMessagesParams()</code> between iterations.</p>
<p>If you do need a manual loop:</p>
<pre><code class="lang-typescript">import Anthropic from &quot;@anthropic-ai/sdk&quot;;
const client = new Anthropic();
const tools: Anthropic.Tool[] = [...]; // Your tool definitions
let messages: Anthropic.MessageParam[] = [{ role: &quot;user&quot;, content: userInput }];
while (true) {
const response = await client.messages.create({
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
tools: tools,
messages: messages,
});
if (response.stop_reason === &quot;end_turn&quot;) break;
// Server-side tool hit iteration limit; append assistant turn and re-send to continue
if (response.stop_reason === &quot;pause_turn&quot;) {
messages.push({ role: &quot;assistant&quot;, content: response.content });
continue;
}
const toolUseBlocks = response.content.filter(
(b): b is Anthropic.ToolUseBlock =&gt; b.type === &quot;tool_use&quot;,
);
messages.push({ role: &quot;assistant&quot;, content: response.content });
const toolResults: Anthropic.ToolResultBlockParam[] = [];
for (const tool of toolUseBlocks) {
const result = await executeTool(tool.name, tool.input);
toolResults.push({
type: &quot;tool_result&quot;,
tool_use_id: tool.id,
content: result,
});
}
messages.push({ role: &quot;user&quot;, content: toolResults });
}</code></pre>
<h3>Streaming Manual Loop</h3>
<p>Use <code>client.messages.stream()</code> + <code>finalMessage()</code> instead of <code>.create()</code> when you need streaming within a manual loop. Text deltas are streamed on each iteration; <code>finalMessage()</code> collects the complete <code>Message</code> so you can inspect <code>stop_reason</code> and extract tool-use blocks:</p>
<pre><code class="lang-typescript">import Anthropic from &quot;@anthropic-ai/sdk&quot;;
const client = new Anthropic();
const tools: Anthropic.Tool[] = [...];
let messages: Anthropic.MessageParam[] = [{ role: &quot;user&quot;, content: userInput }];
while (true) {
const stream = client.messages.stream({
model: &quot;claude-opus-5&quot;,
max_tokens: 64000,
tools,
messages,
});
// Stream text deltas on each iteration
stream.on(&quot;text&quot;, (delta) =&gt; {
process.stdout.write(delta);
});
// finalMessage() resolves with the complete Message — no need to
// manually wire up .on(&quot;message&quot;) / .on(&quot;error&quot;) / .on(&quot;abort&quot;)
const message = await stream.finalMessage();
if (message.stop_reason === &quot;end_turn&quot;) break;
// Server-side tool hit iteration limit; append assistant turn and re-send to continue
if (message.stop_reason === &quot;pause_turn&quot;) {
messages.push({ role: &quot;assistant&quot;, content: message.content });
continue;
}
const toolUseBlocks = message.content.filter(
(b): b is Anthropic.ToolUseBlock =&gt; b.type === &quot;tool_use&quot;,
);
messages.push({ role: &quot;assistant&quot;, content: message.content });
const toolResults: Anthropic.ToolResultBlockParam[] = [];
for (const tool of toolUseBlocks) {
const result = await executeTool(tool.name, tool.input);
toolResults.push({
type: &quot;tool_result&quot;,
tool_use_id: tool.id,
content: result,
});
}
messages.push({ role: &quot;user&quot;, content: toolResults });
}</code></pre>
<blockquote><p><strong>Important:</strong> Don&#x27;t wrap <code>.on()</code> events in <code>new Promise()</code> to collect the final message — use <code>stream.finalMessage()</code> instead. The SDK handles all error/abort/completion states internally.</p></blockquote>
<blockquote><p><strong>Error handling in the loop:</strong> Use the SDK&#x27;s typed exceptions (e.g., <code>Anthropic.RateLimitError</code>, <code>Anthropic.APIError</code>) — see <a href="./README.md#error-handling">Error Handling</a> for examples. Don&#x27;t check error messages with string matching.</p></blockquote>
<blockquote><p><strong>SDK types:</strong> Use <code>Anthropic.MessageParam</code>, <code>Anthropic.Tool</code>, <code>Anthropic.ToolUseBlock</code>, <code>Anthropic.ToolResultBlockParam</code>, <code>Anthropic.Message</code>, etc. for all API-related data structures. Don&#x27;t redefine equivalent interfaces.</p></blockquote>
<hr>
<h2>Handling Tool Results</h2>
<pre><code class="lang-typescript">const response = await client.messages.create({
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
tools: tools,
messages: [{ role: &quot;user&quot;, content: &quot;What&#x27;s the weather in Paris?&quot; }],
});
for (const block of response.content) {
if (block.type === &quot;tool_use&quot;) {
const result = await executeTool(block.name, block.input);
const followup = await client.messages.create({
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
tools: tools,
messages: [
{ role: &quot;user&quot;, content: &quot;What&#x27;s the weather in Paris?&quot; },
{ role: &quot;assistant&quot;, content: response.content },
{
role: &quot;user&quot;,
content: [
{ type: &quot;tool_result&quot;, tool_use_id: block.id, content: result },
],
},
],
});
}
}</code></pre>
<hr>
<h2>Tool Choice</h2>
<pre><code class="lang-typescript">const response = await client.messages.create({
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
tools: tools,
tool_choice: { type: &quot;tool&quot;, name: &quot;get_weather&quot; },
messages: [{ role: &quot;user&quot;, content: &quot;What&#x27;s the weather in Paris?&quot; }],
});</code></pre>
<hr>
<h2>Anthropic-Defined Tools</h2>
<p>Version-suffixed <code>type</code> literals; <code>name</code> is fixed per interface. Web search and code execution are server-executed; bash and text editor are client-executed (you handle the <code>tool_use</code> locally — see <code>shared/tool-use-concepts.md</code>). Pass plain object literals — the <code>ToolUnion</code> type is satisfied structurally. <strong>The <code>name</code>/<code>type</code> pair must match the interface</strong>: mixing <code>str_replace_based_edit_tool</code> (20250728 name) with <code>text_editor_20250124</code> (which expects <code>str_replace_editor</code>) is a TS2322.</p>
<p><strong>Don&#x27;t type-annotate as <code>Tool[]</code></strong> — <code>Tool</code> is just the custom-tool variant. Let structural typing infer from the <code>tools</code> param, or annotate as <code>Anthropic.Messages.ToolUnion[]</code> if you must:</p>
<pre><code class="lang-typescript">// ✓ let inference work — no annotation
const response = await client.messages.create({
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
tools: [
{ type: &quot;text_editor_20250728&quot;, name: &quot;str_replace_based_edit_tool&quot; },
{ type: &quot;bash_20250124&quot;, name: &quot;bash&quot; },
{ type: &quot;web_search_20260209&quot;, name: &quot;web_search&quot; },
{ type: &quot;code_execution_20260120&quot;, name: &quot;code_execution&quot; },
],
messages: [{ role: &quot;user&quot;, content: &quot;...&quot; }],
});
// ✗ this is a TS2352 — Tool is the CUSTOM tool variant only
// const tools: Anthropic.Tool[] = [{ type: &quot;text_editor_20250728&quot;, ... }]</code></pre>
<p>| Interface | <code>name</code> | <code>type</code> | |---|---|---| | <code>ToolTextEditor20250124</code> | <code>str_replace_editor</code> | <code>text_editor_20250124</code> | | <code>ToolTextEditor20250429</code> | <code>str_replace_based_edit_tool</code> | <code>text_editor_20250429</code> | | <code>ToolTextEditor20250728</code> | <code>str_replace_based_edit_tool</code> | <code>text_editor_20250728</code> | | <code>ToolBash20250124</code> | <code>bash</code> | <code>bash_20250124</code> | | <code>WebSearchTool20260209</code> | <code>web_search</code> | <code>web_search_20260209</code> | | <code>WebFetchTool20260209</code> | <code>web_fetch</code> | <code>web_fetch_20260209</code> | | <code>CodeExecutionTool20260120</code> | <code>code_execution</code> | <code>code_execution_20260120</code> |</p>
<p><strong>Don&#x27;t mix beta and non-beta types</strong>: if you call <code>client.beta.messages.create()</code>, the response <code>content</code> is <code>BetaContentBlock[]</code> — you cannot pass that to a non-beta <code>ContentBlockParam[]</code> without narrowing each element.</p>
<hr>
<h2>Code Execution</h2>
<h3>Basic Usage</h3>
<pre><code class="lang-typescript">import Anthropic from &quot;@anthropic-ai/sdk&quot;;
const client = new Anthropic();
const response = await client.messages.create({
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
messages: [
{
role: &quot;user&quot;,
content:
&quot;Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]&quot;,
},
],
tools: [{ type: &quot;code_execution_20260120&quot;, name: &quot;code_execution&quot; }],
});</code></pre>
<h3>Reading Local Files (ESM note)</h3>
<p><code>__dirname</code> doesn&#x27;t exist in ES modules. For script-relative paths use <code>import.meta.url</code>:</p>
<pre><code class="lang-typescript">import { readFileSync } from &quot;fs&quot;;
import { fileURLToPath } from &quot;url&quot;;
import { dirname, join } from &quot;path&quot;;
const __dirname = dirname(fileURLToPath(import.meta.url));
const pdfBytes = readFileSync(join(__dirname, &quot;sample.pdf&quot;));</code></pre>
<p>Or use a CWD-relative path if the script runs from a known directory: <code>readFileSync(&quot;./sample.pdf&quot;)</code>.</p>
<h3>Upload Files for Analysis</h3>
<pre><code class="lang-typescript">import Anthropic, { toFile } from &quot;@anthropic-ai/sdk&quot;;
import { createReadStream } from &quot;fs&quot;;
const client = new Anthropic();
// 1. Upload a file
const uploaded = await client.beta.files.upload({
file: await toFile(createReadStream(&quot;sales_data.csv&quot;), undefined, {
type: &quot;text/csv&quot;,
}),
betas: [&quot;files-api-2025-04-14&quot;],
});
// 2. Pass to code execution
// Code execution is GA; Files API is still beta (pass via RequestOptions)
const response = await client.messages.create(
{
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
messages: [
{
role: &quot;user&quot;,
content: [
{
type: &quot;text&quot;,
text: &quot;Analyze this sales data. Show trends and create a visualization.&quot;,
},
{ type: &quot;container_upload&quot;, file_id: uploaded.id },
],
},
],
tools: [{ type: &quot;code_execution_20260120&quot;, name: &quot;code_execution&quot; }],
},
{ headers: { &quot;anthropic-beta&quot;: &quot;files-api-2025-04-14&quot; } },
);</code></pre>
<h3>Retrieve Generated Files</h3>
<pre><code class="lang-typescript">import path from &quot;path&quot;;
import fs from &quot;fs&quot;;
const OUTPUT_DIR = &quot;./claude_outputs&quot;;
await fs.promises.mkdir(OUTPUT_DIR, { recursive: true });
for (const block of response.content) {
if (block.type === &quot;bash_code_execution_tool_result&quot;) {
const result = block.content;
if (result.type === &quot;bash_code_execution_result&quot; &amp;&amp; result.content) {
for (const fileRef of result.content) {
if (fileRef.type === &quot;bash_code_execution_output&quot;) {
const metadata = await client.beta.files.retrieveMetadata(
fileRef.file_id,
);
const downloadResponse = await client.beta.files.download(fileRef.file_id);
const fileBytes = Buffer.from(await downloadResponse.arrayBuffer());
const safeName = path.basename(metadata.filename);
if (!safeName || safeName === &quot;.&quot; || safeName === &quot;..&quot;) {
console.warn(`Skipping invalid filename: ${metadata.filename}`);
continue;
}
const outputPath = path.join(OUTPUT_DIR, safeName);
await fs.promises.writeFile(outputPath, fileBytes);
console.log(`Saved: ${outputPath}`);
}
}
}
}
}</code></pre>
<h3>Container Reuse</h3>
<pre><code class="lang-typescript">// First request: set up environment
const response1 = await client.messages.create({
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
messages: [
{
role: &quot;user&quot;,
content: &quot;Install tabulate and create data.json with sample user data&quot;,
},
],
tools: [{ type: &quot;code_execution_20260120&quot;, name: &quot;code_execution&quot; }],
});
// Reuse container
// container is nullable — set only when using server-side code execution
const containerId = response1.container!.id;
const response2 = await client.messages.create({
container: containerId,
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
messages: [
{
role: &quot;user&quot;,
content: &quot;Read data.json and display as a formatted table&quot;,
},
],
tools: [{ type: &quot;code_execution_20260120&quot;, name: &quot;code_execution&quot; }],
});</code></pre>
<hr>
<h2>Memory Tool</h2>
<h3>Basic Usage</h3>
<pre><code class="lang-typescript">const response = await client.messages.create({
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
messages: [
{
role: &quot;user&quot;,
content: &quot;Remember that my preferred language is TypeScript.&quot;,
},
],
tools: [{ type: &quot;memory_20250818&quot;, name: &quot;memory&quot; }],
});</code></pre>
<h3>SDK Memory Helper</h3>
<p>Use <code>betaMemoryTool</code> with a <code>MemoryToolHandlers</code> implementation:</p>
<pre><code class="lang-typescript">import {
betaMemoryTool,
type MemoryToolHandlers,
} from &quot;@anthropic-ai/sdk/helpers/beta/memory&quot;;
const handlers: MemoryToolHandlers = {
async view(command) { ... },
async create(command) { ... },
async str_replace(command) { ... },
async insert(command) { ... },
async delete(command) { ... },
async rename(command) { ... },
};
const memory = betaMemoryTool(handlers);
const runner = client.beta.messages.toolRunner({
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
tools: [memory],
messages: [{ role: &quot;user&quot;, content: &quot;Remember my preferences&quot; }],
});
for await (const message of runner) {
console.log(message);
}</code></pre>
<p>For full implementation examples, use WebFetch:</p>
<ul><li><code>https://github.com/anthropics/anthropic-sdk-typescript/blob/main/examples/tools-helpers-memory.ts</code></li></ul>
<hr>
<h2>Structured Outputs</h2>
<h3>JSON Outputs (Zod — Recommended)</h3>
<pre><code class="lang-typescript">import Anthropic from &quot;@anthropic-ai/sdk&quot;;
import { z } from &quot;zod&quot;;
import { zodOutputFormat } from &quot;@anthropic-ai/sdk/helpers/zod&quot;;
const ContactInfoSchema = z.object({
name: z.string(),
email: z.string(),
plan: z.string(),
interests: z.array(z.string()),
demo_requested: z.boolean(),
});
const client = new Anthropic();
const response = await client.messages.parse({
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
messages: [
{
role: &quot;user&quot;,
content:
&quot;Extract: Jane Doe ([email protected]) wants Enterprise, interested in API and SDKs, wants a demo.&quot;,
},
],
output_config: {
format: zodOutputFormat(ContactInfoSchema),
},
});
// parsed_output is null if parsing failed — assert or guard
console.log(response.parsed_output!.name); // &quot;Jane Doe&quot;</code></pre>
<h3>Strict Tool Use</h3>
<pre><code class="lang-typescript">const response = await client.messages.create({
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
messages: [
{
role: &quot;user&quot;,
content: &quot;Book a flight to Tokyo for 2 passengers on March 15&quot;,
},
],
tools: [
{
name: &quot;book_flight&quot;,
description: &quot;Book a flight to a destination&quot;,
strict: true,
input_schema: {
type: &quot;object&quot;,
properties: {
destination: { type: &quot;string&quot; },
date: { type: &quot;string&quot;, format: &quot;date&quot; },
passengers: {
type: &quot;integer&quot;,
enum: [1, 2, 3, 4, 5, 6, 7, 8],
},
},
required: [&quot;destination&quot;, &quot;date&quot;, &quot;passengers&quot;],
additionalProperties: false,
},
},
],
});</code></pre>
<hr>
<h2>Agent Skills</h2>
<p>Enable an Anthropic-managed skill (e.g., <code>pptx</code>) via <code>container.skills</code> + the <code>code_execution</code> tool on the beta path. Both beta headers are required. Outputs land as files in the response content — download by file ID via the Files API.</p>
<pre><code class="lang-typescript">const response = await client.beta.messages.create({
model: &quot;claude-opus-5&quot;,
max_tokens: 16000,
container: {
skills: [{ type: &quot;anthropic&quot;, skill_id: &quot;pptx&quot;, version: &quot;latest&quot; }],
},
tools: [{ type: &quot;code_execution_20260521&quot;, name: &quot;code_execution&quot; }],
betas: [&quot;code-execution-2025-08-25&quot;, &quot;skills-2025-10-02&quot;],
messages: [{ role: &quot;user&quot;, content: &quot;Create a 3-slide deck about X.&quot; }],
});
// Find the file_id in response.content, then:
// await client.beta.files.download(fileId)</code></pre>
<footer>
<div class="fmap">
<div><b>Build</b>
<a href="https://hanzo.app">hanzo.app</a> app builder
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
<div><b>Run</b>
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
<div><b>Account</b>
<a href="https://hanzo.id">hanzo.id</a> sign in
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
<div><b>Company</b>
<a href="https://hanzo.ai">hanzo.ai</a> canonical
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
</div>
<div class="fend"><a href="/tool-use.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>