원클릭으로
claude-api
Claude AI assistant API for text generation, analysis, conversation, streaming, tool use, vision, and batch processing
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
메뉴
Claude AI assistant API for text generation, analysis, conversation, streaming, tool use, vision, and batch processing
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
SOC 직업 분류 기준
SDK V2 Session API 기반 에이전트 오케스트레이션 패턴. layer2 코드 구현 시 참조.
코드 품질 기준, Result 패턴, 에러 처리, 리뷰 체크리스트. 모든 코드 작성 시 참조.
7개 에이전트 역할, Phase FSM, Coder×N Git branch, documenter 이벤트 트리거. layer2 구현 시 참조.
LanceDB 벡터 DB, 4-Provider Tier 임베딩, 코드 인덱싱. rag 모듈 구현 시 참조.
Fail-Fast 원칙, 계단식 통합 검증, 테스트 수량. 테스트 관련 코드 구현 시 참조.
| name | claude-api |
| description | Claude AI assistant API for text generation, analysis, conversation, streaming, tool use, vision, and batch processing |
| metadata | {"languages":"javascript","versions":"0.78.0","updated-on":"2026-03-05","source":"maintainer","tags":"anthropic,sdk,llm,ai,claude"} |
You are an Anthropic API coding expert. Help me with writing code using the Anthropic API calling the official libraries and SDKs.
You can find the official SDK documentation and code samples here: https://docs.anthropic.com/claude/reference/
Always use the Anthropic TypeScript SDK to call the Claude models, which is the standard library for all Anthropic API interactions. Do not use legacy libraries or unofficial SDKs.
@anthropic-ai/sdkInstallation:
npm install @anthropic-ai/sdkAPIs and Usage:
import Anthropic from '@anthropic-ai/sdk'const client = new Anthropic({})await client.messages.create(...)await client.messages.stream(...)AnthropicClient or AnthropicAPIclient.generate or client.completionsThe @anthropic-ai/sdk library requires creating an Anthropic instance for all API calls.
const client = new Anthropic({}) to create an instance.ANTHROPIC_API_KEY environment variable, which will be picked up automatically.import Anthropic from '@anthropic-ai/sdk';
// Uses the ANTHROPIC_API_KEY environment variable if apiKey not specified
const client = new Anthropic({});
// Or pass the API key directly
// const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
By default, use the following models as of March 2026:
claude-sonnet-4-6-20250827claude-opus-4-6-20250826claude-haiku-4-5-20251001Previous generation models (still supported):
claude-sonnet-4-20250514, claude-opus-4-20250514claude-3-5-haiku-20241022Do not use deprecated models: claude-3-7-sonnet, claude-3-5-sonnet, claude-3-opus
Here's how to generate a response from a text prompt.
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({}); // Assumes ANTHROPIC_API_KEY is set
async function run() {
const message = await client.messages.create({
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello, Claude' }],
model: 'claude-sonnet-4-20250514',
});
console.log(message.content);
}
run();
Multimodal inputs are supported by passing image data in the messages array. You can include images, documents, and other file types using base64 encoding or file uploads.
For file uploads, use the client.beta.files.upload method:
import fs from 'fs';
import Anthropic, { toFile } from '@anthropic-ai/sdk';
const client = new Anthropic();
// File upload example
await client.beta.files.upload({
file: await toFile(fs.createReadStream('/path/to/file'), undefined, { type: 'application/json' }),
betas: ['files-api-2025-04-14'],
});
We provide comprehensive support for streaming responses using Server Sent Events (SSE).
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
const stream = await client.messages.create({
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello, Claude' }],
model: 'claude-sonnet-4-20250514',
stream: true,
});
for await (const messageStreamEvent of stream) {
console.log(messageStreamEvent.type);
}
The SDK provides powerful streaming helpers for convenience:
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
async function main() {
const stream = client.messages
.stream({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [
{
role: 'user',
content: 'Say hello there!',
},
],
})
.on('text', (text) => {
console.log(text);
});
const message = await stream.finalMessage();
console.log(message);
}
main();
You can cancel streams by calling stream.controller.abort() or breaking from loops.
The SDK supports tool use (function calling) for extending Claude's capabilities.
Define custom functions that Claude can call:
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
async function run() {
const response = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: "What's the weather like in San Francisco?" }],
tools: [
{
name: 'get_weather',
description: 'Get the current weather in a given location',
input_schema: {
type: 'object',
properties: {
location: { description: 'The city and state, e.g. San Francisco, CA', type: 'string' },
unit: { description: 'Unit for the output - one of (celsius, fahrenheit)', type: 'string' },
},
required: ['location'],
},
type: 'custom',
},
],
tool_choice: { type: 'auto' },
});
// Handle tool use in the response
if (response.content.some((block) => block.type === 'tool_use')) {
// Process tool calls and provide results back to Claude
console.log('Claude wants to use a tool!');
}
}
run();
The beta API provides specialized built-in tools.
const response = await client.beta.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: 'List the files in the current directory' }],
tools: [{ type: 'bash_20250124', name: 'bash' }],
});
const response = await client.beta.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Take a screenshot' }],
tools: [
{
type: 'computer_20250124',
name: 'computer',
display_width_px: 1920,
display_height_px: 1080,
},
],
});
const response = await client.beta.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Create a Python script' }],
tools: [{ type: 'text_editor_20250124', name: 'str_replace_editor' }],
});
Control how Claude uses tools:
{ type: 'auto' } - Claude decides when to use tools{ type: 'any' } - Claude must use a tool{ type: 'tool', name: 'specific_tool' } - Force a specific tool{ disable_parallel_tool_use: true } - Disable parallel tool executionThe SDK supports the Message Batches API for processing multiple requests efficiently.
await client.messages.batches.create({
requests: [
{
custom_id: 'my-first-request',
params: {
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello, world' }],
},
},
{
custom_id: 'my-second-request',
params: {
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hi again, friend' }],
},
},
],
});
const results = await client.messages.batches.results(batch_id);
for await (const entry of results) {
if (entry.result.type === 'succeeded') {
console.log(entry.result.message.content);
}
}
Guide Claude's behavior with system instructions:
const response = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello' }],
system: [{ text: 'You are a helpful assistant that responds in a pirate voice.', type: 'text' }],
});
Configure Claude's extended thinking (reasoning process):
const response = await client.messages.create({
model: 'claude-sonnet-4-6-20250827',
max_tokens: 16000,
messages: [{ role: 'user', content: 'Solve this complex problem...' }],
thinking: { type: 'enabled', budget_tokens: 10000 },
});
Control randomness and output:
const response = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Write a creative story' }],
temperature: 0.7,
top_k: 5,
top_p: 0.9,
});
Count tokens before making requests:
const tokenCount = await client.messages.countTokens({
messages: [{ role: 'user', content: 'Hello, Claude' }],
model: 'claude-sonnet-4-20250514',
});
console.log(tokenCount); // { input_tokens: 25, output_tokens: 13 }
Handle paginated responses automatically:
async function fetchAllMessageBatches(params) {
const allMessageBatches = [];
// Automatically fetches more pages as needed.
for await (const messageBatch of client.messages.batches.list({ limit: 20 })) {
allMessageBatches.push(messageBatch);
}
return allMessageBatches;
}
The SDK provides comprehensive error handling with specific error types:
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
try {
const message = await client.messages.create({
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello, Claude' }],
model: 'claude-sonnet-4-20250514',
});
} catch (err) {
if (err instanceof Anthropic.APIError) {
console.log(err.status); // 400
console.log(err.name); // BadRequestError
console.log(err.headers); // {server: 'nginx', ...}
console.log(err.requestID); // request id string
} else {
throw err;
}
}
| Status Code | Error Type |
|---|---|
| 400 | BadRequestError |
| 401 | AuthenticationError |
| 403 | PermissionDeniedError |
| 404 | NotFoundError |
| 422 | UnprocessableEntityError |
| 429 | RateLimitError |
| >=500 | InternalServerError |
| N/A | APIConnectionError |
All errors extend from AnthropicError which extends the standard Error class.
All responses include a _request_id property for debugging:
const message = await client.messages.create({
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello, Claude' }],
model: 'claude-sonnet-4-20250514',
});
console.log(message._request_id);
Configure automatic retry behavior:
// Configure default retries for all requests
const client = new Anthropic({
maxRetries: 3, // default is 2
});
// Or configure per-request
await client.messages.create(
{ max_tokens: 1024, messages: [{ role: 'user', content: 'Hello, Claude' }], model: 'claude-sonnet-4-20250514' },
{ maxRetries: 5 },
);
Set custom timeout values:
// Configure default timeout for all requests
const client = new Anthropic({
timeout: 20 * 1000, // 20 seconds (default is 10 minutes)
});
// Override per-request
await client.messages.create(
{ max_tokens: 1024, messages: [{ role: 'user', content: 'Hello, Claude' }], model: 'claude-sonnet-4-20250514' },
{ timeout: 5 * 1000 },
);
Enable debug logging:
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
logLevel: 'debug', // Show all log messages
});
// Or use environment variable
// ANTHROPIC_LOG=debug
Customize the underlying fetch behavior:
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
fetchOptions: {
// Custom RequestInit options
},
});