typescriptbeginner

Claude Messages API (Anthropic SDK)

Send messages to Claude using the official Anthropic SDK with system prompt and user turn.

typescript
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

export async function askClaude(userMessage: string): Promise<string> {
  const msg = await client.messages.create({
    model: "claude-opus-4-5",
    max_tokens: 1024,
    system: "You are a helpful coding assistant. Be concise.",
    messages: [{ role: "user", content: userMessage }],
  });

  const block = msg.content[0];
  return block.type === "text" ? block.text : "";
}

// Usage
const answer = await askClaude("What is the difference between RAG and fine-tuning?");
console.log(answer);

Sponsored

Build with Claude β€” Anthropic API

Use Cases

  • AI assistant
  • text generation
  • code review bot

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.