← Back to all spotlights

Anthropic TypeScript SDK: Claude 3.5 Tool Calling & Streaming

Master the official Anthropic TypeScript SDK for building type-safe Claude 3.5 Sonnet applications with tool calling and streaming.

P24
By Pickwise24 Editorial Team
Verified Open-Source Review

Introduction: Taming the Claude 3.5 API with Pure TypeScript

If you have ever spent a rainy Tuesday afternoon debugging an untyped JSON payload returned from a large language model, you will know the unique despair of the TypeError: Cannot read properties of undefined (reading 'content'). It is the digital equivalent of stubbing your toe on a Lego brick in the dark.

Enter the anthropic/anthropic-sdk-typescript repository—the official, heavily typed lifeline for developers wiring Claude 3.5 Sonnet and its sibling models directly into Node.js and browser runtimes.

As AI engineering shifts away from messy prompt-string concatenation toward rigorous, deterministic agent architectures, having robust types isn't just a luxury; it is the difference between a production application that handles edge cases gracefully and one that hallucinates runtime crashes at three in the morning.


+------------------------------------------------------------+
|                  Your TypeScript Application               |
+------------------------------------------------------------+
                              |
                              v (Fully typed request payload)
+------------------------------------------------------------+
|            anthropic-sdk-typescript Client                 |
+------------------------------------------------------------+
                              |
                              v (HTTPS / Server-Sent Events)
+------------------------------------------------------------+
|               Claude 3.5 Sonnet API Endpoint               |
+------------------------------------------------------------+

What Problem Does It Solve?

Let's be honest: interacting with raw HTTP endpoints for LLMs is tedious boilerplate. You have to manually manage bearer tokens, construct nested content arrays, handle chunked Transfer-Encodings for streaming responses, and parse complex JSON schemas for tool calling without any compile-time safety nets.

The Anthropic TypeScript SDK abstracts this plumbing away. It provides:

  • Compile-time safety: Complete TypeScript definitions for every request parameter, response shape, and tool definition.
  • First-class streaming: Native AsyncIterables that make consuming Server-Sent Events (SSE) as simple as a for await...of loop.
  • Robust tool use (function calling): Seamless declaration of tools, automatic type inference for tool inputs, and structured error propagation.

Architectural Details & Key Design Choices

The repository is structured with clean modularity, mirroring the modern Node ecosystem while maintaining compatibility with Edge runtimes (like Cloudflare Workers and Vercel Edge).

Instead of hiding the underlying transport, Anthropic built the SDK on top of a clean fetch-based client. This means proxy configuration, custom headers, and request retries are handled uniformly without pulling in bloated legacy networking dependencies.

Core Features at a Glance

FeatureDescriptionTypeScript Benefit
Messages APIThe primary interface for multi-turn conversations with Claude.Enforces valid role alternation (user vs assistant).
Tool CallingExposing external functions and APIs to the model.Generates strict JSON schemas from TypeScript definitions.
StreamingReal-time token generation via Server-Sent Events.Typed event streams (content_block_delta, message_stop).
Automatic RetriesBuilt-in exponential backoff for rate limits and 5xx errors.Zero custom retry wrapper code required.

Local Setup & Installation

Getting started takes less time than making a proper cup of tea. First, install the package via your package manager of choice:


# Using npm
npm install @anthropic-ai/sdk

# Using pnpm (because we like symlinks)
pnpm add @anthropic-ai/sdk

# Using bun (for maximum velocity)
bun add @anthropic-ai/sdk

Next, ensure you have your API key set in your environment variables:


export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here"

Practical Code Walkthrough

Let's look at a concrete, production-ready example demonstrating a basic message generation request paired with tool calling and streaming.

1. Basic Client Initialization & Message Request


import Anthropic from '@anthropic-ai/sdk';

// Automatically picks up ANTHROPIC_API_KEY from process.env
const anthropic = new Anthropic();

async function runChat() {
  const response = await anthropic.messages.create({
    model: 'claude-3-5-sonnet-20241022',
    max_tokens: 1024,
    messages: [{ role: 'user', content: 'Explain quantum computing in one sharp paragraph.' }],
  });

  // Fully typed response block access
  const textContent = response.content.find(block => block.type === 'text');
  if (textContent) {
    console.log(textContent.text);
  }
}

runChat();

2. Advanced Streaming with Async Iterators

When building chat interfaces, waiting for the full response to render feels sluggish. Here is how to stream tokens efficiently:


import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic();

async function streamResponse() {
  const stream = await anthropic.messages.stream({
    model: 'claude-3-5-sonnet-20241022',
    max_tokens: 500,
    messages: [{ role: 'user', content: 'Write a haiku about compiling code without tests.' }],
  });

  for await (const chunk of stream) {
    if (chunk.type === 'content_block_delta' && chunk.delta.type === 'text_delta') {
      process.stdout.write(chunk.delta.text);
    }
  }
  console.log('\n');
}

streamResponse();

3. Tool Calling Implementation

Tool calling allows Claude to request data from external systems. The SDK makes defining and handling these tools straightforward:


import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic();

const weatherTool: Anthropic.Tool = {
  name: 'get_current_weather',
  description: 'Get the current weather for a given city.',
  input_schema: {
    type: 'object',
    properties: {
      location: { type: 'string', description: 'The city and country, e.g. London, UK' },
      unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
    },
    required: ['location'],
  },
};

async function runWithTools() {
  const response = await anthropic.messages.create({
    model: 'claude-3-5-sonnet-20241022',
    max_tokens: 1024,
    tools: [weatherTool],
    messages: [{ role: 'user', content: 'What is the weather like in Manchester right now?' }],
  });

  for (const content of response.content) {
    if (content.type === 'tool_use') {
      console.log(`Model requested tool: ${content.name}`);
      console.log(`Arguments:`, content.input);
      
      // Execute your local function here using content.input
    }
  }
}

runWithTools();

Why This Repository Stands Out

Community consensus across GitHub issues, Discord developer channels, and technical deep-dives on YouTube highlights a few standout qualities of this repository:

1. Zero-Guesswork Typing: The type definitions directly mirror the official Anthropic API documentation, meaning your IDE auto-completes properties precisely as they exist on the wire.

2. First-Class Edge Support: Because it avoids legacy Node.js core modules (net, tls, fs), deploying agentic workflows to serverless functions or edge networks requires zero polyfill gymnastics.

3. Active Maintenance: Anthropic updates this client in lockstep with model releases, ensuring new features like extended thinking blocks or advanced prompting parameters are available on day one.

If you are building anything serious with Claude 3.5 Sonnet, wrapping your logic in raw fetch calls is an unnecessary friction point. Clone or install the SDK, leverage the strict types, and spend your time building features rather than debugging JSON payloads.

🛡️ Editorial Standards & Methodology

Every repository featured on Pickwise24 undergoes testing on local workstation hardware before publication. We verify CLI installation steps, review open-source repository licensing, benchmark computational footprint, and evaluate architectural trade-offs to provide genuine, high-utility developer intelligence.