anthropic

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: Apache-2.0 Imports: 27 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package anthropic implements the Anthropic Messages wire API.

It is keyed by WIRE API, not by vendor: the same implementation serves Anthropic direct and any gateway that speaks Messages.

Index

Constants

View Source
const (
	APIKeyVar        = "ANTHROPIC_API_KEY"
	AuthTokenVar     = "ANTHROPIC_AUTH_TOKEN"
	OAuthTokenVar    = "ANTHROPIC_OAUTH_TOKEN"
	BaseURLVar       = "ANTHROPIC_BASE_URL"
	VertexEnableVar  = "CLAUDE_CODE_USE_VERTEX"
	VertexProjectVar = "ANTHROPIC_VERTEX_PROJECT_ID"
	GoogleProjectVar = "GOOGLE_CLOUD_PROJECT"
	VertexRegionVar  = "CLOUD_ML_REGION"
	VertexBaseURLVar = "ANTHROPIC_VERTEX_BASE_URL"
	BedrockEnableVar = "CLAUDE_CODE_USE_BEDROCK"
)

The variables Resolve reads.

View Source
const API core.API = "anthropic-messages"

API is the wire API id.

View Source
const APIVersion = "2023-06-01"

APIVersion is the anthropic-version the SDK sends.

View Source
const AbortText = "Request was aborted"

AbortText is the one error string that means "the caller stopped this". It is matched by text because it has to survive a round trip through an AssistantMessage's ErrorMessage.

View Source
const BetaOAuth = "oauth-2025-04-20"

BetaOAuth is the beta the Messages API requires alongside an OAuth bearer (ANTHROPIC_OAUTH_TOKEN, sk-ant-oat…).

View Source
const DefaultBedrockRegion = "us-east-1"

DefaultBedrockRegion is the AWS region when neither AWS_REGION nor AWS_DEFAULT_REGION is set.

View Source
const DefaultMaxTokens = 4096

DefaultMaxTokens is sent when neither the request nor the model bounds the output. max_tokens is REQUIRED on this wire and 0 is rejected, so a hand-built Model with no output cap still needs a positive number; this one is sized so a normal answer fits.

View Source
const DefaultVertexRegion = "global"

DefaultVertexRegion is the Vertex location when CLOUD_ML_REGION is unset.

View Source
const SyntheticResultText = "No result provided"

SyntheticResultText is the content of a tool result invented by rule 6. It is model-visible, so it is pinned here rather than formatted at the call site.

View Source
const VertexAPIVersion = "vertex-2023-10-16"

VertexAPIVersion is the anthropic_version a Vertex request body carries.

Variables

View Source
var ErrNoCredentials = errors.New("anthropic: missing credentials: set " + APIKeyVar + ", " +
	AuthTokenVar + " or " + OAuthTokenVar + ", or select Vertex AI (" + VertexEnableVar + "=1) or Bedrock (" +
	BedrockEnableVar + "=1)")

ErrNoCredentials is returned when no deployment is selected and the environment holds no Anthropic credential.

View Source
var ErrStreamTruncated = errors.New("agentkit: stream ended before message_stop")

ErrStreamTruncated is a stream that ended before message_stop.

Functions

func BuildRequestJSON

func BuildRequestJSON(req core.Request, m core.Model) ([]byte, error)

BuildRequestJSON is the request body for req on m, byte for byte as it is sent, with the short cache retention. Replayed tool_use input and replayed raw blocks keep the exact bytes they arrived with; json.Marshal of a BuildRequest result would compact them.

func BuildRequestJSONWith

func BuildRequestJSONWith(req core.Request, m core.Model, opts Options) ([]byte, error)

BuildRequestJSONWith is BuildRequestJSON for a provider configured with opts: the options that shape the request body (CacheRetention, NonStrictTools) apply, and the rest are not read.

func DecodeResponse

func DecodeResponse(m *core.Model, data []byte, lookup func(string) *core.Model) (*core.AssistantMessage, error)

DecodeResponse decodes a NON-streaming Messages response.

TranslateMessage decodes through it, and so does the conformance test: the streaming and whole-response paths must produce byte-identical ToolUseBlock.Input for the same call. Sharing the assembler is what makes that true by construction rather than by coincidence, and DecodeResponse is how the test can say so.

func MapStopReason

func MapStopReason(s string) core.StopReason

MapStopReason normalizes an Anthropic stop_reason. The provider's own string is preserved verbatim by the caller in RawStopReason; this mapping is lossy on purpose and never drives control flow.

func NormalizeToolCallID

func NormalizeToolCallID(s string) string

NormalizeToolCallID rewrites an id into Anthropic's accepted shape: characters outside [A-Za-z0-9_-] become '_', truncated to 64. It is the function RepairTranscript's rule 5 uses when replaying a transcript produced by another provider.

func Provider

func Provider(m core.Model, opts Options) core.ProviderClient

Provider returns a core.ProviderClient for the model m.

func SalvageJSON

func SalvageJSON(b []byte) (json.RawMessage, bool)

SalvageJSON repairs the argument bytes of a tool call whose stream was cut off, so that a truncated call is REPRESENTABLE rather than undecodable.

It returns the input UNCHANGED, and repaired=false, whenever the input already parses. That is not an optimization: the bytes a provider streamed are authoritative for every replay and fingerprint, so the salvage path must be a no-op on the overwhelmingly common case; a repair that "normalizes" valid input would reorder keys on every turn and shift the prompt-cache prefix.

WHAT IT DOES WITH A TRUNCATED VALUE, and why: it DROPS the incomplete member rather than closing it — and a member whose value is a container still open at the cut is a truncated member too, dropped whole.

Closing an open string is the friendlier-looking choice and it is the wrong one here. `{"path":"/etc/pas` becomes a syntactically perfect call to delete a file nobody named, indistinguishable from a complete one — the file-corrupting case the loop's refusal to run truncated calls exists for, now wearing valid JSON. Dropping the member instead makes the truncation SURVIVE as a missing required property, where schema validation of the arguments rejects it and the caller is told what happened. Complete top-level members before the cut are kept; only the partial one is lost, however deep inside it the cut fell.

This is a safety net under that refusal, never a substitute for it: the loop still refuses to execute any tool call from a `max_tokens` turn, because a call can be truncated at a point where the remaining JSON is both valid and wrong.

func StampCacheControl

func StampCacheControl(r *request, retention core.CacheRetention, m *core.Model)

StampCacheControl places the prompt-cache breakpoints.

Three placements, and a fourth when the request carries a Prefix, all recomputed on EVERY request:

  1. the LAST system block only — a marker caches everything rendered before it, and the wire renders tools, then system, then messages, so one breakpoint here covers the tool list and the whole system prompt together. Stamping every system block spent one of the four breakpoints per block, and a prompt with three or more blocks pushed the request over the limit;
  2. the last IMMEDIATE tool — the marker covers all preceding tools, so one breakpoint suffices and the budget is not spent on the tool list;
  3. the last content block of the last message, when that message is a user message and the block is text, image or tool_result.

The fourth is the last block of the encoded Prefix: the prefix is the same on every request, so its end is a stable breakpoint.

Placement 3 is a ROLLING breakpoint: it moves forward every turn, extending the cached prefix to include the previous turn's tool results. That is the whole point. The "optimization" of recomputing only when the system prompt or tool list changes produces a static prefix-only breakpoint, which re-pays full input price on the entire growing transcript — the dominant cost in exactly the multi-turn agent workload this SDK exists for.

Under CacheRetentionLong the 1h TTL goes on every placement but the rolling one. The rolling breakpoint stays at the default 5-minute TTL: it is rewritten every turn anyway, a 1h write bills at twice the 5m rate, and the wire requires every 1h entry to precede every 5m one — which tools -> system -> messages order satisfies exactly when the last breakpoint is the short one.

func TranslateMessage

func TranslateMessage(m *core.Model, msg sdk.Message) (core.AssistantMessage, error)

TranslateMessage translates a whole (non-streamed) SDK Message for m into an assistant message: thinking, text and tool_use blocks, the stop reason, and the usage priced at m's rates. It decodes the message's own JSON, so a tool_use input keeps the bytes the API sent.

func TranslateUsage

func TranslateUsage(start sdk.Usage, delta sdk.MessageDeltaUsage) core.Usage

TranslateUsage folds the usage a stream reports in message_start and then in message_delta into one usage for one request. A field the delta reports supersedes the start's.

Types

type Env

type Env interface {
	Lookup(name string) (string, bool)
}

Env looks up environment variables. An empty value is treated as unset.

type MapEnv

type MapEnv map[string]string

MapEnv is an Env backed by a map, for tests and for an embedder that configures a client without touching the process environment.

func (MapEnv) Lookup

func (m MapEnv) Lookup(name string) (string, bool)

Lookup implements Env.

type OSEnv

type OSEnv struct{}

OSEnv is the process environment.

func (OSEnv) Lookup

func (OSEnv) Lookup(name string) (string, bool)

Lookup implements Env.

type Options

type Options struct {
	// Client is the official SDK client requests go through. Nil resolves one
	// from the environment.
	Client *sdk.Client

	BaseURL    string
	HTTPClient *http.Client
	// Getenv is injectable so a test never mutates process environment
	// Nil means os.Getenv.
	Getenv func(string) string
	// MaxRetries overrides the SDK's retry count; nil keeps its default.
	MaxRetries *int
	// Betas are sent as anthropic-beta, verbatim.
	Betas []string
	// VertexProject selects the Vertex AI deployment whatever the
	// environment says, and VertexLocation sets its region; both otherwise
	// come from the environment (see Resolve).
	VertexProject  string
	VertexLocation string
	// VertexTokenSource supplies the Google OAuth token a Vertex request is
	// authorized with. Nil uses a Google access token in ANTHROPIC_AUTH_TOKEN
	// when there is one, and Application Default Credentials otherwise.
	VertexTokenSource oauth2.TokenSource
	// BillingLookup resolves a SERVED model id to its catalog row. Nil bills
	// a fallback-served response at the requested model's rates and still
	// records the served name.
	BillingLookup func(string) *core.Model
	// ToolPrefix is the per-session schema cache. Nil means this
	// provider value owns one, which is the right scope in practice: a
	// registry is built per agent config. Pass one explicitly to share it, or
	// to read its reconciliation reports.
	ToolPrefix *provider.ToolPrefix
	// OnToolPrefixSync reports each reconciliation, so an embedder can count
	// prompt-cache prefix invalidations.
	OnToolPrefixSync func(provider.SyncReport)
	// Now is injectable for deterministic timestamps in tests.
	Now func() time.Time

	// CacheRetention places the prompt-cache breakpoints; empty is short.
	CacheRetention core.CacheRetention
	// NonStrictTools names tools that are never declared strict (`strict:
	// true`), however well they would fit. The API totals its strict-mode
	// limits over a request: at most 20 strict tools and 16 union parameters,
	// and a compiled grammar it will not say the size of. A request past any
	// is refused whole, so an embedder whose request is refused for the
	// grammar names its simple tools here and leaves the budget to the
	// complex ones. A named tool spends none of the budget; its schema is
	// sent as it would have been sent strict, and its arguments are still
	// validated before it runs. A name that is no tool of the request is
	// ignored.
	NonStrictTools []string
	// Headers merge into every request. A present-nil value is a DELETION
	// MARKER suppressing a default of that name; no string
	// value can express that.
	Headers map[string]*string
	// Timeout bounds each request, independently of the caller's context;
	// zero is none.
	Timeout time.Duration
	// Env is consulted before Getenv when resolving the deployment. An empty
	// override falls through rather than masking.
	Env map[string]string
	// Transport replaces the HTTP transport.
	Transport http.RoundTripper
	// OnPayload runs after canonical->wire translation and before the first
	// byte. Returning (nil, nil) leaves the payload unchanged; its error ends
	// the turn unmodified.
	OnPayload func(payload any, model *core.Model) (any, error)
	// OnResponse sees each HTTP response before it is read; its error ends
	// the turn.
	OnResponse func(resp *http.Response, model *core.Model) error
	// Warnf receives the transcript repair report; nil discards it.
	Warnf func(format string, args ...any)
}

Options configures the provider. The zero value is usable.

type RepairReport

type RepairReport struct {
	DroppedFailedTurns   int
	DroppedOrphanResults int
	SyntheticResults     int
	DowngradedThinking   int
	DroppedRedacted      int
	StrippedSignatures   int
	RewrittenIDs         int
}

RepairReport records what a repair pass changed. It is returned rather than logged: a caller diagnosing a 400 needs to know whether the transcript it sent was the transcript it holds, and a log line is not available to a test.

func BuildRequest

func BuildRequest(m *core.Model, req core.Request, retention core.CacheRetention) (*request, RepairReport, error)

BuildRequest converts a canonical request into the Anthropic wire body. It is exported so the golden tests can capture the exact bytes without a network call or an API key; BuildRequestJSON returns them as sent.

It runs the transcript repair pass (RepairTranscript) first — that is part of the provider contract, not the loop's, because the loop is not running when a transcript is loaded from disk.

func BuildRequestCached

func BuildRequestCached(m *core.Model, req core.Request, retention core.CacheRetention,
	prefix *provider.ToolPrefix) (*request, RepairReport, provider.SyncReport, error)

BuildRequestCached is BuildRequest with a per-session schema cache attached. A nil prefix marshals every schema, which is what BuildRequest does and what a one-shot caller wants.

It exists rather than being an internal detail because tool schema serialization must be computed once per session and cached, not recomputed on every model call: at 128 tools that recomputation is ~0.9 ms of the ~1.5 ms it takes to build a request — the dominant term, paid on every turn, for bytes that did not change.

func RepairTranscript

func RepairTranscript(in core.Messages, t Target) (core.Messages, RepairReport)

RepairTranscript is the unconditional pass this provider runs on every request, before wire-format conversion.

It is part of the provider contract and not the loop's, because the loop is not running when a transcript is loaded from disk and no caller may be able to skip it. It produces a VIEW: the input is never mutated, and the result is never persisted, so the durable log stays complete while the request stays valid.

The rules, in order. Order matters twice: rule 2b depends on rule 2 having run, and rule 6's synthetic results must carry the ids rule 5 rewrote.

1  compute same_model from the model id
2  drop assistant messages whose stop reason is Error or Aborted
2b drop tool results orphaned BY rule 2                       <-- see below
3  cross-model: downgrade signed thinking, drop redacted, strip signatures
4  demote thinking blocks with no signature to plain text
5  cross-model: rewrite tool-call ids, remembering the mapping
6  insert a synthetic result for any tool_use still unanswered

Rule 2b

Rule 2 drops an aborted assistant message — including its tool_use blocks. But the ToolResultMessages that answered those blocks are SEPARATE canonical messages and survive rule 2 untouched. Every provider rejects a tool result whose tool_use is absent, so the other rules alone produce an INVALID request on the single commonest damaged transcript: Ctrl-C during a tool batch, then resume.

Rule 2b closes that hole. Without it the repair pass creates the exact failure it exists to prevent, and only on the resume path — which no single-process test exercises.

func (RepairReport) Changed

func (r RepairReport) Changed() bool

func (RepairReport) String

func (r RepairReport) String() string

type Source

type Source string

Source is the deployment a client was resolved for.

const (
	SourceDirect  Source = "direct"
	SourceVertex  Source = "vertex"
	SourceBedrock Source = "bedrock"
)

func Resolve

func Resolve(env Env) (*sdk.Client, Source, error)

Resolve builds an SDK client from env, choosing the deployment:

  • Vertex AI when CLAUDE_CODE_USE_VERTEX is 1 or true: project from ANTHROPIC_VERTEX_PROJECT_ID or GOOGLE_CLOUD_PROJECT, location from CLOUD_ML_REGION (then GOOGLE_CLOUD_LOCATION, CLOUDSDK_COMPUTE_REGION; default "global"), and ANTHROPIC_VERTEX_BASE_URL as a proxy;
  • Bedrock when CLAUDE_CODE_USE_BEDROCK is 1 or true;
  • otherwise the Anthropic API, with ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN and an optional ANTHROPIC_BASE_URL.

0 or false turns a cloud deployment off whatever else is set. Resolve reads nothing but env and makes no network request; credentials a deployment fetches (Google's, AWS's) are fetched on the first request.

type StatusError

type StatusError struct {
	Code int
	Text string
}

StatusError is a non-2xx response: the status code and the error text.

func (*StatusError) Error

func (e *StatusError) Error() string

type Target

type Target struct {
	Model string
	// NormalizeToolCallID rewrites an id into this API's accepted shape. Nil
	// means ids pass through unchanged.
	NormalizeToolCallID func(string) string
}

Target describes the model a transcript is being repaired FOR. same_model compares model ids: every turn is Claude over the Messages API, so the model is the whole of a turn's provenance, and getting it wrong silently downgrades every signed thinking block to plain text on the next request.

func TargetFor

func TargetFor(m *core.Model, normalize func(string) string) Target

TargetFor builds a Target from a resolved model.

Jump to

Keyboard shortcuts

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