vmodel

package
v0.260604.1 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2026 License: MPL-2.0 Imports: 3 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

vmodel

Virtual models — synthetic, protocol-compliant provider implementations that power the production /virtual/v1/* endpoint (used for onboarding, demos, and dry-runs without configuring a real upstream provider). They are wired into the virtual server at vmodel/virtualserver and shipped in the production binary via server.UseVirtualModelEndpoints.

The same primitives are reused as an in-process LLM substitute by test packages that need wire-format-correct fixtures (see internal/protocoltest).

Layout

vmodel/
├── interface.go        // base VirtualModel interface (provider-neutral)
├── types.go            // VirtualModelType, Model, ToolCallConfig, helpers
├── registry.go         // GenericRegistry[T] — shared thread-safe registry
├── base_mock.go        // BaseMockModel — shared identity/metadata methods
├── stream.go           // ResolveChunkDelay, EmitChunks — shared stream helpers
├── defaults_shared.go  // SharedDefaultMocks() + ErrorMockSpecs() — shared specs
├── error_injection.go  // ErrorInjection, ErrorInjectingModel, EmitGate
├── README.md
├── anthropic/          // Anthropic-protocol models + Registry alias
├── openai/             // OpenAI Chat-protocol models + Registry alias
├── virtualserver/      // Production Gin HTTP handler + Service wiring
└── benchmark/          // Load-test client + local server factory
    └── examples/       // Runnable server/client examples

The root package contains provider-neutral primitives shared by all sub-packages. Concrete models, protocol-specific request/response types, stream events, and the Registry alias live in the anthropic and openai sub-packages. The two sub-packages do not import each other.

Positioning & registration discipline

vmodel is a business-first package: it ships in production to back the public /virtual/v1/* endpoint, and it is the single source of truth for synthetic, protocol-compliant model behavior across the codebase. Test packages are secondary consumers that reuse the same primitives.

Role Surface Consumer
Primary (production) /virtual/v1/messages, /virtual/v1/chat/completions internal/server mounts virtualserver.Service for end-user demos / onboarding / dry-runs
Secondary (tests) In-process GenericRegistry[T] internal/protocoltest.Scenario, cli/harness --mock

Registration discipline. Anything added to anthropic.RegisterDefaults or openai.RegisterDefaults is visible to end users of the production endpoint. Therefore the defaults registry must contain only user-facing demo entries — protocol-compliant, named clearly, useful for onboarding and dry-runs (echo-model, ask-user-question, virtual-claude-3, virtual-gpt-4, the compact transforms, etc.).

Test-only fixtures (protocol corner cases, wire-format edge cases, scenario-specific stubs) must not be added to RegisterDefaults. Tests that need bespoke synthetic models should construct their own GenericRegistry[T] (the way protocoltest does for Scenario) and register fixtures there — keeping the production defaults clean.

Opt-in fixture sets. Two named registration helpers ship alongside RegisterDefaults for callers that want pre-built fixtures without polluting the production endpoint:

Helper What it registers When to call
RegisterStreamTestMocks(reg) virtual-stream-test, virtual-stream-test-tool — advertise the full usage shape (prompt / completion / cached / cache-creation / reasoning) Streaming-converter tests that need deterministic usage emission
RegisterErrorMocks(reg) virtual-fail-precontent-{429,500}, virtual-fail-midstream-{close,event} — always fail per the configured stage Failover / resilience tests that need a deterministic broken upstream

Both helpers live in each per-protocol sub-package (anthropic.Register… and openai.Register…), source their specs from the root defaults_shared.go, and are kept out of RegisterDefaults so production registries stay clean.

Design

GenericRegistry

GenericRegistry[T VirtualModel] is a thread-safe, generic registry that underpins all per-protocol registries in this module:

// anthropic.Registry and openai.Registry are type aliases:
type Registry = virtualmodel.GenericRegistry[VirtualModel]

Any package that needs to store objects satisfying virtualmodel.VirtualModel can instantiate its own GenericRegistry directly — protocoltest.Scenario does this for test scenarios.

One registry per protocol
anthropicReg := anthropic.NewRegistry()
anthropic.RegisterDefaults(anthropicReg)

openaiReg := openai.NewRegistry()
openai.RegisterDefaults(openaiReg)

A model registered in anthropic.Registry is callable only via /virtual/v1/messages; a model in openai.Registry is callable only via /virtual/v1/chat/completions. The registry is the protocol context — there is no runtime Protocols() declaration, no byProtocol index, and no protocol type assertions in lookup paths.

When a client requests a model that does not exist in the registry for the endpoint it called, the handler returns 404 Not Found (not 501). A model is either registered for that protocol or it isn't.

The same ID can exist in both registries simultaneously, holding two independent concrete instances. echo-model, ask-user-question, ask-confirmation, and web-search-example are registered in both defaults exactly this way. Each instance only implements its own protocol's interface, so there is no possibility of a model "lying" about which protocols it speaks.

Anthropic v1 vs. beta

The real Anthropic API distinguishes MessageNewParams (v1) and BetaMessageNewParams (beta) on the wire, gated by ?beta=true. The virtual server accepts both and canonicalizes to the beta superset at the HTTP boundary (virtualserver/handler.go). Vmodels see exactly one request type — *protocol.AnthropicBetaMessagesRequest — so the protocol-version distinction does not leak into the VirtualModel interface.

Interfaces

Base (interface.go)
type VirtualModel interface {
    GetID() string
    GetName() string
    GetDescription() string
    GetType() VirtualModelType
    SimulatedDelay() time.Duration
    ToModel() Model
}
Anthropic sub-interface (anthropic/interface.go)
type VirtualModel interface {
    virtualmodel.VirtualModel
    HandleAnthropic(req *protocol.AnthropicBetaMessagesRequest) (VModelResponse, error)
    HandleAnthropicStream(req *protocol.AnthropicBetaMessagesRequest, emit func(any)) error
}
OpenAI sub-interface (openai/interface.go)
type VirtualModel interface {
    virtualmodel.VirtualModel
    HandleOpenAIChat(req *protocol.OpenAIChatCompletionRequest) (VModelResponse, error)
    HandleOpenAIChatStream(req *protocol.OpenAIChatCompletionRequest, emit func(any)) error
}

Shared root-package primitives

BaseMockModel

BaseMockModel implements the six identity/metadata methods of the base VirtualModel interface (GetID, GetName, GetDescription, GetType, SimulatedDelay, ToModel). Protocol-specific mock types embed it and only add their Handle* methods:

type MockModel struct {
    virtualmodel.BaseMockModel
    cfg *MockModelConfig
}
ResolveChunkDelay / EmitChunks

ResolveChunkDelay(totalDelay, chunkCount) distributes a model's simulated latency evenly across stream chunks. EmitChunks is the shared inner loop — it calls the emit closure once per chunk with the appropriate sleep in between. Both the anthropic and openai DefaultStream helpers use these.

SharedDefaultMocks

SharedDefaultMocks() returns the specs for the four mocks that are registered in both default registries. Each protocol's RegisterDefaults calls this and wraps each spec in its own MockModel:

for _, spec := range virtualmodel.SharedDefaultMocks() {
    _ = reg.Register(NewMockModel(&MockModelConfig{
        ID: spec.ID, Name: spec.Name, Content: spec.Content,
        ToolCall: spec.ToolCall, Delay: spec.Delay,
    }))
}

Model categories

VirtualModelType (declared in types.go) tags every vmodel so the extension UI and registry consumers can group by behavior:

Type Meaning Examples
static Returns a fixed text response virtual-claude-3, virtual-gpt-4, echo-model
tool Returns a tool_use / tool_calls block ask-user-question, ask-confirmation, web-search-example
proxy Applies a transform chain (no upstream call; same model also runs in real proxy paths) compact-thinking, claude-code-compact

Default model allocation

Model ID Anthropic registry OpenAI registry
virtual-claude-3 X
virtual-gpt-4 X
echo-model X X
ask-user-question X X
ask-confirmation X X
web-search-example X X
compact-thinking X
compact-round-only X
compact-round-files X
claude-code-compact X
claude-code-strategy X

Compact transforms are Anthropic-only because they operate on the Anthropic message shape. They could be ported to OpenAI by adding an OpenAI-side TransformModel, but no production use case currently calls for it.

The four shared mocks (echo-model, ask-user-question, ask-confirmation, web-search-example) are defined once in defaults_shared.go and registered by both anthropic.RegisterDefaults and openai.RegisterDefaults.

Adding a model

Single protocol
reg := service.GetAnthropicRegistry()
_ = reg.Register(anthropic.NewMockModel(&anthropic.MockModelConfig{
    ID:      "my-mock",
    Name:    "My Mock",
    Content: "fixed reply",
    Delay:   50 * time.Millisecond,
}))
Both protocols (same logical model)

Register two separate concrete instances under the same ID — one per registry. They can share configuration but not state:

cfg := myConfig{...}
_ = anthropicReg.Register(anthropic.NewMockModel(&anthropic.MockModelConfig{
    ID: "my-dual", Content: cfg.Reply,
}))
_ = openaiReg.Register(openai.NewMockModel(&openai.MockModelConfig{
    ID: "my-dual", Content: cfg.Reply,
}))

For richer dual-protocol models with shared logic, factor the logic into a private core type and embed it in two thin wrappers — one in each sub-package — that implement the respective Handle* methods.

Custom (non-mock) model

Implement the relevant sub-interface directly. The sub-package must own the type so it cannot accidentally implement the other protocol's interface.

Streaming

Each sub-package defines its own stream event types, used by the Handle*Stream methods to emit deltas via the emit func(any) callback:

  • anthropic: StreamStartEvent, TextDeltaEvent, ToolUseEvent, DoneEvent
  • openai: DeltaEvent, ToolEvent, DoneEvent

The virtual server (virtualserver/handler.go) translates these into the wire-format SSE frames expected by each protocol.

DefaultStream in each sub-package converts a non-streaming Handle* response into a stream event sequence using the shared EmitChunks helper, so static and tool mocks get streaming for free.

Error injection

A small facility lets a mock simulate an upstream failure without writing a custom handler. It is opt-in per model — set MockModelConfig.Error (or MockScenario.Error) to an ErrorInjection, and the virtual server handler honors it. Models with no Error field set behave exactly as before.

type ErrorInjection struct {
    Stage ErrorStage // ErrorStagePreContent or ErrorStageMidStream

    // Pre-content fields
    Status  int    // HTTP status (defaults to 500)
    Message string // rendered into the protocol-specific error envelope
    Type    string // defaults to "api_error"

    // Mid-stream fields
    AfterEvents   int           // emit N real events first (default 1)
    MidStreamMode MidStreamMode // ConnectionClose (TCP hijack) or ErrorEvent (SSE error frame)
}

The two stages correspond to two distinct gateway paths (and are exactly the cases the priority-routing firstChunkGate must handle differently):

Stage Wire behavior What it exercises
ErrorStagePreContent Handler returns Status + protocol-shaped error envelope before any streaming starts. No SSE frames. Gate stays buffered → retryable; failover MUST retry.
ErrorStageMidStream Handler writes 200 + headers + AfterEvents real chunks, then either hijacks and closes the TCP connection or emits a final SSE error frame. Gate already committed → bytes on the wire; failover MUST NOT retry.
Architecture: model declares, handler enforces

Mock stream loops are kept gate-free: DefaultStream and MockModel.Handle*Stream simply emit every event they would normally emit. The virtualserver handler owns the mid-stream cutoff:

  1. Before invoking Handle*Stream, the handler asks the model whether it implements ErrorInjectingModel and configures an injection.
  2. If a mid-stream injection is configured, the handler wraps the model's emit callback in a counting gate. After AfterEvents events have been admitted, subsequent events (including terminal DoneEvent / UsageEvent) are silently dropped.
  3. Once the model's stream loop returns, the handler applies the configured MidStreamMode (hijackAndClose or applyMidStreamBreak*).

For pre-content injection there's no gate — the handler short-circuits with writePreContentError{OpenAI,Anthropic} before dispatching to the model at all.

This split keeps the failure-injection surface narrow (one small facility, isolated to the handler) and leaves the common mock path uncluttered.

Pre-registered fail mocks

vmodel.ErrorMockSpecs() defines four well-known broken upstreams. Register them into either per-protocol registry with the opt-in helper:

openai.RegisterErrorMocks(svc.GetOpenAIRegistry())
anthropic.RegisterErrorMocks(svc.GetAnthropicRegistry())
Model ID Behavior
virtual-fail-precontent-429 HTTP 429 + rate_limit_error envelope (retryable)
virtual-fail-precontent-500 HTTP 500 + api_error envelope (retryable)
virtual-fail-midstream-close One real chunk then TCP close (not retryable)
virtual-fail-midstream-event One real chunk then SSE error frame (not retryable)

Failover e2e tests (internal/protocoltest) use these directly via SetupFailoverRoute(... primaryFailModel: pt.FailMockPreContent429) instead of standing up ad-hoc httptest.Server instances.

Benchmarking (benchmark/)

benchmark.NewLocalServer() boots a virtualserver.Service with the default registries as an in-process HTTP server. BenchmarkClient drives load against any HTTP endpoint that speaks the virtual server API.

srv := benchmark.NewLocalServer()
defer srv.Close()

client := benchmark.NewBenchmarkClient(srv.URL())
result, _ := client.RunChatBenchmark(ctx, benchmark.BenchmarkConfig{
    Concurrency: 10,
    Requests:    100,
})
fmt.Printf("TPS: %.1f  p99: %v\n", result.TPS, result.P99Latency)

See benchmark/examples/ for runnable server and client programs.

  • vmodel/virtualserver — Production Gin HTTP handler, routes, request/response shaping. Owns the v1 → beta lift for Anthropic.
  • internal/protocoltest — Test-only consumer that reuses GenericRegistry[Scenario] as a primitive (its Scenario type satisfies vmodel.VirtualModel). Serves pre-rendered byte/SSE payloads for wire-format protocol testing. It does not inherit production defaults from RegisterDefaults; it owns its own registry of test fixtures.
  • internal/protocol/transform — Transform chain types used by anthropic.TransformModel (e.g. compact-thinking).
  • internal/smart_compact — Concrete transform implementations.

Documentation

Overview

Package virtualmodel defines the protocol-agnostic primitives for virtual models. Concrete provider-specific implementations and registries live in the anthropic and openai sub-packages — this top-level package contains only the base interface and shared value types.

These primitives back the production /virtual/v1/* endpoint (onboarding, demos, dry-runs without a real upstream provider) and are also reused as an in-process LLM substitute by test packages such as protocoltest and servertest. The production endpoint is the package's primary surface; test consumers are secondary and use GenericRegistry directly rather than RegisterDefaults — see README.md "Positioning & registration discipline".

Index

Constants

View Source
const DefaultMockDescription = "A virtual model that returns fixed responses for testing"

DefaultMockDescription is the description returned by mock virtual models when their config does not provide an explicit one.

View Source
const DefaultMockOwnedBy = "tingly-box-virtual"

DefaultMockOwnedBy is the OwnedBy value reported by every built-in mock virtual model in the OpenAI-compatible models list.

View Source
const DefaultStreamChunkDelay = 50 * time.Millisecond

DefaultStreamChunkDelay is the per-chunk sleep used by stream helpers when no explicit total simulated delay is configured.

Variables

This section is empty.

Functions

func EmitChunks

func EmitChunks(chunks []string, perChunkDelay time.Duration, emit func(index int, chunk string))

EmitChunks invokes emit for every chunk in order, sleeping perChunkDelay before each emission. It is the protocol-neutral inner loop shared by mock streams. Callers construct their own protocol-specific event types inside the emit closure.

func ResolveChunkDelay

func ResolveChunkDelay(totalDelay time.Duration, chunkCount int) time.Duration

ResolveChunkDelay computes the per-chunk sleep duration for a stream.

  • if totalDelay > 0 and chunkCount > 0 → totalDelay / chunkCount
  • otherwise → DefaultStreamChunkDelay

This is the shared latency-distribution rule used by all mock streams across protocols.

func ToolCallDisplayContent

func ToolCallDisplayContent(args map[string]interface{}) string

ToolCallDisplayContent extracts display text from tool call arguments. It checks for "message" and "question" keys, returning the first non-empty value found.

Types

type BaseMockModel

type BaseMockModel struct {
	ID          string
	Name        string
	Description string
	Type        VirtualModelType
	Delay       time.Duration
}

BaseMockModel is the protocol-neutral half of an in-memory mock virtual model. Protocol-specific mocks embed it and only need to add their own Handle*/Handle*Stream methods. All identity / metadata methods of the VirtualModel interface live here.

func (*BaseMockModel) GetDescription

func (b *BaseMockModel) GetDescription() string

func (*BaseMockModel) GetID

func (b *BaseMockModel) GetID() string

func (*BaseMockModel) GetName

func (b *BaseMockModel) GetName() string

func (*BaseMockModel) GetType

func (b *BaseMockModel) GetType() VirtualModelType

func (*BaseMockModel) SimulatedDelay

func (b *BaseMockModel) SimulatedDelay() time.Duration

func (*BaseMockModel) ToModel

func (b *BaseMockModel) ToModel() Model

ToModel returns the OpenAI-compatible models-list entry for this mock.

type EmitGate added in v0.260604.1

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

EmitGate is a counting gate used by mock streams to honor mid-stream injection. After Allow() has returned true `cutoff` times, all subsequent Allow() calls return false. Callers should bail out of the stream loop the first time Allow() returns false to avoid emitting events past the cutoff.

A cutoff of <= 0 disables the gate (Allow() always returns true).

func NewEmitGate added in v0.260604.1

func NewEmitGate(cutoff int) *EmitGate

NewEmitGate constructs a gate. Pass the return value of MidStreamCutoff (or -1 to disable).

func (*EmitGate) Allow added in v0.260604.1

func (g *EmitGate) Allow() bool

Allow reports whether the next event should be emitted, incrementing the internal counter on success.

func (*EmitGate) Tripped added in v0.260604.1

func (g *EmitGate) Tripped() bool

Tripped reports whether the gate has refused at least one event (or would refuse the next one). Use after a stream loop completes to decide whether to emit terminal events (DoneEvent / message_stop).

type ErrorInjectingModel added in v0.260604.1

type ErrorInjectingModel interface {
	ErrorInjection() *ErrorInjection
}

ErrorInjectingModel is the optional interface a mock virtual model implements to declare a synthetic failure. The virtualserver handler type-asserts to this interface before dispatching the request.

type ErrorInjection added in v0.260604.1

type ErrorInjection struct {
	Stage ErrorStage

	// PreContent fields: HTTP status (defaults to 500 if zero) and an
	// optional message that the handler renders into the protocol-specific
	// error envelope (OpenAI: error.message; Anthropic: error.error.message).
	// Type defaults to "api_error" if empty.
	Status  int
	Message string
	Type    string

	// MidStream fields: number of stream events to emit before tripping
	// (default 1; values <= 0 are treated as 1), and how to terminate.
	AfterEvents   int
	MidStreamMode MidStreamMode
}

ErrorInjection describes a synthetic failure that a mock virtual model should simulate. Attach one to MockScenario.Error (or MockModelConfig.Error) and the virtualserver handler honors it without any real upstream involvement.

Two stages are supported, and they exercise different gateway paths:

  • PreContent: HTTP status + error body, no streaming started. The gateway's firstChunkGate stays buffered → failover retries.
  • MidStream: handler writes a 200 + Content-Type + AfterEvents real events, then either closes the TCP connection or emits a final SSE error event. firstChunkGate is already committed → failover MUST NOT retry.

func ExtractErrorInjection added in v0.260604.1

func ExtractErrorInjection(vm any) *ErrorInjection

ExtractErrorInjection reports the model's error injection configuration, or nil if the model does not implement ErrorInjectingModel or has none set.

type ErrorStage added in v0.260604.1

type ErrorStage int

ErrorStage selects when in the request lifecycle a mock model's error injection fires.

const (
	// ErrorStagePreContent is a failure before any response body is written:
	// the handler returns the configured HTTP status with an error JSON envelope
	// and never invokes the model's Handle* methods past that point. This is
	// the case that priority-routing failover MUST retry — the gate stays
	// buffered, the orchestrator sees a retryable status and discards.
	ErrorStagePreContent ErrorStage = iota

	// ErrorStageMidStream is a failure after the handler has already started
	// streaming. The model emits AfterEvents real stream events, then the
	// handler applies MidStreamMode: it either hijacks and closes the TCP
	// connection (truncated stream from the client's POV) or emits a single
	// SSE error event before stopping. This is the case that priority-routing
	// failover MUST NOT retry — the gate has committed, bytes left the process.
	ErrorStageMidStream
)

type GenericRegistry

type GenericRegistry[T VirtualModel] struct {
	// contains filtered or unexported fields
}

GenericRegistry is a thread-safe registry of virtual models indexed by ID, parameterised by a protocol-specific VirtualModel sub-interface T. Each protocol sub-package (anthropic, openai, ...) instantiates its own Registry alias so models cannot leak across protocols.

func NewGenericRegistry

func NewGenericRegistry[T VirtualModel]() *GenericRegistry[T]

NewGenericRegistry creates an empty registry.

func (*GenericRegistry[T]) Clear

func (r *GenericRegistry[T]) Clear()

Clear removes all registered models.

func (*GenericRegistry[T]) Get

func (r *GenericRegistry[T]) Get(id string) T

Get returns the virtual model for id, or the zero value of T if not registered.

func (*GenericRegistry[T]) Has

func (r *GenericRegistry[T]) Has(id string) bool

Has reports whether a model with the given ID is registered.

func (*GenericRegistry[T]) List

func (r *GenericRegistry[T]) List() []T

List returns all registered virtual models.

func (*GenericRegistry[T]) ListModels

func (r *GenericRegistry[T]) ListModels() []Model

ListModels returns all registered models in the OpenAI-compatible Model format.

func (*GenericRegistry[T]) Register

func (r *GenericRegistry[T]) Register(vm T) error

Register adds a virtual model. Returns an error if the ID is already taken.

func (*GenericRegistry[T]) Unregister

func (r *GenericRegistry[T]) Unregister(id string)

Unregister removes a virtual model by ID. No-op if not present.

type MidStreamMode added in v0.260604.1

type MidStreamMode int

MidStreamMode selects how a mid-stream failure terminates the stream after AfterEvents events have been emitted to the wire.

const (
	// MidStreamModeConnectionClose hijacks the underlying TCP connection and
	// closes it. The client sees an EOF / abrupt disconnect mid-stream —
	// exactly the shape an unstable upstream produces when it dies during a
	// long response.
	MidStreamModeConnectionClose MidStreamMode = iota

	// MidStreamModeErrorEvent emits one final protocol-specific error event
	// (SSE "event: error" frame) before returning. The stream is well-formed
	// up to that point; the client sees an in-band error.
	MidStreamModeErrorEvent
)

type MockUsage added in v0.260604.1

type MockUsage struct {
	PromptTokens             int64 // input_tokens / prompt_tokens
	CompletionTokens         int64 // output_tokens / completion_tokens
	CachedInputTokens        int64 // OpenAI prompt_tokens_details.cached_tokens / Anthropic cache_read_input_tokens
	CacheCreationInputTokens int64 // Anthropic cache_creation_input_tokens (no OpenAI analogue)
	ReasoningTokens          int64 // OpenAI completion_tokens_details.reasoning_tokens
}

MockUsage carries deterministic token-usage values that a mock model emits over its streaming wire format. All fields are optional; a zero value means "do not advertise this dimension". Used so streaming converters / observers can be tested for completeness (cache and reasoning tokens, not just plain prompt/completion).

type Model

type Model struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Created int64  `json:"created"`
	OwnedBy string `json:"owned_by"`
}

Model represents a virtual model in the models list (OpenAI-compatible format).

type SharedMockSpec

type SharedMockSpec struct {
	ID       string
	Name     string
	Content  string          // static text response (ignored if ToolCall is set)
	ToolCall *ToolCallConfig // if non-nil, this is a tool model
	Delay    time.Duration
	Usage    *MockUsage      // optional explicit usage to advertise in the stream
	Error    *ErrorInjection // optional synthetic failure for error-injection mocks
}

SharedMockSpec describes a built-in mock that is identical across protocols (anthropic + openai). Each protocol's RegisterDefaults converts a SharedMockSpec into its own protocol-specific MockModelConfig.

Entries returned by SharedDefaultMocks are user-facing demo defaults: they are mounted into the production /virtual/v1/* endpoint and visible to end users via the virtual provider. Test-only fixtures must NOT be added here; tests should build their own GenericRegistry rather than pollute the production defaults set.

func ErrorMockSpecs added in v0.260604.1

func ErrorMockSpecs() []SharedMockSpec

ErrorMockSpecs returns opt-in fixtures that always fail. They exist so a consumer (priority-routing failover tests, gateway integration tests, demos) can register a "broken upstream" mock by name instead of standing up an ad-hoc httptest.Server. Each spec covers one of the two failover-relevant stages:

  • virtual-fail-precontent-429 / -500: pre-content failures the failover orchestrator MUST retry (gate stays buffered, retryable status).
  • virtual-fail-midstream-close / -event: mid-stream failures the orchestrator MUST NOT retry (gate committed, bytes on the wire).

Like StreamTestMockSpecs, these are intentionally NOT in SharedDefaultMocks so production registries stay clean — register via RegisterErrorMocks.

func SharedDefaultMocks

func SharedDefaultMocks() []SharedMockSpec

SharedDefaultMocks returns the mocks registered by BOTH the Anthropic and OpenAI default registries. Per-protocol unique entries (e.g. virtual-claude-3 for Anthropic, virtual-gpt-4 for OpenAI, the compact transforms) live in their respective sub-packages.

func StreamTestMockSpecs added in v0.260604.1

func StreamTestMockSpecs() []SharedMockSpec

StreamTestMockSpecs returns deterministic stream-test fixtures (static + tool variants) that advertise the full usage shape — prompt, completion, cached input, cache-creation input, and reasoning tokens. These are opt-in (NOT in SharedDefaultMocks): consumers wire them into their own registry via RegisterStreamTestMocks helpers in the per-protocol sub-packages.

type ToolCallConfig

type ToolCallConfig struct {
	Name      string                 `json:"name" yaml:"name"`
	Arguments map[string]interface{} `json:"arguments" yaml:"arguments"`
}

ToolCallConfig defines a tool call to be returned by the virtual model.

type VirtualModel

type VirtualModel interface {
	GetID() string
	GetName() string
	GetDescription() string
	GetType() VirtualModelType
	SimulatedDelay() time.Duration
	ToModel() Model
}

VirtualModel is the base interface common to all virtual model types. Provider-specific extensions are defined in the anthropic and openai sub-packages, each adding the Handle methods for that protocol.

type VirtualModelType

type VirtualModelType string

VirtualModelType represents the type/category of a virtual model.

const (
	// VirtualModelTypeStatic represents static mock models that return fixed responses.
	VirtualModelTypeStatic VirtualModelType = "static"

	// VirtualModelTypeProxy represents proxy/transform models that modify requests before forwarding.
	VirtualModelTypeProxy VirtualModelType = "proxy"

	// VirtualModelTypeTool represents tool models that return tool_use blocks.
	VirtualModelTypeTool VirtualModelType = "tool"
)

Directories

Path Synopsis
Package anthropic provides Anthropic-protocol virtual models.
Package anthropic provides Anthropic-protocol virtual models.
Package benchmark provides a load-testing client and an in-process server factory for the virtualmodel HTTP service.
Package benchmark provides a load-testing client and an in-process server factory for the virtualmodel HTTP service.
examples/client command
Stand-alone benchmark client driver: starts an in-process LocalServer (vmodel-backed) and drives it with the BenchmarkClient against both the OpenAI Chat and Anthropic Messages routes, printing a metrics summary.
Stand-alone benchmark client driver: starts an in-process LocalServer (vmodel-backed) and drives it with the BenchmarkClient against both the OpenAI Chat and Anthropic Messages routes, printing a metrics summary.
examples/server command
Stand-alone benchmark mock server: starts a local HTTP server backed by the production virtualmodel registries (with their default mock models pre-registered) so external benchmark drivers can hit a realistic vmodel surface over loopback.
Stand-alone benchmark mock server: starts a local HTTP server backed by the production virtualmodel registries (with their default mock models pre-registered) so external benchmark drivers can hit a realistic vmodel surface over loopback.
Package openai provides OpenAI-protocol virtual models.
Package openai provides OpenAI-protocol virtual models.
Package virtualserver provides the HTTP handler for virtual model endpoints.
Package virtualserver provides the HTTP handler for virtual model endpoints.

Jump to

Keyboard shortcuts

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