core

package
v1.14.0 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package core provides the Anthropic API client and core conversation functionality. ABOUTME: HTTP client for Anthropic Messages API ABOUTME: Handles authentication, request formatting, and response parsing

Package core provides the Anthropic API client and core conversation functionality. ABOUTME: Configuration loading with multi-source precedence support ABOUTME: Handles env vars, .env files, YAML config, and defaults via Viper

Package core provides the Anthropic API client and core conversation functionality. ABOUTME: Application-wide constants and default values ABOUTME: Centralizes magic strings and configuration defaults

Package core provides the Anthropic API client and core conversation functionality. ABOUTME: Image loading and encoding for vision API support ABOUTME: Handles file validation, size limits, and base64 encoding

internal/core/migration.go ABOUTME: Migrates existing config.yaml to config.toml format ABOUTME: Preserves all existing settings and adds provider structure

Package core provides the Anthropic API client and core conversation functionality. ABOUTME: SSE streaming support for Anthropic API ABOUTME: Parses server-sent events, accumulates deltas, yields chunks

Index

Constants

View Source
const DefaultModel = "claude-sonnet-4-5-20250929"

DefaultModel is the default AI model to use when none is specified

View Source
const DefaultSystemPrompt = `` /* 3145-byte string literal not displayed */

DefaultSystemPrompt is the default system prompt for the assistant

View Source
const HeadlessGuidance = `` /* 605-byte string literal not displayed */

HeadlessGuidance is appended to the system prompt when running in non-interactive mode

View Source
const (
	// MaxImageSize is the maximum allowed image file size (5MB)
	// This matches Claude API limits
	MaxImageSize = 5 * 1024 * 1024
)

Variables

This section is empty.

Functions

func EncodeImage

func EncodeImage(data []byte, _ string) string

EncodeImage encodes image data to base64

Types

type Client

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

Client is the Anthropic API client

func NewClient

func NewClient(apiKey string, opts ...ClientOption) *Client

NewClient creates a new API client

func (*Client) CreateMessage

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

CreateMessage sends a message to the API

func (*Client) CreateMessageStream

func (c *Client) CreateMessageStream(ctx context.Context, req MessageRequest) (<-chan *StreamChunk, error)

CreateMessageStream sends a streaming request and returns a channel of chunks

type ClientOption

type ClientOption func(*Client)

ClientOption configures a Client

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL sets a custom base URL

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client

func WithStreamBufferSize added in v1.6.0

func WithStreamBufferSize(size int) ClientOption

WithStreamBufferSize sets the streaming channel buffer size

type Config

type Config struct {
	Provider        string                    `mapstructure:"provider"`
	Model           string                    `mapstructure:"model"`
	ProviderConfigs map[string]ProviderConfig `mapstructure:"providers"`
	DefaultTools    []string                  `mapstructure:"default_tools"`
	PermissionMode  string                    `mapstructure:"permission_mode"`
}

Config holds application configuration

func LoadConfig

func LoadConfig() (*Config, error)

LoadConfig loads configuration from multiple sources Priority (highest to lowest): 1. Environment variables (HEX_*) 2. Provider-specific env vars (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.) 3. .env file (current directory) 4. ~/.hex/config.toml (migrated from config.yaml if needed) 5. Defaults

func (*Config) GetAPIKey

func (c *Config) GetAPIKey() (string, error)

GetAPIKey returns the API key for backward compatibility Deprecated: Use GetProviderConfig instead

func (*Config) GetProviderConfig added in v1.6.0

func (c *Config) GetProviderConfig() (ProviderConfig, error)

GetProviderConfig returns the config for the selected provider

func (*Config) ValidateProvider added in v1.6.0

func (c *Config) ValidateProvider() error

ValidateProvider ensures the selected provider is configured

type Content

type Content struct {
	Type  string                 `json:"type"` // "text" or "tool_use"
	Text  string                 `json:"text,omitempty"`
	ID    string                 `json:"id,omitempty"`
	Name  string                 `json:"name,omitempty"`
	Input map[string]interface{} `json:"input,omitempty"`
}

Content represents a content block in the response

type ContentBlock

type ContentBlock struct {
	Type      string                 `json:"type"`                  // "text", "image", "tool_use", or "tool_result"
	Text      string                 `json:"text,omitempty"`        // For text blocks
	Source    *ImageSource           `json:"source,omitempty"`      // For image blocks
	ID        string                 `json:"id,omitempty"`          // For tool_use and tool_result blocks
	Name      string                 `json:"name,omitempty"`        // For tool_use blocks
	Input     map[string]interface{} `json:"input,omitempty"`       // For tool_use blocks
	ToolUseID string                 `json:"tool_use_id,omitempty"` // For tool_result blocks (ID field above is for tool_use)
	Content   string                 `json:"content,omitempty"`     // For tool_result blocks
}

ContentBlock represents a single block of content (text, image, tool_use, or tool_result)

func NewImageBlock

func NewImageBlock(source *ImageSource) ContentBlock

NewImageBlock creates an image content block

func NewTextBlock

func NewTextBlock(text string) ContentBlock

NewTextBlock creates a text content block

func NewToolResultBlock

func NewToolResultBlock(toolUseID string, content string) ContentBlock

NewToolResultBlock creates a tool_result content block

type Delta

type Delta struct {
	Type         string `json:"type"`
	Text         string `json:"text,omitempty"`
	PartialJSON  string `json:"partial_json,omitempty"`  // For input_json_delta
	StopReason   string `json:"stop_reason,omitempty"`   // For message_delta
	StopSequence string `json:"stop_sequence,omitempty"` // For message_delta
}

Delta represents incremental content in streaming

type ImageSource

type ImageSource struct {
	Type      string `json:"type"`       // Always "base64"
	MediaType string `json:"media_type"` // e.g., "image/png"
	Data      string `json:"data"`       // Base64 encoded image data
}

ImageSource represents an image for vision API

func LoadImage

func LoadImage(path string) (*ImageSource, error)

LoadImage loads an image from a file path and returns an ImageSource Returns error if file doesn't exist, is too large, or has unsupported format

type Message

type Message struct {
	ID           string         `json:"id,omitempty"`
	Role         string         `json:"role"` // "user", "assistant", "system"
	Content      string         `json:"-"`    // Internal field, not directly serialized
	ContentBlock []ContentBlock `json:"-"`    // Internal field, not directly serialized
	ToolCalls    []ToolUse      `json:"tool_calls,omitempty"`
	CreatedAt    *time.Time     `json:"created_at,omitempty"`
}

Message represents a single message in a conversation

func (Message) MarshalJSON

func (m Message) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshalling for Message This handles the Claude API requirement that 'content' can be either a string or an array

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshalling for Message

func (*Message) Validate

func (m *Message) Validate() error

Validate checks if the message is valid

type MessageRequest

type MessageRequest struct {
	Model     string           `json:"model"`
	Messages  []Message        `json:"messages"`
	MaxTokens int              `json:"max_tokens"`
	Stream    bool             `json:"stream,omitempty"`
	Tools     []ToolDefinition `json:"tools,omitempty"`
	System    string           `json:"system,omitempty"`
}

MessageRequest is sent to the API

type MessageResponse

type MessageResponse struct {
	ID         string    `json:"id"`
	Type       string    `json:"type"`
	Role       string    `json:"role"`
	Content    []Content `json:"content"`
	Model      string    `json:"model"`
	StopReason string    `json:"stop_reason,omitempty"`
	Usage      Usage     `json:"usage"`
}

MessageResponse is received from the API

func (*MessageResponse) GetTextContent

func (r *MessageResponse) GetTextContent() string

GetTextContent extracts text content from response

type ProviderConfig added in v1.6.0

type ProviderConfig struct {
	APIKey  string `mapstructure:"api_key"`
	BaseURL string `mapstructure:"base_url"`
}

ProviderConfig holds provider-specific configuration

type StreamAccumulator

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

StreamAccumulator accumulates text deltas from streaming chunks

func NewStreamAccumulator

func NewStreamAccumulator() *StreamAccumulator

NewStreamAccumulator creates a new accumulator

func (*StreamAccumulator) Add

func (a *StreamAccumulator) Add(chunk *StreamChunk)

Add accumulates a chunk's text delta

func (*StreamAccumulator) GetText

func (a *StreamAccumulator) GetText() string

GetText returns the accumulated text

func (*StreamAccumulator) Reset

func (a *StreamAccumulator) Reset()

Reset clears the accumulated text

type StreamChunk

type StreamChunk struct {
	Type         string   `json:"type"`
	Delta        *Delta   `json:"delta,omitempty"`
	Content      *Content `json:"content,omitempty"`
	ContentBlock *Content `json:"content_block,omitempty"` // For content_block_start events
	Index        int      `json:"index,omitempty"`         // Content block index
	Usage        *Usage   `json:"usage,omitempty"`
	Done         bool     `json:"-"`
}

StreamChunk represents a chunk in streaming response

func ParseSSEChunk

func ParseSSEChunk(data string) (*StreamChunk, error)

ParseSSEChunk parses a single SSE data line into a StreamChunk

type ToolDefinition

type ToolDefinition struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	InputSchema map[string]interface{} `json:"input_schema"`
}

ToolDefinition defines a tool's schema

type ToolUse

type ToolUse struct {
	Type  string                 `json:"type"` // "tool_use"
	ID    string                 `json:"id"`
	Name  string                 `json:"name"`
	Input map[string]interface{} `json:"input"`
}

ToolUse represents a tool invocation from the API

type Usage

type Usage struct {
	InputTokens      int `json:"input_tokens"`
	OutputTokens     int `json:"output_tokens"`
	CacheReadTokens  int `json:"cache_read_input_tokens,omitempty"`
	CacheWriteTokens int `json:"cache_creation_input_tokens,omitempty"`
}

Usage tracks token usage

Jump to

Keyboard shortcuts

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