spec

package
v1.261203.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: MPL-2.0 Imports: 25 Imported by: 1 module, 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.

README

Unified VModel definitions

spec.Definition is the file contract for model identity, behavior, supported protocols and test expectations. spec.Load accepts JSON or YAML, one object or a list. spec.New compiles those definitions once for both HTTP serving and the existing scenario/matrix adapters.

# Start a standalone provider; no running tb instance is required.
tb vmodel --config model.yaml
# The identical file supplies the upstream response and its assertions.
go run ./cli/harness matrix --mode single --config model.yaml

A small shared definition:

id: hello
kind: mock
mock:
  content: Hello.
  delay: 10ms
expect:
  http_status: 200
  content_equals: Hello.

Common fields are id, optional name/description, kind, optional protocols, tags, expect, structural and skip_transitive. Exactly one behavior block is allowed. Both id and kind are required; identity and metadata live only in the outer envelope.

Kind Behavior block Meaning
mock mock Content, multiple tool_calls, chunks, usage, completion reasons and synthetic errors
recording responses Per-protocol JSON bodies and SSE recordings
sequence sequence Ordered steps, repetitions, default content and exhaustion policy
decision decision first/stable strategy and confidence
transform transform A registered builtin transform, e.g. compact-round-only
builtin builtin A stable reference to a registered Go behavior, e.g. scenario/tool_result

Durations in mock/sequence blocks accept strings such as 50ms or integer nanoseconds; export uses readable strings. The protocol names are openai_chat, openai_responses, anthropic, google, and decisions. Omitting protocols exposes the protocols the behavior actually supports; explicit selections are checked against those capabilities. An unknown model or unsupported protocol returns 404, and missing stream/nonstream recordings return 400. A request never falls back to another model or response format.

A recording uses the same identity and expectations:

id: recorded
kind: recording
responses:
  openai_chat:
    status: 200
    body:
      id: chatcmpl-recorded
      object: chat.completion
      model: recorded
      choices:
        - index: 0
          message: {role: assistant, content: Hello.}
          finish_reason: stop
expect:
  http_status: 200
  content_equals: Hello.

body stores structured JSON. raw_body stores exact response bytes, including whitespace or intentionally malformed JSON. stream retains the SSE line representation. raw_stream retains exact SSE bytes, including comments, CRLFs, IDs, multiline data and event separators. Body alternatives and stream alternatives are mutually exclusive. Completion frames are never appended to a recording. stream_http_error selects a pre-content HTTP failure; its status must agree with status if both are set.

expect uses the existing assertion library. Alongside content/status/tool checks, body_contains and json_fields work on the raw response body for native endpoints. Shared matrix expectations must apply to the client-facing protocol after conversion: for example, completion reasons differ between Chat (stop), Anthropic (end_turn) and Responses (completed). A native recording should use portable content/status checks when testing all clients:

id: choose
kind: decision
decision: {strategy: first}
expect:
  http_status: 200
  json_fields:
    answers.pick.choice: a

In Go, pass an HTTP result with HTTPStatus and RawBody to runtime.Check(id, result). Chat-specific checks additionally use the parsed fields of the existing check.RoundTripResult. A missing expectation is an error when checking, rather than an automatic pass. The chat protocol matrix uses runtime.Scenario(id); native-only decisions are exercised through /v1/decisions and Check. Missing matrix protocols/modes are skipped.

Existing data and Go behavior

All model files use the common envelope. Flat mock/sequence documents, name/mock_responses documents and singular tool_call are rejected. Use tool_calls, including for a single call. The separate LoadMockSpec, DecodeMockSpec, scenario.LoadFixture and scenario.DecodeFixture APIs and protocol-specific MockScenario wrappers have been removed. Runtime mock/sequence structs remain typed Go behavior configuration, not alternative file formats.

# Export the complete core inventory, including opt-in test models/scenarios.
tb vmodel --export catalog.yaml
# Combine canonical definitions into one list without starting a provider.
tb vmodel --config model.json --config recorded.yaml --export models.yaml
# Load the exported inventory again.
tb vmodel --config catalog.yaml

DefaultDefinitions covers every model shipped by the existing default registries. Plain mocks and sequences become data; registered transforms keep behavior references. AllDefinitions additionally includes usage mocks, extended errors and every scenario.AllScenarios() validation fixture. Test-only definitions are not added to production defaults.

Go functions cannot be serialized as JSON/YAML. Request-dependent builtin fixtures keep their original builders and Go assertions through named references. Their responses are not captured once and flattened into static payloads. Custom Go code registers a name before loading:

catalog := spec.NewCatalog()
err := catalog.Register("company/tool-round", func(d spec.Definition) (scenario.Scenario, error) {
    s := makeFreshToolRoundScenario() // retains NonStreamFor/StreamFor and Go assertions
    s.Name = d.ID
    return s, nil
})
// Handle err, then compile with the same definitions used by files.
runtime, err := spec.NewWithCatalog(definitions, catalog)

RegisterModels similarly adapts custom OpenAI/Anthropic models, decision choosers and transform chains. Each factory must return fresh instances for a new runtime. Files refer to these names with kind: builtin and builtin: company/tool-round; a binary without the registration fails clearly.

FromMock and FromSequence wrap common typed Go values in the canonical envelope. Protocol-specific scenario constructors have been consolidated into the same shared mock configuration, with tool_calls in both protocols. Anonymous application-specific callbacks must be given a name by their owning package; they are not automatically discovered or exported. Captured requests and golden output files remain test inputs/evidence, rather than being misidentified as complete model definitions.

Documentation

Overview

Package spec is the shared file contract and execution adapter for virtual models. CLI services and tests load the same Definition values.

Index

Constants

View Source
const FormatDecisions scenario.ResponseFormat = "decisions"

Variables

This section is empty.

Functions

func Export

func Export(defs []Definition, format string) ([]byte, error)

Export emits the same validated contract accepted by Load. No function is silently serialized or discarded: custom Go callbacks need a catalog name.

Types

type Catalog

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

func NewCatalog

func NewCatalog() *Catalog

func (*Catalog) Register

func (c *Catalog) Register(name string, f Factory) error

func (*Catalog) RegisterModels

func (c *Catalog) RegisterModels(name string, f ModelFactory) error

RegisterModels adapts custom Go virtual models, choosers and transform chains. The stable name is serializable; the implementation remains Go code.

type DecisionSpec

type DecisionSpec struct {
	Strategy   string  `json:"strategy"`
	Confidence float64 `json:"confidence,omitempty"`
}

type Definition

type Definition struct {
	ID             string                                        `json:"id"`
	Name           string                                        `json:"name,omitempty"`
	Description    string                                        `json:"description,omitempty"`
	Kind           Kind                                          `json:"kind,omitempty"`
	Protocols      []scenario.ResponseFormat                     `json:"protocols,omitempty"`
	Mock           *vmodel.SharedMockSpec                        `json:"mock,omitempty"`
	Responses      map[scenario.ResponseFormat]scenario.Response `json:"responses,omitempty"`
	Sequence       *SequenceSpec                                 `json:"sequence,omitempty"`
	Decision       *DecisionSpec                                 `json:"decision,omitempty"`
	Transform      *TransformSpec                                `json:"transform,omitempty"`
	Builtin        string                                        `json:"builtin,omitempty"`
	Script         *script.Script                                `json:"script,omitempty"`
	Tags           []string                                      `json:"tags,omitempty"`
	Expect         *scenario.Expect                              `json:"expect,omitempty"`
	Structural     *scenario.Expect                              `json:"structural,omitempty"`
	SkipTransitive bool                                          `json:"skip_transitive,omitempty"`
}

Definition keeps identity, protocol selection and assertions identical across every behavior. Exactly one behavior block is selected by kind.

func AllDefinitions

func AllDefinitions() []Definition

AllDefinitions is the migration/export inventory, including opt-in error and usage fixtures and the request-dependent built-in matrix scenarios. It is deliberately not installed into production defaults.

func Decode

func Decode(data []byte) ([]Definition, error)

func DefaultDefinitions

func DefaultDefinitions() []Definition

DefaultDefinitions converts all shipped user-facing models to the common definition. Plain responses are exported as data; transforms keep explicit behavior references so their request-dependent Go logic stays intact.

func FromMock

func FromMock(s vmodel.SharedMockSpec) Definition

func FromSequence

func FromSequence(s vmodel.SequenceConfig) Definition

func Load

func Load(path string) ([]Definition, error)

Load accepts one canonical definition or a list. Identity and kind are explicit.

func (Definition) MarshalJSON

func (d Definition) MarshalJSON() ([]byte, error)

MarshalJSON writes identity once with readable durations. Runtime-only mock identity is restored by Normalize.

func (Definition) MarshalYAML

func (d Definition) MarshalYAML() (any, error)

func (*Definition) Normalize

func (d *Definition) Normalize() error

Normalize validates Go-built and file-built definitions with the same rules.

type Factory

type Factory func(Definition) (scenario.Scenario, error)

Catalog names Go behavior factories explicitly. Factories must create fresh instances so sequence cursors and dynamic callbacks never leak across runs.

type Kind

type Kind string
const (
	Mock      Kind = "mock"
	Recording Kind = "recording"
	Sequence  Kind = "sequence"
	Decision  Kind = "decision"
	Transform Kind = "transform"
	Builtin   Kind = "builtin"
	// Script serves a scene of conversations (vmodel/script) rather than one
	// model's behaviour: point --fallback at it so every model id reaches it.
	Script Kind = "script"
)

type ModelFactory

type ModelFactory func(Definition) (Models, error)

type Models

type Models struct {
	Anthropic anthropic.VirtualModel
	OpenAI    openai.VirtualModel
	Decision  decision.VirtualModel
}

type Runtime

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

Runtime is the common service used by the CLI and by scenario adapters.

func New

func New(defs []Definition) (*Runtime, error)

func NewWithCatalog

func NewWithCatalog(defs []Definition, catalog *Catalog) (*Runtime, error)

func (*Runtime) Check

func (r *Runtime) Check(id string, result *check.RoundTripResult) error

Check applies the file's expectations to a native endpoint result. JSON field and raw-body checks work for decisions and recordings as well as chat.

func (*Runtime) IDs

func (r *Runtime) IDs() []string

func (*Runtime) Scenario

func (r *Runtime) Scenario(id string) (scenario.Scenario, error)

Scenario adapts the same compiled runtime to the existing protocol matrix. Native Go callbacks remain callbacks; generated models are rendered by the production handler rather than duplicated protocol templates.

func (*Runtime) ScriptIDs added in v1.261126.1

func (r *Runtime) ScriptIDs() []string

ScriptIDs are the ids of the runtime's scripts, sorted.

func (*Runtime) Scripts added in v1.261126.1

func (r *Runtime) Scripts() map[string]*script.Engine

Scripts are the runtime's script engines by id.

func (*Runtime) ServeHTTP

func (r *Runtime) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Runtime) SetFallback added in v1.261126.1

func (r *Runtime) SetFallback(fallbackID string) error

SetFallback makes request model ids that no definition names be served by the definition fallbackID, on the protocols that definition supports (other protocols still answer 404). Replies echo the id the client asked for. It is opt-in: without it unknown models stay a 404, which is the contract tests and the production /virtual endpoint rely on. Call it before serving.

type SequenceSpec

type SequenceSpec struct {
	Steps          []vmodel.SequenceStep `json:"steps"`
	DefaultContent string                `json:"default_content,omitempty"`
	OnExhaust      vmodel.ExhaustPolicy  `json:"on_exhaust,omitempty"`
	Delay          time.Duration         `json:"delay,omitempty"`
}

type TransformSpec

type TransformSpec struct {
	Builtin string `json:"builtin"`
}

Transform names are registered transforms, not executable expressions.

Jump to

Keyboard shortcuts

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