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
- Variables
- func ContextWindowFor(provider, model string) int
- func CostUSD(model string, inputTokens, outputTokens int64) float64
- func DefaultModelFor(provider string) string
- func MaxOutputFor(modelName string) (int, bool)
- type AnthropicProvider
- type Capabilities
- type FakeProvider
- func (f *FakeProvider) Calls() []Request
- func (f *FakeProvider) Capabilities() Capabilities
- func (f *FakeProvider) Complete(_ context.Context, req Request) (Response, error)
- func (f *FakeProvider) EnqueueCost(schemaName string, usd float64)
- func (f *FakeProvider) EnqueueError(schemaName string, err error)
- func (f *FakeProvider) EnqueueResponse(schemaName, rawJSON string)
- func (f *FakeProvider) Name() string
- func (f *FakeProvider) SetResponse(schemaName, rawJSON string)
- type GeminiProvider
- type Image
- type Message
- type MissingKeyProvider
- type ModelLister
- type OllamaProvider
- type OpenAIProvider
- type Pricing
- type Provider
- type Registry
- func (r *Registry) Add(name string, p Provider)
- func (r *Registry) Complete(ctx context.Context, spec string, req Request) (Response, error)
- func (r *Registry) Default() string
- func (r *Registry) Get(name string) (Provider, bool)
- func (r *Registry) Len() int
- func (r *Registry) ListModels(ctx context.Context, name string) ([]string, error)
- func (r *Registry) Names() []string
- func (r *Registry) Resolve(spec string) (Provider, string, error)
- func (r *Registry) SetDefault(name string)
- type Request
- type Response
- type StructuredResult
- type Usage
Constants ¶
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.
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 ¶
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"},
"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.
Removed 2026-09-19 (ICP walkthrough finding: "the bundled model catalog lists deprecated models (e.g. gemini-2.5-flash) that 404 at call time"): gemini-2.5-flash and gemini-2.5-pro, which an earlier revision of this catalog kept, deprioritized, "for accounts that can still reach them". A model this catalog already knows returns "no longer available to new users" for every new account has no business staying in a list whose whole purpose is steering new setups away from dead ids -- being last in the list still means a project's config or the Settings picker can offer it. If your account can still reach one of them, set it explicitly with `idea model set gemini/gemini-2.5-flash`; a name absent from this list is a warning, never a rejection (see the package doc above), and a 404 against any model, catalog member or not, now names the model in the error (see model.httpError).
- gemini: gemini-3.8-flash returned 503 "high demand" and gemini-3.1-pro-preview returned 429 (quota) on 2026-09-17, so neither leads, but both exist and are not known-dead the way gemini-2.5-* is.
- ollama: these are library names the operator must pull first. The catalog cannot verify them against a server it does not run.
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.
var ModelContextWindows = map[string]int{
"openai/gpt-4.1": 1047576,
"openai/gpt-4.1-mini": 1047576,
"openai/gpt-4o": 128000,
"openai/gpt-4o-mini": 128000,
"openai/o3-mini": 200000,
}
ModelContextWindows overrides contextWindowFallback with a verified figure for a specific "provider/model" spec, checked against that provider's own model documentation (not a listing, not a guess). Add an entry here only once you have actually looked it up.
This exists for the coding-agent executor (internal/executor/hermescfg.go): Hermes Agent refuses to start below 64,000 tokens of context, and every provider here is wired into Hermes as an explicit custom_provider with no context declared, so without this Hermes has to guess via its own model-family auto-detection -- which is exactly how hermes + openai/gpt-4.1 -mini failed deterministically (ICP walkthrough finding): gpt-4.1-mini actually has a ~1M-token window, real and verified below, but Hermes's own guess for it landed under the 64k floor anyway. Declaring the real number explicitly removes the guess instead of refusing the combination.
Checked 2026-09-19 against developers.openai.com/api/docs/models/<id>.
Functions ¶
func ContextWindowFor ¶ added in v0.6.0
ContextWindowFor returns the context window, in tokens, to declare for a provider/model pair, or 0 when nothing should be declared explicitly (an unrecognized provider, or ollama -- see contextWindowFallback).
func CostUSD ¶
CostUSD returns the cost of input/out tokens (counts) for a model name, using the canonical pricing table and longest-prefix normalization.
func DefaultModelFor ¶
DefaultModelFor returns a sensible default model name for a provider, or "model" if the provider is unknown.
func MaxOutputFor ¶ added in v0.6.0
MaxOutputFor returns the verified real output-token ceiling for a model name (bare, vendor-prefixed, or dot/dash spelled -- see modelCandidates), and ok=false when the model is not in modelMaxOutput. A caller sees ok=false for any model this catalog has not verified -- including a brand-new one that postdates this table -- and must fall back to its provider's own baseline Capabilities.MaxOutput rather than treat 0 as a real ceiling.
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) 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) EnqueueCost ¶ added in v0.6.0
func (f *FakeProvider) EnqueueCost(schemaName string, usd float64)
EnqueueCost appends a CostUSD to report on the NEXT Complete() call for a schema name (FIFO, independent of EnqueueResponse's own queue) -- for tests that need to script a specific per-attempt spend, e.g. proving a retried call's cost is accumulated rather than overwritten by the next attempt's (M5, review fix). A schema with nothing queued reports 0, as before this existed.
func (*FakeProvider) EnqueueError ¶ added in v0.6.0
func (f *FakeProvider) EnqueueError(schemaName string, err error)
EnqueueError appends an error to return on the NEXT Complete() call for a schema name (FIFO, independent of EnqueueResponse's own queue and consumed before it) -- for a test that needs to script a failed attempt, most commonly a truncated one (model.ErrTruncated, via a real provider's own truncatedError), so it can prove a caller's retry-with-reduced-ask or batch-and-merge degrade path actually runs and completes, rather than merely existing in the code and being exercised only by a real, flaky provider call. A schema with nothing queued behaves exactly as before this existed: Complete falls through to its scripted/demo response.
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) 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) 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 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
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 ¶
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) 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 Provider ¶
type Provider interface {
Name() string
// Capabilities describes this provider's BASELINE capabilities -- not
// necessarily what it can do for any one model. A real HTTP provider's
// true output ceiling varies by model (claude-sonnet-5 and
// claude-haiku-4-5 do not share one, nor do gpt-4o and gpt-4.1), so a
// caller that already knows which model it is about to call should
// prefer MaxOutputFor(modelName) over Capabilities().MaxOutput when one
// is available (see workflow.minOutput). Capabilities() stays the
// provider-wide, model-agnostic baseline: the conservative floor a
// provider's own Complete uses for a model MaxOutputFor does not
// recognize (round-6 B1).
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 ¶
NewRegistry builds an empty registry with a default provider name.
func (*Registry) ListModels ¶
ListModels returns live models for a provider, falling back to the catalog.
func (*Registry) Resolve ¶
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 ¶
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 ¶
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.