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
- Variables
- func EstimateRequestTokens(req Request) int
- func IsLoopbackHost(host string) bool
- func IsLoopbackURL(raw string) bool
- func NewHTTPClient(offline bool) *http.Client
- func PricesFromConfig(in map[string]config.Price) map[string]Price
- type APIError
- type Anthropic
- type Fake
- type Message
- type Ollama
- type OpenAI
- type Options
- type Price
- type Pricer
- type Prober
- type Provider
- type Redacting
- func (r *Redacting) Complete(ctx context.Context, req Request) (Response, error)
- func (r *Redacting) Local() bool
- func (r *Redacting) Model() string
- func (r *Redacting) Name() string
- func (r *Redacting) Probe(ctx context.Context) (string, []string, error)
- func (r *Redacting) Redactions() int
- func (r *Redacting) Unwrap() Provider
- type Request
- type Response
- type ToolCall
- type ToolDef
- type ToolResult
- type Usage
Constants ¶
const ( RoleUser = "user" RoleAssistant = "assistant" RoleTool = "tool" )
Roles of a message.
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 ¶
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 ¶
EstimateRequestTokens approximates the input tokens of a request.
func IsLoopbackHost ¶
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 ¶
IsLoopbackURL reports whether a URL points at this machine.
func NewHTTPClient ¶
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.
Types ¶
type APIError ¶
APIError is a non-2xx response from a provider.
type Anthropic ¶
type Anthropic struct {
// contains filtered or unexported fields
}
Anthropic speaks the native Messages API.
func NewAnthropic ¶
NewAnthropic builds the provider. baseURL may be empty for the public API.
func (*Anthropic) Complete ¶
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.
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.
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.
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 ¶
NewOpenAI builds the provider. kind is "openai" or "openai-compatible". baseURL is the API root that /chat/completions is appended to.
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 (Pricer) Cost ¶
Cost fills in CostUSD and CostKnown on a usage record. Local providers cost nothing. A cost the provider reported itself is kept.
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.
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 (*Redacting) Redactions ¶
Redactions returns how many secrets have been removed so far.
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 (Response) AssistantMessage ¶
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 ¶
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.