Documentation
¶
Index ¶
- func HasWithoutEnvironmentDefaults(opts []RequestOption) bool
- type FederationOptions
- type HTTPClient
- type IdentityTokenFunc
- type Middleware
- type MiddlewareNext
- type OpenTelemetryContentMode
- type RequestOption
- func Join(opts ...RequestOption) RequestOption
- func WithAPIKey(value string) RequestOption
- func WithAuthToken(value string) RequestOption
- func WithBaseURL(base string) RequestOption
- func WithConfig(cfg *config.Config) RequestOption
- func WithConfigQuiet(cfg *config.Config) RequestOption
- func WithDebugLog(logger *log.Logger) RequestOption
- func WithEnvironmentProduction() RequestOption
- func WithFederationTokenProvider(provider IdentityTokenFunc, opts FederationOptions) RequestOption
- func WithHTTPClient(client HTTPClient) RequestOption
- func WithHeader(key, value string) RequestOption
- func WithHeaderAdd(key, value string) RequestOption
- func WithHeaderDel(key string) RequestOption
- func WithJSONDel(key string) RequestOption
- func WithJSONSet(key string, value any) RequestOption
- func WithMaxRetries(retries int) RequestOption
- func WithMiddleware(middlewares ...Middleware) RequestOption
- func WithOpenTelemetryConversationID(id string) RequestOption
- func WithOpenTelemetryPropagation(enabled bool) RequestOption
- func WithOpenTelemetryTraces(enabled bool) RequestOption
- func WithOpenTelemetryTracesContentMode(mode OpenTelemetryContentMode) RequestOption
- func WithOpenTelemetryTracesMaxContentBytes(maxBytes int64) RequestOption
- func WithProfile(name string) RequestOption
- func WithQuery(key, value string) RequestOption
- func WithQueryAdd(key, value string) RequestOption
- func WithQueryDel(key string) RequestOption
- func WithRequestBody(contentType string, body any) RequestOption
- func WithRequestTimeout(dur time.Duration) RequestOption
- func WithResponseBodyInto(dst any) RequestOption
- func WithResponseInto(dst **http.Response) RequestOption
- func WithTracerProvider(provider trace.TracerProvider) RequestOption
- func WithWebhookKey(value string) RequestOption
- func WithoutEnvironmentDefaults() RequestOption
- func WithoutOpenTelemetry() RequestOption
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func HasWithoutEnvironmentDefaults ¶ added in v1.39.0
func HasWithoutEnvironmentDefaults(opts []RequestOption) bool
HasWithoutEnvironmentDefaults reports whether opts contains a WithoutEnvironmentDefaults marker, looking inside options combined with Join at any depth. Used by anthropic.NewClient to decide whether to prepend anthropic.DefaultClientOptions.
Types ¶
type FederationOptions ¶ added in v1.39.0
type FederationOptions struct {
// FederationRuleID identifies the OidcFederationRule governing this
// exchange. Required; must be a tagged ID with the "fdrl_" prefix.
FederationRuleID string
// OrganizationID is the UUID of the Anthropic organization the
// federation rule belongs to. Required.
OrganizationID string
// ServiceAccountID is an optional expected-target check for federation
// rules with target_type=SERVICE_ACCOUNT. Must be a tagged ID with the
// "svac_" prefix. Omit for target_type=USER rules, where the principal
// is derived from the JWT claims.
ServiceAccountID string
// WorkspaceID is an optional `wrkspc_*` tagged ID, or the literal
// "default" to scope the token to the organization's default workspace.
// When omitted the server picks the rule's sole enabled workspace, else
// the org default if the rule covers it. Required when the rule enables
// more than one non-default workspace, or to target a specific workspace
// other than the one the server would pick. The minted token is
// workspace-scoped: per-request workspace selection (the
// anthropic-workspace-id header) is not supported for federation
// tokens — switching workspaces requires a new token exchange with a
// different WorkspaceID.
WorkspaceID string
}
FederationOptions configures a federation-based token exchange.
type HTTPClient ¶
HTTPClient is primarily used to describe an *http.Client, but also supports custom implementations.
For bespoke implementations, prefer using an *http.Client with a custom transport. See http.RoundTripper for further information.
type IdentityTokenFunc ¶ added in v1.39.0
IdentityTokenFunc returns a fresh JWT identity token (e.g. from SPIFFE/SPIRE, the GCP metadata server, or any other OIDC-compatible provider). It is invoked once per federation token exchange; implementations should be safe for concurrent use.
func IdentityTokenFile ¶ added in v1.39.0
func IdentityTokenFile(path string) IdentityTokenFunc
IdentityTokenFile returns an IdentityTokenFunc that reads a JWT from path on each invocation. Use it for Kubernetes projected service account tokens and similar rotating on-disk credentials — the file is re-read on every federation exchange so rotations are picked up automatically. Surrounding whitespace is trimmed; an empty file is treated as an error.
Passing this as the provider to WithFederationTokenProvider takes precedence over the ANTHROPIC_IDENTITY_TOKEN_FILE environment variable: explicit options always beat env-var auto-discovery. The env var only applies when the client is constructed without a WithFederationTokenProvider option (or equivalent).
The returned function is safe for concurrent use.
Typical usage:
client := anthropic.NewClient(
option.WithFederationTokenProvider(
option.IdentityTokenFile("/var/run/secrets/anthropic.com/token"),
option.FederationOptions{
FederationRuleID: "fdrl_...",
OrganizationID: os.Getenv("ANTHROPIC_ORGANIZATION_ID"),
},
),
)
type Middleware ¶
Middleware is a function which intercepts HTTP requests, processing or modifying them, and then passing the request to the next middleware or handler in the chain by calling the provided MiddlewareNext function.
type MiddlewareNext ¶
MiddlewareNext is a function which is called by a middleware to pass an HTTP request to the next stage in the middleware chain.
type OpenTelemetryContentMode ¶ added in v1.81.0
type OpenTelemetryContentMode string
OpenTelemetryContentMode is whether the OpenTelemetry spans carry the content of requests and responses.
const ( // OpenTelemetryContentModeMetadataOnly leaves the content out of the spans. OpenTelemetryContentModeMetadataOnly OpenTelemetryContentMode = "metadata_only" // OpenTelemetryContentModeContent puts the content in the spans. OpenTelemetryContentModeContent OpenTelemetryContentMode = "content" )
type RequestOption ¶
type RequestOption = requestconfig.RequestOption
RequestOption is an option for the requests made by the anthropic API Client which can be supplied to clients, services, and methods. You can read more about this functional options pattern in our README.
func Join ¶ added in v1.63.1
func Join(opts ...RequestOption) RequestOption
Join returns a single RequestOption that applies opts in order, at the position the joined option occupies in the caller's option list. It is equivalent to passing opts individually at that position, and lets a function that configures several aspects of a client return one option:
func WithPlatform(cfg Config) option.RequestOption {
return option.Join(
option.WithoutEnvironmentDefaults(),
option.WithBaseURL(cfg.URL),
option.WithMiddleware(cfg.middleware()),
)
}
A WithoutEnvironmentDefaults marker nested inside a Join (at any depth) is still recognized by anthropic.NewClient.
func WithAPIKey ¶
func WithAPIKey(value string) RequestOption
WithAPIKey returns a RequestOption that sets the client setting "api_key".
func WithAuthToken ¶
func WithAuthToken(value string) RequestOption
WithAuthToken returns a RequestOption that sets the client setting "auth_token".
func WithBaseURL ¶
func WithBaseURL(base string) RequestOption
WithBaseURL returns a RequestOption that sets the BaseURL for the client.
For security reasons, ensure that the base URL is trusted.
func WithConfig ¶ added in v1.39.0
func WithConfig(cfg *config.Config) RequestOption
WithConfig returns a RequestOption that authenticates requests using the given config.Config.
Credential resolution is deferred to a request-time middleware so a later WithAPIKey / WithAuthToken (tier-1 explicit-credential precedence) can preempt the profile — even when the profile's credentials are missing or broken. The same escape-hatch shape as [explicitProfileErrorOption] applies: if the final RequestConfig has a static APIKey/AuthToken, or the request already carries an Authorization / X-Api-Key header, the profile is treated as shadowed and resolution is skipped entirely.
The config's non-credential fields (BaseURL, WorkspaceID) apply at option-Apply time and do not depend on credential resolution. BaseURL only takes effect when no explicit WithBaseURL is present.
When a static credential shadows the profile, a one-shot warning is emitted so users migrating from API keys can tell why their profile is being ignored. Use WithConfigQuiet to suppress that warning when the caller has its own, richer diagnostic.
func WithConfigQuiet ¶ added in v1.39.0
func WithConfigQuiet(cfg *config.Config) RequestOption
WithConfigQuiet is identical to WithConfig but suppresses the one-shot "static credential shadows profile" warning. Intended for callers (such as the CLI) that detect the same condition themselves and emit a more specific multi-auth diagnostic, so users don't see two warnings for the same thing.
func WithDebugLog ¶ added in v1.5.0
func WithDebugLog(logger *log.Logger) RequestOption
WithDebugLog logs the HTTP request and response content. If the logger parameter is nil, it uses the default logger.
WithDebugLog is for debugging and development purposes only. It should not be used in production code. The behavior and interface of WithDebugLog is not guaranteed to be stable.
func WithEnvironmentProduction ¶
func WithEnvironmentProduction() RequestOption
WithEnvironmentProduction returns a RequestOption that sets the current environment to be the "production" environment. An environment specifies which base URL to use by default.
func WithFederationTokenProvider ¶ added in v1.39.0
func WithFederationTokenProvider(provider IdentityTokenFunc, opts FederationOptions) RequestOption
WithFederationTokenProvider returns a RequestOption that authenticates requests using workload identity federation, exchanging a caller-supplied identity token for a short-lived Anthropic access token. Use this to integrate custom OIDC token sources (SPIFFE/SPIRE, cloud provider SDKs, etc.) without staging the token through a file.
provider is called on each token exchange to fetch a fresh JWT. opts.FederationRuleID and opts.OrganizationID are required.
The auth.TokenCache built by auth.WithAuthMiddleware is shared across requests, so a token is only re-exchanged when it enters the refresh window.
func WithHTTPClient ¶
func WithHTTPClient(client HTTPClient) RequestOption
WithHTTPClient returns a RequestOption that changes the underlying http client used to make this request, which by default is http.DefaultClient.
For custom uses cases, it is recommended to provide an *http.Client with a custom http.RoundTripper as its transport, rather than directly implementing HTTPClient.
func WithHeader ¶
func WithHeader(key, value string) RequestOption
WithHeader returns a RequestOption that sets the header value to the associated key. It overwrites any value if there was one already present.
func WithHeaderAdd ¶
func WithHeaderAdd(key, value string) RequestOption
WithHeaderAdd returns a RequestOption that adds the header value to the associated key. It appends onto any existing values.
func WithHeaderDel ¶
func WithHeaderDel(key string) RequestOption
WithHeaderDel returns a RequestOption that deletes the header value(s) associated with the given key.
func WithJSONDel ¶
func WithJSONDel(key string) RequestOption
WithJSONDel returns a RequestOption that deletes the body's JSON value associated with the key. The key accepts a string as defined by the sjson format.
func WithJSONSet ¶
func WithJSONSet(key string, value any) RequestOption
WithJSONSet returns a RequestOption that sets the body's JSON value associated with the key. The key accepts a string as defined by the sjson format.
func WithMaxRetries ¶
func WithMaxRetries(retries int) RequestOption
WithMaxRetries returns a RequestOption that sets the maximum number of retries that the client attempts to make. When given 0, the client only makes one request. By default, the client retries two times.
WithMaxRetries panics when retries is negative.
func WithMiddleware ¶
func WithMiddleware(middlewares ...Middleware) RequestOption
WithMiddleware returns a RequestOption that applies the given middleware to the requests made. Each middleware will execute in the order they were given.
func WithOpenTelemetryConversationID ¶ added in v1.81.0
func WithOpenTelemetryConversationID(id string) RequestOption
WithOpenTelemetryConversationID returns a RequestOption that links the calls it applies to into one conversation, with an ID that the application chooses.
The SDK does not send the ID to the API. It sets the gen_ai.conversation.id attribute on the OpenTelemetry span of each call. A tool runner passes the option to each request it sends, so every span of its loop has the same ID.
Without the option, the span of a call to a Session thread has the thread's ID as its conversation ID, as the API's spans of the thread have, and the span of any other call has none.
func WithOpenTelemetryPropagation ¶ added in v1.81.0
func WithOpenTelemetryPropagation(enabled bool) RequestOption
WithOpenTelemetryPropagation returns a RequestOption that turns the trace-context headers of the requests of API calls on or off, and leaves the spans as they are. They are on by default: turn them off when the instrumentation of your HTTP client already sends the trace context, so that a request does not carry it twice.
Without this option, the environment variable ANTHROPIC_OPEN_TELEMETRY_PROPAGATION turns them off when its value is "false".
func WithOpenTelemetryTraces ¶ added in v1.81.0
func WithOpenTelemetryTraces(enabled bool) RequestOption
WithOpenTelemetryTraces returns a RequestOption that turns the OpenTelemetry spans of API calls, and the trace-context headers of their requests, on or off. They are on by default.
Without this option, or WithoutOpenTelemetry, the environment variable ANTHROPIC_OPEN_TELEMETRY turns them off when its value is "false".
func WithOpenTelemetryTracesContentMode ¶ added in v1.81.0
func WithOpenTelemetryTracesContentMode(mode OpenTelemetryContentMode) RequestOption
WithOpenTelemetryTracesContentMode returns a RequestOption that sets whether the OpenTelemetry spans of API calls carry the content of requests and responses. The default is OpenTelemetryContentModeMetadataOnly.
Without this option, the environment variable ANTHROPIC_OPEN_TELEMETRY_TRACES_CONTENT_MODE selects OpenTelemetryContentModeContent when its value is "content".
func WithOpenTelemetryTracesMaxContentBytes ¶ added in v1.81.0
func WithOpenTelemetryTracesMaxContentBytes(maxBytes int64) RequestOption
WithOpenTelemetryTracesMaxContentBytes returns a RequestOption that sets how many bytes of content the OpenTelemetry span of an API call carries at most, in OpenTelemetryContentModeContent. Content over the maximum is cut from the span, which then has the attribute anthropic.content.truncated. The default is 750,000 bytes, and so is a maximum below 1.
Without this option, the environment variable ANTHROPIC_OPEN_TELEMETRY_TRACES_MAX_CONTENT_BYTES sets the maximum when its value is a whole number of at least 1.
func WithProfile ¶ added in v1.39.0
func WithProfile(name string) RequestOption
WithProfile returns a RequestOption that loads the named profile from the default config directory (see config.DefaultDir) and authenticates requests using it — equivalent to setting ANTHROPIC_PROFILE=name and constructing a zero-config client. Shorthand for:
cfg, err := config.LoadProfile(config.DefaultDir(), name) ... option.WithConfig(cfg)
If the profile cannot be loaded, the error is deferred to the first request and is preempted by a static credential (WithAPIKey / WithAuthToken) — the same escape hatch as the ANTHROPIC_PROFILE env path. As with WithConfig, a static credential shadows the profile at request time and a one-shot warning is emitted.
func WithQuery ¶
func WithQuery(key, value string) RequestOption
WithQuery returns a RequestOption that sets the query value to the associated key. It overwrites any value if there was one already present.
func WithQueryAdd ¶
func WithQueryAdd(key, value string) RequestOption
WithQueryAdd returns a RequestOption that adds the query value to the associated key. It appends onto any existing values.
func WithQueryDel ¶
func WithQueryDel(key string) RequestOption
WithQueryDel returns a RequestOption that deletes the query value(s) associated with the key.
func WithRequestBody ¶
func WithRequestBody(contentType string, body any) RequestOption
WithRequestBody returns a RequestOption that provides a custom serialized body with the given content type.
body accepts an io.Reader or raw []bytes.
func WithRequestTimeout ¶
func WithRequestTimeout(dur time.Duration) RequestOption
WithRequestTimeout returns a RequestOption that sets the timeout for each request attempt. This should be smaller than the timeout defined in the context, which spans all retries.
An attempt that exceeds this timeout is retried (see WithMaxRetries) for as long as the context passed to the method is not done, so a call can take up to roughly (retries + 1) * dur plus backoff before it fails with context.DeadlineExceeded.
func WithResponseBodyInto ¶
func WithResponseBodyInto(dst any) RequestOption
WithResponseBodyInto returns a RequestOption that overwrites the deserialization target with the given destination. If provided, we don't deserialize into the default struct.
func WithResponseInto ¶
func WithResponseInto(dst **http.Response) RequestOption
WithResponseInto returns a RequestOption that copies the *http.Response into the given address.
func WithTracerProvider ¶ added in v1.81.0
func WithTracerProvider(provider trace.TracerProvider) RequestOption
WithTracerProvider returns a RequestOption that sets the OpenTelemetry tracer provider that creates the span of each API call, in place of the provider registered with the OpenTelemetry API. A nil provider selects the registered one.
The client emits spans without this option, through the registered provider.
func WithWebhookKey ¶ added in v1.41.0
func WithWebhookKey(value string) RequestOption
WithWebhookKey returns a RequestOption that sets the client setting "webhook_key".
func WithoutEnvironmentDefaults ¶ added in v1.39.0
func WithoutEnvironmentDefaults() RequestOption
WithoutEnvironmentDefaults returns a marker RequestOption that, when passed to anthropic.NewClient, causes it to skip the environment-based credential autoload performed by anthropic.DefaultClientOptions (ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_PROFILE, env federation, fallback profile, ANTHROPIC_BASE_URL). The hardcoded production base-URL default is still applied so callers that supply only credentials get a working client.
Intended for callers that perform their own credential resolution (such as the CLI) and want full control over which auth source is used, without the SDK's autoloader contributing a second WithConfig that would emit a duplicate shadow-warning.
func WithoutOpenTelemetry ¶ added in v1.81.0
func WithoutOpenTelemetry() RequestOption
WithoutOpenTelemetry returns a RequestOption that turns off the OpenTelemetry spans of API calls. It is the short form of WithOpenTelemetryTraces(false).