model

package
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: Apache-2.0 Imports: 18 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.",` +
	`"requirement":"` + DemoRequirementPlaceholder + `",` +
	`"justification":"The revision restated the outcome but still names nothing a test could measure. This is synthetic demo output."` +
	`}]}`

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.

"requirement" and "justification" are what keep it blocking under the review loop's convergence rules (review.convergence, guarded by default): a finding that cites no active requirement is scope expansion and is made advisory, and a finding that repeats an addressed prior-cycle finding without saying why the revision did not resolve it is made advisory too. The citation is DemoRequirementPlaceholder, which Complete replaces with the first requirement code the request lists -- the code changes every cycle, since each revision supersedes the requirement set, so no fixed code would still be active by cycle 2.

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.

View Source
const DemoRequirementPlaceholder = "{{first_requirement}}"

DemoRequirementPlaceholder, anywhere in a scripted or queued response, is replaced by the first requirement code the request lists -- or, when it lists none (the plan review lists tasks), the first task code -- and left as is when it lists neither. It lets a fixed response cite a requirement whose code is not known until the run has minted it.

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"},
	"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.
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.

View Source
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

func ContextWindowFor(provider, model string) int

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

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.

func MaxOutputFor added in v0.6.0

func MaxOutputFor(modelName string) (int, bool)

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) 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) 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) Name

func (f *FakeProvider) Name() string

Name implements Provider.

func (*FakeProvider) SetDefaultCost added in v0.7.0

func (f *FakeProvider) SetDefaultCost(usd float64)

SetDefaultCost makes every call with no queued cost report usd. The demo provider uses it for demo.cost_per_call_usd, so a spending cap can be reached without a real 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 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

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