Parameters & Responses
Set max_tokens to cap output, then read content, stop_reason, and usage from the response.
A request is shaped by a few key parameters, and the response comes back as a structured object you read from your code.
Key request parameters
model— which Claude model to use.max_tokens— the maximum length of the reply. Hitting this cap truncates the answer.system— optional persistent instructions.messages— the conversation so far.
Reading the response
content— a list of blocks; text lives in blocks withtype: "text".stop_reason— why Claude stopped:end_turn(finished),max_tokens(ran out of room),tool_use, and others.usage— how many input and output tokens the call used.
Example
const res = await client.messages.create({
model: "claude-opus-4-8",
max_tokens: 1024,
messages: [{ role: "user", content: "Explain flexbox in three sentences." }],
});
// Pull out the pieces you care about
const text = res.content.filter((b) => b.type === "text").map((b) => b.text).join("");
console.log(text);
console.log("stop_reason:", res.stop_reason); // e.g. "end_turn"
console.log("input tokens:", res.usage.input_tokens);
console.log("output tokens:", res.usage.output_tokens);When to use it
- Check stop_reason to detect when Claude stopped because it hit max_tokens rather than finishing naturally.
- Read the usage object after each request to aggregate daily token spend across all users.
- Use max_tokens to cap the output length for a product-description feature that must stay under 100 words.
More examples
Read content and stop_reason
Shows how to read the two most-used fields: the text content and the reason the response ended.
const msg = await client.messages.create({
model: "claude-haiku-4-5",
max_tokens: 64,
messages: [{ role: "user", content: "Explain quantum computing." }],
});
console.log("Text:", msg.content[0].text);
console.log("Stop reason:", msg.stop_reason); // 'end_turn' or 'max_tokens'Track token usage per request
Destructures the usage object to log per-request token counts for cost monitoring.
const msg = await client.messages.create({
model: "claude-sonnet-4-5",
max_tokens: 256,
messages: [{ role: "user", content: "Write a haiku about Node.js." }],
});
const { input_tokens, output_tokens } = msg.usage;
console.log(`Input: ${input_tokens}, Output: ${output_tokens}, Total: ${input_tokens + output_tokens}`);Cap output with max_tokens
Sets a tight max_tokens budget and checks stop_reason to detect when the description was cut short.
// Force a short product description
const msg = await client.messages.create({
model: "claude-haiku-4-5",
max_tokens: 80, // roughly 60 words
system: "Write concise e-commerce product descriptions.",
messages: [{ role: "user", content: "Describe: Wireless noise-cancelling headphones, black." }],
});
if (msg.stop_reason === "max_tokens") {
console.warn("Description was truncated");
}
Discussion