api

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 4, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

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

AnthropicVersion is the value sent for the `anthropic-version` header on every request. Hardcoded to match decoded/0168.js:370.

View Source
const SDKPackageVersion = "0.81.0"

SDKPackageVersion is the @anthropic-ai/sdk version we identify as. The real CLI bundles SDK 0.81.0 (decoded/0133.js:7); since Anthropic's API rate-limits clients whose Stainless headers don't look like the official CLI's, we report the same string.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Type    string `json:"type"`
	Message string `json:"message"`
}

APIError is the inner error body.

type APIErrorEnvelope

type APIErrorEnvelope struct {
	Type  string   `json:"type"`
	Error APIError `json:"error"`
}

APIErrorEnvelope is the shape Anthropic returns on 4xx/5xx.

type CacheControl

type CacheControl struct {
	Type  string `json:"type"`            // "ephemeral"
	TTL   string `json:"ttl,omitempty"`   // "5m" | "1h"
	Scope string `json:"scope,omitempty"` // "global" (optional)
}

CacheControl mirrors the prompt-caching directive on system / message blocks.

type Client

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

Client posts to /v1/messages.

func NewClient

func NewClient(cfg Config, httpClient *http.Client) *Client

NewClient returns a Client. If httpClient is nil, http.DefaultClient is used.

func NewClientWithProxy

func NewClientWithProxy(cfg Config) *Client

NewClientWithProxy builds a Client whose transport honours HTTPS_PROXY / HTTP_PROXY environment variables (via http.ProxyFromEnvironment). This is the recommended constructor for production use; NewClient is kept for tests that supply their own httptest.Server transport.

func (*Client) CreateMessage

func (c *Client) CreateMessage(ctx context.Context, req *MessageRequest) (*MessageResponse, error)

CreateMessage performs a non-streaming POST /v1/messages?beta=true.

On 401 the Client invokes OnAuth401 to refresh credentials, then retries the same request once. Reference: decoded/4500.js:32-44 (single retry on 401 after refresh handler runs).

Errors from the API are returned as a fmt.Errorf-wrapped error containing the error type and message, so callers can `errors.As` against APIError for finer control once we add typed errors in M2.

func (*Client) SetAuthToken

func (c *Client) SetAuthToken(tok string)

SetAuthToken updates the bearer token used for subsequent requests. Safe to call from any goroutine, including from inside an OnAuth401 callback.

func (*Client) StreamMessage

func (c *Client) StreamMessage(ctx context.Context, req *MessageRequest) (*Stream, error)

StreamMessage opens an event-stream connection to /v1/messages?beta=true. Headers and 401 retry mirror CreateMessage. The caller is responsible for reading until io.EOF and calling Close.

Reference: decoded/0158.js (create), 0137.js (SSE consumption), 4500.js (retry semantics). The wire is HTTP+SSE — no protobuf/binary framing.

type Config

type Config struct {
	// BaseURL is the API origin, e.g. https://api.anthropic.com. No trailing slash.
	BaseURL string
	// AuthToken is the OAuth bearer token. Required when APIKey is empty.
	// Mutually exclusive with APIKey at runtime — set exactly one.
	AuthToken string
	// APIKey is the legacy x-api-key. Set this xor AuthToken.
	APIKey string
	// BetaHeaders are joined into the `anthropic-beta` header.
	// For OAuth-Max users include "oauth-2025-04-20".
	BetaHeaders []string
	// SessionID becomes the X-Claude-Code-Session-Id header.
	SessionID string
	// UserAgent overrides the default User-Agent. Leave empty for default.
	UserAgent string
	// ClaudeCodeID is the value of the `x-app` header. Defaults to "cli".
	ClaudeCodeID string
	// OnAuth401 is called when the API returns 401 to refresh credentials.
	// It must update the same Client's AuthToken and return nil to retry,
	// or return an error to surface to the caller. The retry is done at
	// most once per outbound request. Reference: decoded/4500.js:32-44.
	OnAuth401 func(ctx context.Context) error
	// ExtraHeaders are merged into every request after the standard set.
	// Use for headers like `anthropic-dangerous-direct-browser-access` that
	// the real CLI sends but aren't part of the canonical core set.
	ExtraHeaders map[string]string
}

Config configures a Client.

type ContentBlock

type ContentBlock struct {
	// Common
	Type string `json:"type"` // "text" | "image" | "document" | "tool_use" | "tool_result"

	// type=text
	Text string `json:"text,omitempty"`

	// type=image or type=document (user-sent content — clipboard paste, file attach)
	// For documents: source.media_type = "application/pdf"
	Source *ImageSource `json:"source,omitempty"`

	// type=tool_use (assistant → us)
	ID    string         `json:"id,omitempty"`    // tool use ID, e.g. "toolu_01..."
	Name  string         `json:"name,omitempty"`  // tool name
	Input map[string]any `json:"input,omitempty"` // parsed tool input

	// type=tool_result (us → assistant, in a user-role message)
	ToolUseID string `json:"tool_use_id,omitempty"` // matches ID from tool_use block
	IsError   bool   `json:"is_error,omitempty"`
	// Content for tool_result: string or []ContentBlock. We send string for simplicity.
	ResultContent string `json:"content,omitempty"`
}

ContentBlock is one block of content in a message. Union of text | image | document | tool_use | tool_result. Fields are set according to Type.

type ImageSource

type ImageSource struct {
	Type      string `json:"type"`       // "base64"
	MediaType string `json:"media_type"` // "image/png" | "image/jpeg" | "image/gif" | "image/webp"
	Data      string `json:"data"`       // base64-encoded bytes
}

ImageSource is the source payload for a type=image content block. Mirrors the Anthropic API image source shape.

type Message

type Message struct {
	Role    string         `json:"role"` // "user" | "assistant"
	Content []ContentBlock `json:"content"`
}

Message is one turn in the conversation.

type MessageRequest

type MessageRequest struct {
	Model     string         `json:"model"`
	MaxTokens int            `json:"max_tokens"`
	System    []SystemBlock  `json:"system,omitempty"`
	Messages  []Message      `json:"messages"`
	Stream    bool           `json:"stream,omitempty"`
	Tools     []ToolDef      `json:"tools,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
	// Thinking enables extended thinking (interleaved-thinking-2025-05-14 beta).
	// When non-nil, sent as {"type":"enabled","budget_tokens":N}.
	Thinking *ThinkingConfig `json:"thinking,omitempty"`
}

MessageRequest is the body of POST /v1/messages.

type MessageResponse

type MessageResponse 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"`
}

MessageResponse is the JSON response shape from a non-streaming Messages call.

type Stream

type Stream struct {

	// ResponseHeader holds the HTTP response headers from the initial connection.
	// Use this to read rate-limit headers (anthropic-ratelimit-*).
	ResponseHeader http.Header
	// contains filtered or unexported fields
}

Stream is an open SSE connection. Call Next() until io.EOF; always Close().

func (*Stream) Close

func (s *Stream) Close() error

Close releases the underlying HTTP connection. Safe to call multiple times.

func (*Stream) Next

func (s *Stream) Next() (sse.Event, error)

Next returns the next non-skipped event, or io.EOF when the stream ends. Sentinel: a *sse.Error means the API surfaced an error event mid-stream.

type SystemBlock

type SystemBlock struct {
	Type         string        `json:"type"`
	Text         string        `json:"text"`
	CacheControl *CacheControl `json:"cache_control,omitempty"`
}

SystemBlock is one block of the multi-block `system` field.

type ThinkingConfig

type ThinkingConfig struct {
	Type         string `json:"type"`          // always "enabled"
	BudgetTokens int    `json:"budget_tokens"` // token budget for thinking
}

ThinkingConfig enables the extended thinking feature. Reference: interleaved-thinking-2025-05-14 beta, effort-2025-11-24 beta.

type ToolDef

type ToolDef struct {
	// Type is the tool type. Empty means standard custom tool. Examples of
	// native types: "web_search_20250305".
	Type        string         `json:"type,omitempty"`
	Name        string         `json:"name,omitempty"`
	Description string         `json:"description,omitempty"`
	InputSchema map[string]any `json:"input_schema,omitempty"`

	// Extra holds additional native-tool fields (e.g. max_uses, allowed_domains).
	// Keys from Extra are merged into the JSON output via custom MarshalJSON.
	Extra map[string]any `json:"-"`
}

ToolDef is a tool declaration in the request `tools` array. For standard tools: Name, Description, InputSchema are set; Type is empty (defaults to "custom"). For native server tools (e.g. web_search_20250305): Type is set; other fields may be empty.

func (ToolDef) MarshalJSON

func (td ToolDef) MarshalJSON() ([]byte, error)

MarshalJSON serialises ToolDef, merging Extra fields into the top-level object.

type Usage

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"`
}

Usage is the token counter block returned with every response.

Jump to

Keyboard shortcuts

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