anthropic

package module
v0.61.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 36 Imported by: 6

Documentation

Overview

Package anthropic implements the Anthropic Messages wire protocol reused by native and compatible provider endpoints inside the models module.

A nonempty Config BaseURL overrides ANTHROPIC_BASE_URL; when both are absent, the SDK production endpoint applies. Construction validates and freezes the selected URL. The SDK does not reload environment credentials, endpoints, or headers: APIKey, Headers, and HTTPClient belong to this binding. A nil HTTPClient retains the SDK's response-header deadline without limiting a streaming body. The official binding uses the Anthropic v2 SDK's native API revision and bearer authentication. Sampling controls are not accepted by that API. Dialect.Revision, Dialect.APIKeyScheme, and Dialect.SupportsSampling bind independent wire, authentication, and capability facts explicitly; other headers cannot replace or add credentials. The SDK owns its retry policy.

Constructors:

  • NewMessages — native /v1/messages: extended thinking blocks, tool_use with signature continuity, citations, fine-grained tool-result content blocks, cache_control.

A successful stream begins with one message_start, opens each content block before its deltas, and ends with message_stop after all blocks close and a message_delta supplies the finish reason. Invalid event order or mismatched delta types fail with [chat.ErrInvalidResponse]. Native server-tool blocks, unrepresentable content, and pause_turn fail with errors.ErrUnsupported: continuing these responses requires native content and tools that this binding cannot replay. Previously emitted deltas remain observable; no local Tool call or successful terminal response is fabricated. Thinking and redacted blocks retain their identities through aggregation and history replay. Document citations resolve document_index against the exact request projection, including documents in tool results. The response title and file_id cannot replace a request source. URL sources retain their URI; inline sources retain Media.ID when supplied, otherwise their byte digest supplies a stable URI. Response IDs are not required to identify those documents. This binding does not expose the per-document citations.enabled request control.

Native output schemas must be enforceable without weakening their domain constraints. Unconstrained JSON, open objects, numeric bounds, recursive schemas, and other unsupported native features fail before Call, Stream, or CountInputTokens dispatch with chat.ErrUnsupportedOutputFormat. Descriptions never replace validation constraints; optional properties remain optional.

Provider packages exposing an Anthropic-compatible endpoint reuse the Messages protocol through NewMessages and select one typed Dialect. Application code continues to use the provider's own chat type.

Messages.CountInputTokens exposes the provider-specific complete-request token endpoint. the Messages text-counter binding serves isolated text workflows.

Messages.ListModels follows the SDK's native model pagination using this binding. Count and total response-byte budgets are explicit per operation; the context owns the deadline. A partial scan never returns successful IDs. Catalog enrichment and model selection remain consumer policy.

Anthropic's Message Batches API (~50% pricing, up to 24h asynchronous) doesn't fit core/chat's synchronous request/response shape and is not exposed.

Model id constants aren't exported — anthropic-sdk-go owns them (anthropicsdk.ModelClaudeOpus5, anthropicsdk.ModelClaudeSonnet5, anthropicsdk.ModelClaudeFable5, etc.). Import the SDK directly when you need them. Token counts and HTTP error envelopes are bounded by Core's httpclient.DefaultMaxJSONResponseBytes before SDK decoding. Successful SSE receives the same budget per wire event, including framing and comments, without limiting the lifetime of the stream. Model discovery keeps its caller-supplied aggregate budget across pages. Local output-schema references use URI-fragment JSON Pointer semantics; escaping cannot change the provider's unsupported-recursion constraint.

Index

Examples

Constants

View Source
const (
	CompatibleRequestExtensionSuffix = "/anthropic_request"
	CompatibleStreamExtensionSuffix  = "/anthropic_stream_event"
)
View Source
const (
	ProviderID = "anthropic"
)
View Source
const (
	// RequestExtensionKey stores provider-owned top-level Messages API fields in
	// a Core request for fields without a provider-neutral equivalent.
	RequestExtensionKey = ProviderID + "/request"
)
View Source
const (
	// StreamEventExtensionKey preserves each official Anthropic stream event.
	StreamEventExtensionKey = ProviderID + "/stream_event"
)

Variables

This section is empty.

Functions

func NewRedactedThinkingPart

func NewRedactedThinkingPart(data []byte) (corechat.Part, error)

NewRedactedThinkingPart preserves an opaque Anthropic thinking block without pretending its content is readable text.

func NewThinkingPart

func NewThinkingPart(text string, signature []byte) (corechat.Part, error)

NewThinkingPart preserves the signature Anthropic requires when thinking is replayed in a later request.

Types

type APIKeyScheme added in v0.60.0

type APIKeyScheme uint8

Credential placement belongs to the endpoint binding. Ordinary metadata cannot replace a key or select a second authentication mechanism.

const (
	APIKeySchemeBearer APIKeyScheme = iota + 1
	APIKeySchemeXAPIKey
	APIKeySchemeAPIKey
)

type Dialect

type Dialect struct {
	// Provider scopes opaque reasoning state to the API that issued it. It is
	// required even when the provider uses Anthropic's wire shape because signed
	// thinking is not portable across vendors.
	Provider         string
	Revision         MessagesRevision
	APIKeyScheme     APIKeyScheme
	SupportsSampling bool
	// NativeJSONSchema reports whether this endpoint implements Anthropic's
	// output_config.format JSON Schema control. Compatible providers that do not
	// declare it reject that output format with ErrUnsupportedOutputFormat.
	NativeJSONSchema bool
	// PrepareRequest applies provider policy to the resolved, independently
	// owned request before the Messages wire projection is built. Fields holds
	// the decoded native request extension and may be changed by the provider.
	PrepareRequest func(*corechat.Request, map[string]any) error
}

Dialect declares the protocol differences selected by an Anthropic-compatible provider adapter.

type Messages added in v0.13.0

type Messages struct {
	// contains filtered or unexported fields
}

Messages implements Anthropic's Messages protocol and is also the reusable protocol base for provider packages exposing a compatible endpoint.

func NewMessages added in v0.13.0

func NewMessages(ctx context.Context, config MessagesConfig, dialect Dialect) (*Messages, error)

func (*Messages) Call added in v0.13.0

func (m *Messages) Call(ctx context.Context, req *corechat.Request) (*corechat.Response, error)

func (*Messages) CountInputTokens added in v0.13.0

func (m *Messages) CountInputTokens(ctx context.Context, req *corechat.Request) (int64, error)

CountInputTokens calls the provider's Messages token-count endpoint with the same provider request projection used by Call.

func (*Messages) ListModels added in v0.40.0

func (m *Messages) ListModels(ctx context.Context, maxModels int, maxResponseBytes int64) ([]string, error)

ListModels returns the model IDs visible to this binding in provider order. Both limits must be positive. maxResponseBytes bounds the total response bytes across all pages; maxModels counts advertised entries, including duplicates. Failure or incomplete pagination returns no IDs. The caller owns the deadline; discovery performs no retries and preserves HTTPStatus and HTTPHeader errors.

Example
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
	writer.Header().Set("Content-Type", "application/json")
	if request.URL.Query().Get("after_id") == "" {
		_, _ = io.WriteString(writer, `{"data":[{"id":"first"}],"has_more":true,"last_id":"first"}`)
		return
	}
	_, _ = io.WriteString(writer, `{"data":[{"id":"second"}],"has_more":false,"last_id":"second"}`)
}))
defer server.Close()
model, err := anthropic.NewMessages(context.Background(), anthropic.MessagesConfig{APIKey: "test-key", BaseURL: server.URL, HTTPClient: server.Client()}, testMessagesDialect())
if err != nil {
	fmt.Println(err)
	return
}
ids, err := model.ListModels(context.Background(), 2, 1024)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(ids)
ids, err = model.ListModels(context.Background(), 1, 1024)
fmt.Println("incomplete result rejected:", ids == nil && err != nil)
Output:
[first second]
incomplete result rejected: true

func (*Messages) Stream added in v0.13.0

Stream performs one streaming Messages API request and yields provider deltas without accumulating text or tool arguments across events.

func (*Messages) TextCounter added in v0.59.0

func (m *Messages) TextCounter() (*TextCounter, error)

TextCounter binds text-only counting to this exact endpoint and vocabulary; a model selected only at request time cannot identify a text vocabulary.

type MessagesConfig added in v0.13.0

type MessagesConfig struct {
	APIKey         string
	DefaultOptions corechat.Options
	BaseURL        string
	HTTPClient     *http.Client
	// A header with no values removes the SDK's default for that name.
	Headers http.Header
}

Defaults are copied during construction; callers may select the model per request.

func (MessagesConfig) Validate added in v0.13.0

func (m MessagesConfig) Validate() error

type MessagesRevision added in v0.60.0

type MessagesRevision string
const (
	MessagesRevision20230601 MessagesRevision = "2023-06-01"
	MessagesRevision20261021 MessagesRevision = "2026-10-21"
)

func (MessagesRevision) Validate added in v0.60.0

func (m MessagesRevision) Validate() error

type ReasoningBlockKind

type ReasoningBlockKind string

ReasoningBlockKind identifies the official Anthropic reasoning block carried by a Core reasoning part.

const (
	ReasoningBlockThinking ReasoningBlockKind = "thinking"
	ReasoningBlockRedacted ReasoningBlockKind = "redacted_thinking"
)

The vocabulary is closed because these kinds classify reasoning blocks the service returns. A redacted block carries no readable text but must still round trip intact for a later turn to remain valid, so it cannot be folded into the thinking kind.

func ReasoningBlockKindOf

func ReasoningBlockKindOf(part corechat.Part) (ReasoningBlockKind, bool, error)

ReasoningBlockKindOf reports whether part contains Anthropic-issued reasoning replay state and, when it does, which official block variant it is.

type TextCounter added in v0.21.0

type TextCounter struct {
	// contains filtered or unexported fields
}

TextCounter reports input-token counts via Anthropic's /messages/count_tokens endpoint. Implements tokenizer.TextCounter so it drops into code paths already gating on token budgets (RAG chunking, prompt-window checks, cost preflight).

Every count is a network round-trip; for high-QPS counting reach for an offline tokenizer instead.

func (*TextCounter) CountText added in v0.21.0

func (t *TextCounter) CountText(ctx context.Context, text string) (int, error)

CountText returns the prompt-token count Anthropic would charge if text were sent as a single user message under the configured model.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL