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

Index

Constants

View Source
const (
	MaxRequestBytes = 8 * 1024 * 1024 // 8 MiB max request body
	MaxJSONDepth    = 64
)
View Source
const (
	ProtocolFamily           = "openresponses"
	ProfileVersion           = "2026-04-24"
	SourceCommit             = "92c12d96d7b61d6d15e2214daa5e9c6000ab6e1c"
	SourceRepository         = "openresponses/openresponses"
	LicenseName              = "Apache-2.0"
	LicenseAttribution       = "Licensed under the Apache License, Version 2.0"
	DefaultBasePath          = "/openresponses/v1"
	ExpectedSchemaDigest     = "sha256:997c4cf16c349751502813f46ea79b2c88880b23171b69f7f2c3d4bf5b330529"
	ExpectedComplianceDigest = "sha256:63b5e6595ac831ee74b8e887af76c28d69aee8e2ec7d9e99dc688eec4bccb7fb"
	ExpectedLicenseDigest    = "sha256:43070e2d4e532684de521b885f385d0841030efa2b1a20bafb76133a5e1379c1"
)

Profile identity constants for official OpenResponses 2026-04-24 specification.

Variables

View Source
var (
	ErrDecodeFailed          = errors.New("openresponses: decode failed")
	ErrUnsupportedBackground = errors.New("openresponses: background execution mode is unsupported")
	ErrUnknownDiscriminator  = errors.New("openresponses: unknown unprefixed discriminator")
	ErrDuplicateAuthority    = errors.New("openresponses: conflicting raw item and legacy message authorities")
	ErrTrailingData          = errors.New("openresponses: trailing data after JSON payload")
	ErrEncodeFailed          = errors.New("openresponses: encode failed")
	ErrBuildResourceFailed   = errors.New("openresponses: resource build failed")
	ErrSequenceViolation     = errors.New("openresponses: sequence violation")
	ErrDuplicateTerminal     = errors.New("openresponses: duplicate terminal event")
	ErrOutputAfterTerminal   = errors.New("openresponses: output emitted after terminal event")
	ErrMismatchedID          = errors.New("openresponses: mismatched item or call ID")
	ErrInvalidLifecycleState = errors.New("openresponses: invalid lifecycle transition")
)
View Source
var ErrLimitExceeded = errors.New("openresponses: limit exceeded")

ErrLimitExceeded is the sentinel root error for limit exceedances.

Functions

func ConservativeLegacyNormalize

func ConservativeLegacyNormalize(envelope EnvelopeMetadata, options lipapi.GenerationOptions, events []lipapi.Event) ([]StreamEvent, *WireResponseResource, error)

ConservativeLegacyNormalize maps a slice of lipapi.Event into a slice of StreamEvents using conservative normalization rules (no invented phase, replay, compaction, or extensions).

func DecodeItem

func DecodeItem(wire WireItem, limits Limits) (lipapi.Item, error)

DecodeItem converts a WireItem into a canonical lipapi.Item under the caller-provided operational limits.

func EncodeOutboundRequest

func EncodeOutboundRequest(call lipapi.Call, opts OutboundEncodeOptions) ([]byte, error)

EncodeOutboundRequest encodes a canonical lipapi.Call into an outbound request JSON payload.

func EncodeRequest

func EncodeRequest(call lipapi.Call) ([]byte, error)

EncodeRequest converts a canonical lipapi.Call into WireResponseParam and marshals it to JSON bytes.

func FormatSSEEvent

func FormatSSEEvent(evt StreamEvent) ([]byte, error)

FormatSSEEvent formats a StreamEvent into SSE wire bytes: event: <Type>\n data: <JSON>\n\n

func FormattedDONE

func FormattedDONE() []byte

FormattedDONE returns the literal terminal SSE payload: data: [DONE]\n\n

func MapErrorToWire

func MapErrorToWire(err error) (int, WireErrorEnvelope, ErrorClassification)

MapErrorToWire classifies internal errors and maps them to HTTP status code, WireErrorEnvelope, and ErrorClassification. Wire error messages are sanitized to prevent leaking raw payloads, secrets, or internal stack traces.

func StreamErrorToRawMessage

func StreamErrorToRawMessage(err *lipapi.StreamError) json.RawMessage

StreamErrorToRawMessage converts a lipapi.StreamError into raw JSON bytes for event.error payloads.

func ValidateContinuationRef

func ValidateContinuationRef(ref string, limits Limits) error

ValidateContinuationRef checks continuation reference string length against limits.

func ValidateContinuationRefCount

func ValidateContinuationRefCount(count int, limits Limits) error

ValidateContinuationRefCount checks number of referenced continuation items against limits.

func ValidateEventCount

func ValidateEventCount(count int, limits Limits) error

ValidateEventCount checks accumulated stream event count against limits.

func ValidateItemCount

func ValidateItemCount(count int, limits Limits) error

ValidateItemCount checks item array length against limits.

func ValidateItemDepth

func ValidateItemDepth(depth int, limits Limits) error

ValidateItemDepth checks item nesting depth against limits.

func ValidateOpaquePayloadSize

func ValidateOpaquePayloadSize(size int, limits Limits) error

ValidateOpaquePayloadSize checks vendor extension payload size against limits.

func ValidateRequestBytes

func ValidateRequestBytes(data []byte, limits Limits) error

ValidateRequestBytes checks payload size before JSON unmarshal to prevent allocation amplification.

func ValidateResourceBytes

func ValidateResourceBytes(data []byte, limits Limits) error

ValidateResourceBytes checks resource size against independent limits.

func ValidateSchemaSize

func ValidateSchemaSize(size int, limits Limits) error

ValidateSchemaSize checks tool/output schema byte size against limits.

Types

type EnvelopeMetadata

type EnvelopeMetadata struct {
	ResponseID         string
	PreviousResponseID string
	CreatedAt          time.Time
	CompletedAt        *time.Time
	Model              string
	Status             string
	Store              *bool
}

EnvelopeMetadata carries proxy-owned response metadata for resource construction.

type ErrorClassification

type ErrorClassification string

ErrorClassification represents internal stable error taxonomy categories for OpenResponses.

const (
	ClassificationInvalidRequest       ErrorClassification = "invalid_request_error"
	ClassificationAuthenticationFailed ErrorClassification = "authentication_error"
	ClassificationPermissionDenied     ErrorClassification = "permission_error"
	ClassificationNotFound             ErrorClassification = "not_found_error"
	ClassificationRateLimitExceeded    ErrorClassification = "rate_limit_error"
	ClassificationPayloadTooLarge      ErrorClassification = "payload_too_large_error"
	ClassificationUnsupportedParameter ErrorClassification = "unsupported_parameter_error"
	ClassificationInternalError        ErrorClassification = "server_error"
	ClassificationBackendUnavailable   ErrorClassification = "service_unavailable_error"
	ClassificationTimeout              ErrorClassification = "timeout_error"
)

type LimitExceededError

type LimitExceededError struct {
	Param   string
	Limit   int
	Actual  int
	Message string
	Err     error
}

LimitExceededError carries structured context when an operational limit is exceeded.

func (*LimitExceededError) Error

func (e *LimitExceededError) Error() string

func (*LimitExceededError) Unwrap

func (e *LimitExceededError) Unwrap() error

type Limits

type Limits struct {
	MaxRequestSizeBytes         int
	MaxResourceSizeBytes        int
	MaxEventCount               int
	MaxItemCount                int
	MaxItemDepth                int
	MaxSchemaSizeBytes          int
	MaxOpaquePayloadSizeBytes   int
	MaxContinuationRefSizeBytes int
	MaxContinuationRefCount     int
}

Limits holds independent bounded configuration thresholds for OpenResponses payload and state processing.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the standard bounded limits for production OpenResponses operations.

type OutboundEncodeOptions

type OutboundEncodeOptions struct {
	Model             string
	Stream            bool
	IncludeExtensions bool
}

OutboundEncodeOptions holds options for encoding an outbound request.

type ProfileDescriptor

type ProfileDescriptor struct {
	Family             string   `json:"family"`
	Version            string   `json:"version"`
	SourceCommit       string   `json:"source_commit"`
	SourceRepository   string   `json:"source_repository"`
	SchemaDigest       string   `json:"schema_digest"`
	ComplianceDigest   string   `json:"compliance_digest"`
	License            string   `json:"license"`
	LicenseAttribution string   `json:"license_attribution"`
	Deviations         []string `json:"deviations"`
}

ProfileDescriptor defines the immutable protocol profile evidence and metadata.

func GetProfileDescriptor

func GetProfileDescriptor() ProfileDescriptor

GetProfileDescriptor returns the immutable official profile descriptor for OpenResponses 2026-04-24.

type SSEWriter

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

SSEWriter formats and streams OpenResponses events over an io.Writer.

func NewSSEWriter

func NewSSEWriter(w io.Writer) *SSEWriter

NewSSEWriter constructs an SSEWriter wrapping w.

func (*SSEWriter) WriteDONE

func (s *SSEWriter) WriteDONE() error

WriteDONE writes the terminal data: [DONE]\n\n chunk.

func (*SSEWriter) WriteEvent

func (s *SSEWriter) WriteEvent(evt StreamEvent) error

WriteEvent formats and writes a single StreamEvent.

type SequenceError

type SequenceError struct {
	Code     string
	Event    string
	ID       string
	Sequence int
	Message  string
	Err      error
}

SequenceError carries structured context for sequence and lifecycle errors.

func (*SequenceError) Error

func (e *SequenceError) Error() string

func (*SequenceError) Unwrap

func (e *SequenceError) Unwrap() error

type StateMachine

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

StateMachine is the production semantic event normalizer and state machine for OpenResponses. It is context-free except explicit owned state and manages sequence numbers, trajectory accumulation, lifecycle validation, resource building, and event output.

func NewStateMachine

func NewStateMachine(envelope EnvelopeMetadata, options lipapi.GenerationOptions, configured ...Limits) *StateMachine

NewStateMachine constructs a new StateMachine for a given response envelope and generation options.

func (*StateMachine) AccumulateResource

func (sm *StateMachine) AccumulateResource() (*WireResponseResource, []byte, error)

AccumulateResource returns the accumulated WireResponseResource and JSON bytes.

func (*StateMachine) ProcessCanonicalEvent

func (sm *StateMachine) ProcessCanonicalEvent(ev lipapi.Event) (events []StreamEvent, err error)

ProcessCanonicalEvent processes one canonical lipapi.Event, validates sequence/lifecycle rules, updates accumulated state, and returns zero or more OpenResponses StreamEvents.

func (*StateMachine) SequenceNumber

func (sm *StateMachine) SequenceNumber() int

SequenceNumber returns the current sequence number.

func (*StateMachine) State

func (sm *StateMachine) State() StateMachineState

State returns the current StateMachineState.

func (*StateMachine) Status

func (sm *StateMachine) Status() string

Status returns the current status string ("in_progress", "completed", "failed", "incomplete").

func (*StateMachine) Trajectory

func (sm *StateMachine) Trajectory() []lipapi.Item

Trajectory returns a deep copy of accumulated canonical items.

type StateMachineState

type StateMachineState string
const (
	StateInit     StateMachineState = "init"
	StateStarted  StateMachineState = "in_progress"
	StateTerminal StateMachineState = "terminal"
)

type StreamEvent

type StreamEvent struct {
	Type           string                `json:"type"`
	SequenceNumber int                   `json:"sequence_number"`
	Response       *WireResponseResource `json:"response,omitempty"`
	OutputIndex    *int                  `json:"output_index,omitempty"`
	ContentIndex   *int                  `json:"content_index,omitempty"`
	Item           *WireItem             `json:"item,omitempty"`
	Part           *WireContentPart      `json:"part,omitempty"`
	ItemID         string                `json:"item_id,omitempty"`
	CallID         string                `json:"call_id,omitempty"`
	Delta          string                `json:"delta,omitempty"`
	Text           string                `json:"text,omitempty"`
	Refusal        string                `json:"refusal,omitempty"`
	Summary        string                `json:"summary,omitempty"`
	Arguments      string                `json:"arguments,omitempty"`
	Signature      string                `json:"signature,omitempty"`
	Opaque         json.RawMessage       `json:"opaque,omitempty"`
	Error          json.RawMessage       `json:"error,omitempty"`
}

StreamEvent represents an OpenResponses event on the wire (SSE/WebSocket).

type UsageStats

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

UsageStats carries token count statistics for building ResponseResource / CompactResource.

type WireCompactResource

type WireCompactResource struct {
	ID           string          `json:"id"`
	Object       string          `json:"object"`
	CreatedAt    int64           `json:"created_at"`
	Status       string          `json:"status"`
	Model        string          `json:"model"`
	Output       []WireItem      `json:"output"`
	Usage        WireUsage       `json:"usage"`
	UsagePresent bool            `json:"-"`
	RawJSON      json.RawMessage `json:"-"`
}

WireCompactResource represents the OpenResponses response.compaction resource.

func BuildCompactResource

func BuildCompactResource(envelope EnvelopeMetadata, trajectory []lipapi.Item, usage UsageStats) (*WireCompactResource, []byte, error)

BuildCompactResource constructs the OpenResponses CompactResource JSON bytes and wire struct.

func (*WireCompactResource) UnmarshalJSON

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

type WireContentPart

type WireContentPart struct {
	Type     string          `json:"type"`
	Text     string          `json:"text"`
	ImageURL json.RawMessage `json:"image_url,omitempty"`
	// FileID and VideoData capture wire fields that the pinned 2026-04-24
	// profile does not define. The decoder rejects non-null values before
	// canonical construction so an unpinned file/video carrier is never silently
	// dropped; the fields exist only to prove presence and are never emitted.
	FileID    json.RawMessage `json:"file_id,omitempty"`
	FileURL   json.RawMessage `json:"file_url,omitempty"`
	FileData  json.RawMessage `json:"file_data,omitempty"`
	Filename  string          `json:"filename,omitempty"`
	VideoURL  json.RawMessage `json:"video_url,omitempty"`
	VideoData json.RawMessage `json:"video_data,omitempty"`
	Refusal   string          `json:"refusal,omitempty"`

	Reasoning    json.RawMessage `json:"reasoning,omitempty"`
	Summary      string          `json:"summary,omitempty"`
	Annotations  json.RawMessage `json:"annotations,omitempty"`
	AssistantRef string          `json:"assistant_ref,omitempty"`
	Logprobs     json.RawMessage `json:"logprobs,omitempty"`
	// contains filtered or unexported fields
}

WireContentPart represents a content part inside a message or tool result on the wire.

func (WireContentPart) MarshalJSON

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

MarshalJSON emits a prefixed custom content part verbatim when the decoder preserved its raw structured payload; otherwise it renders the typed struct.

type WireErrorDetails

type WireErrorDetails struct {
	Type    string `json:"type"`
	Message string `json:"message"`
	Param   string `json:"param,omitempty"`
	Code    string `json:"code,omitempty"`
}

WireErrorDetails represents the inner error structure on the wire for OpenResponses errors.

type WireErrorEnvelope

type WireErrorEnvelope struct {
	Error WireErrorDetails `json:"error"`
}

WireErrorEnvelope represents the top-level wire error response payload.

type WireItem

type WireItem struct {
	ID        string          `json:"id,omitempty"`
	Type      string          `json:"type"`
	Status    string          `json:"status,omitempty"`
	Role      string          `json:"role,omitempty"`
	Phase     string          `json:"phase,omitempty"`
	Content   json.RawMessage `json:"content,omitempty"`
	CallID    string          `json:"call_id,omitempty"`
	Name      string          `json:"name,omitempty"`
	Arguments json.RawMessage `json:"arguments,omitempty"`
	Output    json.RawMessage `json:"output,omitempty"`
	Reasoning json.RawMessage `json:"reasoning,omitempty"`
	// Summary is the official reasoning-item summary array. Content is reused
	// for the official reasoning-item content array and for message content.
	Summary json.RawMessage `json:"summary,omitempty"`
	// Signature preserves canonical reasoning integrity metadata that is not
	// represented by the legacy text-only reasoning field.
	Signature string `json:"signature,omitempty"`
	// ReasoningEncryptedContent carries exact reasoning-item encrypted_content
	// presence without changing the legacy string compaction field below.
	ReasoningEncryptedContent        json.RawMessage `json:"-"`
	ReasoningEncryptedContentPresent bool            `json:"-"`
	SummaryPresent                   bool            `json:"-"`
	ContentPresent                   bool            `json:"-"`

	EncapsulatedID string `json:"encapsulated_id,omitempty"`
	Dialect        string `json:"dialect,omitempty"`
	Implementor    string `json:"implementor,omitempty"`
	// EncryptedContent is the pinned-profile compaction blob carried on a
	// response.compaction output item.
	EncryptedContent string          `json:"encrypted_content,omitempty"`
	Opaque           json.RawMessage `json:"opaque,omitempty"`
	Namespace        string          `json:"namespace,omitempty"`
	Direction        string          `json:"direction,omitempty"`
	Data             json.RawMessage `json:"data,omitempty"`
}

WireItem represents a single item on the wire in OpenResponses.

func EncodeItem

func EncodeItem(item lipapi.Item) (WireItem, error)

EncodeItem converts a canonical lipapi.Item into WireItem.

func (WireItem) MarshalJSON

func (w WireItem) MarshalJSON() ([]byte, error)

MarshalJSON emits official reasoning encrypted_content presence without affecting compaction's legacy string field.

func (*WireItem) UnmarshalJSON

func (w *WireItem) UnmarshalJSON(data []byte) error

UnmarshalJSON preserves reasoning encrypted_content, including explicit null, while retaining the legacy string field used by compaction items.

type WireResponseParam

type WireResponseParam struct {
	Model                *string         `json:"model,omitempty"`
	Input                json.RawMessage `json:"input"`
	Instructions         *string         `json:"instructions,omitempty"`
	Tools                []WireTool      `json:"tools,omitempty"`
	ToolChoice           json.RawMessage `json:"tool_choice,omitempty"`
	ParallelToolCalls    *bool           `json:"parallel_tool_calls,omitempty"`
	Temperature          *float64        `json:"temperature,omitempty"`
	TopP                 *float64        `json:"top_p,omitempty"`
	MaxOutputTokens      *int            `json:"max_output_tokens,omitempty"`
	MaxToolCalls         *int            `json:"max_tool_calls,omitempty"`
	Truncation           *string         `json:"truncation,omitempty"`
	Text                 json.RawMessage `json:"text,omitempty"`
	Reasoning            json.RawMessage `json:"reasoning,omitempty"`
	Store                *bool           `json:"store,omitempty"`
	Background           *bool           `json:"background,omitempty"`
	PreviousResponseID   *string         `json:"previous_response_id,omitempty"`
	Metadata             json.RawMessage `json:"metadata,omitempty"`
	ServiceTier          *string         `json:"service_tier,omitempty"`
	SafetyIdentifier     *string         `json:"safety_identifier,omitempty"`
	PromptCacheKey       *string         `json:"prompt_cache_key,omitempty"`
	PromptCacheRetention *string         `json:"prompt_cache_retention,omitempty"`
	// Include selects additional fields to include in the response resource.
	Include []string `json:"include,omitempty"`
	// PresencePenalty/FrequencyPenalty/TopLogprobs are pinned standard sampling
	// controls the canonical call cannot represent; non-null values are rejected
	// before network by frontend admission.
	PresencePenalty  *float64 `json:"presence_penalty,omitempty"`
	FrequencyPenalty *float64 `json:"frequency_penalty,omitempty"`
	TopLogprobs      *int     `json:"top_logprobs,omitempty"`
	// StreamOptions is the pinned standard SSE transport control. It is a typed
	// known field; non-null values are rejected before network because the
	// canonical call has no lossless carrier.
	StreamOptions json.RawMessage            `json:"stream_options,omitempty"`
	ExtraFields   map[string]json.RawMessage `json:"-"`
}

WireResponseParam represents the wire request body for OpenResponses POST /responses.

func DecodeRequest

func DecodeRequest(data []byte, configured ...Limits) (*WireResponseParam, lipapi.Call, error)

DecodeRequest unmarshals JSON request bytes into WireResponseParam and converts it to a canonical lipapi.Call. An omitted limits argument uses DefaultLimits for compatibility with existing internal callers; production frontends may pass their validated limits.

type WireResponseResource

type WireResponseResource struct {
	ID                   string          `json:"id"`
	Object               string          `json:"object"`
	CreatedAt            int64           `json:"created_at"`
	Status               string          `json:"status"`
	CompletedAt          *int64          `json:"completed_at"`
	Model                string          `json:"model"`
	Output               []WireItem      `json:"output"`
	ParallelToolCalls    bool            `json:"parallel_tool_calls"`
	Reasoning            json.RawMessage `json:"reasoning"`
	Store                bool            `json:"store"`
	Background           bool            `json:"background"`
	Temperature          *float64        `json:"temperature"`
	Text                 map[string]any  `json:"text"`
	ToolChoice           json.RawMessage `json:"tool_choice"`
	Tools                []WireTool      `json:"tools"`
	TopP                 *float64        `json:"top_p"`
	PresencePenalty      float64         `json:"presence_penalty"`
	FrequencyPenalty     float64         `json:"frequency_penalty"`
	TopLogprobs          int             `json:"top_logprobs"`
	Truncation           string          `json:"truncation"`
	Usage                WireUsage       `json:"usage"`
	Metadata             map[string]any  `json:"metadata"`
	ServiceTier          string          `json:"service_tier"`
	MaxOutputTokens      *int            `json:"max_output_tokens"`
	MaxToolCalls         *int            `json:"max_tool_calls"`
	Instructions         *string         `json:"instructions"`
	PreviousResponseID   *string         `json:"previous_response_id"`
	Error                json.RawMessage `json:"error"`
	IncompleteDetails    json.RawMessage `json:"incomplete_details"`
	SafetyIdentifier     *string         `json:"safety_identifier"`
	PromptCacheKey       *string         `json:"prompt_cache_key"`
	PromptCacheRetention *string         `json:"prompt_cache_retention"`
	UsagePresent         bool            `json:"-"`
	RawJSON              json.RawMessage `json:"-"`
}

WireResponseResource represents the complete OpenResponses response resource.

func BuildResponseResource

func BuildResponseResource(envelope EnvelopeMetadata, trajectory []lipapi.Item, usage UsageStats, options lipapi.GenerationOptions, streamErr *lipapi.StreamError) (*WireResponseResource, []byte, error)

BuildResponseResource constructs the complete OpenResponses ResponseResource JSON bytes and wire struct.

func (*WireResponseResource) UnmarshalJSON

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

type WireTool

type WireTool struct {
	Type        string          `json:"type"`
	Name        string          `json:"name,omitempty"`
	Description string          `json:"description,omitempty"`
	Parameters  json.RawMessage `json:"parameters,omitempty"`
	Strict      *bool           `json:"strict,omitempty"`
}

WireTool represents a tool definition on the wire.

type WireToolChoiceAllowedToolRef

type WireToolChoiceAllowedToolRef struct {
	Type string `json:"type"`
	Name string `json:"name"`
}

WireToolChoiceAllowedToolRef names one tool in an allowed_tools subset.

type WireToolChoiceAllowedTools

type WireToolChoiceAllowedTools struct {
	Type  string                         `json:"type"`
	Tools []WireToolChoiceAllowedToolRef `json:"tools"`
	Mode  string                         `json:"mode,omitempty"`
}

WireToolChoiceAllowedTools is the object form of an allowed_tools tool choice: it restricts which tools the model may invoke to the named subset while the full Tools list stays visible (cache-preserving control surface). Mode is one of "auto", "none", or "required"; empty means auto.

type WireToolChoiceFunction

type WireToolChoiceFunction struct {
	Type string `json:"type"`
	Name string `json:"name"`
}

WireToolChoiceFunction is the official direct object form of a required function tool choice: {"type":"function","name":"..."}.

type WireToolChoiceFunctionName

type WireToolChoiceFunctionName struct {
	Name string `json:"name"`
}

WireToolChoiceFunctionName is retained as a decode-only compatibility shape for older nested function tool_choice payloads.

type WireUsage

type WireUsage struct {
	InputTokens         int                    `json:"input_tokens"`
	InputTokensDetails  WireUsageInputDetails  `json:"input_tokens_details"`
	OutputTokens        int                    `json:"output_tokens"`
	OutputTokensDetails WireUsageOutputDetails `json:"output_tokens_details"`
	TotalTokens         int                    `json:"total_tokens"`
	InputTokensPresent  bool                   `json:"-"`
	OutputTokensPresent bool                   `json:"-"`
	TotalTokensPresent  bool                   `json:"-"`
	RawJSON             json.RawMessage        `json:"-"`
}

WireUsage represents token usage statistics on the wire.

func (*WireUsage) UnmarshalJSON

func (u *WireUsage) UnmarshalJSON(data []byte) error

type WireUsageInputDetails

type WireUsageInputDetails struct {
	CachedTokens        int  `json:"cached_tokens"`
	TextTokens          int  `json:"text_tokens,omitempty"`
	AudioTokens         int  `json:"audio_tokens,omitempty"`
	Images              int  `json:"images,omitempty"`
	CachedTokensPresent bool `json:"-"`
	TextTokensPresent   bool `json:"-"`
	AudioTokensPresent  bool `json:"-"`
	ImagesPresent       bool `json:"-"`
}

WireUsageInputDetails captures known input token detail counters.

func (*WireUsageInputDetails) UnmarshalJSON

func (d *WireUsageInputDetails) UnmarshalJSON(data []byte) error

type WireUsageOutputDetails

type WireUsageOutputDetails struct {
	ReasoningTokens        int  `json:"reasoning_tokens"`
	TextTokens             int  `json:"text_tokens,omitempty"`
	AudioTokens            int  `json:"audio_tokens,omitempty"`
	Images                 int  `json:"images,omitempty"`
	ReasoningTokensPresent bool `json:"-"`
	TextTokensPresent      bool `json:"-"`
	AudioTokensPresent     bool `json:"-"`
	ImagesPresent          bool `json:"-"`
}

WireUsageOutputDetails captures known output token detail counters.

func (*WireUsageOutputDetails) UnmarshalJSON

func (d *WireUsageOutputDetails) UnmarshalJSON(data []byte) error

Jump to

Keyboard shortcuts

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