Claude API JavaScript Tutorial: Sonnet & Opus Integration
Introduction
Claude 3.5 Sonnet excels at long-form content, nuanced analysis, and complex reasoning. Through AI API Hub's OpenAI-compatible endpoint, you can use Claude with the familiar OpenAI JavaScript SDK. This guide covers everything from basic setup to advanced streaming and Next.js integration.
Why Claude?
| Feature | Claude 3.5 Sonnet | GPT-4o | |---|---|---| | Context Window | 200K | 128K | | Input Price | $3.00/1M | $2.50/1M | | Output Price | $15.00/1M | $10.00/1M | | Nuanced Writing | Excellent | Very Good | | Code Generation | Very Good | Excellent | | Safety Alignment | Industry-leading | Standard |
Quick Setup
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "your-api-key",
baseURL: "https://api.apiyihe.org/v1",
});
Basic Claude 3.5 Sonnet Call
const response = await client.chat.completions.create({
model: "claude-3.5-sonnet",
messages: [
{
role: "system",
content: "You are an expert technical writer. Write clear, concise documentation.",
},
{
role: "user",
content: "Write API documentation for a REST endpoint that handles file uploads.",
},
],
max_tokens: 2000,
temperature: 0.7,
});
console.log(response.choices[0].message.content);
Streaming with Claude
const stream = await client.chat.completions.create({
model: "claude-3.5-sonnet",
messages: [{ role: "user", content: "Write a 500-word article about AI safety" }],
stream: true,
max_tokens: 3000,
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || "";
process.stdout.write(content);
}
200K Context: Processing Long Documents
import fs from "node:fs";
const longDocument = fs.readFileSync("research-paper.txt", "utf-8");
const response = await client.chat.completions.create({
model: "claude-3.5-sonnet",
messages: [
{
role: "system",
content: "You are a research assistant. Summarize key findings.",
},
{
role: "user",
content: `Please analyze this document:\n\n${longDocument}\n\nProvide: 1) Key findings, 2) Methodology critique, 3) Future research directions.`,
},
],
max_tokens: 4000,
});
console.log(response.choices[0].message.content);
Next.js Integration
// app/api/chat/route.ts
import { NextResponse } from "next/server";
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.AI_API_HUB_KEY,
baseURL: "https://api.apiyihe.org/v1",
});
export async function POST(req: Request) {
const { messages } = await req.json();
const stream = await client.chat.completions.create({
model: "claude-3.5-sonnet",
messages,
stream: true,
});
const encoder = new TextEncoder();
const readable = new ReadableStream({
async start(controller) {
for await (const chunk of stream) {
const text = chunk.choices[0]?.delta?.content || "";
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ text })}\n\n`));
}
controller.close();
},
});
return new Response(readable, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
});
}
Claude vs GPT-4o for Writing
async function compareModels(prompt) {
const models = ["claude-3.5-sonnet", "gpt-4o"];
for (const model of models) {
const r = await client.chat.completions.create({
model,
messages: [{ role: "user", content: prompt }],
});
console.log(`\n=== ${model} ===\n${r.choices[0].message.content}`);
}
}
await compareModels("Write a persuasive essay on renewable energy");
Common Issues
| Issue | Fix |
|---|---|
| Token limit exceeded | Reduce max_tokens or split the prompt |
| Claude refuses unsafe content | Claude is safety-aligned; rephrase the prompt |
| Response too verbose | Lower temperature (0.3-0.5) for concise output |
| High latency | Reduce context size; use claude-3.5-haiku for faster responses |
Pricing Comparison
| Model | Input/1M | Output/1M | Best For | |---|---|---|---| | Claude 3.5 Sonnet | $3.00 | $15.00 | Analysis, writing | | Claude 3.5 Haiku | $0.25 | $1.25 | Fast chat, lightweight | | GPT-4o | $2.50 | $10.00 | Coding, general |
FAQ
Q: Can I use Claude with the Python SDK?
A: Yes. The OpenAI-compatible API works identically with Python's openai library.
Q: Does Claude support function calling? A: Yes, Claude 3.5 Sonnet supports tool use/function calling through the OpenAI-compatible format.
Q: What's the maximum output length? A: Claude can generate up to 8192 tokens in a single response.
Q: Is Claude better than GPT-4o for long documents? A: Yes. Claude's 200K context window handles significantly longer documents than GPT-4o's 128K.