Documentation
¶
Overview ¶
Package anthropic is a client for the Anthropic (Claude) API, built on the goloop/ai interface.
The Client implements ai.Client, so Generate and Stream work the same as with any other goloop AI provider. On top of that it exposes Anthropic's native endpoints: the Messages API with Anthropic-only options (top_k, extended thinking, metadata and prompt caching), token counting, model listing and the message batches API.
c := anthropic.New(os.Getenv("ANTHROPIC_API_KEY"))
resp, err := c.Generate(ctx, &ai.Request{
Model: anthropic.ModelClaudeSonnet5,
Messages: []ai.Message{ai.UserText("Say hello in one word.")},
})
Structured output ¶
ai.Request.Format is honoured, but this provider has no response_format of its own, so the request is put to the model in the system prompt - in the wording every driver without native support shares - and ai.Response.Format reports ai.FormatEmulated. Read that literally: the model was asked, not constrained. ai.Response.JSON decodes the reply, unwrapping the code fence a model asked this way tends to add.
Hosted web search ¶
ai.Request.Hosted maps onto Anthropic's server-side web search tool, which rides in the same tools list as the caller's own:
resp, err := c.Generate(ctx, &ai.Request{
Model: anthropic.ModelClaudeSonnet5,
Messages: []ai.Message{ai.UserText("What shipped this week?")},
Hosted: []ai.Hosted{{Kind: ai.HostedWebSearch}},
})
for _, c := range resp.Citations() { ... }
The provider runs the search itself, so its own tool blocks never surface as ai.ToolUse parts: a tool loop sees nothing new and has nothing extra to answer. The sources come back as ai.Citation values on the text they support. Anthropic reports the fragment of the source it used rather than a position in the answer, so Citation.CitedText is filled and the byte range stays zero.
ai.Response.Hosted says whether the search actually ran. A model offered a search can answer without it, and the two answers are indistinguishable from the outside; ai.HostedRequired turns that into ai.ErrHostedRequired instead of an answer that only looks researched.
Anthropic takes either allowed or blocked domains, never both, so a request that sets both is ai.ErrNoHosted before it leaves. The tool is versioned by date; WithWebSearchTool reaches a version newer than WebSearchToolType.
Search combines with a Format here, because this driver has no native structured output to conflict with it: the format is asked for in the system prompt either way.
Asking what this driver can do ¶
Capabilities describes this driver for the decision taken before a call: whether to offer a feature at all, and whether it needs one request or two.
if ai.SupportsHosted(c, ai.Hosted{Kind: ai.HostedWebSearch}) { ... }
It is a hint and not a permission - support also depends on the model, the account and the region - so ai.ErrNoHosted and ai.ErrNoFormat remain the source of truth and a caller still handles them. What changes is that a refusal the provider only reports as a 400 now arrives as those same sentinels, wrapped around the original ai.APIError, so one errors.Is covers a limitation this driver knew in advance and one it learned over the wire.
It speaks the Messages API, including system prompts, multimodal image input, tool use and streaming, and depends only on goloop/ai and the standard library.
Index ¶
- Constants
- Variables
- type Batch
- type BatchCounts
- type BatchItem
- type BatchResult
- type CacheControl
- type Citation
- type Client
- func (c *Client) BatchResults(ctx context.Context, b *Batch) ([]BatchResult, error)
- func (c *Client) CancelBatch(ctx context.Context, id string) (*Batch, error)
- func (c *Client) Capabilities() ai.Capabilities
- func (c *Client) CountTokens(ctx context.Context, req *ai.Request) (int, error)
- func (c *Client) CreateBatch(ctx context.Context, items []BatchItem) (*Batch, error)
- func (c *Client) Generate(ctx context.Context, req *ai.Request) (*ai.Response, error)
- func (c *Client) GetBatch(ctx context.Context, id string) (*Batch, error)
- func (c *Client) GetModel(ctx context.Context, id string) (*Model, error)
- func (c *Client) ListBatches(ctx context.Context) ([]Batch, error)
- func (c *Client) Messages(ctx context.Context, req *MessagesRequest) (*MessagesResponse, error)
- func (c *Client) MessagesStream(ctx context.Context, req *MessagesRequest) iter.Seq2[StreamEvent, error]
- func (c *Client) Models(ctx context.Context) ([]Model, error)
- func (c *Client) Stream(ctx context.Context, req *ai.Request) iter.Seq2[ai.Chunk, error]
- type ContentBlock
- type MessageParam
- type MessagesRequest
- type MessagesResponse
- type Metadata
- type Model
- type Option
- func WithBaseURL(u string) Option
- func WithBeta(features ...string) Option
- func WithHTTPClient(c *http.Client) Option
- func WithHeader(key, value string) Option
- func WithMaxRetries(n int) Option
- func WithMaxTokens(n int) Option
- func WithTimeout(d time.Duration) Option
- func WithVersion(v string) Option
- func WithWebSearchTool(t string) Option
- type ServerToolUse
- type Source
- type StreamDelta
- type StreamEvent
- type Thinking
- type ToolChoice
- type ToolDefinition
- type Usage
- type UserLocation
- type WebSearchResult
Examples ¶
Constants ¶
const ( // DefaultBaseURL is the Anthropic API base URL. DefaultBaseURL = "https://api.anthropic.com" // DefaultVersion is the anthropic-version header sent with every request. DefaultVersion = "2023-06-01" // DefaultMaxTokens is used when a Request leaves MaxTokens unset, which the // Messages API requires. DefaultMaxTokens = 1024 )
Defaults for a new Client.
const ( ModelClaudeSonnet5 = "claude-sonnet-5" ModelClaudeOpus48 = "claude-opus-4-8" ModelClaudeHaiku45 = "claude-haiku-4-5-20251001" )
Convenience model identifiers for the current model generation. Any model string is accepted; use Models to discover what the account can call.
const WebSearchToolType = "web_search_20250305"
WebSearchToolType is the identifier of Anthropic's server-side web search tool. Anthropic versions its server tools by date and keeps older versions working, so the identifier is a constant here and can be replaced with WithWebSearchTool when a newer one ships before this package names it.
Variables ¶
var ErrNoResults = errors.New("anthropic: batch results are not ready")
ErrNoResults is returned by BatchResults when a batch has not produced a results URL yet (it has not finished processing).
Functions ¶
This section is empty.
Types ¶
type Batch ¶
type Batch struct {
ID string `json:"id"`
Type string `json:"type"`
ProcessingStatus string `json:"processing_status"`
RequestCounts BatchCounts `json:"request_counts"`
CreatedAt time.Time `json:"created_at"`
EndedAt *time.Time `json:"ended_at"`
ExpiresAt *time.Time `json:"expires_at"`
ResultsURL string `json:"results_url"`
}
Batch is the state of a message batch.
type BatchCounts ¶
type BatchCounts struct {
Processing int `json:"processing"`
Succeeded int `json:"succeeded"`
Errored int `json:"errored"`
Canceled int `json:"canceled"`
Expired int `json:"expired"`
}
BatchCounts breaks down how many requests are in each processing state.
type BatchItem ¶
BatchItem is one request in a message batch, tagged with a custom ID you choose so results can be correlated back to it.
type BatchResult ¶
type BatchResult struct {
CustomID string `json:"custom_id"`
Result json.RawMessage `json:"result"`
}
BatchResult is one line of a batch's results: a custom ID and the raw result object for that request.
type CacheControl ¶ added in v0.1.1
type CacheControl struct {
Type string `json:"type"`
}
CacheControl marks a prompt-caching breakpoint. Type is "ephemeral".
type Citation ¶ added in v1.0.0
type Citation struct {
Type string `json:"type"`
URL string `json:"url,omitempty"`
Title string `json:"title,omitempty"`
CitedText string `json:"cited_text,omitempty"`
EncryptedIndex string `json:"encrypted_index,omitempty"`
}
Citation is one source a server-side tool attached to a text block. Anthropic reports the fragment of the source it used rather than offsets into the answer, which is why ai.Citation carries CitedText and leaves its byte range at zero here.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an Anthropic API client. It implements ai.Client and adds the provider's native endpoints (token counting, models, message batches).
func New ¶
New returns a Client for the given API key. Shared options (WithBaseURL, WithHTTPClient, WithTimeout, WithMaxRetries, WithHeader) and Anthropic options (WithVersion, WithBeta, WithMaxTokens, WithWebSearchTool) configure it.
Example ¶
package main
import (
"fmt"
"github.com/goloop/anthropic"
)
func main() {
c := anthropic.New("sk-ant-...")
_ = c // use c.Generate, c.Stream, ...
fmt.Println(anthropic.ModelClaudeSonnet5)
}
Output: claude-sonnet-5
func (*Client) BatchResults ¶
BatchResults fetches and parses the JSONL results of a finished batch. The batch must have ended and carry a ResultsURL; otherwise ErrNoResults is returned.
func (*Client) CancelBatch ¶
CancelBatch requests cancellation of a batch still in progress.
func (*Client) Capabilities ¶ added in v1.1.0
func (c *Client) Capabilities() ai.Capabilities
Capabilities describes what this driver can be asked for. It is a hint for the decision taken before a call - whether to offer a feature, and whether it needs one request or two - and never a substitute for handling ai.ErrNoHosted, ai.ErrNoFormat or ai.ErrFormatWithHosted, because support also depends on the model, the account and the region.
func (*Client) CountTokens ¶
CountTokens reports how many input tokens the given request would use, without generating a response.
func (*Client) CreateBatch ¶
CreateBatch submits a set of message requests for asynchronous processing.
func (*Client) Generate ¶
Generate sends a single messages request and returns the whole response. It implements ai.Client.
Example ¶
ExampleClient_Generate builds a request. Sending it needs a real API key, so this example only shows the shape.
package main
import (
"fmt"
"github.com/goloop/ai"
"github.com/goloop/anthropic"
)
func main() {
req := &ai.Request{
Model: anthropic.ModelClaudeHaiku45,
MaxTokens: 128,
Messages: []ai.Message{
ai.UserText("Name the capital of France."),
},
}
fmt.Println(req.Model, len(req.Messages))
}
Output: claude-haiku-4-5-20251001 1
func (*Client) ListBatches ¶
ListBatches returns batches for the account, most recent first.
func (*Client) Messages ¶ added in v0.1.1
func (c *Client) Messages(ctx context.Context, req *MessagesRequest) (*MessagesResponse, error)
Messages sends a native Messages API request and returns the whole response. Use it for Anthropic-only options; use Client.Generate for the shared, provider-agnostic path.
Example ¶
ExampleClient_Messages shows the native Messages request, which reaches Anthropic-only options the shared ai.Request does not model: top_k, extended thinking, metadata and prompt caching via CacheControl.
package main
import (
"fmt"
"github.com/goloop/anthropic"
)
func main() {
topK := 40
req := &anthropic.MessagesRequest{
Model: anthropic.ModelClaudeSonnet5,
MaxTokens: 1024,
TopK: &topK,
Thinking: &anthropic.Thinking{Type: "enabled", BudgetTokens: 2048},
Messages: []anthropic.MessageParam{{
Role: "user",
Content: []anthropic.ContentBlock{{
Type: "text",
Text: "Summarize the document.",
CacheControl: &anthropic.CacheControl{Type: "ephemeral"},
}},
}},
}
fmt.Println(req.Model, *req.TopK)
}
Output: claude-sonnet-5 40
func (*Client) MessagesStream ¶ added in v0.1.1
func (c *Client) MessagesStream(ctx context.Context, req *MessagesRequest) iter.Seq2[StreamEvent, error]
MessagesStream sends a native streaming Messages request and yields each raw event as it arrives. Use it for Anthropic-only options; use Client.Stream for the shared, provider-agnostic chunk stream.
func (*Client) Stream ¶
Stream sends a messages request with streaming enabled and returns an iterator over response chunks. It implements ai.Client. Text deltas arrive as chunks with Text set; a completed tool call arrives as a chunk with ToolCall set; the final chunk has Done true and carries token usage.
type ContentBlock ¶ added in v0.1.1
type ContentBlock struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
Source *Source `json:"source,omitempty"`
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Input json.RawMessage `json:"input,omitempty"`
ToolUseID string `json:"tool_use_id,omitempty"`
Content string `json:"content,omitempty"`
IsError bool `json:"is_error,omitempty"`
CacheControl *CacheControl `json:"cache_control,omitempty"`
// Citations are the sources a server-side tool attached to a text block.
// They arrive on the reply only; nothing sends them back.
Citations []Citation `json:"citations,omitempty"`
// SearchResults holds what a "web_search_tool_result" block carried. That
// block puts a list where every other block puts a string, which is why
// it needs a field of its own rather than sharing Content. It is filled
// on decoding and never sent.
SearchResults []WebSearchResult `json:"-"`
}
ContentBlock is one block of a message's content. The Type field selects which of the remaining fields apply: "text", "image", "tool_use" or "tool_result". Set CacheControl to mark a cache breakpoint up to this block.
func (*ContentBlock) UnmarshalJSON ¶ added in v1.0.0
func (b *ContentBlock) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a content block, accepting either shape of "content". A tool result the caller sent carries a string there; a search result the provider produced carries a list of pages. Without this, one search result block would fail the whole reply, and the reply is the answer.
type MessageParam ¶ added in v0.1.1
type MessageParam struct {
Role string `json:"role"`
Content []ContentBlock `json:"content"`
}
MessageParam is one input message: a role ("user" or "assistant") and its content blocks.
type MessagesRequest ¶ added in v0.1.1
type MessagesRequest struct {
Model string `json:"model"`
MaxTokens int `json:"max_tokens"`
System string `json:"system,omitempty"`
Messages []MessageParam `json:"messages"`
Tools []ToolDefinition `json:"tools,omitempty"`
ToolChoice *ToolChoice `json:"tool_choice,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
TopK *int `json:"top_k,omitempty"`
StopSequences []string `json:"stop_sequences,omitempty"`
Metadata *Metadata `json:"metadata,omitempty"`
Thinking *Thinking `json:"thinking,omitempty"`
Stream bool `json:"stream,omitempty"`
}
MessagesRequest is the native Messages API request body. The shared Client.Generate builds one from an ai.Request; build it directly to reach Anthropic-only options such as TopK, Thinking, Metadata and prompt caching via CacheControl.
type MessagesResponse ¶ added in v0.1.1
type MessagesResponse struct {
ID string `json:"id"`
Type string `json:"type"`
Role string `json:"role"`
Model string `json:"model"`
Content []ContentBlock `json:"content"`
StopReason string `json:"stop_reason"`
Usage Usage `json:"usage"`
}
MessagesResponse is the native Messages API response.
type Metadata ¶ added in v0.1.1
type Metadata struct {
UserID string `json:"user_id,omitempty"`
}
Metadata carries request metadata, such as an opaque end-user identifier for abuse monitoring.
type Model ¶
type Model struct {
ID string `json:"id"`
DisplayName string `json:"display_name"`
CreatedAt time.Time `json:"created_at"`
Type string `json:"type"`
}
Model describes a model returned by the models endpoint.
type Option ¶
type Option func(*settings)
Option configures a Client in New.
func WithBaseURL ¶
WithBaseURL overrides the API base URL (proxies, gateways, mock servers).
func WithHTTPClient ¶
WithHTTPClient sets the HTTP client used for requests.
func WithHeader ¶
WithHeader adds a header sent with every request.
func WithMaxRetries ¶
WithMaxRetries sets how many times a request is retried on 429 and 5xx.
func WithMaxTokens ¶
WithMaxTokens sets the default max_tokens used when a Request leaves it unset.
func WithTimeout ¶
WithTimeout sets the per-request timeout when no custom HTTP client is set.
func WithVersion ¶
WithVersion overrides the anthropic-version header.
func WithWebSearchTool ¶ added in v1.0.0
WithWebSearchTool overrides the identifier of the server-side web search tool, which defaults to WebSearchToolType. Anthropic versions its server tools by date, so this is the way to reach a newer one without waiting for this package to name it.
type ServerToolUse ¶ added in v1.0.0
type ServerToolUse struct {
WebSearchRequests int `json:"web_search_requests,omitempty"`
}
ServerToolUse counts how many times Anthropic ran each of its own tools for a request.
type Source ¶ added in v0.1.1
type Source struct {
Type string `json:"type"`
MediaType string `json:"media_type,omitempty"`
Data string `json:"data,omitempty"`
URL string `json:"url,omitempty"`
}
Source is the origin of an image block: inline base64 data or a URL.
type StreamDelta ¶ added in v0.1.1
type StreamDelta struct {
Type string `json:"type"`
Text string `json:"text"`
PartialJSON string `json:"partial_json"`
StopReason string `json:"stop_reason"`
// Citation carries one source, on a delta of type "citations_delta".
Citation *Citation `json:"citation,omitempty"`
}
StreamDelta is the incremental payload of a content_block_delta or message_delta event.
type StreamEvent ¶ added in v0.1.1
type StreamEvent struct {
Type string `json:"type"`
Index int `json:"index"`
Message *MessagesResponse `json:"message"`
ContentBlock *ContentBlock `json:"content_block"`
Delta *StreamDelta `json:"delta"`
Usage *Usage `json:"usage"`
Error *struct {
Type string `json:"type"`
Message string `json:"message"`
} `json:"error"`
}
StreamEvent is one raw event of a streaming Messages response. The Type field selects which fields are populated ("message_start", "content_block_ start", "content_block_delta", "content_block_stop", "message_delta", "message_stop", "error").
type Thinking ¶ added in v0.1.1
type Thinking struct {
Type string `json:"type"`
BudgetTokens int `json:"budget_tokens,omitempty"`
}
Thinking enables extended thinking. Set Type to "enabled" and BudgetTokens to the number of tokens the model may spend reasoning before it answers.
type ToolChoice ¶ added in v0.1.1
ToolChoice controls whether and how the model may call tools. Type is "auto", "any", "tool" (with Name) or "none".
type ToolDefinition ¶ added in v0.1.1
type ToolDefinition struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
InputSchema json.RawMessage `json:"input_schema,omitempty"`
CacheControl *CacheControl `json:"cache_control,omitempty"`
// Type names a server-side tool. It is empty for a caller's own tool,
// which is how the Messages API tells the two apart.
Type string `json:"type,omitempty"`
// MaxUses bounds how many times Anthropic may run the tool.
MaxUses int `json:"max_uses,omitempty"`
// AllowedDomains and BlockedDomains narrow a search. Anthropic rejects a
// request that sets both.
AllowedDomains []string `json:"allowed_domains,omitempty"`
BlockedDomains []string `json:"blocked_domains,omitempty"`
// UserLocation biases results towards a place.
UserLocation *UserLocation `json:"user_location,omitempty"`
}
ToolDefinition declares a tool the model may call. InputSchema is a JSON Schema object describing the tool's arguments.
The same list also carries Anthropic's own server-side tools, which is how the Messages API takes them: those set Type to a versioned tool identifier such as WebSearchToolType, carry no schema, and are answered by Anthropic rather than by the caller. The fields below Type only apply to those.
type Usage ¶ added in v0.1.1
type Usage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"`
// ServerToolUse counts work Anthropic did on its own side. It is billed
// apart from tokens, so it is the only place the cost of a search shows.
ServerToolUse *ServerToolUse `json:"server_tool_use,omitempty"`
}
Usage reports token counts for a request. Cache fields are populated when prompt caching is used.
type UserLocation ¶ added in v1.0.0
type UserLocation struct {
Type string `json:"type"`
City string `json:"city,omitempty"`
Region string `json:"region,omitempty"`
Country string `json:"country,omitempty"`
Timezone string `json:"timezone,omitempty"`
}
UserLocation biases search results towards a place. Type is "approximate".
type WebSearchResult ¶ added in v1.0.0
type WebSearchResult struct {
Type string `json:"type"`
URL string `json:"url,omitempty"`
Title string `json:"title,omitempty"`
PageAge string `json:"page_age,omitempty"`
EncryptedContent string `json:"encrypted_content,omitempty"`
}
WebSearchResult is one page a server-side search found.