Claude API Fundamentals
Connect to the Anthropic Claude API, configure system prompts, select model tiers, and inspect response stop reasons.
TL;DR
- Set
ANTHROPIC_API_KEYand let the SDK read it automatically. - Call
client.messages.createwith a model,max_tokens, and messages. - Check
stop_reasonbefore trusting text: it reveals truncated answers.
Client Configuration
Anthropic Client SetupInstantiate SDK client reading credentials from environment variables.
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
// Reads ANTHROPIC_API_KEY automaticallyModel Tier ConstantsDeclare type-safe constants for verified production model IDs.
const OPUS = 'claude-opus-5-5';
const SONNET = 'claude-sonnet-5-5';
const HAIKU = 'claude-haiku-4-5';
// IDs are complete as-is: no date suffixRetries And TimeoutsTune automatic retries and the request timeout (milliseconds) once per client.
const client = new Anthropic({
maxRetries: 3, // default is 2
timeout: 60_000, // ms
});The Messages API
Top-Level System PromptPass system instructions as dedicated string parameter outside messages.
const res = await client.messages.create({
model: SONNET,
max_tokens: 500,
system: 'Respond strictly in bullet points.',
messages: [{ role: 'user', content: 'Explain DNS' }],
});Message Content BlocksExtract text from response content block array safely.
const block = res.content[0];
if (block.type === 'text') {
console.log(block.text);
}Multi-Turn DialoguePreserve prior assistant turns to maintain contextual continuity.
const history = [
{ role: 'user', content: 'Hi' },
{ role: 'assistant', content: 'Hello!' },
{ role: 'user', content: 'Summarize chat' },
];Stop Reasons And Flow Control
End Turn DetectionConfirm message completed naturally without hitting token boundaries.
if (res.stop_reason === 'end_turn') {
// Normal completion finished
}Truncation HandlingDetect when output reached max tokens and trigger continuation.
if (res.stop_reason === 'max_tokens') {
console.warn('Response truncated at token limit');
}Custom Stop SequencesHalt generation immediately when encountering a sentinel string.
const res = await client.messages.create({
model: SONNET,
max_tokens: 200,
stop_sequences: ['===END==='],
messages: [{ role: 'user', content: 'Generate' }],
});Token Usage And Latency
Usage BreakdownInspect input and output token counts for cost accounting.
const inTok = res.usage.input_tokens;
const outTok = res.usage.output_tokens;
console.log(`Tokens: ${inTok} in / ${outTok} out`);Cache Read MetricsMonitor prompt cache hits and creation write tokens.
const u = res.usage;
const read = u.cache_read_input_tokens ?? 0;
const write = u.cache_creation_input_tokens ?? 0;
// Cache reads cost 90% lessModel Switching LogicRoute requests dynamically based on prompt complexity.
const model = prompt.length > 2000 ? SONNET : HAIKU;
const out = await client.messages.create(
{ model, ...opts }
);Tips
- Use the exact model ID string, such as
claude-sonnet-5-5, and keep it in one constant. The IDs are complete as-is, so never add a date suffix. - Supply system instructions via the top-level
systemproperty rather than nesting them inside the message role array.
Warnings
- Always define an explicit
max_tokensparameter because Anthropic requests fail validation if this property is omitted. - Check for
max_tokensstop reasons to identify when model responses have been cut off mid-sentence.
In Practice
Executes an Anthropic messages API query with pinned model version and stop reason verification.
- Instantiate Anthropic client using environment authentication credentials.
- Dispatch messages request with pinned model version and system prompt.
- Check stop_reason to verify output did not encounter truncation.
- Extract generated text block and print reply.
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
async function runClaude() {
const message = await client.messages.create({
model: 'claude-sonnet-5-5',
max_tokens: 250,
system: 'You are an expert compiler engineer.',
messages: [
{ role: 'user', content: 'Explain SSA' }
],
});
const block = message.content[0];
if (block?.type === 'text') console.log(block.text);
}
await runClaude();FAQ
Define the ANTHROPIC_API_KEY environment variable on your server. The Anthropic client library reads this key automatically upon initialization without requiring explicit constructor arguments.
Start with claude-opus-5-5, the most capable everyday model. Drop to claude-sonnet-5-5 for faster, cheaper everyday work, and claude-haiku-4-5 for high-volume tagging and routing. Check the model docs for current IDs, since new models ship often.
The stop_reason indicates why Claude finished generating tokens. Values include end_turn for normal completion, max_tokens for truncated responses, and stop_sequence when a custom trigger was encountered.