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
- Variables
- type Client
- func (c *Client) Compact(ctx context.Context, params CompactParams) (*CompactResource, error)
- func (c *Client) Create(ctx context.Context, params CreateParams) (*ResponseResource, error)
- func (c *Client) CreateStream(ctx context.Context, params CreateParams, handler EventHandler) (*ResponseResource, error)
- func (c *Client) LastError() error
- func (c *Client) LastRequest() RequestObservation
- func (c *Client) LastStatusCode() int
- func (c *Client) RequestCount() int64
- type Clock
- type CompactParams
- type CompactResource
- type Config
- type ContentPart
- type CreateParams
- type ErrorObject
- type Event
- type EventHandler
- type HTTPError
- type IDGenerator
- type Input
- type Item
- type ParseError
- type ParseOptions
- type ReasoningItem
- type RequestObservation
- type ResponseResource
- type RoundTripFunc
- type SSEParser
- type ScenarioDescriptor
- type ScenarioKind
- type Tool
- type TurnResult
- type Usage
- type VirtualClock
- type WSDialOptions
- type WSSession
Constants ¶
const ( ItemMessage = "message" ItemFunctionCall = "function_call" ItemFunctionCallOutput = "function_call_output" ItemReasoning = "reasoning" ItemItemReference = "item_reference" ItemCompaction = "compaction" )
Portable item discriminator constants.
Variables ¶
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 (*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) LastRequest ¶
func (c *Client) LastRequest() RequestObservation
LastRequest returns the most recent captured request.
func (*Client) LastStatusCode ¶
LastStatusCode returns the most recent HTTP status.
func (*Client) RequestCount ¶
RequestCount returns the number of requests issued by this client.
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 ¶
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) IsTerminal ¶
IsTerminal reports whether the event is a terminal response event.
type EventHandler ¶
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.
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 ¶
Input is the request `input` field: either a string or an ordered item array.
func (Input) MarshalJSON ¶
MarshalJSON renders string or item-array input; empty input marshals as null.
func (*Input) UnmarshalJSON ¶
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 ¶
NewCustomItem builds an opaque prefixed extension item. The type discriminator is injected into the preserved raw object when absent.
func NewFunctionCallItem ¶
NewFunctionCallItem builds a function_call output item.
func NewFunctionCallOutputItem ¶
NewFunctionCallOutputItem builds a function_call_output item from a call id.
func NewItemReference ¶
NewItemReference builds an item_reference item.
func NewMessageItem ¶
NewMessageItem builds a portable message item with one content part.
func (Item) IsExtension ¶
IsExtension reports whether the item uses a prefixed implementor slug.
func (Item) MarshalJSON ¶
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 ¶
UnmarshalJSON parses a discriminated wire item. Known portable types are typed; unknown valid prefixed types are preserved opaquely; unknown unprefixed types fail.
type ParseError ¶
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 ¶
RoundTripFunc adapts a handler func to 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.
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 ¶
IsExtension reports whether the tool uses a prefixed implementor slug.
func (Tool) MarshalJSON ¶
MarshalJSON renders the tool definition back onto the wire.
func (*Tool) UnmarshalJSON ¶
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) 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.