Claude Messages API (Anthropic SDK)
Send messages to Claude using the official Anthropic SDK with system prompt and user turn.
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.
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
RAG Pipeline (Retrieve + Augment + Generate)
Minimal RAG implementation: embed a query, retrieve top-k chunks, inject into prompt.
LangChain Prompt Chain (Python)
Build a simple LLMChain with a prompt template and ChatOpenAI in LangChain.
DALLΒ·E 3 Image Generation
Generate images from a text prompt using the OpenAI DALLΒ·E 3 API and return a URL.