본문으로 건너뛰기

Anthropic

Anthropic 어댑터를 사용하면 Claude Fable 5, Claude Sonnet 5, Claude Opus 4.8 등을 포함한 Claude 모델에 액세스할 수 있습니다.

설치​

npm install @tanstack/ai-anthropic

기본 사용법​

import { chat } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";

const stream = chat({
adapter: anthropicText("claude-sonnet-4-6"),
messages: [{ role: "user", content: "Hello!" }],
});

기본 사용법 - 사용자 지정 API 키​

import { chat } from "@tanstack/ai";
import { createAnthropicChat } from "@tanstack/ai-anthropic";

const adapter = createAnthropicChat("claude-sonnet-4-6", process.env.ANTHROPIC_API_KEY!, {
// ... your config options
});

const stream = chat({
adapter,
messages: [{ role: "user", content: "Hello!" }],
});

구성​

import { createAnthropicChat, type AnthropicTextConfig } from "@tanstack/ai-anthropic";

const config: Omit<AnthropicTextConfig, "apiKey"> = {
baseURL: "https://api.anthropic.com", // Optional, for custom endpoints
};

const adapter = createAnthropicChat("claude-sonnet-4-6", process.env.ANTHROPIC_API_KEY!, config);

Vertex의 Claude​

Claude를 Vertex AI에서 실행해야 할 때는 @tanstack/ai-anthropic/vertex를 사용합니다. 지역별 엔드포인트와 Google Cloud 자격 증명을 사용하려면 이 경로를 이용합니다.

Anthropic 어댑터와 함께 Vertex SDK를 설치합니다.

npm install @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
import { chat } from "@tanstack/ai";
import { anthropicVertexText } from "@tanstack/ai-anthropic/vertex";

const stream = chat({
adapter: anthropicVertexText("claude-sonnet-5", {
project: "my-project",
location: "europe-west1",
}),
messages: [{ role: "user", content: "Hello!" }],
});

anthropicVertexText는 Vertex 카탈로그에 있는 Claude 모델만 허용합니다. claude-opus-5-fast와 같은 Anthropic 전용 id는 허용하지 않습니다.

project와 location은 @tanstack/ai-vertex와 같은 이름을 사용하므로 하나의 인증 객체를 Gemini와 Claude에 사용할 수 있습니다.

project를 생략해도 Application Default Credentials가 값을 채울 수 있습니다. location은 필수입니다. 팩토리에 전달하거나 GOOGLE_CLOUD_LOCATION, GOOGLE_VERTEX_LOCATION, CLOUD_ML_REGION을 설정할 수 있습니다.

Vertex의 Gemini는 @tanstack/ai-vertex에 있습니다.

사용자 지정 Anthropic 클라이언트​

Anthropic 호환 클라이언트가 이미 있을 때는 createAnthropicChatWithClient를 사용합니다. 어댑터에는 beta.messages.create만 필요합니다. 메시지 매핑, 스트리밍, 도구, 미디어, 사용량, 구조화된 출력은 동일한 TanStack 경로를 유지합니다.

npm install @tanstack/ai-anthropic @anthropic-ai/vertex-sdk
import { AnthropicVertex } from "@anthropic-ai/vertex-sdk";
import { createAnthropicChatWithClient } from "@tanstack/ai-anthropic";

const client = new AnthropicVertex({
projectId: "my-project",
region: "europe-west1",
});

const adapter = createAnthropicChatWithClient("claude-sonnet-5", client);

주입하는 클라이언트는 Anthropic Beta Messages 프로토콜을 구현해야 합니다. 엔드포인트별 모델 및 기능 지원은 호출자가 처리해야 합니다.

예제: 채팅 완성​

import { chat, toServerSentEventsResponse } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";

export async function POST(request: Request) {
const { messages } = await request.json();

const stream = chat({
adapter: anthropicText("claude-sonnet-4-6"),
messages,
});

return toServerSentEventsResponse(stream);
}

예제: 도구 사용​

import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";
import { z } from "zod";

const searchDatabaseDef = toolDefinition({
name: "search_database",
description: "Search the database",
inputSchema: z.object({
query: z.string(),
}),
});

const searchDatabase = searchDatabaseDef.server(async ({ query }) => {
// Search database
return { results: [] };
});

export async function POST(request: Request) {
const { messages } = await request.json();

const stream = chat({
adapter: anthropicText("claude-sonnet-4-6"),
messages,
tools: [searchDatabase],
});

return toServerSentEventsResponse(stream);
}

모델 옵션​

Anthropic은 다양한 공급자별 옵션을 지원합니다. 샘플링 매개변수인 temperature, top_p, max_tokens도 chat()의 최상위 prop이 아니라 여기에 지정합니다.

import { chat } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";

const stream = chat({
adapter: anthropicText("claude-sonnet-4-6"),
messages: [{ role: "user", content: "Hello!" }],
modelOptions: {
max_tokens: 4096,
temperature: 0.7,
top_p: 0.9,
top_k: 40,
stop_sequences: ["END"],
},
});

이전에 chat()의 최상위에 temperature / topP / maxTokens를 전달했다면 샘플링 옵션을 modelOptions로 이동을 참고합니다.

max_tokens 기본값​

Anthropic의 Messages API는 모든 요청에 max_tokens를 _필수로 요구_하므로 어댑터는 항상 값을 전송합니다. modelOptions.max_tokens를 설정하지 않으면 선택한 모델의 전체 출력 한도(모델 메타데이터의 max_output_tokens — 예: Sonnet은 64K, Opus는 128K)로 기본 설정되며, 인식하지 못한 모델에는 안전한 상수값을 사용합니다. max_tokens는 예약량이 아니라 상한이며 실제 생성된 토큰을 기준으로 과금되므로 이 기본값으로 추가 비용이 발생하지 않습니다. 또한 낮은 기본값으로 인해 응답 중간에 조용히 잘리는 현상(stop_reason: "max_tokens")을 방지합니다. 모델 한도보다 낮게 출력을 _제한_하려는 경우에만 max_tokens를 명시적으로 설정합니다. 기본 상한을 사용하는 동안 응답이 잘리면 어댑터가 경고를 기록합니다(디버그 로깅을 활성화하면 표시됨).

예외가 하나 있습니다. 비스트리밍 최종화 경로를 사용하는 모델에서 구조화된 출력(chat({ outputSchema }))을 사용하면 이 기본값이 약 21K 토큰으로 제한됩니다. Anthropic SDK는 max_tokens가 10분 타임아웃을 초과할 수 있는 비스트리밍 요청을 거부하므로 이 경우 전체 한도를 사용할 수 없습니다. 스트리밍 채팅에는 영향이 없습니다. 구조화된 출력의 한도를 모델의 실제 최대값에 가깝게 높이려면 응답을 스트리밍합니다.

사고(확장 사고)​

토큰 예산으로 확장 사고를 활성화합니다. 그러면 Claude가 추론 과정을 표시하며, 이 과정은 thinking 청크로 스트리밍됩니다.

modelOptions: {
thinking: {
type: "enabled",
budget_tokens: 2048, // Maximum tokens for thinking
},
}

참고: budget_tokens는 modelOptions.max_tokens보다 작아야 합니다. 사고 예산과 표시할 응답을 함께 담을 수 있도록 max_tokens를 충분히 높게 설정하지 않으면 요청이 거부됩니다.

적응형 사고(Claude 4.6 이상, Sonnet 5, Fable 5)​

최신 Claude 모델은 적응형 사고를 사용합니다. 모델이 언제 얼마나 사고할지 결정하며, 깊이는 토큰 예산 대신 output_config.effort로 조정합니다.

import { chat } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";

const stream = chat({
adapter: anthropicText("claude-sonnet-5"),
messages: [{ role: "user", content: "Plan a database migration." }],
modelOptions: {
thinking: { type: "adaptive", display: "summarized" },
output_config: { effort: "xhigh" },
max_tokens: 64_000,
},
});

모델별 규칙(어댑터의 타입으로 적용됨):

  • claude-sonnet-5, claude-opus-4-8, claude-opus-4-7 — 명시적으로 { type: "disabled" }를 지정해 해제할 수 있는 적응형 사고를 사용합니다. 수동 { type: "enabled", budget_tokens } 형태는 400 오류로 거부되며, 샘플링 매개변수(temperature, top_p, top_k)는 허용되지 않습니다(Sonnet 5에서는 API가 기본값이 아닌 값을 거부하고, Opus 4.7/4.8에서는 매개변수가 완전히 제거됨).
  • claude-fable-5 — 사고가 항상 활성화됩니다. 명시적으로 허용되는 구성은 { type: "adaptive" }뿐이며(disabled와 budget_tokens는 모두 400 오류 반환), 샘플링 매개변수는 거부됩니다.
  • claude-opus-4-6 / claude-sonnet-4-6 — 더 이상 권장되지 않는 { type: "enabled", budget_tokens } 형태와 함께 { type: "adaptive" }를 허용하며, 샘플링 매개변수도 계속 허용합니다.
  • display — Opus 4.7 이상 및 5세대 모델에서 기본값은 "omitted"입니다. 추론 텍스트를 스트리밍하려면 "summarized"로 설정합니다.
  • effort — "low" | "medium" | "high" | "xhigh" | "max"를 허용합니다. "xhigh"는 Claude Opus 4.7 이상, Claude Sonnet 5, Claude Fable 5에서 사용할 수 있습니다.

프롬프트 캐싱​

성능을 높이고 비용을 줄이려면 프롬프트를 캐시합니다.

import { chat } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";

const stream = chat({
adapter: anthropicText("claude-sonnet-4-6"),
messages: [
{
role: "user",
content: [
{
type: "text",
content: "What is the capital of France?",
metadata: {
cache_control: {
type: "ephemeral",
},
},
},
],
},
],
});

요약​

Anthropic은 텍스트 요약을 지원합니다.

import { summarize } from "@tanstack/ai";
import { anthropicSummarize } from "@tanstack/ai-anthropic";

const result = await summarize({
adapter: anthropicSummarize("claude-sonnet-4-6"),
text: "Your long text to summarize...",
maxLength: 100,
style: "concise", // "concise" | "bullet-points" | "paragraph"
});

console.log(result.summary);

환경 변수​

환경 변수에 API 키를 설정합니다.

ANTHROPIC_API_KEY=sk-ant-...

API 레퍼런스​

모든 팩토리 쌍은 동일한 형태를 따릅니다. 짧은 팩토리(anthropicText, anthropicSummarize)는 환경에서 ANTHROPIC_API_KEY를 읽고, createAnthropicChat / createAnthropicSummarize는 API 키를 명시적으로 받습니다. 두 팩토리 모두 첫 번째 인수로 model을 받습니다. Vertex의 Claude에는 @tanstack/ai-anthropic/vertex의 anthropicVertexText를 사용합니다. 그 밖의 사용자 지정 전송에는 Anthropic 호환 Messages 클라이언트를 받는 createAnthropicChatWithClient를 사용합니다.

anthropicText(model, config?) / createAnthropicChat(model, apiKey, config?)​

Anthropic 채팅 어댑터를 생성합니다.

매개변수:

  • model - Claude 모델 id(예: "claude-sonnet-5", "claude-fable-5", "claude-opus-4-8")
  • config?.baseURL - 사용자 지정 기본 URL(선택 사항)

anthropicVertexText(model, config?)​

Vertex에서 Anthropic 채팅 어댑터를 생성합니다. 다음에서 가져옵니다. @tanstack/ai-anthropic/vertex.

Parameters:

  • model - Claude 모델 ID
  • config.project - GCP 프로젝트 ID (ADC 가 해결할 수 있으면 선택 사항)
  • config.location - Vertex 지역 (또는 GOOGLE_CLOUD_LOCATION 설정)

createAnthropicChatWithClient(model, client)​

주입한 클라이언트를 사용해 Anthropic 채팅 어댑터를 생성합니다.

Parameters:

  • model Claude 모델 ID
  • client 클라이언트는 beta.messages.create을 노출합니다

anthropicSummarize(model, config?) / createAnthropicSummarize(model, apiKey, config?)​

Anthropic 요약 어댑터를 생성합니다.

제한 사항​

  • 이미지 생성: Anthropic은 이미지 생성을 지원하지 않습니다. 이미지 생성에는 OpenAI 또는 Gemini를 사용합니다.

다음 단계​

공급자 도구​

Anthropic은 사용자가 정의한 함수 호출 외에도 여러 네이티브 도구를 제공합니다. 이를 @tanstack/ai-anthropic/tools에서 가져와 chat({ tools: [...] }).

전체 개념, 비교 표, 타입 제한 세부 정보는 공급자 도구를 참고합니다.

webSearchTool​

Claude가 인라인 인용과 함께 Anthropic의 네이티브 웹 검색을 실행하도록 합니다. allowed_domains 또는 blocked_domains(상호 배타적)로 검색 범위를 지정하고, max_uses로 턴당 비용 상한을 설정합니다.

import { chat } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";
import { webSearchTool } from "@tanstack/ai-anthropic/tools";

const stream = chat({
adapter: anthropicText("claude-opus-4-7"),
messages: [{ role: "user", content: "What's new in AI this week?" }],
tools: [
webSearchTool({
name: "web_search",
type: "web_search_20250305",
max_uses: 2,
}),
],
});

지원 모델: 등록된 모든 Claude 모델입니다. 공급자 도구를 참고합니다.

webFetchTool​

Claude가 URL의 콘텐츠를 직접 가져오도록 합니다. 검색을 실행하는 대신 모델이 특정 페이지를 읽게 할 때 유용합니다. 필수 인수는 없으며, 기본값을 재정의하려면 선택적 구성 객체를 전달합니다.

import { chat } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";
import { webFetchTool } from "@tanstack/ai-anthropic/tools";

const stream = chat({
adapter: anthropicText("claude-sonnet-4-6"),
messages: [{ role: "user", content: "Summarise https://example.com" }],
tools: [webFetchTool()],
});

지원 모델: Claude Sonnet 4.x 이상입니다. 공급자 도구를 참고합니다.

codeExecutionTool​

Claude에 샌드박스 처리된 코드 실행 환경을 제공하므로 Python 스니펫을 실행하고 데이터를 분석해 결과를 인라인으로 반환할 수 있습니다. 원하는 API 개정판에 맞는 버전 문자열을 선택합니다.

import { chat } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";
import { codeExecutionTool } from "@tanstack/ai-anthropic/tools";

const stream = chat({
adapter: anthropicText("claude-sonnet-4-6"),
messages: [{ role: "user", content: "Plot a histogram of [1,2,2,3,3,3]" }],
tools: [
codeExecutionTool({ name: "code_execution", type: "code_execution_20250825" }),
],
});

지원 모델: Claude Sonnet 4.x 이상입니다. 공급자 도구를 참고합니다.

호스팅된 스킬 첨부​

공급자가 관리하는 스킬 번들을 샌드박스에 로드하려면 두 번째 인수로 skills 배열을 전달합니다. 어댑터가 이를 API의 container.skills param으로 자동 승격하고 필요한 beta 헤더를 추가합니다.

import { chat, toServerSentEventsResponse } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";
import { codeExecutionTool } from "@tanstack/ai-anthropic/tools";

export async function POST(request: Request) {
const { messages } = await request.json();

const stream = chat({
adapter: anthropicText("claude-sonnet-4-5"),
messages,
tools: [
codeExecutionTool(
{ type: "code_execution_20250825", name: "code_execution" },
{
skills: [{ type: "anthropic", skill_id: "pptx", version: "latest" }],
},
),
],
});

return toServerSentEventsResponse(stream);
}

스킬 형태, 제약 조건, 범위 및 OpenAI 동등 기능에 대한 전체 레퍼런스는 공급자 스킬을 참고합니다.

computerUseTool​

Claude가 가상 데스크톱(스크린샷)을 관찰하고 키보드 및 마우스 이벤트로 상호작용하도록 합니다. Claude가 정확한 좌표를 계산할 수 있도록 화면 해상도를 제공합니다.

import { chat } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";
import { computerUseTool } from "@tanstack/ai-anthropic/tools";

const stream = chat({
adapter: anthropicText("claude-sonnet-4-6"),
messages: [{ role: "user", content: "Open the browser and go to example.com" }],
tools: [
computerUseTool({
type: "computer_20250124",
name: "computer",
display_width_px: 1024,
display_height_px: 768,
}),
],
});

지원 모델: Claude Sonnet 3.5 이상입니다. 공급자 도구를 참고합니다.

bashTool​

Claude에 영속적인 bash 셸 세션을 제공하므로 임의의 명령을 실행하고 패키지를 설치하거나 호스트의 파일을 조작할 수 있습니다. API 개정판에 맞는 type 문자열을 선택합니다.

import { chat } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";
import { bashTool } from "@tanstack/ai-anthropic/tools";

const stream = chat({
adapter: anthropicText("claude-sonnet-4-6"),
messages: [{ role: "user", content: "List all TypeScript files in src/" }],
tools: [bashTool({ name: "bash", type: "bash_20250124" })],
});

지원 모델: Claude Sonnet 3.5 이상입니다. 공급자 도구를 참고합니다.

textEditorTool​

Claude에 str_replace, create, view, undo_edit 명령으로 파일을 보고 수정할 수 있는 구조화된 텍스트 편집기 인터페이스를 제공합니다. 대상 API 개정판에 맞는 type 문자열을 선택합니다.

import { chat } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";
import { textEditorTool } from "@tanstack/ai-anthropic/tools";

const stream = chat({
adapter: anthropicText("claude-sonnet-4-6"),
messages: [{ role: "user", content: "Fix the bug in src/index.ts" }],
tools: [
textEditorTool({ type: "text_editor_20250124", name: "str_replace_editor" }),
],
});

지원 모델: Claude Sonnet 3.5 이상입니다. 공급자 도구를 참고합니다.

memoryTool​

Anthropic의 관리형 메모리 서비스를 사용해 Claude가 대화 턴 사이에 정보를 저장하고 검색하도록 합니다. 기본 구성을 사용하려면 인수 없이 호출합니다.

import { chat } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";
import { memoryTool } from "@tanstack/ai-anthropic/tools";

const stream = chat({
adapter: anthropicText("claude-sonnet-4-6"),
messages: [{ role: "user", content: "Remember that I prefer metric units" }],
tools: [memoryTool()],
});

지원 모델: Claude Sonnet 4.x 이상입니다. 공급자 도구를 참고합니다.

customTool​

toolDefinition()을 거치지 않고 인라인 JSON Schema 입력 정의를 사용하는 도구를 생성합니다. 스키마 형태를 세밀하게 제어하거나 cache_control을 추가해야 할 때 유용합니다. 브랜드가 있는 공급자 도구와 달리 customTool은 일반 Tool을 반환하며 모든 채팅 모델에서 허용됩니다.

import { chat } from "@tanstack/ai";
import { anthropicText } from "@tanstack/ai-anthropic";
import { customTool } from "@tanstack/ai-anthropic/tools";
import { z } from "zod";

const stream = chat({
adapter: anthropicText("claude-sonnet-4-6"),
messages: [{ role: "user", content: "Look up user 42" }],
tools: [
customTool(
"lookup_user",
"Look up a user by ID and return their profile",
z.object({ userId: z.number() }),
),
],
});

지원 모델: 현재 제공되는 모든 Claude 모델입니다. 공급자 도구를 참고합니다.