4 min read
This tutorial will guide you through using the Anthropic API with Node.js to interact with Claude models programmatically.
Prerequisites
- Node.js 14+
- npm or yarn
- An Anthropic API key (obtain from https://console.anthropic.com/)
Installation
npm install @anthropic-ai/sdk
# or using yarn
yarn add @anthropic-ai/sdk
Basic Usage
1. Setting Up
First, import the Anthropic client and set up your API key:
const Anthropic = require('@anthropic-ai/sdk');
// Or using ES modules:
// import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: 'your-api-key-here', // Replace with your actual API key
});
2. Sending a Basic Message
async function sendMessage() {
try {
const message = await anthropic.messages.create({
model: 'claude-3-opus-20240229',
max_tokens: 1000,
messages: [
{ role: 'user', content: 'What is the capital of France?' }
]
});
console.log(message.content);
} catch (error) {
console.error('Error:', error);
}
}
sendMessage();
3. Having a Multi-turn Conversation
async function haveConversation() {
try {
const conversation = await anthropic.messages.create({
model: 'claude-3-opus-20240229',
max_tokens: 1000,
messages: [
{ role: 'user', content: 'What is machine learning?' },
{ role: 'assistant', content: 'Machine learning is a subset of artificial intelligence...' },
{ role: 'user', content: 'Can you give me an example?' }
]
});
console.log(conversation.content);
} catch (error) {
console.error('Error:', error);
}
}
Advanced Features
1. System Prompts
Using system prompts to set context and behavior:
async function useSystemPrompt() {
try {
const response = await anthropic.messages.create({
model: 'claude-3-opus-20240229',
system: 'You are a helpful math tutor who explains concepts step by step.',
messages: [
{ role: 'user', content: 'Explain how to solve quadratic equations' }
]
});
console.log(response.content);
} catch (error) {
console.error('Error:', error);
}
}
2. Handling Stream Responses
For real-time streaming responses:
async function streamResponse() {
try {
const stream = await anthropic.messages.create({
model: 'claude-3-opus-20240229',
max_tokens: 1000,
messages: [{ role: 'user', content: 'Write a story about a space adventure' }],
stream: true
});
for await (const chunk of stream) {
if (chunk.type === 'content_block_delta') {
process.stdout.write(chunk.delta.text);
}
}
} catch (error) {
console.error('Error:', error);
}
}
3. Error Handling with Express.js
const express = require('express');
const app = express();
app.post('/ask-claude', async (req, res) => {
try {
const response = await anthropic.messages.create({
model: 'claude-3-opus-20240229',
messages: [{ role: 'user', content: req.body.question }]
});
res.json({ answer: response.content });
} catch (error) {
if (error instanceof Anthropic.APIError) {
res.status(500).json({ error: 'API Error', details: error.message });
} else if (error instanceof Anthropic.RateLimitError) {
res.status(429).json({ error: 'Rate limit exceeded' });
} else {
res.status(500).json({ error: 'Unexpected error' });
}
}
});
Best Practices
- Environment Variables Using dotenv for API key management:
// Install dotenv: npm install dotenv
require('dotenv').config();
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
- Rate Limiting and Retries Using axios-retry for automatic retries:
const axiosRetry = require('axios-retry');
const axios = require('axios');
// Configure retry behavior
axiosRetry(axios, {
retries: 3,
retryDelay: axiosRetry.exponentialDelay,
retryCondition: (error) => {
return axiosRetry.isNetworkOrIdempotentRequestError(error) ||
error.response?.status === 429;
}
});
- Async/Await Wrapper Utility function for cleaner error handling:
const asyncHandler = (fn) => (req, res, next) => {
return Promise.resolve(fn(req, res, next)).catch(next);
};
// Usage in Express
app.post('/ask-claude', asyncHandler(async (req, res) => {
const response = await anthropic.messages.create({
model: 'claude-3-opus-20240229',
messages: [{ role: 'user', content: req.body.question }]
});
res.json({ answer: response.content });
}));
Common Use Cases
1. Content Generation API
const express = require('express');
const router = express.Router();
router.post('/generate-blog', async (req, res) => {
try {
const { topic } = req.body;
const response = await anthropic.messages.create({
model: 'claude-3-opus-20240229',
messages: [
{ role: 'user', content: `Write a blog post about ${topic}` }
]
});
res.json({ blogPost: response.content });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
2. Text Analysis Service
class TextAnalysisService {
constructor(anthropicClient) {
this.anthropic = anthropicClient;
}
async analyzeSentiment(text) {
const response = await this.anthropic.messages.create({
model: 'claude-3-opus-20240229',
messages: [
{ role: 'user', content: `Analyze the sentiment of this text: ${text}` }
]
});
return response.content;
}
}
module.exports = TextAnalysisService;
Example Express.js Application
const express = require('express');
const Anthropic = require('@anthropic-ai/sdk');
require('dotenv').config();
const app = express();
app.use(express.json());
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
app.post('/chat', async (req, res) => {
try {
const response = await anthropic.messages.create({
model: 'claude-3-opus-20240229',
messages: req.body.messages
});
res.json(response);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Resources
Remember to always check the official documentation for the most up-to-date information and best practices.
Related Posts
API management solutionsAPI management softwarebest API management toolsBlog
5 min read
APIs (Application Programming Interfaces) are the backbone of modern digital applications. They allow different software systems to communicate, exchange data, and collaborate seamlessly. As businesse...