client

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package client provides a clean wrapper around the Claude SDK client.

Package client provides resilience wrappers for API calls.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotConnected indicates the client is not connected.
	ErrNotConnected = errors.New("client not connected")

	// ErrInvalidProvider indicates an unsupported provider was specified.
	ErrInvalidProvider = errors.New("invalid provider")
)
View Source
var (
	// ErrCircuitOpen indicates the circuit breaker is open.
	ErrCircuitOpen = errors.New("circuit breaker is open")

	// ErrRateLimited indicates rate limiting is active.
	ErrRateLimited = errors.New("rate limited")

	// ErrMaxRetriesExceeded indicates all retry attempts failed.
	ErrMaxRetriesExceeded = errors.New("max retries exceeded")
)

Resilience errors.

Functions

This section is empty.

Types

type CharBasedCounter

type CharBasedCounter struct{}

CharBasedCounter estimates tokens as chars/4.

func (*CharBasedCounter) Count

func (c *CharBasedCounter) Count(text string) int

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	// Name identifies the circuit breaker.
	Name string

	// MaxRequests is the maximum number of requests allowed in half-open state.
	MaxRequests uint32

	// Interval is the cyclic period for clearing counts in closed state.
	Interval time.Duration

	// Timeout is the duration in open state before transitioning to half-open.
	Timeout time.Duration

	// ConsecutiveFailures is the number of consecutive failures to trip the breaker.
	ConsecutiveFailures uint32

	// OnStateChange is called when the circuit breaker state changes.
	OnStateChange func(name string, from, to gobreaker.State)
}

CircuitBreakerConfig configures the circuit breaker.

func DefaultCircuitBreakerConfig

func DefaultCircuitBreakerConfig() *CircuitBreakerConfig

DefaultCircuitBreakerConfig returns sensible defaults.

type Client

type Client interface {
	// Query sends a prompt and returns the complete response.
	Query(ctx context.Context, prompt string) (string, error)

	// QueryStream sends a prompt and streams the response.
	QueryStream(ctx context.Context, prompt string) (<-chan Message, <-chan error)

	// WithSystemPrompt returns a new client with the given system prompt.
	WithSystemPrompt(prompt string) Client

	// WithTools returns a new client with the given tools.
	WithTools(tools ...*Tool) Client

	// Close releases resources associated with the client.
	Close() error
}

Client provides a simplified interface for interacting with Claude.

func New

func New(ctx context.Context, sdkOpts []claude.ClientOption, clientOpts ...ClientOption) (Client, error)

New creates a new Client with the given SDK options.

type ClientOption

type ClientOption func(*clientOptions)

ClientOption configures a Client.

func WithCircuitBreaker

func WithCircuitBreaker(cfg *CircuitBreakerConfig) ClientOption

WithCircuitBreaker enables circuit breaker protection. Opens after consecutive failures, half-opens after timeout.

func WithRateLimiter

func WithRateLimiter(cfg *RateLimiterConfig) ClientOption

WithRateLimiter enables adaptive rate limiting with 429 detection.

func WithResilience

func WithResilience() ClientOption

WithResilience enables all resilience features with default configs.

func WithRetry

func WithRetry(cfg *RetryConfig) ClientOption

WithRetry enables retry with exponential backoff for transient failures.

type CompactionMessage

type CompactionMessage struct {
	Role    string
	Content string
	Tokens  int // Estimated token count
}

CompactionMessage represents a conversation message for compaction.

type Compactor

type Compactor interface {
	// ShouldCompact returns true if compaction is needed.
	ShouldCompact(messages []CompactionMessage, maxTokens int) bool

	// Compact summarizes messages to reduce token count.
	Compact(ctx context.Context, messages []CompactionMessage) ([]CompactionMessage, error)

	// EstimateTokens estimates token count for a message.
	EstimateTokens(content string) int
}

Compactor handles context compaction when approaching token limits.

type CompactorConfig

type CompactorConfig struct {
	// Threshold is the percentage of max tokens that triggers compaction (0.0-1.0).
	Threshold float64

	// KeepRecent is the number of recent messages to preserve uncompacted.
	KeepRecent int

	// SummaryPrompt is the prompt used for summarization.
	SummaryPrompt string

	// MaxSummaryTokens limits the summary size.
	MaxSummaryTokens int
}

CompactorConfig configures compaction behavior.

func DefaultCompactorConfig

func DefaultCompactorConfig() *CompactorConfig

DefaultCompactorConfig returns sensible defaults.

type Message

type Message = claude.Message

Message represents a message from the AI.

type Provider

type Provider string

Provider represents an AI provider.

const (
	// ProviderAnthropic uses the Anthropic Claude API via agent-sdk-go.
	ProviderAnthropic Provider = "anthropic"

	// ProviderZAI uses the Z.AI API (placeholder).
	ProviderZAI Provider = "zai"

	// ProviderSynthetic uses synthetic responses for testing (placeholder).
	ProviderSynthetic Provider = "synthetic"
)

type ProviderConfig

type ProviderConfig struct {
	Provider Provider
	Model    string
	APIKey   string
	BaseURL  string
}

ProviderConfig contains provider-specific configuration.

type ProviderFactory

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

ProviderFactory creates clients for different providers.

func NewProviderFactory

func NewProviderFactory() *ProviderFactory

NewProviderFactory creates a new provider factory with default providers.

func (*ProviderFactory) Create

func (f *ProviderFactory) Create(ctx context.Context, cfg ProviderConfig, opts ...claude.ClientOption) (Client, error)

Create creates a client for the specified provider.

func (*ProviderFactory) Register

func (f *ProviderFactory) Register(provider Provider, fn func(ctx context.Context, cfg ProviderConfig, opts ...claude.ClientOption) (Client, error))

Register registers a provider factory function.

type RateLimitError

type RateLimitError struct {
	RetryAfter time.Duration
	Message    string
}

RateLimitError represents a 429 response.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

type RateLimiterConfig

type RateLimiterConfig struct {
	// InitialBackoff is the initial backoff after a 429.
	InitialBackoff time.Duration

	// MaxBackoff is the maximum backoff duration.
	MaxBackoff time.Duration

	// BackoffMultiplier increases backoff on consecutive 429s.
	BackoffMultiplier float64
}

RateLimiterConfig configures rate limiting with 429 detection.

func DefaultRateLimiterConfig

func DefaultRateLimiterConfig() *RateLimiterConfig

DefaultRateLimiterConfig returns sensible defaults.

type ResilienceConfig

type ResilienceConfig struct {
	// Circuit breaker settings
	CircuitBreaker *CircuitBreakerConfig

	// Retry settings
	Retry *RetryConfig

	// Rate limiter settings
	RateLimiter *RateLimiterConfig
}

ResilienceConfig configures resilience behavior.

type ResilienceWrapper

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

ResilienceWrapper wraps API calls with resilience patterns.

func NewResilienceWrapper

func NewResilienceWrapper(config *ResilienceConfig) *ResilienceWrapper

NewResilienceWrapper creates a new resilience wrapper.

func (*ResilienceWrapper) Counts

func (w *ResilienceWrapper) Counts() gobreaker.Counts

Counts returns the current circuit breaker counts.

func (*ResilienceWrapper) Execute

func (w *ResilienceWrapper) Execute(ctx context.Context, operation func() (string, error)) (string, error)

Execute runs the operation with all configured resilience patterns.

func (*ResilienceWrapper) State

func (w *ResilienceWrapper) State() gobreaker.State

State returns the current circuit breaker state.

type RetryConfig

type RetryConfig struct {
	// MaxRetries is the maximum number of retry attempts.
	MaxRetries uint64

	// InitialInterval is the initial backoff interval.
	InitialInterval time.Duration

	// MaxInterval is the maximum backoff interval.
	MaxInterval time.Duration

	// Multiplier is the factor by which the interval increases.
	Multiplier float64

	// RandomizationFactor adds jitter to prevent thundering herd.
	RandomizationFactor float64
}

RetryConfig configures retry behavior.

func DefaultRetryConfig

func DefaultRetryConfig() *RetryConfig

DefaultRetryConfig returns sensible defaults.

type ServerError

type ServerError struct {
	StatusCode int
	Message    string
}

ServerError represents a 5xx response.

func (*ServerError) Error

func (e *ServerError) Error() string

type SimpleCompactor

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

SimpleCompactor provides basic compaction using token estimation.

func NewSimpleCompactor

func NewSimpleCompactor(config *CompactorConfig, summarizer func(ctx context.Context, prompt string) (string, error)) *SimpleCompactor

NewSimpleCompactor creates a new compactor.

func (*SimpleCompactor) Compact

func (c *SimpleCompactor) Compact(ctx context.Context, messages []CompactionMessage) ([]CompactionMessage, error)

Compact summarizes older messages while keeping recent ones.

func (*SimpleCompactor) EstimateTokens

func (c *SimpleCompactor) EstimateTokens(content string) int

EstimateTokens provides a rough token estimate (4 chars per token).

func (*SimpleCompactor) ShouldCompact

func (c *SimpleCompactor) ShouldCompact(messages []CompactionMessage, maxTokens int) bool

ShouldCompact checks if compaction is needed.

type SlidingWindowCompactor

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

SlidingWindowCompactor uses a sliding window approach (no LLM needed).

func NewSlidingWindowCompactor

func NewSlidingWindowCompactor(windowSize int) *SlidingWindowCompactor

NewSlidingWindowCompactor creates a simple sliding window compactor.

func (*SlidingWindowCompactor) Compact

Compact keeps only the most recent messages within window.

func (*SlidingWindowCompactor) EstimateTokens

func (c *SlidingWindowCompactor) EstimateTokens(content string) int

EstimateTokens provides a rough estimate.

func (*SlidingWindowCompactor) ShouldCompact

func (c *SlidingWindowCompactor) ShouldCompact(messages []CompactionMessage, _ int) bool

ShouldCompact checks if messages exceed window size.

type TokenCounter

type TokenCounter interface {
	Count(text string) int
}

TokenCounter provides accurate token counting.

type Tool

type Tool struct {
	Name        string
	Description string
	InputSchema map[string]any
	Handler     func(ctx context.Context, input map[string]any) (any, error)
}

Tool represents a tool available to the AI.

type WordBasedCounter

type WordBasedCounter struct{}

WordBasedCounter estimates tokens as words * 1.3.

func (*WordBasedCounter) Count

func (c *WordBasedCounter) Count(text string) int

Jump to

Keyboard shortcuts

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