Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

anthropic.md

779 lines29.8 KB

1---
2title: Anthropic
3id: anthropic-adapter
4order: 2
5description: "Use Anthropic Claude models with TanStack AI — Claude Fable 5, Claude Sonnet 5, Claude Opus, and more via the @tanstack/ai-anthropic adapter."
6keywords:
7 - tanstack ai
8 - anthropic
9 - claude
10 - claude fable 5
11 - claude sonnet 5
12 - claude opus
13 - adapter
14 - llm
15---
16​
17The Anthropic adapter provides access to Claude models, including Claude Fable 5, Claude Sonnet 5, Claude Opus 4.8, and more.
18​
19## Installation
20​
21<!-- ::start:tabs variant="package-manager" mode="install" -->
22​
23react: @tanstack/ai-anthropic
24vue: @tanstack/ai-anthropic
25solid: @tanstack/ai-anthropic
26svelte: @tanstack/ai-anthropic
27preact: @tanstack/ai-anthropic
28angular: @tanstack/ai-anthropic
29vanilla: @tanstack/ai-anthropic
30octane: @tanstack/ai-anthropic
31​
32<!-- ::end:tabs -->
33​
34## Basic Usage
35​
36```typescript
37import { chat } from "@tanstack/ai";
38import { anthropicText } from "@tanstack/ai-anthropic";
39​
40const stream = chat({
41 adapter: anthropicText("claude-sonnet-4-6"),
42 messages: [{ role: "user", content: "Hello!" }],
43});
44```
45​
46## Basic Usage - Custom API Key
47​
48```typescript
49import { chat } from "@tanstack/ai";
50import { createAnthropicChat } from "@tanstack/ai-anthropic";
51​
52const adapter = createAnthropicChat("claude-sonnet-4-6", process.env.ANTHROPIC_API_KEY!, {
53 // ... your config options
54});
55​
56const stream = chat({
57 adapter,
58 messages: [{ role: "user", content: "Hello!" }],
59});
60```
61​
62## Bearer and OAuth tokens
63​
64Got a Bearer token instead of an API key? Pass it as the credential and set `auth: "bearer"`. The adapter sends `Authorization: Bearer <token>` and no `x-api-key` header:
65​
66```typescript
67import { chat } from "@tanstack/ai";
68import { createAnthropicChat } from "@tanstack/ai-anthropic";
69​
70const adapter = createAnthropicChat("claude-sonnet-5-5", process.env.MY_CLAUDE_TOKEN!, {
71 auth: "bearer",
72});
73​
74const stream = chat({
75 adapter,
76 messages: [{ role: "user", content: "Hello!" }],
77});
78```
79​
80`auth` takes one of three values:
81​
82- `"api-key"`: sends the `x-api-key` header. This is the default.
83- `"bearer"`: sends `Authorization: Bearer <token>` and no `x-api-key` header.
84- `"oauth"`: sends the token like `"bearer"`, plus the Claude Code extras below.
85​
86Got a Claude OAuth token? It contains `sk-ant-oat`, and the adapter picks `"oauth"` for you, so you can leave `auth` out. In OAuth mode, every request also gets:
87​
88- the Claude Code identity system block, before your own system prompts.
89- the Claude Code CLI headers (`user-agent` and `x-app`).
90- the `claude-code-20250219` and `oauth-2025-04-20` betas.
91​
92An explicit `auth` always wins. To send an `sk-ant-oat` token as a plain Bearer token, without the extras, set `auth: "bearer"`.
93​
94Is the token in your environment? Then `anthropicText` finds it and picks `auth` for you. See [Environment Variables](#environment-variables) for the order:
95​
96```typescript
97import { chat } from "@tanstack/ai";
98import { anthropicText } from "@tanstack/ai-anthropic";
99​
100// ANTHROPIC_AUTH_TOKEN=my-token in your environment
101const stream = chat({
102 adapter: anthropicText("claude-sonnet-5-5"),
103 messages: [{ role: "user", content: "Hello!" }],
104});
105```
106​
107To call Claude models through a GitHub Copilot plan, see [GitHub Copilot](./openai-compatible#claude-models).
108​
109## Configuration
110​
111```typescript
112import { createAnthropicChat, type AnthropicTextConfig } from "@tanstack/ai-anthropic";
113​
114const config: Omit<AnthropicTextConfig, "apiKey"> = {
115 baseURL: "https://api.anthropic.com", // Optional, for custom endpoints
116};
117​
118const adapter = createAnthropicChat("claude-sonnet-4-6", process.env.ANTHROPIC_API_KEY!, config);
119```
120​
121Need a header on each request, or a log of each model call? This adapter supports [`wrapFetch`](../advanced/middleware#change-the-http-requests-of-a-call). An adapter with your own client (Claude on Vertex, or `createAnthropicChatWithClient`) ignores it, because the adapter cannot reach the fetch of that client.
122​
123## Replay thinking through a gateway
124​
125Your gateway speaks the Anthropic protocol, but it returns thinking with no signature. By default the adapter does not send unsigned thinking back, so the next turn loses it. Turn on `allowEmptySignature`:
126​
127```typescript
128import { anthropicText } from "@tanstack/ai-anthropic";
129​
130const gateway = anthropicText("claude-sonnet-5-5", {
131 baseURL: "https://gateway.example.com",
132 provider: "my-gateway",
133 allowEmptySignature: true,
134});
135​
136console.log(gateway.provider); // "my-gateway"
137```
138​
139- `allowEmptySignature` is `false` by default. It sends unsigned thinking back only for history from the same source.
140- Redacted thinking still needs its encrypted data.
141- `provider` names the gateway. History from the gateway then counts as a different source from Anthropic itself. See [Keep saved history when you switch](../advanced/runtime-adapter-switching#keep-saved-history-when-you-switch).
142​
143## Claude on Vertex
144​
145Use `@tanstack/ai-anthropic/vertex` when Claude must run on Vertex AI. That
146is the path for regional endpoints and Google Cloud credentials.
147​
148Install the Vertex SDK next to the Anthropic adapter:
149​
150<!-- ::start:tabs variant="package-manager" mode="install" -->
151​
152react: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
153vue: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
154solid: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
155svelte: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
156preact: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
157angular: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
158vanilla: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
159octane: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
160​
161<!-- ::end:tabs -->
162​
163```typescript
164import { chat } from "@tanstack/ai";
165import { anthropicVertexText } from "@tanstack/ai-anthropic/vertex";
166​
167const stream = chat({
168 adapter: anthropicVertexText("claude-sonnet-5", {
169 project: "my-project",
170 location: "europe-west1",
171 }),
172 messages: [{ role: "user", content: "Hello!" }],
173});
174```
175​
176`anthropicVertexText` accepts only the Claude models in the Vertex catalog.
177It does not accept Anthropic-only ids such as `claude-opus-5-fast`.
178​
179`project` and `location` use the same names as `@tanstack/ai-vertex`, so one
180auth object works for Gemini and Claude.
181​
182If you omit `project`, Application Default Credentials can still fill it.
183`location` is required. You can pass it on the factory or set
184`GOOGLE_CLOUD_LOCATION`, `GOOGLE_VERTEX_LOCATION`, or `CLOUD_ML_REGION`.
185​
186Gemini on Vertex lives in [`@tanstack/ai-vertex`](./vertex).
187​
188## Custom Anthropic client
189​
190Use `createAnthropicChatWithClient` when you already have an
191Anthropic-compatible client. The adapter only needs `beta.messages.create`.
192Message mapping, streaming, tools, media, usage, and structured output stay
193on the same TanStack path.
194​
195<!-- ::start:tabs variant="package-manager" mode="install" -->
196​
197react: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
198vue: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
199solid: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
200svelte: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
201preact: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
202angular: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
203vanilla: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
204octane: @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
205​
206<!-- ::end:tabs -->
207​
208```typescript
209import { AnthropicVertex } from "@anthropic-ai/vertex-sdk";
210import { createAnthropicChatWithClient } from "@tanstack/ai-anthropic";
211​
212const client = new AnthropicVertex({
213 projectId: "my-project",
214 region: "europe-west1",
215});
216​
217const adapter = createAnthropicChatWithClient("claude-sonnet-5", client);
218```
219​
220The injected client must implement the Anthropic Beta Messages protocol.
221Endpoint-specific model and feature support stays the caller's job.
222​
223## Example: Chat Completion
224​
225```typescript
226import { chat, toServerSentEventsResponse } from "@tanstack/ai";
227import { anthropicText } from "@tanstack/ai-anthropic";
228​
229export async function POST(request: Request) {
230 const { messages } = await request.json();
231​
232 const stream = chat({
233 adapter: anthropicText("claude-sonnet-4-6"),
234 messages,
235 });
236​
237 return toServerSentEventsResponse(stream);
239```
240​
241## Example: With Tools
242​
243```typescript
244import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
245import { anthropicText } from "@tanstack/ai-anthropic";
246import { z } from "zod";
247​
248const searchDatabaseDef = toolDefinition({
249 name: "search_database",
250 description: "Search the database",
251 inputSchema: z.object({
252 query: z.string(),
253 }),
254});
255​
256const searchDatabase = searchDatabaseDef.server(async ({ query }) => {
257 // Search database
258 return { results: [] };
259});
260​
261export async function POST(request: Request) {
262 const { messages } = await request.json();
263​
264 const stream = chat({
265 adapter: anthropicText("claude-sonnet-4-6"),
266 messages,
267 tools: [searchDatabase],
268 });
269​
270 return toServerSentEventsResponse(stream);
272```
273​
274## Model Options
275​
276Anthropic supports various provider-specific options. Sampling parameters live here too — `temperature`, `top_p`, and `max_tokens` — rather than as root-level props on `chat()`:
277​
278```typescript
279import { chat } from "@tanstack/ai";
280import { anthropicText } from "@tanstack/ai-anthropic";
281​
282const stream = chat({
283 adapter: anthropicText("claude-sonnet-4-6"),
284 messages: [{ role: "user", content: "Hello!" }],
285 modelOptions: {
286 max_tokens: 4096,
287 temperature: 0.7,
288 top_p: 0.9,
289 top_k: 40,
290 stop_sequences: ["END"],
291 },
292});
293```
294​
295> If you previously passed `temperature` / `topP` / `maxTokens` at the root of `chat()`, see [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
296​
297#### `max_tokens` default
298​
299Anthropic's Messages API _requires_ `max_tokens` on every request, so the adapter always sends a value. When you don't set `modelOptions.max_tokens`, it defaults to the selected model's full output ceiling (`max_output_tokens` from the model metadata — e.g. 64K for Sonnet, 128K for Opus), falling back to a safe constant for unrecognized models. `max_tokens` is a ceiling, not a reservation — billing is on tokens actually generated — so this default costs nothing extra and avoids the silent mid-response truncation (`stop_reason: "max_tokens"`) that a low default would cause. Set `max_tokens` explicitly only when you want to _cap_ output below the model ceiling. If a response is truncated while using the default cap, the adapter logs a warning (visible with [debug logging](../advanced/debug-logging) enabled).
300​
301A streamed response that stops at `max_tokens` ends in a `RUN_ERROR` with `code: 'max_tokens'`. Anthropic bills the tokens of that call, so this `RUN_ERROR` carries the `usage` of the call. The `onUsage` middleware hook fires only for `RUN_FINISHED`. To count these tokens too, read `usage` from the `RUN_ERROR` chunk, in the stream or in an `onChunk` middleware.
302​
303One exception: structured output (`chat({ outputSchema })`) on models that use the non-streaming finalization path clamps this default to ~21K tokens. The Anthropic SDK rejects a non-streaming request whose `max_tokens` could exceed its 10-minute timeout, so the full ceiling can't be used there. Streaming chat is unaffected. To raise the structured-output ceiling toward a model's true max, stream the response.
304​
305### Reasoning
306​
307Want Claude to think harder, or not at all? Set `reasoning` on `chat()`. The adapter turns the level into the right thinking fields for the model.
308​
309```typescript
310import { chat } from "@tanstack/ai";
311import { anthropicText } from "@tanstack/ai-anthropic";
312​
313const stream = chat({
314 adapter: anthropicText("claude-opus-5-5"),
315 messages: [{ role: "user", content: "Plan a database migration." }],
316 reasoning: "xhigh",
317});
318```
319​
320What goes on the wire:
321​
322- `off` sends `thinking: { type: "disabled" }` on the models with `off` in the table below. On a model without `off`, such as `claude-fable-5`, the types reject it, and at run time it moves to the lowest level that the model has.
323- Claude 4.6 and later get adaptive thinking and `output_config.effort`. With an `outputSchema`, the adapter adds `output_config.format` next to the effort.
324- Budget models get `thinking: { type: "enabled", budget_tokens }`. The level picks the budget, or you set it with `budgetTokens`. The adapter raises `max_tokens` when it is below the budget.
325- `summary: false` sends `display: "omitted"`, so the thinking text does not stream.
326​
327The levels of each model:
328​
329| Model | Levels | `budgetTokens` |
330| --- | --- | --- |
331| `claude-opus-5-5`, `claude-sonnet-5-5`, `claude-fable-5-1`, `claude-fable-5`, `claude-opus-5`, `claude-opus-4-8`, `claude-opus-4-7` | `low` to `max` | no |
332| `claude-haiku-5-5`, `claude-sonnet-5` | `off`, `low` to `max` | no |
333| `claude-opus-5-fast` | `off`, `low` to `max` | yes |
334| `claude-opus-4-6`, `claude-sonnet-4-6` | `low`, `medium`, `high`, `max` | yes |
335| `claude-opus-4-5` | `low`, `medium`, `high` | yes |
336| `claude-haiku-4-5`, `claude-sonnet-4-5`, `claude-opus-4-1` | `off` to `high` | yes |
337​
338A budget model with `budgetTokens`:
339​
340```typescript
341import { chat } from "@tanstack/ai";
342import { anthropicText } from "@tanstack/ai-anthropic";
343​
344const stream = chat({
345 adapter: anthropicText("claude-haiku-4-5"),
346 messages: [{ role: "user", content: "Check this proof." }],
347 reasoning: { level: "high", budgetTokens: 8000 },
348});
349```
350​
351Claude Sonnet 5, Claude Opus 4.7 and later, and the 5-generation models reject the sampling options (`temperature`, `top_p`, `top_k`). The types take them only on the models that accept them. See [Reasoning](../chat/reasoning) for the levels and the nearest-level rule.
352​
353Structured output forces a tool, and Claude cannot think while a tool is forced. So the structured output call sends no thinking.
354​
355### Prompt Caching
356​
357`chat()` caches Claude prompts by default. It adds `cache_control` markers to the last start tool, the last block of the last user or mid-conversation system message, and the system blocks. At most 4 markers. The last start tool is the tool before the deferred placeholder, or the last tool. Pass `promptCache: 'long'` for the 1-hour cache, or `promptCache: 'none'` to send no markers. For the key and the cost, see [Prompt Caching](../advanced/prompt-caching).
358​
359Want the markers in other places? Set `cache_control` in the `metadata` of a message part, a system prompt, or a tool. One marker of your own turns the automatic markers off for that request:
360​
361```typescript
362import { chat } from "@tanstack/ai";
363import { anthropicText } from "@tanstack/ai-anthropic";
364​
365const stream = chat({
366 adapter: anthropicText("claude-opus-5-5"),
367 messages: [
368 {
369 role: "user",
370 content: [
371 {
372 type: "text",
373 content: "What is the capital of France?",
374 metadata: {
375 cache_control: {
376 type: "ephemeral",
377 },
378 },
379 },
380 ],
381 },
382 ],
383});
384```
385​
386`modelOptions.cache_control` also turns the automatic markers off.
387​
388`usage.promptTokens` counts the full input, cached tokens included. The cache reads and writes are also on `usage.promptTokensDetails`. See [Token usage](../chat/stream-events#token-usage).
389​
390#### Tools and prompts added during a conversation
391​
392On `claude-opus-4-8`, `claude-opus-5`, `claude-opus-5-5`, `claude-fable-5`, and `claude-fable-5-1`, a tool or a system prompt that you add between model calls goes into the conversation. The cached start of the request stays the same.
393​
394What the adapter sends on these models:
395​
396- `system` keeps the system prompts of the first call.
397- A request with tools gets the `mid-conversation-tool-changes-2026-07-01` beta and one placeholder tool, `__tanstack_deferred_placeholder__`. The model never calls it.
398- An added tool goes at the end of `tools` with `defer_loading: true`. A `system` message names it in a `tool_addition` block.
399- An added system prompt goes into a `system` message, before the next assistant message or at the end.
400- With a provider tool such as `webSearchTool()`, `tools` is the full list and has no placeholder.
401​
402The automatic tool marker stays on the last tool of the first call, so the marked start does not move.
403​
404The channels are on by default with Anthropic's own API. A custom `baseURL`, a custom `fetch`, `ANTHROPIC_BASE_URL`, or your own client turns them off. Set `midConversationChannels` to choose:
405​
406```typescript
407import { anthropicText } from "@tanstack/ai-anthropic";
408​
409export const fullLists = anthropicText("claude-opus-5-5", {
410 midConversationChannels: false,
411});
412​
413export const throughProxy = anthropicText("claude-opus-5-5", {
414 baseURL: "https://llm-proxy.example.com",
415 midConversationChannels: true,
416});
417```
418​
419If that endpoint sends the request and the `anthropic-beta` header on to Anthropic as they are, set `true`. See [Mid-Conversation Changes](../advanced/mid-conversation-changes).
420​
421## Summarization
422​
423Anthropic supports text summarization:
424​
425```typescript
426import { summarize } from "@tanstack/ai";
427import { anthropicSummarize } from "@tanstack/ai-anthropic";
428​
429const result = await summarize({
430 adapter: anthropicSummarize("claude-sonnet-4-6"),
431 text: "Your long text to summarize...",
432 maxLength: 100,
433 style: "concise", // "concise" | "bullet-points" | "paragraph"
434});
435​
436console.log(result.summary);
437```
438​
439## Environment Variables
440​
441Set one of these. `anthropicText`, `anthropicSummarize`, and `anthropicFiles` use the first one that is set:
442​
4431. `ANTHROPIC_AUTH_TOKEN`: sent as a Bearer token. An `sk-ant-oat` token here turns on OAuth mode.
4442. `ANTHROPIC_OAUTH_TOKEN`: sent as a Bearer token, in OAuth mode.
4453. `ANTHROPIC_API_KEY`: sent as `x-api-key`.
446​
447```bash
448ANTHROPIC_API_KEY=sk-ant-...
449```
450​
451If none of them is set, these factories throw. An `auth` in the config wins over the kind that the adapter picks. See [Bearer and OAuth tokens](#bearer-and-oauth-tokens) for what OAuth mode adds.
452​
453The `create*` factories (`createAnthropicChat`, `createAnthropicSummarize`, `createAnthropicFiles`) never read a credential from the environment. They use only the credential that you pass.
454​
455## API Reference
456​
457Every factory pair has the same shape. The short factory (`anthropicText`, `anthropicSummarize`) reads the credential from the [environment](#environment-variables). `createAnthropicChat` / `createAnthropicSummarize` take an explicit credential and never read one from the environment. Both take `model` as the first argument. For Claude on Vertex, use `anthropicVertexText` from `@tanstack/ai-anthropic/vertex`. For any other custom transport, `createAnthropicChatWithClient` accepts an Anthropic-compatible Messages client.
458​
459### `anthropicText(model, config?)` / `createAnthropicChat(model, apiKey, config?)`
460​
461Creates an Anthropic chat adapter.
462​
463`adapter.inputModalities` lists the input kinds of the selected model. It is `undefined` for a model that this package does not know. See [Check what a model accepts](../advanced/extend-adapter#check-what-a-model-accepts).
464​
465**Parameters:**
466​
467- `model` - Claude model id (e.g. `"claude-sonnet-5"`, `"claude-fable-5"`, `"claude-opus-4-8"`)
468- `apiKey` - API key, Bearer token, or Claude OAuth token (`createAnthropicChat` only)
469- `config?.baseURL` - Custom base URL (optional)
470- `config?.auth` - How to send the credential: `"api-key"`, `"bearer"`, or `"oauth"` (optional, see [Bearer and OAuth tokens](#bearer-and-oauth-tokens))
471- `config?.allowEmptySignature` - Send unsigned thinking back to the same source (optional, default `false`, see [Replay thinking through a gateway](#replay-thinking-through-a-gateway))
472- `config?.provider` - The source name for a gateway (optional, default `"anthropic"`)
473​
474### `anthropicVertexText(model, config?)`
475​
476Creates an Anthropic chat adapter on Vertex. Import it from
477`@tanstack/ai-anthropic/vertex`.
478​
479**Parameters:**
480​
481- `model` - Claude model id
482- `config.project` - GCP project id (optional if ADC can resolve it)
483- `config.location` - Vertex region (or set `GOOGLE_CLOUD_LOCATION`)
484​
485### `createAnthropicChatWithClient(model, client)`
486​
487Creates an Anthropic chat adapter using an injected client.
488​
489**Parameters:**
490​
491- `model` - Claude model id
492- `client` - Client exposing `beta.messages.create`
493​
494### `anthropicSummarize(model, config?)` / `createAnthropicSummarize(model, apiKey, config?)`
495​
496Creates an Anthropic summarization adapter.
497​
498## Limitations
499​
500- **Image Generation**: Anthropic does not support image generation. Use OpenAI or Gemini for image generation.
501​
502## Next Steps
503​
504- [Getting Started](../getting-started/quick-start) - Learn the basics
505- [Tools Guide](../tools/tools) - Learn about tools
506- [Other Adapters](./openai) - Explore other providers
507​
508## Provider Tools
509​
510Anthropic exposes several native tools beyond user-defined function calls.
511Import them from `@tanstack/ai-anthropic/tools` and pass them into
512`chat({ tools: [...] })`.
513​
514> For the full concept, a comparison matrix, and type-gating details, see
515> [Provider Tools](../tools/provider-tools.md).
516​
517### `webSearchTool`
518​
519Enables Claude to run Anthropic's native web search with inline citations.
520Scope the search with `allowed_domains` or `blocked_domains` (mutually
521exclusive); set `max_uses` to cap per-turn cost.
522​
523```typescript
524import { chat } from "@tanstack/ai";
525import { anthropicText } from "@tanstack/ai-anthropic";
526import { webSearchTool } from "@tanstack/ai-anthropic/tools";
527​
528const stream = chat({
529 adapter: anthropicText("claude-opus-4-7"),
530 messages: [{ role: "user", content: "What's new in AI this week?" }],
531 tools: [
532 webSearchTool({
533 name: "web_search",
534 type: "web_search_20250305",
535 max_uses: 2,
536 }),
537 ],
538});
539```
540​
541**Supported models:** every registered Claude model. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
542​
543### `webFetchTool`
544​
545Lets Claude fetch the contents of a URL directly, useful when you want the
546model to read a specific page rather than run a search. Takes no required
547arguments — pass an optional config object to override defaults.
548​
549```typescript
550import { chat } from "@tanstack/ai";
551import { anthropicText } from "@tanstack/ai-anthropic";
552import { webFetchTool } from "@tanstack/ai-anthropic/tools";
553​
554const stream = chat({
555 adapter: anthropicText("claude-sonnet-4-6"),
556 messages: [{ role: "user", content: "Summarise https://example.com" }],
557 tools: [webFetchTool()],
558});
559```
560​
561**Supported models:** Claude Sonnet 4.x and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
562​
563### `codeExecutionTool`
564​
565Gives Claude a sandboxed code-execution environment so it can run Python
566snippets, analyse data, and return results inline. Choose the version string
567that matches your desired API revision.
568​
569```typescript
570import { chat } from "@tanstack/ai";
571import { anthropicText } from "@tanstack/ai-anthropic";
572import { codeExecutionTool } from "@tanstack/ai-anthropic/tools";
573​
574const stream = chat({
575 adapter: anthropicText("claude-sonnet-4-6"),
576 messages: [{ role: "user", content: "Plot a histogram of [1,2,2,3,3,3]" }],
577 tools: [
578 codeExecutionTool({ name: "code_execution", type: "code_execution_20250825" }),
579 ],
580});
581```
582​
583**Supported models:** Claude Sonnet 4.x and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
584​
585#### Attaching hosted skills
586​
587Pass a `skills` array as the second argument to load provider-managed skill
588bundles into the sandbox. The adapter auto-lifts them into the API's
589`container.skills` param and adds the required beta headers for you.
590​
591```typescript
592import { chat, toServerSentEventsResponse } from "@tanstack/ai";
593import { anthropicText } from "@tanstack/ai-anthropic";
594import { codeExecutionTool } from "@tanstack/ai-anthropic/tools";
595​
596export async function POST(request: Request) {
597 const { messages } = await request.json();
598​
599 const stream = chat({
600 adapter: anthropicText("claude-sonnet-4-5"),
601 messages,
602 tools: [
603 codeExecutionTool(
604 { type: "code_execution_20250825", name: "code_execution" },
605 {
606 skills: [{ type: "anthropic", skill_id: "pptx", version: "latest" }],
607 },
608 ),
609 ],
610 });
611​
612 return toServerSentEventsResponse(stream);
614```
615​
616For the full reference — skill shape, constraints, scope, and the OpenAI
617equivalent — see [Provider Skills](../tools/provider-skills.md).
618​
619### `computerUseTool`
620​
621Claude can look at a screen and use the mouse and the keyboard. Your app runs each action and sends back a screenshot. `createComputerUse` from `@tanstack/ai-computer-use` does this on a Playwright browser or an E2B desktop. Each thread gets its own machine:
622​
623```typescript
624import { chat } from "@tanstack/ai";
625import { anthropicText } from "@tanstack/ai-anthropic";
626import { createComputerUse } from "@tanstack/ai-computer-use";
627import { playwrightComputer } from "@tanstack/ai-computer-playwright";
628​
629declare const threadId: string;
630​
631const computerUse = createComputerUse({
632 driver: playwrightComputer({ startUrl: "https://tanstack.com" }),
633});
634​
635const stream = chat({
636 adapter: anthropicText("claude-opus-5-5"),
637 messages: [{ role: "user", content: "Find the TanStack AI docs" }],
638 threadId,
639 tools: computerUse.tools,
640 middleware: [computerUse.middleware],
641 interrupts: [computerUse.interrupt],
642});
643```
644​
645The adapter sends the `computer` tool to Claude as the newest native computer tool that your model takes.
646​
647- For the setup, the threads, and how to close the machines, see [Computer use](../computer-use/computer-use.md).
648- For your own machine, see [Custom driver](../computer-use/custom-driver.md).
649​
650#### The raw tool
651​
652`computerUseTool` from `@tanstack/ai-anthropic/tools` is the native tool with no `execute`. Use it when your app runs the actions itself. Pick the version that your model takes:
653​
654| Version | Models |
655| --- | --- |
656| `computer_toolset_20260801` | Claude Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5.1, Fable 5, Opus 5, Sonnet 5, Opus 4.8 |
657| `computer_20251124` | Claude Fable 5.1, Fable 5, Opus 5, Sonnet 5, Opus 4.8, Opus 4.7, Opus 4.6, Sonnet 4.6, Opus 4.5 |
658| `computer_20250124` | Claude Sonnet 4.5, Haiku 4.5, Opus 4.1 |
659​
660```typescript
661import { computerUseTool } from "@tanstack/ai-anthropic/tools";
662​
663const computer = computerUseTool({ type: "computer_toolset_20260801" });
664```
665​
666The earlier versions also take a name and the screen size:
667​
668```typescript
669import { computerUseTool } from "@tanstack/ai-anthropic/tools";
670​
671const computer = computerUseTool({
672 type: "computer_20251124",
673 name: "computer",
674 display_width_px: 1280,
675 display_height_px: 800,
676});
677```
678​
679Add an `execute` that runs the action and returns a result:
680​
681- Every version calls `execute` with the action in `input.action`. With the toolset, Claude calls each action as its own tool. The adapter gives you each call as one `computer` call.
682- Return a screenshot as an image part for the `screenshot` action, and `"OK"` for the other actions.
683- Send screenshots that fit the image limits of the model. The toolset refuses a large screenshot. It does not make it smaller.
684- The toolset turns on `zoom` by default. Return an image for the `zoom` action, or turn it off with `configs: { zoom: { enabled: false } }`.
685- The adapter sends the beta header that an earlier version needs. The toolset needs no beta header.
686​
687Claude gives coordinates in the pixels of your screenshots.
688​
689A version that your model does not take is a type error. `claude-opus-5-fast` takes no provider tools. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
690​
691### `bashTool`
692​
693Provides Claude with a persistent bash shell session, letting it run arbitrary
694commands, install packages, or manipulate files on the host. Choose the type
695string that matches your API revision.
696​
697```typescript
698import { chat } from "@tanstack/ai";
699import { anthropicText } from "@tanstack/ai-anthropic";
700import { bashTool } from "@tanstack/ai-anthropic/tools";
701​
702const stream = chat({
703 adapter: anthropicText("claude-sonnet-4-6"),
704 messages: [{ role: "user", content: "List all TypeScript files in src/" }],
705 tools: [bashTool({ name: "bash", type: "bash_20250124" })],
706});
707```
708​
709**Supported models:** Claude Sonnet 3.5 and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
710​
711### `textEditorTool`
712​
713Gives Claude a structured text-editor interface for viewing and modifying files
714using `str_replace`, `create`, `view`, and `undo_edit` commands. Choose the
715type string for the API revision you target.
716​
717```typescript
718import { chat } from "@tanstack/ai";
719import { anthropicText } from "@tanstack/ai-anthropic";
720import { textEditorTool } from "@tanstack/ai-anthropic/tools";
721​
722const stream = chat({
723 adapter: anthropicText("claude-sonnet-4-6"),
724 messages: [{ role: "user", content: "Fix the bug in src/index.ts" }],
725 tools: [
726 textEditorTool({ type: "text_editor_20250124", name: "str_replace_editor" }),
727 ],
728});
729```
730​
731**Supported models:** Claude Sonnet 3.5 and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
732​
733### `memoryTool`
734​
735Enables Claude to store and retrieve information across conversation turns
736using Anthropic's managed memory service. Call with no arguments to use
737default configuration.
738​
739```typescript
740import { chat } from "@tanstack/ai";
741import { anthropicText } from "@tanstack/ai-anthropic";
742import { memoryTool } from "@tanstack/ai-anthropic/tools";
743​
744const stream = chat({
745 adapter: anthropicText("claude-sonnet-4-6"),
746 messages: [{ role: "user", content: "Remember that I prefer metric units" }],
747 tools: [memoryTool()],
748});
749```
750​
751**Supported models:** Claude Sonnet 4.x and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
752​
753### `customTool`
754​
755Creates a tool with an inline JSON Schema input definition instead of going
756through `toolDefinition()`. Useful when you need fine-grained control over the
757schema shape or want to add `cache_control`. Unlike branded provider tools,
758`customTool` returns a plain `Tool` and is accepted by any chat model.
759​
760```typescript
761import { chat } from "@tanstack/ai";
762import { anthropicText } from "@tanstack/ai-anthropic";
763import { customTool } from "@tanstack/ai-anthropic/tools";
764import { z } from "zod";
765​
766const stream = chat({
767 adapter: anthropicText("claude-sonnet-4-6"),
768 messages: [{ role: "user", content: "Look up user 42" }],
769 tools: [
770 customTool(
771 "lookup_user",
772 "Look up a user by ID and return their profile",
773 z.object({ userId: z.number() }),
774 ),
775 ],
776});
777```
778​
779**Supported models:** all current Claude models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).