Anthropic TypeScript SDK

repository·main·Indexed 24 days ago

https://github.com/anthropics/anthropic-sdk-typescript

The official TypeScript library for the Anthropic API, providing a programmatic interface to access Claude from server-side TypeScript or JavaScript applications. It includes specialized packages for various cloud platforms: @anthropic-ai/bedrock-sdk for AWS Bedrock, @anthropic-ai/foundry-sdk for Microsoft Azure AI Foundry, @anthropic-ai/google-cloud-sdk for the Claude Platform on Google Cloud, and @anthropic-ai/vertex-sdk for Google Vertex AI.

Tokens
31.3K
Snippets
55
Records
172
Agent score
80%

What's inside @anthropic-ai/sdk

  1. Iterate through messages with `BetaToolRunner`

    main

    A BetaToolRunner is an async iterator. You can use for await...of to process each message (including intermediate tool calls and assistant responses) as it arrives. This is useful for monitoring the conversation flow or updating a UI in real-time.

    const runner = anthropic.beta.messages.toolRunner({
      model: 'claude-sonnet-5',
      max_tokens: 1000,
      messages: [{ role: 'user', content: 'What is the weather in San Francisco?' }],
      tools: [weatherTool],
    });
    
    // Process each message as it arrives
    for await (const message of runner) {
      console.log(message);
    }
    
    // Get the final result
    console.log(await runner);
  2. Use Model Deployments in Azure AI Foundry

    main

    When using configured model deployments, the SDK can automatically construct the correct URL path (e.g., /deployments/{deployment_name}/messages). Ensure you provide the resource and appropriate credentials to the AnthropicFoundry client.

    const client = new AnthropicFoundry({
      apiKey: process.env.ANTHROPIC_FOUNDRY_API_KEY,
      resource: 'example-resource.azure.anthropic.com',
    });
    
    // The SDK will automatically use /deployments/my-claude-deployment/messages
    const message = await client.messages.create({
      model: 'claude-3-5-sonnet-20241022',
      max_tokens: 1024,
      messages: [{ role: 'user', content: 'Hello!' }],
    });
  3. Authenticate with Google Cloud

    main

    Authentication is handled via Google bearer tokens. The client resolves credentials using the following precedence:

    1. An explicit bearerTokenProvider
    2. A googleAuth or authClient (using google-auth-library)
    3. Application Default Credentials (ADC)

    Application Default Credentials (ADC)

    If you have set up ADC (e.g., via gcloud auth application-default login), the client will automatically fetch and refresh tokens without additional configuration.

  4. Stream responses using MessageStream

    main

    Use anthropic.messages.stream() to obtain a MessageStream object. This object provides an event-driven API and helper methods to accumulate stream events into a convenient shape, making it easier to manage conversation state.

    Alternatively, you can use anthropic.messages.create({ stream: true, ... }) to get an async iterable of chunks. This method uses less memory because it does not automatically accumulate a message object for you.

    To cancel a stream, you can either break from a for await loop or call stream.abort().

    anthropic.messages.stream({ … }, options?): MessageStream
  5. Manually drive the Work Poller and Session Tool Runner

    main

    For fine-grained control, you can bypass the high-level worker() and drive the components separately. This is useful if you need to observe tool calls or manage the work lifecycle manually.

    1. client.beta.environments.work.poller(...): A control-plane component that claims work items from an environment and yields them.
    2. setupSkills(ctx): Fetches the session's agent and downloads skills into {workdir}/skills/<name>/. It returns a cleanupSkills function that must be called when work is finished.
    3. client.beta.sessions.events.toolRunner(...): A SessionToolRunner that runs matching tools from your registry for each agent.tool_use event and yields DispatchedToolCall objects.

    Note: The environmentKey should be used to scope a client via client.withOptions({ authToken: environmentKey }) to authenticate per-session calls.

    import {
      betaAgentToolset20260401,
      setupSkills,
      type AgentToolContext,
    } from '@anthropic-ai/sdk/tools/agent-toolset/node';
    
    const environmentKey = process.env.ANTHROPIC_ENVIRONMENT_KEY!;
    const sessionClient = client.withOptions({ authToken: environmentKey });
    
    for await (const work of client.beta.environments.work.poller({
      environmentId: process.env.ANTHROPIC_ENVIRONMENT_ID!,
      environmentKey,
    })) {
      if (work.data.type !== 'session') continue;
    
      const ctx: AgentToolContext = { workdir: '/workspace', client, sessionId: work.data.id };
      const cleanupSkills = await setupSkills(ctx);
      
      try {
        for await (const call of sessionClient.beta.sessions.events.toolRunner(work.data.id, {
          tools: betaAgentToolset20260401(ctx),
        })) {
          console.log(`${call.name} -> ${call.isError ? 'error' : 'ok'}`);
        }
      } finally {
        await cleanupSkills();
      }
    }
  6. Use named path parameters for multi-parameter methods

    main

    Methods that take multiple path parameters now use named arguments instead of positional arguments to prevent errors. For a method targeting an endpoint like /v1/parents/{parent_id}/children/{child_id}, only the last path parameter remains positional; all preceding parameters must be passed as a named object.

    // Before
    client.parents.children.retrieve('p_123', 'c_456');
    
    // After
    client.parents.children.retrieve('c_456', { parent_id: 'p_123' });
  7. Use the Anthropic SDK migration CLI

    main

    To automate the migration of your codebase to the latest version of the Anthropic TypeScript SDK, use the provided migration tool. This tool helps update code that relies on deprecated patterns (like node-fetch) to the new Web fetch-based implementation.

    1. Upgrade the @anthropic-ai/sdk package to the latest version.
    2. Run the migration command pointing to your source directories: ./node_modules/.bin/anthropic-ai-sdk migrate ./your/src/folders
    3. To preview changes without modifying your files, use the --dry flag.
  8. Authenticate with Google Vertex AI

    main

    The SDK supports three main ways to handle authentication with Google Cloud:

    1. Default Authentication

    Provide the region and projectId in the constructor. The client will use the default Google Cloud authentication flow (e.g., Application Default Credentials).

    2. Custom GoogleAuth Configuration

    Pass a googleAuth instance from the google-auth-library to specify custom scopes or a specific keyFile (service account JSON).

    3. Pre-configured AuthClient

    For advanced scenarios like service account impersonation, you can pass a pre-configured authClient directly to the constructor.

    import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
    import { GoogleAuth } from 'google-auth-library';
    
    // --- Default Authentication ---
    const clientDefault = new AnthropicVertex({
      region: 'us-central1',
      projectId: 'my-project-id',
    });
    
    // --- Custom GoogleAuth configuration ---
    const clientCustomAuth = new AnthropicVertex({
      googleAuth: new GoogleAuth({
        scopes: 'https://www.googleapis.com/auth/cloud-platform',
        keyFile: '/path/to/service-account.json',
      }),
      region: 'us-central1',
      projectId: 'my-project-id',
    });
    
    // --- Pre-configured AuthClient (e.g., Impersonation) ---
    import { Impersonated } from 'google-auth-library';
    
    const authClient = new Impersonated({
      sourceClient: await new GoogleAuth().getClient(),
      targetPrincipal: 'impersonated-account@projectID.iam.gserviceaccount.com',
      lifetime: 30,
      delegates: [],
      targetScopes: ['https://www.googleapis.com/auth/cloud-platform'],
    });
    
    const clientImpersonated = new AnthropicVertex({
      authClient,
      region: 'us-central1',
      projectId: 'my-project-id',
    });
  9. Use `toolRunner` to automate tool execution

    main

    The anthropic.beta.messages.toolRunner() method automates the loop of sending messages to the model, receiving tool calls, executing the tools, and sending the results back. It returns a BetaToolRunner which can be iterated over or awaited to get the final result.

    import { betaZodTool } from '@anthropic-ai/sdk/helpers/beta/zod';
    import { z } from 'zod';
    
    const weatherTool = betaZodTool({
      name: 'get_weather',
      inputSchema: z.object({
        location: z.string(),
      }),
      description: 'Get the current weather in a given location',
      run: (input) => {
        return `The weather in ${input.location} is foggy and 60°F`;
      },
    });
    
    const finalMessage = await anthropic.beta.messages.toolRunner({
      model: 'claude-sonnet-5',
      max_tokens: 1000,
      messages: [{ role: 'user', content: 'What is the weather in San Francisco?' }],
      tools: [weatherTool],
    });
    
    console.log(finalMessage.content);
  10. Use Node.js streams for file handling instead of `fileFromPath`

    main

    The deprecated fileFromPath helper has been removed. Use native Node.js streams (e.g., fs.createReadStream) for file handling. If using Bun, use Bun.file instead.

    // Before
    Anthropic.fileFromPath('path/to/file');
    
    // After
    import fs from 'fs';
    fs.createReadStream('path/to/file');
  11. Run a self-hosted environment worker for managed-agents

    main

    The SDK provides building blocks to serve managed-agents sessions in a self-hosted environment. The client.beta.environments.work.worker() method returns an EnvironmentWorker that automates the full lifecycle: polling for work, setting up a work directory, downloading agent skills, running tools against agent.tool_use events, heartbeating the work-item lease, and cleaning up on exit.

    Requirements:

    • To use the betaAgentToolset20260401 (which includes glob), you must use Node 22+. The rest of the SDK supports Node 18+.
    • The environmentKey authenticates both the work-poll calls and all per-session calls (event stream, heartbeat, force-stop).

    Usage Patterns:

    • Full Worker: Use .run() to start a loop that polls, runs, and cleans up automatically.
    • Single Item: Use .handleItem() if you have already claimed a work item (e.g., via a CLI command) and want to run just the per-item flow.
    import Anthropic from '@anthropic-ai/sdk';
    import { betaAgentToolset20260401 } from '@anthropic-ai/sdk/tools/agent-toolset/node';
    
    const client = new Anthropic();
    
    // One-stop worker: poll → run the toolset for each session → force-stop → loop.
    await client.beta.environments.work
      .worker({
        environmentId: process.env.ANTHROPIC_ENVIRONMENT_ID!,
        environmentKey: process.env.ANTHROPIC_ENVIRONMENT_KEY!,
        workdir: '/workspace',
        tools: (ctx) => [...betaAgentToolset20260401(ctx), myCustomTool],
      })
      .run(AbortSignal.timeout(60 * 60_000));