Polyweave

@polyweave/anthropic (1.0.9)

Published 2026-07-11 14:49:32 +00:00 by Dvorak

Installation

@polyweave:registry=https://hub.kl1.tenere.ai/api/packages/Polyweave/npm/
npm install @polyweave/anthropic@1.0.9
"@polyweave/anthropic": "1.0.9"

About this package

@polyweave/anthropic

Anthropic Claude adapter for Polyweave. Raw HTTPS streaming with Server-Sent Events, cost tracking via anytime-valid e-processes, and full frame protocol support including tools, thinking, and system prompts.

Synopsis

import { createAnthropicAdapter } from '@polyweave/anthropic';

const adapter = createAnthropicAdapter({
  apiKey: process.env.ANTHROPIC_API_KEY,
  baseURL: 'https://api.anthropic.com'
});

adapter.source.pipe(mySink);
adapter.sink.write({ type: 'PARAM', content: { key: 'model', value: 'claude-sonnet-4-20250514' } });
adapter.sink.write({ type: 'TEXT', content: { text: 'Explain quantum computing' } });
adapter.sink.write({ type: 'END' });

Install

npm install @polyweave/anthropic

Why

Provides a Polyweave frame-protocol interface to Anthropic's Claude models. Unlike SDK wrappers, the adapter speaks the frame protocol natively — accepting TEXT, AUDIO, IMAGE, TOOL_RESULT, PARAM, COST_CHECK, START, and END frames, and emitting TEXT, RECEIPT, TOOL_CALL, COST, ERROR, and END frames. Cost tracking uses the anytime-valid ratio e-process for statistical budget guarantees. No SDK dependency — uses raw Node.js HTTPS with SSE parsing.

API

createAnthropicAdapter(config)

Returns { source, sink } frame duplex.

Parameter Type Default Description
apiKey string process.env.ANTHROPIC_API_KEY Anthropic API key. Can also be set via PARAM { key: 'apiKey' } at runtime
baseURL string process.env.ANTHROPIC_BASE_URL or https://api.anthropic.com API base URL
budget number 0 Global spend limit in USD. 0 disables

Frame Protocol

Input frames accepted on sink:

Frame Effect
TEXT Appends user message to conversation. Triggers API call if stream is active
AUDIO Audio input (forwarded to multimodal API)
IMAGE Image input (forwarded to multimodal API)
TOOL_RESULT Appends tool result to conversation. Triggers continuation
START Opens a new request stream
END Closes the request stream and flushes the API call
PARAM { key, value } Sets adapter parameter at runtime (see table below)
COST_CHECK { maxBudget } Returns estimated cost without executing the call
TOPOLOGY_SCAN Returns TOPOLOGY_REPORT with adapter state
CANCEL Cancels active request
ABORT Aborts adapter

Runtime PARAM keys:

Key Type Description
apiKey string Override API key at runtime
model string Anthropic model ID (default: claude-3-5-haiku-20241022)
max_tokens number Max output tokens (default: 1024)
system string System prompt
temperature number Sampling temperature
tools array Tool definitions (Anthropic format)
tool_choice string Tool choice directive
thinking object Extended thinking configuration
logprobs boolean Enable logprobs
top_logprobs number Number of top logprobs to return
receipt_mode string 'none', 'final', or 'progressive' (default: 'final')
receipt_interval number Tokens between progressive receipts (default: 50)

Output frames emitted on source:

Frame When
TEXT Streaming text delta or complete response
RECEIPT Token usage receipt (after response or progressive)
TOOL_CALL Claude requests a tool execution
COST Cost estimate (on COST_CHECK)
ERROR API error or adapter failure
END Request stream complete
TOPOLOGY_REPORT Adapter state on TOPOLOGY_SCAN
START Stream beginning

Errors

Error Code When
AUTHENTICATION_ERROR Missing or invalid API key
RATE_LIMIT_EXCEEDED Anthropic rate limit hit
PROVIDER_ERROR Anthropic API returned an error
PROTOCOL_ERROR Frame received out of order or invalid
ADAPTER_ERROR Internal adapter failure

Error frames include { code, message, provider?: 'anthropic', statusCode?, retryable? }.

Cost Functions

The adapter exports cost helpers re-exported from ./costs.js:

  • getModelCost(provider, model) — returns { mtoksInput, mtoksOutput } or null
  • calculateTokenCost(model, inputTokens, outputTokens, config?) — returns USD cost

These are used internally by the cost estimator but available for direct use.

Budget Enforcement

Set budget at construction or via PARAM { key: 'budget', value: 5.00 }. The adapter tracks cumulative spend from RECEIPT frames. When the budget is exceeded, TEXT frames are blocked and an ERROR frame is emitted.

Cost Check Mode

Send COST_CHECK { maxBudget } to get a cost prediction without executing the call. The adapter buffers subsequent TEXT frames, estimates cost using getModelCost, and returns a COST frame with the estimate. The buffered frames are NOT sent to Anthropic.

Tests

npm test

4 native tests (mock server + frame protocol) + 200 js-rigor property cases covering adapter creation, PARAM accumulation, TEXT/END triggering API calls, START stream management, error handling, cost check buffering, and receipt emission.

Requirements

Node.js 22 or later. ESM only.

Peer dependencies: @polyweave/core, @polyweave/costs, @polyweave/errors.

Dependencies

Dependencies

ID Version
@anthropic-ai/sdk ^0.71.2

Development Dependencies

ID Version
@rigor/core *

Peer Dependencies

ID Version
@polyweave/core *
@polyweave/costs *
@polyweave/errors *

Keywords

polyweave anthropic claude ai adapter
Details
npm
2026-07-11 14:49:32 +00:00
5
John Dvorak
SEE LICENSE IN LICENSE
latest
14 KiB
Assets (1)
Versions (5) View all
1.0.9 2026-07-11
1.0.6 2026-07-10
1.0.5 2026-07-10
1.0.4 2026-07-10
1.0.3 2026-07-10