SPB Git forge

spb/doc-api

Public
2commits 1branches 0releases
15.7 MBsize
maindefault branch
13 days agolast push
Python 88.3% TypeScript 7.6% Shell 4.1%
9.2 KB

# Anthropic client SDKs — Python, TypeScript, Go, Java, Ruby, C#, PHP

Status: Python 1.7.0 and TypeScript 0.126.0 LIVE_VERIFIED 2026-09-18 (installed locally; examples executed). Go/Java/Ruby/C#/PHP DOCUMENTED (not installed). PHP SDK is BETA. Sources: https://platform.claude.com/docs/en/cli-sdks-libraries/overview · …/sdks/python · …/sdks/typescript · …/sdks/go · …/sdks/java · …/sdks/ruby · …/sdks/csharp · …/sdks/php · https://platform.claude.com/docs/en/cli-sdks-libraries/middleware · https://platform.claude.com/docs/en/api/errors#sdk-error-types · sources/anthropic/openapi/{python,node}-sdk-api.md Machine-readable: generated/fragments/sdks/anthropic-sdks.json Last verified: 2026-09-18

# Matrix

Python anthropic TypeScript @anthropic-ai/sdk Go Java Ruby C# PHP
Install pip install anthropic (+[bedrock], [vertex], [aws], [aiohttp]) npm install @anthropic-ai/sdk go get github.com/anthropics/anthropic-sdk-go com.anthropic:anthropic-java:2.63.0 bundle add anthropic dotnet add package Anthropic (≥10) composer require anthropic-ai/sdk guzzlehttp/guzzle:^7
Runtime Python ≥3.10 TS ≥5.0; Node 20+, Deno, Bun, Workers, Edge (browser needs dangerouslyAllowBrowser) Go ≥1.24 Java ≥8 Ruby (Sorbet types) .NET Standard 2.0+ PSR-18
Client Anthropic() / AsyncAnthropic() new Anthropic() anthropic.NewClient() AnthropicOkHttpClient.fromEnv() / …Async Anthropic::Client.new new AnthropicClient() new Anthropic\Client()
Create client.messages.create(**p) client.messages.create(p) client.Messages.New(ctx, p) client.messages().create(p) client.messages.create(...) client.Messages.Create(p) $client->messages->create(...)
Raw stream create(stream=True) → iterator create({stream: true}) → Stream Messages.NewStreaming createStreaming → StreamResponse — CreateStreaming → IAsyncEnumerable createStream
Stream helper messages.stream() → text_stream, get_final_message() messages.stream() → .on('text'), finalMessage() message.Accumulate(ev) MessageAccumulator .stream(...).accumulated_message .Aggregate() / MessageContentAggregator MessageAccumulator::forMessages()
Count tokens messages.count_tokens messages.countTokens Messages.CountTokens messages().countTokens messages.count_tokens Messages.CountTokens messages->countTokens
Beta ns client.beta.messages (betas=[…], tool_runner, parse) client.beta.messages (toolRunner, betaZodTool) yes yes yes yes yes
Retries 2 (conn, 408, 409, 429, ≥500; 0.5 s → 8 s, jitter, retry-after) 2 (maxRetries) 2 (WithMaxRetries) 2 (maxRetries) 2 (max_retries) 2 (MaxRetries) 2 (RequestOptions::with(maxRetries))
Timeout 10 min (httpx2.Timeout(connect=5, read/write/pool=600)) → APITimeoutError 10 min; non-streaming scales 60 min × max_tokens/128000, refuses >10 min without stream → APIConnectionTimeoutError 10 min non-streaming Messages; context / WithRequestTimeout builder timeout timeout: Timeout APITimeoutException
Request id msg._request_id, with_raw_response msg._request_id, .asResponse(), .withResponse() option.WithResponseInto withRawResponse().requestId() middleware WithRawResponse … RequestID ->raw->create
Pagination for m in client.models.list(); .has_next_page(), .get_next_page() for await; .getNextPage() iterator iterator iterator iterator iterator
Cloud clients AnthropicBedrockMantle, AnthropicBedrock, AnthropicVertex/AnthropicGoogleCloud, AnthropicAWS (beta), AnthropicFoundry @anthropic-ai/{bedrock,vertex,aws,foundry}-sdk sub-packages modules — — —

# Python 1.7.0 specifics (verified by introspection)

  • client.messages: create, stream, parse, count_tokens, batches, with_raw_response, with_streaming_response. client.beta.messages adds tool_runner. No client.completions (legacy API removed in v1).
  • temperature, top_p, top_k are no longer keyword arguments of messages.create/stream/parse nor beta.messages.create (TypeError: unexpected keyword argument 'temperature'). Pass extra_body={"temperature": 0.2} for models that still accept them. New kwargs: user_profile_id, workspace_id. count_tokens/stream still accept legacy output_format.
  • Constants: DEFAULT_MAX_RETRIES=2, INITIAL_RETRY_DELAY=0.5, MAX_RETRY_DELAY=8.0, MODEL_NONSTREAMING_TOKENS (Opus 4 / 4.1 ids → 8192).
  • Errors: APIError → APIStatusError → BadRequestError(400) AuthenticationError(401) PermissionDeniedError(403) NotFoundError(404) ConflictError(409) RequestTooLargeError(413) UnprocessableEntityError(422) RateLimitError(429) InternalServerError(≥500) OverloadedError(529) ServiceUnavailableError DeadlineExceededError; APIConnectionError → APITimeoutError; WIF: CredentialsError, WorkloadIdentityError, IdentityTokenFileError. e.status_code, e.request_id, e.body, e.response.headers.
  • Types: anthropic.types.{Message, Usage, StopReason, ContentBlock, RawMessageStreamEvent, MessageParam, …}; Usage fields: cache_creation, cache_creation_input_tokens, cache_read_input_tokens, inference_geo, input_tokens, output_tokens, output_tokens_details, server_tool_use, service_tier.
  • MessageStream: text_stream, get_final_message(), get_final_text(), until_done(), current_message_snapshot, request_id, response, close().
  • Undocumented fields: extra_headers, extra_query, extra_body; response.model_extra; client.get/post. Default header anthropic-version: 2023-06-01. ANTHROPIC_LOG=debug.
  • Middleware: client.with_middleware([...]) / middleware= option; built-in refusal-fallback middleware.

# TypeScript 0.126.0 specifics

  • client.messages.create returns APIPromise (.asResponse(), .withResponse()); create({stream: true}) → Stream<RawMessageStreamEvent> (async iterable, controller.abort()); client.messages.stream() → MessageStream with events streamEvent | text | inputJson | citation | thinking | signature | contentBlock | message | finalMessage | error | abort | end, finalMessage(), finalText().
  • client.completions.create still exists (endpoint deprecated live). client.beta.messages.toolRunner({tools: [betaTool(...)|betaZodTool(...)]}); throw ToolError for tool failures; MCP helpers (UnsupportedMCPValueError).
  • Timeout formula (client.js): expected = 60 min × max_tokens / 128000; if expected > 10 min or max_tokens > MODEL_NONSTREAMING_TOKENS[model] (Opus 4.x ids: 8192) and not streaming → throws AnthropicError("Streaming is required for operations that may take longer than 10 minutes…").
  • Errors: AnthropicError, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, RetryableError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError. e.status, e.requestID, e.headers, e.error (parsed body).
  • Logging ANTHROPIC_LOG / logLevel: debug|info|warn|error|off; fetchOptions for proxies; // @ts-expect-error or {body, query, headers} request options for undocumented fields.

# Other SDK notes

  • Go: single error type *anthropic.Error (StatusCode, Request, Response, JSON body) via errors.As; param.SetJSON (≥1.20.0); middleware option.WithMiddleware concatenates client-then-method.
  • Java: AnthropicException → AnthropicServiceException (HTTP), AnthropicIoException, AnthropicRetryableException, AnthropicInvalidDataException; async via client.async().messages().createStreaming(p).subscribe(...) on a cached thread pool; tool names camelCase→snake_case.
  • Ruby: Anthropic::Errors::APIError → BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError, APIStatusError, APITimeoutError, APIConnectionError; request_options: {middleware: [...]} to read headers.
  • C#: AnthropicApiException → AnthropicBadRequestException(400) AnthropicUnauthorizedException(401) AnthropicForbiddenException(403) AnthropicNotFoundException(404) AnthropicUnprocessableEntityException(422) AnthropicRateLimitException(429) Anthropic5xxException; all 4xx inherit Anthropic4xxException; AnthropicSseException for mid-stream errors; AnthropicIOException. Streaming methods end in Streaming; IChatClient integration.
  • PHP (beta): PSR-18 discovery, Guzzle recommended for incremental streaming; APIStatusException, APITimeoutException, APIConnectionException.
  • Libraries (not Messages clients): OpenAI-SDK compatibility layer, Swift apple-foundation-models package. Higher-level: Claude Code, Claude Agent SDK, Claude Managed Agents.

Examples executed: examples/anthropic/messages/*.py|*.ts, examples/anthropic/streaming/sdk_stream.{py,ts}, examples/shared/errors/anthropic_error_handling.{py,ts}.