SDK Setup & Messages API
From the course Anthropic Claude API Deep Dive
Getting Started with the Claude API
Anthropic's Claude API offers powerful language models with a focus on safety, long context, and reliable outputs.
Installation & Authentication
npm install @anthropic-ai/sdk
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
The Messages API
Claude uses a messages-based API similar to but distinct from OpenAI:
const message = await client.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 1024,
system: "You are a helpful coding assistant.",
messages: [
{ role: "user", content: "Write a TypeScript function to debounce." }
],
});
console.log(message.content[0].text);
Model Selection
| Model | Strengths | Context | Speed |
|---|---|---|---|
| Claude Opus 4 | Deepest reasoning, complex tasks | 200K | Slower |
| Claude Sonnet 4 | Balanced performance and speed | 200K | Fast |
| Claude Haiku 3.5 | Fastest, most cost-effective | 200K | Fastest |
Key Differences from Other APIs
- System prompt is a separate parameter, not a message role
- max_tokens is required — you must always specify it
- Content blocks — responses are arrays of content blocks, not strings
- Stop reasons —
end_turn,max_tokens,stop_sequence,tool_use
Error Handling Best Practice
Always check the stop_reason before processing content. If stop_reason is "max_tokens", the response was truncated — increase max_tokens or implement a continuation loop. A common pitfall is assuming the first content block is always text; when tool_use is involved, blocks can arrive in any order.
if (message.stop_reason === "max_tokens") {
console.warn("Response truncated — increase max_tokens");
}
const textBlock = message.content.find((b) => b.type === "text");
Choosing the Right Model
Claude Opus 4 is best for tasks where quality is paramount and latency is acceptable — complex legal review, multi-step reasoning, or creative writing. Claude Sonnet 4 is the default for most production workloads: it handles long documents, tool use, and multi-turn conversations at a latency that users tolerate. Claude Haiku 3.5 is ideal for classification, routing, and any workflow where you are making hundreds of small calls per user session. A common architecture caches Haiku responses at the edge and only escalates to Sonnet when the user asks a question that requires deeper reasoning.
Key Takeaways
- •Claude uses a separate system parameter instead of a system message role
- •max_tokens is required for every API call
- •Responses are arrays of content blocks supporting text and tool use
- •Choose between Opus, Sonnet, and Haiku based on task complexity
Progress is kept in this browser only.