provider

package
v1.22.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: GPL-3.0 Imports: 8 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

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnknownProvider   = errors.New("provider: unknown provider")
	ErrUnauthorized      = errors.New("provider: unauthorized (check API key)")
	ErrRateLimit         = errors.New("provider: rate limit exceeded")
	ErrContextTooLong    = errors.New("provider: input exceeds model context window")
	ErrModelNotSupported = errors.New("provider: model not supported by this provider")
	ErrTimeout           = errors.New("provider: request timed out")
)

Functions

func IsCLI added in v1.19.0

func IsCLI(name string) bool

IsCLI reports whether the named provider is CLI-backed (Kind == KindCLI). A provider with no registered metadata is treated as not CLI.

func Names

func Names() []string

func Register

func Register(name string, factory Factory)

Register installs a provider factory under the given name. Intended to be called from package init() functions of provider subpackages. Panics on duplicate registration to surface programmer errors at startup rather than silently overriding.

func RegisterMetadata added in v1.17.0

func RegisterMetadata(m Metadata)

RegisterMetadata records a provider's static description. Call it from the same init() that calls Register, so the two registries cannot disagree about which providers exist.

It panics on a bad registration for the same reason Register does: these are compile-time-constant program facts, and a provider that silently failed to describe itself would surface as a documentation hole rather than a crash.

func ResolveAPIKeyEnv added in v1.19.0

func ResolveAPIKeyEnv(name string, pc config.ProviderConfig) (config.ProviderConfig, error)

ResolveAPIKeyEnv returns the provider block with api_key_env applied: when api_key_env is set, the credential comes from that environment variable and wins over both the provider's fixed env var (ANTHROPIC_API_KEY and friends, already folded into APIKey by config.ApplyEnv) and api_key. When the field is set but the named variable is empty, it is an error rather than a silent fallback — a pinned variable that is missing is almost always a typo, and falling back would send a different credential than the one the user asked for. A block without api_key_env is returned unchanged, so every existing config behaves byte for byte as before.

It lives here (not in internal/cli) so that review, providers and doctor all apply the exact same strict rule.

func UsesAPIKey added in v1.19.0

func UsesAPIKey(name string) bool

UsesAPIKey reports whether the generic api_key_env / api_key overrides mean anything for this provider. The *-cli providers authenticate through their own binary's login, so for them both fields stay inert — exactly as api_key already is today.

Types

type ContextOptions added in v1.3.0

type ContextOptions struct {
	// Enabled is true when --with-context was passed. When false the CLI
	// provider behaves exactly as before (diff-only, no extra read tools,
	// inherited working directory).
	Enabled bool

	// RepoRoot is the repository root the host CLI should run in, so its
	// relative file reads resolve deterministically. Set as the
	// subprocess working directory only when Enabled.
	RepoRoot string
}

ContextOptions carries the --with-context signal (ADR-0017) to the CLI-backed providers via Request.ProviderOpts. It lives in the neutral provider package so the CLI layer can set it without importing a concrete provider subpackage, and the clireview backend reads it via a type assertion. API providers ignore ProviderOpts entirely, so a ContextOptions value is inert for them.

type Factory

type Factory func(cfg config.ProviderConfig) (Provider, error)

type Kind added in v1.17.0

type Kind string

Kind classifies how a provider reaches a model, which is the distinction users actually make when choosing one: a remote paid API, a model running on their own machine, or an already-installed coding CLI acting as the backend.

const (
	KindAPI   Kind = "api"
	KindLocal Kind = "local"
	KindCLI   Kind = "cli"
)

type Metadata added in v1.17.0

type Metadata struct {
	Name           string      `json:"name"`
	Kind           Kind        `json:"kind"`
	DefaultModel   string      `json:"default_model"`
	APIKeyEnv      string      `json:"api_key_env,omitempty"`
	DefaultBaseURL string      `json:"default_base_url,omitempty"`
	Binary         string      `json:"binary,omitempty"`
	Models         []ModelInfo `json:"models,omitempty"`

	// PricingUserDeclared marks a provider whose models and prices CommitBrief
	// cannot know (openai-compatible): a zero price there means "the user
	// did not say", not "free", so the cost is reported as unknown instead
	// of $0.0000. Providers with a genuinely free price (ollama, *-cli)
	// leave it false.
	PricingUserDeclared bool `json:"pricing_user_declared,omitempty"`
}

Metadata is the static, API-key-free description of a provider.

It exists because the Provider interface cannot answer these questions: it is instance-level (ContextWindow and Pricing only answer for a model you already name, and there is no Models method), and New() refuses to build a client without an API key — so an unconfigured provider's facts were unreachable. Documentation needs them for every provider, including ones the reader has not configured. See ADR-0039.

func AllMetadata added in v1.17.0

func AllMetadata() []Metadata

AllMetadata returns every registered description, sorted by name so the generated inventory is byte-stable across runs.

It reports only what has been linked in: the registry is populated by the blank imports in cmd/commitbrief/main.go, so a package that calls this from its own tests must blank-import the providers or it will observe an empty registry and pass vacuously.

func MetadataFor added in v1.17.0

func MetadataFor(name string) (Metadata, bool)

MetadataFor looks up one provider's description.

type ModelInfo added in v1.17.0

type ModelInfo struct {
	ID            string  `json:"id"`
	Default       bool    `json:"default,omitempty"`
	ContextWindow int     `json:"context_window"`
	Pricing       Pricing `json:"pricing"`
}

ModelInfo is everything documentation needs to say about one model. Pricing is USD per 1M tokens; a zero Pricing means "free or not metered" (ollama, the CLI-backed providers), not "unknown".

type PlainTextEmitter added in v0.9.0

type PlainTextEmitter interface {
	Provider
	EmitsPlainText()
}

PlainTextEmitter is the marker interface for providers whose Review() returns formatted plain text instead of the structured findings JSON the API providers contract. The review pipeline uses this to short-circuit JSON parsing, retry-once, and the cards/markdown renderer — the response is emitted to stdout verbatim because the CLI tool has already formatted it.

CLI-based providers (claude-cli, gemini-cli, codex-cli) implement this so they can pass through their host CLI's output without the JSON-contract enforcement that API providers do via native structured-output mechanisms (tool_use / response_format / response_schema).

type Pricing

type Pricing struct {
	InputPer1M  float64 `json:"input_per_1m"`
	OutputPer1M float64 `json:"output_per_1m"`

	// CachedInputPer1M is the per-1M-token price for cached input tokens.
	// Zero means "same as InputPer1M" (no cache discount or not supported).
	CachedInputPer1M float64 `json:"cached_input_per_1m,omitempty"`
}

Pricing's json tags mirror config.ModelPricing's yaml tags so a reader moving between the generated surface inventory and their own config file meets one vocabulary rather than two spellings of the same three numbers.

func (Pricing) Cost

func (p Pricing) Cost(u Usage) float64

type Provider

type Provider interface {
	Name() string

	DefaultModel() string

	ContextWindow(model string) int

	EstimateTokens(text string) int

	Pricing(model string) Pricing

	Review(ctx context.Context, req Request) (Response, error)

	TestConnection(ctx context.Context) error
}

func New

func New(name string, cfg config.ProviderConfig) (Provider, error)

type Request

type Request struct {
	Model        string
	SystemPrompt string
	UserPrompt   string
	Lang         string
	MaxTokens    int

	// FreeForm requests an unstructured plain-text completion (ADR-0015).
	// When true, API providers MUST skip their structured-output
	// enforcement (Anthropic tool_choice, OpenAI response_format, Gemini
	// responseSchema, Ollama format:json) and return the model's raw text
	// in Response.Content. Default false preserves the ADR-0014
	// structured-findings contract, so existing call sites are unaffected.
	// Used by `--suggest-commit` to get a commit message instead of findings.
	FreeForm bool

	// ProviderOpts is an escape hatch (ADR-0001 risk #1) for features that
	// don't fit the common interface, e.g. Anthropic prompt caching or
	// OpenAI logprobs. Providers cast to their expected type; unknown values
	// are ignored.
	ProviderOpts any
}

type Response

type Response struct {
	Content string
	Model   string
	Usage   Usage
}

type TimeoutSetter added in v1.16.0

type TimeoutSetter interface {
	Provider
	SetTimeout(d time.Duration)
}

TimeoutSetter is the optional interface for providers that enforce a hard timeout of their OWN in addition to honouring the caller's context — clireview's per-invocation cap, ollama's http.Client timeout, the Anthropic SDK's 10-minute non-streaming ceiling.

It exists because a context deadline can only SHORTEN a run. A user who passes `--timeout 20m` on a slow review would still be cut off at the provider's built-in five or ten minutes, so the value has to reach the provider itself. Implement it only when there is such a cap to raise; providers that purely follow ctx (openai and its OpenAI-compatible siblings, gemini, mock) deliberately do not.

SetTimeout is called at most once, right after construction and before any Review/TestConnection call, so implementations may simply assign to a field without synchronization.

type Usage

type Usage struct {
	InputTokens  int
	OutputTokens int

	// CachedInputTokens is the subset of InputTokens served from a provider-
	// side prompt cache (Anthropic ephemeral cache, OpenAI cached completions).
	// Zero if unknown or unsupported.
	CachedInputTokens int
}

Directories

Path Synopsis
Package claudecli registers a CLI-tool-backed provider that drives Anthropic's Claude Code (`claude`) binary as the review engine.
Package claudecli registers a CLI-tool-backed provider that drives Anthropic's Claude Code (`claude`) binary as the review engine.
Package clireview is the shared implementation of CLI-tool-backed review providers.
Package clireview is the shared implementation of CLI-tool-backed review providers.
Package codexcli registers a CLI-tool-backed provider that drives OpenAI's Codex CLI (`codex`) binary as the review engine.
Package codexcli registers a CLI-tool-backed provider that drives OpenAI's Codex CLI (`codex`) binary as the review engine.
Package cohere implements the Provider interface against Cohere's OpenAI-compatibility endpoint (https://api.cohere.ai/compatibility/v1), reusing the openai-go SDK — no new dependency.
Package cohere implements the Provider interface against Cohere's OpenAI-compatibility endpoint (https://api.cohere.ai/compatibility/v1), reusing the openai-go SDK — no new dependency.
Package deepseek implements the Provider interface against DeepSeek's OpenAI-compatible Chat Completions API.
Package deepseek implements the Provider interface against DeepSeek's OpenAI-compatible Chat Completions API.
Package geminicli registers a CLI-tool-backed provider that drives Google's Gemini CLI (`gemini`) binary as the review engine.
Package geminicli registers a CLI-tool-backed provider that drives Google's Gemini CLI (`gemini`) binary as the review engine.
Package mistral implements the Provider interface against Mistral's OpenAI-compatible Chat Completions API (https://api.mistral.ai/v1), reusing the openai-go SDK — no new dependency.
Package mistral implements the Provider interface against Mistral's OpenAI-compatible Chat Completions API (https://api.mistral.ai/v1), reusing the openai-go SDK — no new dependency.
Package openaicompat implements the Provider interface against any endpoint that speaks the OpenAI Chat Completions protocol (vLLM, LM Studio, OpenRouter, a corporate gateway, ...).
Package openaicompat implements the Provider interface against any endpoint that speaks the OpenAI Chat Completions protocol (vLLM, LM Studio, OpenRouter, a corporate gateway, ...).

Jump to

Keyboard shortcuts

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