llm

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package llm is Spackle's model provider layer: one small interface, three wire implementations (Anthropic Messages, OpenAI-compatible Chat Completions, Ollama), a scripted fake for tests, and the wrappers that enforce redaction and the offline guarantee.

The providers speak HTTP directly through net/http. No vendor SDK is linked: Spackle needs one endpoint per provider, and every dependency of a security tool is attack surface that has to be audited and kept patched.

Index

Constants

View Source
const (
	RoleUser      = "user"
	RoleAssistant = "assistant"
	RoleTool      = "tool"
)

Roles of a message.

View Source
const (
	StopEnd       = "end"        // the model finished its turn
	StopToolUse   = "tool_use"   // the model wants tool results
	StopMaxTokens = "max_tokens" // output was cut off
	StopRefusal   = "refusal"    // the provider declined the request
)

Stop reasons, normalized across providers.

Variables

View Source
var ErrOffline = errors.New("offline mode: refusing a connection that would leave this machine")

ErrOffline is returned when a call would leave the machine in offline mode.

Functions

func EstimateRequestTokens

func EstimateRequestTokens(req Request) int

EstimateRequestTokens approximates the input tokens of a request.

func IsLoopbackHost

func IsLoopbackHost(host string) bool

IsLoopbackHost reports whether host (without a port) names this machine. Only loopback counts as local. A private LAN address does not: offline mode promises that nothing leaves the machine, and a LAN host is another machine.

func IsLoopbackURL

func IsLoopbackURL(raw string) bool

IsLoopbackURL reports whether a URL points at this machine.

func NewHTTPClient

func NewHTTPClient(offline bool) *http.Client

NewHTTPClient returns the client providers use. In offline mode its dialer refuses every non-loopback address and proxies are ignored, so the guarantee holds even if a base URL check is bypassed or a server redirects elsewhere.

func PricesFromConfig

func PricesFromConfig(in map[string]config.Price) map[string]Price

PricesFromConfig converts config pricing into llm prices.

Types

type APIError

type APIError struct {
	Provider string
	Status   int
	Message  string
}

APIError is a non-2xx response from a provider.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Hint

func (e *APIError) Hint() string

Hint returns what the operator should do about the error.

func (*APIError) Retryable

func (e *APIError) Retryable() bool

Retryable reports whether the request may succeed if sent again.

type Anthropic

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

Anthropic speaks the native Messages API.

func NewAnthropic

func NewAnthropic(model, baseURL, key string, client *http.Client) *Anthropic

NewAnthropic builds the provider. baseURL may be empty for the public API.

func (*Anthropic) Complete

func (a *Anthropic) Complete(ctx context.Context, req Request) (Response, error)

Complete implements Provider.

Notes on the request shape, for current Claude models:

  • No thinking parameter is sent. Thinking is adaptive by default, and explicit budgets or "disabled" are rejected by several models.
  • No temperature, top_p or top_k: they are rejected too.
  • tool_choice is left at its default (auto). Forcing a tool is rejected.
  • Earlier assistant turns are replayed byte for byte from Message.Raw, because thinking blocks are bound to the conversation that made them.

func (*Anthropic) Local

func (a *Anthropic) Local() bool

Local implements Provider.

func (*Anthropic) Model

func (a *Anthropic) Model() string

Model implements Provider.

func (*Anthropic) Name

func (a *Anthropic) Name() string

Name implements Provider.

func (*Anthropic) Probe

func (a *Anthropic) Probe(ctx context.Context) (string, []string, error)

Probe implements Prober with the Models API, which validates the key and the model name without spending tokens.

type Fake

type Fake struct {

	// Handler, when set, is used instead of the script. It gets the request
	// and its index (0-based).
	Handler func(req Request, n int) (Response, error)
	// Requests holds every request received, in order.
	Requests []Request
	// ModelName is reported by Model.
	ModelName string
	// Remote makes Local report false, to test offline refusal.
	Remote bool
	// contains filtered or unexported fields
}

Fake is a scripted provider for tests. It returns queued responses in order and records every request it receives, so tests can assert on what would have been sent to a real model.

func NewFake

func NewFake(script ...Response) *Fake

NewFake returns a fake that plays the given responses.

func (*Fake) Complete

func (f *Fake) Complete(_ context.Context, req Request) (Response, error)

Complete implements Provider.

func (*Fake) Local

func (f *Fake) Local() bool

Local implements Provider.

func (*Fake) Model

func (f *Fake) Model() string

Model implements Provider.

func (*Fake) Name

func (f *Fake) Name() string

Name implements Provider.

func (*Fake) Remaining

func (f *Fake) Remaining() int

Remaining returns how many scripted responses are left.

func (*Fake) Sent

func (f *Fake) Sent() string

Sent returns everything the fake received as one string, for asserting that something was or was not sent to the model.

type Message

type Message struct {
	Role string
	// Text is the user text, or the assistant's visible text.
	Text string
	// ToolCalls are the calls an assistant turn made.
	ToolCalls []ToolCall
	// ToolResults answer the previous assistant turn's calls (Role tool).
	ToolResults []ToolResult
	// Raw is the provider's own encoding of an assistant turn. Providers
	// that require earlier turns to be replayed exactly (Anthropic's
	// thinking blocks are bound to the conversation) send it back verbatim.
	Raw json.RawMessage
}

Message is one turn in provider-neutral form.

type Ollama

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

Ollama speaks Ollama's native chat API.

func NewOllama

func NewOllama(model, baseURL string, client *http.Client) *Ollama

NewOllama builds the provider. baseURL may be empty for the local default.

func (*Ollama) Complete

func (o *Ollama) Complete(ctx context.Context, req Request) (Response, error)

Complete implements Provider.

func (*Ollama) Local

func (o *Ollama) Local() bool

Local implements Provider.

func (*Ollama) Model

func (o *Ollama) Model() string

Model implements Provider.

func (*Ollama) Name

func (o *Ollama) Name() string

Name implements Provider.

func (*Ollama) Probe

func (o *Ollama) Probe(ctx context.Context) (string, []string, error)

Probe implements Prober. It asks Ollama about the model and warns when it lacks tool calling or looks too small for agentic work.

type OpenAI

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

OpenAI speaks the Chat Completions shape. It serves OpenAI itself and any compatible endpoint: OpenRouter, Azure OpenAI, Together, Groq, Fireworks, llama.cpp, LM Studio, vLLM.

func NewOpenAI

func NewOpenAI(kind, model, baseURL, key string, client *http.Client) *OpenAI

NewOpenAI builds the provider. kind is "openai" or "openai-compatible". baseURL is the API root that /chat/completions is appended to.

func (*OpenAI) Complete

func (o *OpenAI) Complete(ctx context.Context, req Request) (Response, error)

Complete implements Provider.

func (*OpenAI) Local

func (o *OpenAI) Local() bool

Local implements Provider.

func (*OpenAI) Model

func (o *OpenAI) Model() string

Model implements Provider.

func (*OpenAI) Name

func (o *OpenAI) Name() string

Name implements Provider.

func (*OpenAI) Probe

func (o *OpenAI) Probe(ctx context.Context) (string, []string, error)

Probe implements Prober. It lists models when the endpoint supports that, which is free. Endpoints without a models route (some Azure deployments) are reported as unverified rather than failed.

type Options

type Options struct {
	Offline bool
	// Getenv reads environment variables; nil means os.Getenv.
	Getenv func(string) string
}

Options control provider construction.

type Price

type Price struct {
	Input  float64
	Output float64
	// CacheRead and CacheWrite price cached input. Zero means "derive from
	// Input": reads at 10 percent, writes at 125 percent.
	CacheRead  float64
	CacheWrite float64
}

Price is the cost of a model in USD per million tokens.

type Pricer

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

Pricer looks up model prices.

func NewPricer

func NewPricer(overrides map[string]Price) Pricer

NewPricer returns a Pricer with the given overrides on top of the built-in table.

func (Pricer) Cost

func (p Pricer) Cost(model string, local bool, u Usage) Usage

Cost fills in CostUSD and CostKnown on a usage record. Local providers cost nothing. A cost the provider reported itself is kept.

func (Pricer) EstimateCost

func (p Pricer) EstimateCost(model string, local bool, inputTokens, outputTokens int) (float64, bool)

EstimateCost prices a hypothetical number of tokens, for the estimate shown before a paid run.

func (Pricer) Lookup

func (p Pricer) Lookup(model string) (Price, bool)

Lookup returns the price of a model and whether it is known.

type Prober

type Prober interface {
	// Probe checks credentials and that the model exists. The note is a
	// short human-readable detail; warnings list concerns that do not block
	// a run (a small local model, no tool-calling support).
	Probe(ctx context.Context) (note string, warnings []string, err error)
}

Prober is implemented by providers that can validate their configuration with a request that costs nothing or close to it.

type Provider

type Provider interface {
	// Name is the provider kind: anthropic, openai, openai-compatible, ollama, fake.
	Name() string
	// Model is the model name requests are sent to.
	Model() string
	// Local reports whether the provider's endpoint is on this machine.
	Local() bool
	Complete(ctx context.Context, req Request) (Response, error)
}

Provider is a model backend.

func New

func New(m config.Model, opts Options) (Provider, error)

New builds the provider for a model config, wrapped with redaction. In offline mode it fails before any request is made if the endpoint is not on this machine, and the HTTP client it uses refuses non-loopback addresses.

type Redacting

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

Redacting wraps a provider so that no secret value can reach it. Every piece of outbound text (system prompt, user text, tool results, tool call arguments being replayed) passes through secret detection first.

This is the last line of defense, not the only one: tools redact their own output too. It exists so that a new tool or prompt that forgets to redact still cannot leak.

func NewRedacting

func NewRedacting(p Provider) *Redacting

NewRedacting wraps p.

func (*Redacting) Complete

func (r *Redacting) Complete(ctx context.Context, req Request) (Response, error)

Complete implements Provider.

func (*Redacting) Local

func (r *Redacting) Local() bool

Local implements Provider.

func (*Redacting) Model

func (r *Redacting) Model() string

Model implements Provider.

func (*Redacting) Name

func (r *Redacting) Name() string

Name implements Provider.

func (*Redacting) Probe

func (r *Redacting) Probe(ctx context.Context) (string, []string, error)

Probe forwards to the wrapped provider when it supports probing.

func (*Redacting) Redactions

func (r *Redacting) Redactions() int

Redactions returns how many secrets have been removed so far.

func (*Redacting) Unwrap

func (r *Redacting) Unwrap() Provider

Unwrap returns the wrapped provider.

type Request

type Request struct {
	System    string
	Messages  []Message
	Tools     []ToolDef
	MaxTokens int
}

Request is one completion request.

type Response

type Response struct {
	Text       string
	ToolCalls  []ToolCall
	StopReason string
	// RefusalNote carries the provider's explanation when StopReason is
	// StopRefusal.
	RefusalNote string
	Usage       Usage
	// Raw is the assistant turn in the provider's own encoding; copy it to
	// Message.Raw when appending the turn to the conversation.
	Raw json.RawMessage
}

Response is one completion.

func Call

func Call(id, name string, args any) Response

Call is a scripted response that calls one tool.

func Say

func Say(text string) Response

Say is a scripted text response.

func (Response) AssistantMessage

func (r Response) AssistantMessage() Message

AssistantMessage converts the response into the message to append to the conversation.

type ToolCall

type ToolCall struct {
	ID   string
	Name string
	Args json.RawMessage
}

ToolCall is a request from the model to run a tool.

type ToolDef

type ToolDef struct {
	Name        string
	Description string
	// Schema is a JSON Schema object for the arguments.
	Schema json.RawMessage
}

ToolDef describes a tool to the model.

type ToolResult

type ToolResult struct {
	CallID  string
	Name    string
	Content string
	IsError bool
}

ToolResult is the outcome of one tool call.

type Usage

type Usage struct {
	// InputTokens counts every input token, including cached ones.
	InputTokens  int
	OutputTokens int
	// CachedInputTokens is the part of InputTokens read from a prompt cache.
	CachedInputTokens int
	// CacheWriteTokens is the part of InputTokens written to a prompt cache.
	CacheWriteTokens int
	// Estimated is true when the provider reported no usage and the counts
	// were estimated from byte lengths.
	Estimated bool
	CostUSD   float64
	// CostKnown is false when the model has no known price. CostUSD is then
	// zero and a USD budget cannot be enforced for the call.
	CostKnown bool
}

Usage is token and cost accounting for one call, normalized so budgets work the same whichever provider served it.

Jump to

Keyboard shortcuts

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