+++++
Snippets(6)
tsQuick Start
Minimal setup — import the SDK and send your first message.
import Anthropic from '@anthropic-ai/sdk'
const client = new Anthropic()
const msg = await client.messages.create({
model: 'claude-opus-4-8',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello!' }],
})
console.log(msg.content[0].text)tsMulti-turn Conversation
Accumulate messages across turns to build a stateful conversation.
import { MessageParam } from '@anthropic-ai/sdk/resources'
const history: MessageParam[] = []
history.push({ role: 'user', content: 'My name is David.' })
const r1 = await client.messages.create({
model: 'claude-opus-4-8',
max_tokens: 256,
messages: history,
})
history.push({ role: 'assistant', content: r1.content })
history.push({ role: 'user', content: 'What is my name?' })
const r2 = await client.messages.create({
model: 'claude-opus-4-8',
max_tokens: 256,
messages: history,
})
console.log(r2.content[0].text) // "Your name is David."tsSystem Prompt
Shape Claude's persona and constraints before the conversation starts.
const msg = await client.messages.create({
model: 'claude-opus-4-8',
max_tokens: 1024,
system: `You are a concise coding assistant.
Be direct. Prefer TypeScript. No filler.`,
messages: [{
role: 'user',
content: 'Write a debounce function.',
}],
})
console.log(msg.content[0].text)tsPrompt Caching
Cache a large system prompt to cut latency and cost on repeated calls.
const msg = await client.messages.create({
model: 'claude-opus-4-8',
max_tokens: 1024,
system: [{
type: 'text',
text: systemPrompt, // your large prompt
cache_control: { type: 'ephemeral' },
}],
messages: [{ role: 'user', content: 'Summarize the key points.' }],
})
const { cache_creation_input_tokens, cache_read_input_tokens } = msg.usage
console.log(`Cache write: ${cache_creation_input_tokens ?? 0}`)
console.log(`Cache read: ${cache_read_input_tokens ?? 0}`)tsTool Use
Give Claude a tool it can call — here, a weather lookup.
const msg = await client.messages.create({
model: 'claude-opus-4-8',
max_tokens: 1024,
tools: [{
name: 'get_weather',
description: 'Get weather for a location',
input_schema: {
type: 'object',
properties: {
location: { type: 'string' },
},
required: ['location'],
},
}],
messages: [{
role: 'user',
content: 'What is the weather in Tokyo?',
}],
})tsStreaming
Stream tokens as they arrive instead of waiting for the full reply.
const stream = client.messages.stream({
model: 'claude-opus-4-8',
max_tokens: 1024,
messages: [{
role: 'user',
content: 'Explain closures in one paragraph.',
}],
})
for await (const chunk of stream) {
if (chunk.type === 'content_block_delta') {
process.stdout.write(chunk.delta.text)
}
}
const final = await stream.finalMessage()