openresponses

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package openresponses is an independent OpenResponses reference client emulator.

It implements black-box client behavior for the OpenResponses 2026-04-24 profile: HTTP JSON create, SSE create, standalone compaction, and persistent sequential WebSocket turns with continuation and errors. It parses tools, multimodal content, assistant phase, reasoning and item lifecycle, prefixed extensions, required response presence, cancellation, and slow-consumer behavior.

Independence: this package is test-only support. It MUST NOT import production OpenResponses protocol, frontend, backend, or state-machine packages, and it must not reuse their wire structs or parsers. Only stdlib plus github.com/gorilla/websocket are used here. The immutable official fixtures under testdata/ are the only protocol inputs shared with production.

Index

Constants

View Source
const (
	ItemMessage            = "message"
	ItemFunctionCall       = "function_call"
	ItemFunctionCallOutput = "function_call_output"
	ItemReasoning          = "reasoning"
	ItemItemReference      = "item_reference"
	ItemCompaction         = "compaction"
)

Portable item discriminator constants.

Variables

View Source
var (
	ErrMalformed        = errors.New("refclient/openresponses: malformed payload")
	ErrRequiredPresence = errors.New("refclient/openresponses: missing required field")
	ErrExceedsLimit     = errors.New("refclient/openresponses: exceeds parse limit")
	ErrEventMismatch    = errors.New("refclient/openresponses: event/type mismatch")
	ErrSequence         = errors.New("refclient/openresponses: sequence violation")
	ErrSSEDone          = errors.New("refclient/openresponses: [DONE] terminal")
	ErrNotExtension     = errors.New("refclient/openresponses: not an extension item")
)

Sentinel errors for the independent client parser.

Functions

This section is empty.

Types

type Client

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

Client is the independent HTTP/SSE OpenResponses client.

func New

func New(cfg Config) *Client

New constructs an independent OpenResponses client.

func (*Client) Compact

func (c *Client) Compact(ctx context.Context, params CompactParams) (*CompactResource, error)

Compact performs a non-streaming POST /responses/compact call.

func (*Client) Create

func (c *Client) Create(ctx context.Context, params CreateParams) (*ResponseResource, error)

Create performs a non-streaming POST /responses call.

func (*Client) CreateStream

func (c *Client) CreateStream(ctx context.Context, params CreateParams, handler EventHandler) (*ResponseResource, error)

CreateStream performs POST /responses with stream enabled and feeds each semantic event to handler. It returns the terminal response resource.

func (*Client) LastError

func (c *Client) LastError() error

LastError returns the most recent request error, if any.

func (*Client) LastRequest

func (c *Client) LastRequest() RequestObservation

LastRequest returns the most recent captured request.

func (*Client) LastStatusCode

func (c *Client) LastStatusCode() int

LastStatusCode returns the most recent HTTP status.

func (*Client) RequestCount

func (c *Client) RequestCount() int64

RequestCount returns the number of requests issued by this client.

type Clock

type Clock interface {
	Now() time.Time
}

Clock provides deterministic time for the emulator.

type CompactParams

type CompactParams struct {
	Model          string
	Input          Input
	Instructions   *string
	Reasoning      json.RawMessage
	PromptCacheKey string
	Extensions     map[string]json.RawMessage
}

CompactParams is the independent wire model of an OpenResponses compact request body.

func (CompactParams) MarshalJSON

func (p CompactParams) MarshalJSON() ([]byte, error)

MarshalJSON renders the compact request body (no stream/transport controls).

type CompactResource

type CompactResource struct {
	ID         string
	Object     string
	CreatedAt  int64
	Status     string
	Model      string
	Output     []Item
	Usage      Usage
	Extensions map[string]json.RawMessage
}

CompactResource is the independent wire model of the response.compaction resource.

func ParseCompactResource

func ParseCompactResource(data []byte, opts ParseOptions) (*CompactResource, error)

ParseCompactResource decodes and validates a response.compaction resource.

func (*CompactResource) IsCompact

func (c *CompactResource) IsCompact() bool

IsCompact reports whether the resource is a compaction resource.

type Config

type Config struct {
	// BaseURL is the server origin, e.g. http://127.0.0.1:PORT. The client appends
	// /responses and /responses/compact paths.
	BaseURL string
	// APIKey is sent as a Bearer token.
	APIKey string
	// HTTPClient overrides the default transport; nil uses http.DefaultClient.
	HTTPClient *http.Client
	// Clock, when set, supplies deterministic timestamps for observations.
	Clock Clock
	// ParseOptions bounds response parsing; zero uses defaults.
	ParseOptions ParseOptions
	// OnRequest, when set, receives each raw request (redacted headers/body).
	OnRequest func(RequestObservation)
	// SlowConsumerDelay, when non-zero, pauses after each streamed event to simulate
	// a slow consumer while remaining context-aware.
	SlowConsumerDelay time.Duration
}

Config configures the independent reference client.

type ContentPart

type ContentPart struct {
	Type        string
	Text        string
	Refusal     string
	Summary     string
	Filename    string
	ImageURL    json.RawMessage
	FileURL     json.RawMessage
	FileData    json.RawMessage
	VideoURL    json.RawMessage
	Annotations json.RawMessage
	Logprobs    json.RawMessage
	Opaque      json.RawMessage
}

ContentPart is a discriminated content part inside a message.

func (ContentPart) IsExtension

func (p ContentPart) IsExtension() bool

IsExtension reports whether the content part uses a prefixed implementor slug.

func (ContentPart) MarshalJSON

func (p ContentPart) MarshalJSON() ([]byte, error)

MarshalJSON renders the content part back onto the wire.

func (*ContentPart) UnmarshalJSON

func (p *ContentPart) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a discriminated content part.

type CreateParams

type CreateParams struct {
	Model                string
	Input                Input
	Instructions         *string
	Tools                []Tool
	ToolChoice           json.RawMessage
	ParallelToolCalls    *bool
	Temperature          *float64
	TopP                 *float64
	MaxOutputTokens      *int
	MaxToolCalls         *int
	Truncation           string
	Text                 json.RawMessage
	Reasoning            json.RawMessage
	Store                *bool
	Background           *bool
	PreviousResponseID   *string
	Metadata             json.RawMessage
	ServiceTier          string
	SafetyIdentifier     string
	PromptCacheKey       string
	PromptCacheRetention string
	Stream               bool
	Extensions           map[string]json.RawMessage
}

CreateParams is the independent wire model of an OpenResponses create request body.

func (CreateParams) MarshalJSON

func (p CreateParams) MarshalJSON() ([]byte, error)

MarshalJSON renders the create request body, omitting zero controls and emitting declared prefixed extensions at the top level.

func (*CreateParams) UnmarshalJSON

func (p *CreateParams) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a create request body, including the official request example.

type ErrorObject

type ErrorObject struct {
	Type    string
	Code    string
	Message string
	Param   string
}

ErrorObject is the structured OpenResponses error payload.

type Event

type Event struct {
	Type           string
	SequenceNumber int64
	Response       *ResponseResource
	Item           *Item
	Part           *ContentPart
	ItemID         string
	CallID         string
	OutputIndex    *int
	ContentIndex   *int
	Delta          string
	Text           string
	Refusal        string
	Summary        string
	Arguments      string
	Error          *ErrorObject
	Opaque         json.RawMessage
}

Event is the independent wire model of an OpenResponses streaming event, shared by SSE data payloads and WebSocket frame payloads.

func ParseEvent

func ParseEvent(data []byte, opts ParseOptions) (*Event, error)

ParseEvent decodes a single event JSON payload (SSE data or WebSocket frame).

func ParseSSE

func ParseSSE(data []byte, opts ParseOptions) ([]Event, bool, error)

ParseSSE parses a complete SSE body and returns the events plus whether [DONE] was seen.

func (*Event) IsError

func (e *Event) IsError() bool

IsError reports whether the event carries an error envelope.

func (*Event) IsTerminal

func (e *Event) IsTerminal() bool

IsTerminal reports whether the event is a terminal response event.

type EventHandler

type EventHandler func(Event) error

EventHandler receives each parsed streaming event.

type HTTPError

type HTTPError struct {
	StatusCode  int
	Status      string
	ErrorObject *ErrorObject
	Body        []byte
}

HTTPError is a non-2xx response carrying the structured error object when present.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type IDGenerator

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

IDGenerator deterministically issues client-owned identifiers.

func NewIDGenerator

func NewIDGenerator(prefix string, clock Clock) *IDGenerator

NewIDGenerator returns a deterministic ID generator.

func (*IDGenerator) Next

func (g *IDGenerator) Next() string

Next returns a deterministic identifier derived from virtual time and a counter.

type Input

type Input struct {
	Text    string
	TextSet bool
	Items   []Item
}

Input is the request `input` field: either a string or an ordered item array.

func (Input) MarshalJSON

func (i Input) MarshalJSON() ([]byte, error)

MarshalJSON renders string or item-array input; empty input marshals as null.

func (*Input) UnmarshalJSON

func (i *Input) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a string or item-array input.

type Item

type Item struct {
	Type             string
	ID               string
	Status           string
	Role             string
	Phase            string
	Content          []ContentPart
	CallID           string
	Name             string
	Arguments        string
	Output           json.RawMessage
	Reasoning        *ReasoningItem
	EncapsulatedID   string
	EncryptedContent string
	Opaque           json.RawMessage
}

Item is the discriminated ordered unit of context on the OpenResponses wire.

func NewCustomItem

func NewCustomItem(typeName, raw string) Item

NewCustomItem builds an opaque prefixed extension item. The type discriminator is injected into the preserved raw object when absent.

func NewFunctionCallItem

func NewFunctionCallItem(id, callID, name, arguments string) Item

NewFunctionCallItem builds a function_call output item.

func NewFunctionCallOutputItem

func NewFunctionCallOutputItem(callID, output string) Item

NewFunctionCallOutputItem builds a function_call_output item from a call id.

func NewItemReference

func NewItemReference(encapsulatedID, id string) Item

NewItemReference builds an item_reference item.

func NewMessageItem

func NewMessageItem(role, partType, text string) Item

NewMessageItem builds a portable message item with one content part.

func (Item) IsExtension

func (it Item) IsExtension() bool

IsExtension reports whether the item uses a prefixed implementor slug.

func (Item) MarshalJSON

func (it Item) MarshalJSON() ([]byte, error)

MarshalJSON renders the item back onto the wire, preserving opaque extension bytes.

func (Item) OpaqueItem

func (it Item) OpaqueItem() json.RawMessage

OpaqueItem returns the raw preserved bytes for extension items, nil otherwise.

func (*Item) UnmarshalJSON

func (it *Item) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a discriminated wire item. Known portable types are typed; unknown valid prefixed types are preserved opaquely; unknown unprefixed types fail.

type ParseError

type ParseError struct {
	Category string
	Message  string
	Err      error
}

ParseError carries the stable category and safe message for a parse failure.

func (*ParseError) Error

func (e *ParseError) Error() string

func (*ParseError) Unwrap

func (e *ParseError) Unwrap() error

type ParseOptions

type ParseOptions struct {
	MaxBodyBytes    int64
	MaxEventBytes   int
	MaxLineBytes    int
	MaxItems        int
	MaxContentParts int
	MaxEvents       int
}

ParseOptions bounds every independent parse. Zero values fall back to defaults on use.

func DefaultParseOptions

func DefaultParseOptions() ParseOptions

DefaultParseOptions returns the documented bounded-parse profile.

type ReasoningItem

type ReasoningItem struct {
	Content             []ContentPart
	EncryptedContent    string
	EncryptedContentSet bool
	Summary             []ContentPart
}

ReasoningItem carries provider-controlled reasoning payloads. Encrypted content is opaque and never interpreted by the client.

func (ReasoningItem) MarshalJSON

func (r ReasoningItem) MarshalJSON() ([]byte, error)

MarshalJSON renders the reasoning item back onto the wire.

func (*ReasoningItem) UnmarshalJSON

func (r *ReasoningItem) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a reasoning item preserving content, summary, and encrypted_content null presence.

type RequestObservation

type RequestObservation struct {
	Method    string
	URLPath   string
	Headers   http.Header
	Body      []byte
	Timestamp time.Time
	Redacted  bool
}

RequestObservation captures a raw client request for test assertions.

type ResponseResource

type ResponseResource struct {
	ID                   string
	Object               string
	CreatedAt            int64
	Status               string
	CompletedAt          *int64
	Model                string
	Output               []Item
	ParallelToolCalls    bool
	Reasoning            json.RawMessage
	Store                bool
	Background           bool
	Temperature          *float64
	Text                 json.RawMessage
	ToolChoice           json.RawMessage
	Tools                []Tool
	TopP                 *float64
	Truncation           string
	Usage                Usage
	Metadata             json.RawMessage
	ServiceTier          string
	MaxOutputTokens      *int
	MaxToolCalls         *int
	Instructions         *string
	PreviousResponseID   *string
	Error                *ErrorObject
	IncompleteDetails    json.RawMessage
	SafetyIdentifier     *string
	PromptCacheKey       *string
	PromptCacheRetention *string
	Extensions           map[string]json.RawMessage
}

ResponseResource is the independent wire model of the complete OpenResponses response resource. Pointer fields preserve null/default presence.

func ParseResponseResource

func ParseResponseResource(data []byte, opts ParseOptions) (*ResponseResource, error)

ParseResponseResource decodes and validates a response resource with bounded reads and required-presence enforcement.

func ParseResponseResourceLoose

func ParseResponseResourceLoose(data []byte, opts ParseOptions) (*ResponseResource, error)

ParseResponseResourceLoose decodes a response resource without required-presence enforcement. It is used for partial response envelopes embedded in streaming events.

func (*ResponseResource) Failed

func (r *ResponseResource) Failed() bool

Failed reports whether the response ended in the failed state.

func (*ResponseResource) OutputText

func (r *ResponseResource) OutputText() string

OutputText concatenates the text of output_text content parts across assistant message items in order.

func (*ResponseResource) Terminal

func (r *ResponseResource) Terminal() bool

Terminal reports whether the resource is in a terminal state.

type RoundTripFunc

type RoundTripFunc func(*http.Request) (*http.Response, error)

RoundTripFunc adapts a handler func to http.RoundTripper.

func (RoundTripFunc) RoundTrip

func (f RoundTripFunc) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type SSEParser

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

SSEParser incrementally parses an OpenResponses `text/event-stream` body. It validates event/type matching, exactly one terminal event followed by the literal [DONE], bounded line lengths, and bounded event counts.

func NewSSEParser

func NewSSEParser(r io.Reader, opts ParseOptions) *SSEParser

NewSSEParser constructs an SSE parser over r.

func (*SSEParser) Done

func (p *SSEParser) Done() bool

Done reports whether [DONE] was consumed.

func (*SSEParser) Next

func (p *SSEParser) Next() (*Event, error)

Next returns the next semantic event. It returns ErrSSEDone after the [DONE] terminal and io.EOF only when a [DONE] already preceded the end of input.

type ScenarioDescriptor

type ScenarioDescriptor struct {
	ID          string
	Kind        ScenarioKind
	Description string
}

ScenarioDescriptor declares a named scenario bound to client emulator behavior.

func (ScenarioDescriptor) Validate

func (s ScenarioDescriptor) Validate() error

Validate enforces declarative scenario hygiene.

type ScenarioKind

type ScenarioKind string

ScenarioKind classifies a declarative emulator scenario.

const (
	ScenarioJSONText     ScenarioKind = "json_text"
	ScenarioSSEText      ScenarioKind = "sse_text"
	ScenarioTools        ScenarioKind = "tools"
	ScenarioMultimodal   ScenarioKind = "multimodal"
	ScenarioReasoning    ScenarioKind = "reasoning"
	ScenarioPhase        ScenarioKind = "phase"
	ScenarioContinuation ScenarioKind = "continuation"
	ScenarioCompaction   ScenarioKind = "compaction"
	ScenarioExtensions   ScenarioKind = "extensions"
	ScenarioWebSocket    ScenarioKind = "websocket"
	ScenarioNegative     ScenarioKind = "negative_validation"
	ScenarioAdversarial  ScenarioKind = "adversarial"
)

type Tool

type Tool struct {
	Type        string
	Name        string
	Description string
	Parameters  json.RawMessage
	Strict      *bool
	Opaque      json.RawMessage
}

Tool is a function tool or a prefixed hosted tool.

func (Tool) IsExtension

func (t Tool) IsExtension() bool

IsExtension reports whether the tool uses a prefixed implementor slug.

func (Tool) MarshalJSON

func (t Tool) MarshalJSON() ([]byte, error)

MarshalJSON renders the tool definition back onto the wire.

func (*Tool) UnmarshalJSON

func (t *Tool) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a wire tool definition.

type TurnResult

type TurnResult struct {
	Events    []Event
	Response  *ResponseResource
	ErrorCode string
	Error     *ErrorObject
	RawText   []string
}

TurnResult is the parsed outcome of one WebSocket turn.

type Usage

type Usage struct {
	InputTokens     int
	CachedTokens    int
	OutputTokens    int
	ReasoningTokens int
	TotalTokens     int
}

Usage carries token counters.

type VirtualClock

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

VirtualClock is a deterministic, goroutine-safe clock for client emulator tests.

func NewClock

func NewClock(initial time.Time) *VirtualClock

NewClock returns a VirtualClock seeded to a fixed reference instant.

func (*VirtualClock) Advance

func (c *VirtualClock) Advance(d time.Duration)

Advance moves the virtual clock forward deterministically.

func (*VirtualClock) Now

func (c *VirtualClock) Now() time.Time

Now returns the current virtual time.

func (*VirtualClock) Set

func (c *VirtualClock) Set(t time.Time)

Set pins the virtual clock to an exact instant.

type WSDialOptions

type WSDialOptions struct {
	// BaseURL is the http(s) origin; /responses is appended and the scheme is
	// switched to ws(s).
	BaseURL string
	APIKey  string
	// Dialer, when set, supplies the gorilla dialer. The dialer is copied per
	// call so its configuration is never mutated by Dial.
	Dialer *websocket.Dialer
	// ParseOptions bounds frame parsing.
	ParseOptions ParseOptions
}

WSDialOptions configures a WebSocket session.

type WSSession

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

WSSession is a persistent sequential OpenResponses WebSocket connection.

func Dial

func Dial(ctx context.Context, opts WSDialOptions) (*WSSession, error)

Dial opens an authenticated OpenResponses WebSocket session.

func (*WSSession) Close

func (s *WSSession) Close() error

Close terminates the WebSocket session.

func (*WSSession) Turn

func (s *WSSession) Turn(ctx context.Context, params CreateParams) (*TurnResult, error)

Turn sends one response.create message and reads events until the terminal response event, a structured error, or a literal [DONE] frame. Turns are serialized.

Jump to

Keyboard shortcuts

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