api

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package api handles LLM API communication via the Anthropic Go SDK.

Package api defines data structures for API communication

Index

Constants

View Source
const (
	DefaultMaxTokens = 8192
	MessagesEndpoint = "/v1/messages"
	AnthropicVersion = "2023-06-01"
)

Constants for API configuration.

Variables

This section is empty.

Functions

func WithPerAttemptTimeout

func WithPerAttemptTimeout(ctx context.Context, d time.Duration) context.Context

WithPerAttemptTimeout returns a context that will apply the given timeout to each individual request attempt. The SDK client extracts this value and passes it as option.WithRequestTimeout, so each retry gets a fresh timeout.

func WithRetryNotifier

func WithRetryNotifier(ctx context.Context, fn func(attempt int, err error)) context.Context

WithRetryNotifier returns a context that carries a callback invoked before each retry attempt. attempt is 1-based; err is the error that triggered the retry.

Types

type Client

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

Client handles communication with the Anthropic API using the official SDK.

func NewClient

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

NewClient creates a new API client backed by the Anthropic Go SDK.

func (*Client) GetModel

func (c *Client) GetModel() string

GetModel returns the model currently configured on the client.

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, prompt string) (string, error)

SendMessage sends a single user message and returns the response text.

func (*Client) SendMessageWithHistory

func (c *Client) SendMessageWithHistory(ctx context.Context, messages []Message) (string, error)

SendMessageWithHistory sends a conversation history and returns the response text.

func (*Client) SendMessageWithTools

func (c *Client) SendMessageWithTools(ctx context.Context, messages []Message, tools []Tool, executor ToolExecutor, onCall ...func(ToolCallResult)) (string, []Message, Usage, error)

SendMessageWithTools sends a conversation with tool definitions, executing any tool calls the model makes and continuing the loop until the model returns a final text response. It returns the final text response, the full accumulated message history, the total token usage across all API calls in the loop, and any error. The optional onCall callback is invoked after each tool execution with the result.

func (*Client) SendMessageWithToolsStreaming

func (c *Client) SendMessageWithToolsStreaming(ctx context.Context, messages []Message, tools []Tool, executor ToolExecutor, onToken func(string), onCall ...func(ToolCallResult)) (string, []Message, Usage, error)

SendMessageWithToolsStreaming is like SendMessageWithTools but streams text tokens via the SSE API. onToken is called for each text token as it arrives; it may be nil. Tool-calling turns are handled the same way as in SendMessageWithTools.

func (*Client) SetModel

func (c *Client) SetModel(model string)

SetModel changes the model used for subsequent API requests.

type ClientOption

type ClientOption func(*Client)

ClientOption is a function that configures a Client.

func WithHTTPClient

func WithHTTPClient(h *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client.

func WithMaxRetries

func WithMaxRetries(n int) ClientOption

WithMaxRetries sets the maximum number of retry attempts after a retryable error.

func WithMaxTokens

func WithMaxTokens(n int) ClientOption

WithMaxTokens sets the maximum number of tokens in API responses.

func WithModel

func WithModel(model string) ClientOption

WithModel sets the model to use for API requests.

func WithSystemPrompt

func WithSystemPrompt(s string) ClientOption

WithSystemPrompt sets the system prompt sent with every request.

type ContentBlock

type ContentBlock struct {
	Type string `json:"type"`

	// text blocks
	Text string `json:"text,omitempty"`

	// tool_use blocks (assistant → us)
	ID    string         `json:"id,omitempty"`
	Name  string         `json:"name,omitempty"`
	Input map[string]any `json:"input,omitempty"`

	// tool_result blocks (us → assistant)
	ToolUseID string `json:"tool_use_id,omitempty"`
	Content   string `json:"content,omitempty"`
}

ContentBlock represents a single content block in a message or response. Type is one of "text", "tool_use", or "tool_result".

type InputSchema

type InputSchema struct {
	Type       string                 `json:"type"`
	Properties map[string]PropertyDef `json:"properties"`
	Required   []string               `json:"required,omitempty"`
}

InputSchema is the JSON Schema for a tool's input object.

type Message

type Message struct {
	Role    string `json:"role"`
	Content any    `json:"content"`
}

Message represents a single message in the conversation. Content may be a plain string or a []ContentBlock (for tool_use/tool_result).

type MultiExecutor

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

MultiExecutor dispatches ExecuteTool calls to the registered executor for each tool name.

func NewMultiExecutor

func NewMultiExecutor() *MultiExecutor

NewMultiExecutor returns an empty MultiExecutor.

func (*MultiExecutor) ExecuteTool

func (m *MultiExecutor) ExecuteTool(ctx context.Context, name string, input map[string]any) (string, error)

ExecuteTool dispatches to the executor registered for name. Returns an error if no executor is registered for name.

func (*MultiExecutor) Register

func (m *MultiExecutor) Register(name string, exec ToolExecutor)

Register associates name with the given executor.

type PropertyDef

type PropertyDef struct {
	Type        string `json:"type"`
	Description string `json:"description"`
}

PropertyDef describes a single property in an InputSchema.

type StatusError

type StatusError struct {
	StatusCode int
	Body       string
}

StatusError is returned when the API responds with a non-2xx status code. It wraps the SDK's *anthropic.Error to preserve the FriendlyMessage API used by tui/api.go without requiring changes there.

func (*StatusError) Error

func (e *StatusError) Error() string

func (*StatusError) FriendlyMessage added in v0.5.0

func (e *StatusError) FriendlyMessage() string

FriendlyMessage returns a short, human-readable error message by parsing the structured JSON body. Falls back to a generic status-code message.

type Tool

type Tool struct {
	Name        string      `json:"name"`
	Description string      `json:"description"`
	InputSchema InputSchema `json:"input_schema"`
}

Tool describes a tool the model may call.

type ToolCallResult

type ToolCallResult struct {
	Name   string
	Input  map[string]any
	Output string
	Err    error
}

ToolCallResult records a single tool execution that occurred during a request.

type ToolExecutor

type ToolExecutor interface {
	ExecuteTool(ctx context.Context, name string, input map[string]any) (string, error)
}

ToolExecutor executes a named tool with the given input and returns output.

type Usage

type Usage struct {
	InputTokens  int
	OutputTokens int
}

Usage holds the token counts reported by the API.

func (Usage) Add

func (u Usage) Add(other Usage) Usage

Add returns the sum of two Usage values.

Jump to

Keyboard shortcuts

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