model

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 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 model provides the provider abstraction (§40) and the centralized structured-output pipeline (§39). Providers are config-driven; the fake provider is the deterministic CI path, while the HTTP adapters are exercised by the tagged real-provider smoke test.

Index

Constants

View Source
const DemoBlockingReviewJSON = `{"findings":[{` +
	`"severity":"high",` +
	`"confidence":"high",` +
	`"category":"vague acceptance criteria",` +
	`"finding":"The requirement states an outcome with no measurable acceptance criterion, ` +
	`so nothing can verify it. This is synthetic demo output.",` +
	`"recommendation":"State a metric, a target and the condition it is measured under."` +
	`}]}`

DemoBlockingReviewJSON is one blocking adversarial-review finding, in the exact shape schema.Review requires.

All five of severity, confidence, category, finding and recommendation are required; a response missing any of them fails DecodeStructured, and runModel retries three times and then fails the initiative -- so a "blocking" finding with a field missing would fail the run rather than block the review, which looks the same from a distance and is not the same thing at all.

`high` is what makes it block: EvaluateApproval blocks on Severity.Blocking() with no disposition, and Blocking() is critical-or-high. The model cannot set a disposition -- ParseFindings does not read one -- so an empty disposition is the only possible state here.

View Source
const DemoDanglingPlanJSON = `{` +
	`"summary":"Synthetic demo execution plan with a dependency that was never planned.",` +
	`"tasks":[{` +
	`"title":"Implement the core",` +
	`"statement":"Build the core of the idea.",` +
	`"requirement":"REQ-1",` +
	`"priority":"must",` +
	`"estimate":"M",` +
	`"depends_on":["A prerequisite that was never planned"]` +
	`}]}`

DemoDanglingPlanJSON is an execution plan whose one task depends on a title no task has, which is what produces errUnresolvedDependencies and parks the initiative on JudgmentPlanDependencies.

Every field schema.ExecutionPlan requires is present. A plan missing one fails DecodeStructured, and runModel retries three times and then fails the initiative -- which from the outside looks like the block this is meant to produce and is not the same thing at all.

The depends_on entry must not normalise-match the task title, or the dependency resolves and the plan is simply approved.

Variables

View Source
var DefaultModels = map[string][]string{
	"openai":     {"gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.5", "gpt-5.4-mini", "gpt-4.1", "gpt-4.1-mini", "gpt-4o", "gpt-4o-mini", "o3-mini"},
	"anthropic":  {"claude-sonnet-5", "claude-opus-5", "claude-fable-5-1", "claude-haiku-4-5-20251001", "claude-opus-4-8", "claude-sonnet-4-5-20250929", "claude-sonnet-4-5"},
	"gemini":     {"gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash", "gemini-3.5-flash", "gemini-3.1-pro-preview", "gemini-2.5-flash", "gemini-2.5-pro"},
	"deepseek":   {"deepseek-v4-pro", "deepseek-flash", "deepseek-chat", "deepseek-reasoner"},
	"openrouter": {"anthropic/claude-sonnet-5", "openai/gpt-5.6-luna", "google/gemini-3.6-flash", "deepseek/deepseek-v4-pro-0813", "qwen/qwen3.8-max-0902", "moonshotai/kimi-k3", "z-ai/glm-5.3", "openai/gpt-4o", "meta-llama/llama-4-maverick"},
	"ollama":     {"qwen3.8", "gpt-oss:20b", "gemma4:26b", "llama3.1", "llama3.2", "qwen2.5", "mistral", "deepseek-r1"},
}

DefaultModels is a curated catalog of common models per provider. It seeds the UI/CLI pickers and, since audit 4, backs config.UnknownModelProblems.

Still advisory in the sense that matters: any model name is accepted, and a name absent from this list produces a *warning*, never a rejection, because a valid model can postdate the catalog. But it is no longer only cosmetic -- deleting an entry here makes a correct id start warning, so keep it current.

Order matters: DefaultModelFor returns models[0], and that is the model a new user gets when they set only a provider key. Put a model first only after a real call to it returns 200; a listing is not enough.

Refreshed 2026-09-17 against each provider's live API. Every id below answered a one-token chat completion with 200 that day, except where noted. Removed because they returned 404: claude-3-7-sonnet-latest, claude-3-5-haiku-latest, claude-opus-4-1, gemini-2.0-flash, gemini-1.5-pro and openrouter's anthropic/claude-3.7-sonnet.

  • gemini: gemini-2.5-flash and gemini-2.5-pro still appear in Google's listing, but return 404 "no longer available to new users". They stay for accounts that can still reach them, and must never lead. gemini-3.8-flash returned 503 "high demand" and gemini-3.1-pro-preview returned 429 (quota), so neither leads, but both exist.
  • ollama: these are library names the operator must pull first. The catalog cannot verify them against a server it does not run.
View Source
var ErrTruncated = errors.New("model: output truncated at the token budget")

ErrTruncated reports that the provider stopped because it hit the output budget rather than because the model finished.

This is the safety net under the stage-budget cap. Capping a request to the provider's ceiling turns a guaranteed 400 into a request that succeeds -- but a structured reply cut mid-object is NOT reliably caught downstream: repairJSON closes unterminated strings and containers, and the review schema has no minItems, so a findings list truncated from 15 entries to 1 validates clean. The result would be a silently shorter adversarial review.

So truncation is detected where it is actually visible -- the provider's own finish reason -- and raised loudly. The engine's retry loop resends the same request, so a truncation surfaces as a real failure with a message naming the cause instead of a quietly diminished artifact.

Functions

func CostUSD

func CostUSD(model string, inputTokens, outputTokens int64) float64

CostUSD returns the cost of input/out tokens (counts) for a model name, using the canonical pricing table and longest-prefix normalization.

func DefaultModelFor

func DefaultModelFor(provider string) string

DefaultModelFor returns a sensible default model name for a provider, or "model" if the provider is unknown.

Types

type AnthropicProvider

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

AnthropicProvider calls the Anthropic messages API natively (§41).

func NewAnthropic

func NewAnthropic(apiKey, baseURL string) *AnthropicProvider

NewAnthropic builds an Anthropic provider.

func (*AnthropicProvider) Capabilities

func (p *AnthropicProvider) Capabilities() Capabilities

func (*AnthropicProvider) Complete

func (p *AnthropicProvider) Complete(ctx context.Context, req Request) (Response, error)

Complete implements Provider.

func (*AnthropicProvider) ListModels

func (p *AnthropicProvider) ListModels(ctx context.Context) ([]string, error)

ListModels lists models for Anthropic via GET /models.

func (*AnthropicProvider) Name

func (p *AnthropicProvider) Name() string

type Capabilities

type Capabilities struct {
	StructuredOutput  bool
	Tools             bool
	Streaming         bool
	ReasoningControls bool
	ContextLimit      int
	MaxOutput         int
}

Capabilities describes what a provider/model supports (§40).

type FakeProvider

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

FakeProvider is a deterministic provider for hermetic CI and tests. When no scripted response is registered it generates input-aware (but clearly synthetic) output from the user's idea, so the no-provider demo responds to what the user actually typed instead of returning hardcoded content.

func NewFakeProvider

func NewFakeProvider() *FakeProvider

NewFakeProvider returns a fake provider with full capabilities.

func (*FakeProvider) Calls

func (f *FakeProvider) Calls() []Request

Calls returns the requests seen so far (for assertions).

func (*FakeProvider) Capabilities

func (f *FakeProvider) Capabilities() Capabilities

Capabilities implements Provider.

func (*FakeProvider) Complete

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

Complete implements Provider.

func (*FakeProvider) EnqueueResponse

func (f *FakeProvider) EnqueueResponse(schemaName, rawJSON string)

EnqueueResponse appends a response to the FIFO queue for a schema name; the queue is consumed before the default response.

func (*FakeProvider) Name

func (f *FakeProvider) Name() string

Name implements Provider.

func (*FakeProvider) SetResponse

func (f *FakeProvider) SetResponse(schemaName, rawJSON string)

SetResponse registers the raw JSON to return for a schema name.

type GeminiProvider

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

GeminiProvider calls the Google generative-language API natively (§41).

func NewGemini

func NewGemini(apiKey, baseURL string) *GeminiProvider

NewGemini builds a Google Gemini provider. baseURL defaults to the v1beta generative-language endpoint.

func (*GeminiProvider) Capabilities

func (p *GeminiProvider) Capabilities() Capabilities

func (*GeminiProvider) Complete

func (p *GeminiProvider) Complete(ctx context.Context, req Request) (Response, error)

Complete implements Provider.

func (*GeminiProvider) ListModels

func (p *GeminiProvider) ListModels(ctx context.Context) ([]string, error)

ListModels lists models for Google Gemini via GET /models.

func (*GeminiProvider) Name

func (p *GeminiProvider) Name() string

type Image

type Image struct {
	Data      []byte
	MediaType string // e.g. "image/png", "image/jpeg"
}

Image is one image attached to a request (for vision models).

type Message

type Message struct {
	Role    string `json:"role"` // system | user | assistant
	Content string `json:"content"`
}

Message is a single conversation turn.

type MissingKeyProvider added in v0.5.0

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

MissingKeyProvider stands in for a keyed provider whose API key is not set in the daemon's environment or the project's .env (F1).

Without this, registering the real HTTP client anyway sent every request straight to the provider, which answered 401 with its own JSON error body -- and that raw body reached the UI verbatim, since nothing between the provider and the response surface recognized "no key" as a distinct, actionable case. Complete here fails before any network call, with a message naming the exact variable to set and the fix (`idea daemon stop`, so the next start re-reads the environment).

It deliberately does NOT implement ModelLister: a model-listing call on a keyless entry should fall back to the bundled catalog (buildProvidersView's `ready` gate already keeps it from calling in here), not fail loudly for a feature (browsing models) that does not need the key at all.

func NewMissingKeyProvider added in v0.5.0

func NewMissingKeyProvider(name, keyEnv string) *MissingKeyProvider

NewMissingKeyProvider returns a provider that always fails with a message naming keyEnv as the fix, for a provider named name.

func (*MissingKeyProvider) Capabilities added in v0.5.0

func (p *MissingKeyProvider) Capabilities() Capabilities

Capabilities returns the zero value: nothing about this provider is ever actually used to shape a request, since Complete always fails first.

func (*MissingKeyProvider) Complete added in v0.5.0

func (p *MissingKeyProvider) Complete(ctx context.Context, req Request) (Response, error)

Complete always fails, before any HTTP call, naming the missing key and the fix.

func (*MissingKeyProvider) Name added in v0.5.0

func (p *MissingKeyProvider) Name() string

Name reports the provider's registered name.

type ModelLister

type ModelLister interface {
	ListModels(ctx context.Context) ([]string, error)
}

ModelLister is implemented by providers that can list their available models. The catalog (DefaultModels) is only a fallback when a provider cannot (or does not need to) enumerate models live.

type OllamaProvider

type OllamaProvider struct {
	*OpenAIProvider
	// contains filtered or unexported fields
}

OllamaProvider is an OpenAI-compatible local provider that additionally enumerates installed models via GET /api/tags (at the server root, not /v1).

func NewOllama

func NewOllama(baseURL string) *OllamaProvider

NewOllama builds an Ollama provider for the given OpenAI-compatible base URL (e.g. http://localhost:11434/v1).

func (*OllamaProvider) ListModels

func (p *OllamaProvider) ListModels(ctx context.Context) ([]string, error)

ListModels lists installed Ollama models via GET /api/tags.

type OpenAIProvider

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

OpenAIProvider calls an OpenAI-compatible chat-completions API (§41). It is used for OpenAI, OpenRouter, Ollama, and any custom OpenAI-compatible endpoint (Groq, Together, LM Studio, …).

func NewOpenAI

func NewOpenAI(apiKey, baseURL string) *OpenAIProvider

NewOpenAI builds an OpenAI provider.

func NewOpenAICompat

func NewOpenAICompat(name, apiKey, baseURL string) *OpenAIProvider

NewOpenAICompat builds an OpenAI-compatible provider with a custom name.

func (*OpenAIProvider) Capabilities

func (p *OpenAIProvider) Capabilities() Capabilities

func (*OpenAIProvider) Complete

func (p *OpenAIProvider) Complete(ctx context.Context, req Request) (Response, error)

Complete implements Provider.

func (*OpenAIProvider) ListModels

func (p *OpenAIProvider) ListModels(ctx context.Context) ([]string, error)

ListModels lists models for an OpenAI-compatible provider (OpenAI, OpenRouter, Groq, Together, …) via GET /models.

func (*OpenAIProvider) Name

func (p *OpenAIProvider) Name() string

type Pricing

type Pricing struct {
	InputUSD  float64
	OutputUSD float64
}

Pricing is the USD cost per 1,000,000 tokens for a model family.

type Provider

type Provider interface {
	Name() string
	Capabilities() Capabilities
	// Complete runs one request and returns a response. It must set
	// ActualModel to the model actually used (no silent fallback, §36).
	Complete(ctx context.Context, req Request) (Response, error)
}

Provider is a model provider adapter.

type Registry

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

Registry holds multiple named providers and routes requests by model spec ("provider/model"). It supports OpenAI, Anthropic, Gemini, OpenRouter, Ollama, and arbitrary OpenAI-compatible endpoints (§40).

func NewRegistry

func NewRegistry(defaultProvider string) *Registry

NewRegistry builds an empty registry with a default provider name.

func (*Registry) Add

func (r *Registry) Add(name string, p Provider)

Add registers a provider under a name.

func (*Registry) Complete

func (r *Registry) Complete(ctx context.Context, spec string, req Request) (Response, error)

Complete resolves a spec and runs it on the matching provider.

func (*Registry) Default

func (r *Registry) Default() string

Default returns the default provider name.

func (*Registry) Get

func (r *Registry) Get(name string) (Provider, bool)

Get returns a provider by name.

func (*Registry) Len

func (r *Registry) Len() int

Len returns the number of registered providers.

func (*Registry) ListModels

func (r *Registry) ListModels(ctx context.Context, name string) ([]string, error)

ListModels returns live models for a provider, falling back to the catalog.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns the registered provider names, sorted.

func (*Registry) Resolve

func (r *Registry) Resolve(spec string) (Provider, string, error)

Resolve maps a model spec to a provider and model name. A spec of "provider/model" selects that provider; a bare model name uses the default provider (§40). Splitting is on the first slash.

func (*Registry) SetDefault

func (r *Registry) SetDefault(name string)

SetDefault sets the provider used when a model spec has no "/" prefix.

type Request

type Request struct {
	Model           string
	System          string
	Messages        []Message
	Images          []Image
	ReasoningEffort string
	MaxOutput       int
	JSONSchema      []byte // if set, structured output is requested
	JSONSchemaName  string
}

Request is a normalized model request. Images, when present, are attached to the (single) user message as vision content by providers that support it.

type Response

type Response struct {
	Text        string
	RawJSON     string
	Usage       Usage
	ActualModel string
}

Response is a normalized model response. RawJSON is the provider's raw (post-redaction) output; Text is the plain-text form when not structured.

type StructuredResult

type StructuredResult struct {
	Raw         []byte         // raw model output (post-redaction)
	Repaired    []byte         // repaired content (post-redaction)
	Valid       map[string]any // validated object
	WasRepaired bool
}

StructuredResult is the outcome of the structured-output pipeline (§39).

func DecodeStructured

func DecodeStructured(raw []byte, schema []byte) (*StructuredResult, error)

DecodeStructured validates raw JSON against schema, applying bounded repair on failure (single pass). It returns the validated object and whether repair was used. Raw and repaired content are returned for digest storage.

type Usage

type Usage struct {
	InputTokens  int64
	OutputTokens int64
	CostUSD      float64
}

Usage records token/cost usage (§36).

Jump to

Keyboard shortcuts

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