Documentation
¶
Overview ¶
Package anthropic is the weft adapter for the Anthropic Messages API, wrapping the official anthropic-sdk-go. weft never owns the HTTP: every request goes through the SDK's client, and the SDK's stream type is the contract.
Mapping highlights (ADR 0013 has the full tables):
- weft's batched RoleTool message is already Anthropic's shape: one user message with N tool_result blocks.
- Streamed input_json_delta argument fragments surface live as ModelToolCallDelta progress; the assembled call is emitted whole before ModelFinish.
- Empty content the API rejects never reaches the wire: an empty tool result travels as "(empty tool output)", a user message with no sendable parts as "(empty message)", and an assistant message with nothing sendable is skipped.
- Reasoning round-trips as thinking blocks with their signature; an unsigned ReasoningPart (a transcript from another provider) is dropped rather than failing the call.
- SequentialTools sets tool_choice.auto with disable_parallel_tool_use.
- ModelRequest.Thinking overrides the Thinking(true) construction default: Off disables explicitly, a Budget pins budget_tokens, a bare level sends adaptive (ADR 0013 amendment 9).
- max_tokens is required by the API; the adapter defaults it to 4096 when MaxTokens is not given.
- ModelRequest.Params folds over the construction Temperature/ TopP/Stop defaults. The Messages API has no seed: a RequestParams.Seed is dropped — seed is a determinism hint on every provider, not a contract (ADR 0013's 2026-09-22 amendment). TopK stays out for the same reason it is out everywhere: no other provider has it in Chat Completions.
Retry stance: transport retries (429, 5xx, net.Error) belong to the SDK via MaxRetries; the weft loop never retries a model call, and logic retries are model-seam middleware.
Vertex/Bedrock clients compose through Client(c).
Index ¶
- func Model(name string, opts ...Option) weft.Model
- type Option
- func APIKey(k string) Option
- func BaseURL(u string) Option
- func Client(c *anthropic.Client) Option
- func ExtraBody(fields map[string]any) Option
- func ExtraHeaders(h http.Header) Option
- func IdleTimeout(d time.Duration) Option
- func MaxRetries(n int) Option
- func MaxTokens(n int) Option
- func PromptCache() Option
- func Stop(seqs ...string) Option
- func Temperature(t float64) Option
- func Thinking(on bool) Option
- func TopP(p float64) Option
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Model ¶
Model returns a weft.Model backed by the Anthropic Messages API. A Model is immutable and safe for concurrent runs; tool definitions are converted per request (ADR 0013).
Example ¶
Constructing a model performs no I/O; a key ($ANTHROPIC_API_KEY) is read only when a run starts. Swap providers by swapping this one line.
package main
import (
"context"
"github.com/weftgo/weft"
"github.com/weftgo/weft/anthropic"
)
func main() {
m := anthropic.Model("claude-sonnet-5", anthropic.Thinking(true))
echo := weft.Tool("echo", "Echo a message.", func(ctx context.Context, in struct {
Message string `json:"message" jsonschema:"the text to repeat"`
}) (string, error) {
return in.Message, nil
})
agt := weft.New(m, echo)
_ = agt // a run is agt.Generate(ctx, weft.Prompt("Echo: hello"))
}
Output:
Types ¶
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option configures the adapter at construction, the same functional style as the core. The zero configuration reads $ANTHROPIC_API_KEY; the SDK's transport default applies (2 retries on 429/5xx/connection errors).
func BaseURL ¶
BaseURL points the adapter at a custom endpoint (a gateway, a proxy). Also read from $ANTHROPIC_BASE_URL when the option is not given.
func Client ¶
Client uses an already-configured SDK client (Vertex AI and Bedrock clients, test doubles); it overrides BaseURL, APIKey, and MaxRetries. The WEFT_MODEL_REQUESTS kill switch guards egress from clients the adapter builds from credentials; an injected client's destinations are the caller's responsibility — which is why it stays reachable under deny (ADR 0013's kill-switch clause).
func ExtraBody ¶ added in v0.3.0
ExtraBody adds fields to every request's JSON body — the generic valve for vendor knobs weft has no option for. Deep-merged into the body weft built: nested maps merge recursively, every other value replaces, and **your key wins on conflict** — the escape hatch is you taking responsibility for bytes weft did not choose, and the default-bytes tests do not cover what it sends. Construction-time only, and a snapshot: the values are deep-copied when the option applies, so mutating the map you passed afterwards never reaches the Model (safe for concurrent runs). It applies to the requests the adapter makes, including through an injected Client(c).
func ExtraHeaders ¶ added in v0.3.0
ExtraHeaders adds HTTP headers to every request, verbatim. A header the SDK itself sets (Authorization, Content-Type) is yours not to clobber — the option does not check. Construction-time only, and a snapshot: the slices are copied when the option applies, so mutating the header values you passed afterwards never reaches the Model.
func IdleTimeout ¶
IdleTimeout is the maximum gap between two stream events before the call fails wrapping weft.ErrStreamIdle (default 60s; zero disables it). The wait for response headers is the first gap: it covers the SDK's transport retries and their sleeps too (a 429 whose retry-after the SDK honours sleeps inside it), so a retry sequence longer than the timeout fails ErrStreamIdle with the provider's error discarded — hand retries to mw.Retry with MaxRetries(0), or raise the timeout. The ctx deadline stays the hard limit on the whole call — a slow but actively streaming response is never killed.
func MaxRetries ¶
MaxRetries sets the SDK's transport retry count (429/5xx/connection errors only; the SDK's own default is 2 when the option is absent). MaxRetries(0) switches the SDK's retries off — the pairing for mw.Retry, which then owns every retry and reads the provider's retry-after itself instead of the SDK sleeping on it under the idle timer (see IdleTimeout). A negative n is 0. The weft loop never retries a model call; logic retries are model-seam middleware (TODO §4.1).
func MaxTokens ¶
MaxTokens sets the per-step output-token limit. Anthropic requires the field; the adapter defaults it to 4096 when unset.
func PromptCache ¶ added in v0.3.0
func PromptCache() Option
PromptCache marks the request's stable prefix edges as cacheable: cache_control:{"type":"ephemeral"} on the system text block, the final tool definition, and the final content block of the final message — three of Anthropic's four breakpoint budget, placed where the transcript grows (Crush's placement; the fourth stays unspent for a compaction summary block). Opt-in: without the option no cache_control appears anywhere, and the request bytes are exactly v0.2.0's.
Economics: cache writes bill 1.25× and cache reads 0.1× the base input-token price, so a long transcript whose prefix repeats across steps saves from the second step on — watch Usage's CachedInputTokens and CacheWriteTokens to see it measured. Prefix discipline is the caller's: a PrepareStep function that trims messages invalidates the trailing breakpoint on purpose (the option composes with deliberate trimming, it does not forbid it), and weft.ToolChoiceNone is the way to stop tool calls without dropping the tool definitions — and the cache prefix they anchor — from the request. No TTL or position options in v0.3.0: one good default, revisit when a consumer asks.
func Stop ¶ added in v0.3.0
Stop sets stop sequences (stop_sequences); not sent unless the option is given. A per-request weft.RequestParams.Stop overrides it for one call. The Messages API has no seed — a RequestParams.Seed is dropped (see doc.go), because seed is a determinism hint everywhere, not a contract.
func Temperature ¶
Temperature sets the sampling temperature; it is not sent unless the option is given. A per-request weft.RequestParams.Temperature overrides it for one call.