ai

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2026 License: AGPL-3.0 Imports: 10 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RoleCanonicalSystem     = op.RoleCanonicalSystem
	RoleCanonicalDeveloper  = op.RoleCanonicalDeveloper
	RoleCanonicalUser       = op.RoleCanonicalUser
	RoleCanonicalAssistant  = op.RoleCanonicalAssistant
	RoleCanonicalTool       = op.RoleCanonicalTool
	RoleCanonicalCompaction = op.RoleCanonicalCompaction
)
View Source
const (
	BlockText       = op.BlockText
	BlockThinking   = op.BlockThinking
	BlockImage      = op.BlockImage
	BlockToolCall   = op.BlockToolCall
	BlockToolResult = op.BlockToolResult
	BlockCompaction = op.BlockCompaction
)
View Source
const (
	ServiceTierPriority = "priority"
	ServiceTierFlex     = "flex"
)
View Source
const (
	StopReasonStop    = op.StopReasonStop
	StopReasonLength  = op.StopReasonLength
	StopReasonToolUse = op.StopReasonToolUse
	StopReasonError   = op.StopReasonError
	StopReasonAborted = op.StopReasonAborted
)

Variables

View Source
var ErrStreamingNotSupported = errors.New("streaming not supported")

Functions

func CloneToolArguments

func CloneToolArguments(args map[string]any) map[string]any

func ContinuationRequiredForCanonicalMessages

func ContinuationRequiredForCanonicalMessages(messages []ConversationMessage) bool

func ContinuationRequiredForOpMessages

func ContinuationRequiredForOpMessages(messages []op.Message) bool

func HasSemanticCanonicalResponse

func HasSemanticCanonicalResponse(resp *ProviderResponse) bool

func HasSemanticConversationMessage

func HasSemanticConversationMessage(msg ConversationMessage) bool

func IsRetryableStatusCode

func IsRetryableStatusCode(statusCode int) bool

func MarshalCanonicalAPIRequestJSON

func MarshalCanonicalAPIRequestJSON(modelID string, req *ProviderRequest) ([]byte, error)

func MarshalCanonicalWebsocketCreateJSON

func MarshalCanonicalWebsocketCreateJSON(modelID string, req *ProviderRequest) ([]byte, error)

func MarshalResponsesAPIRequestJSON

func MarshalResponsesAPIRequestJSON(req *ResponsesRequest) ([]byte, error)

func MarshalResponsesInputItemJSON

func MarshalResponsesInputItemJSON(item ResponseItem, idx int) (json.RawMessage, error)

MarshalResponsesInputItemJSON encodes one replay/input item into Responses API request-shape JSON.

func MarshalResponsesInputItemsJSON

func MarshalResponsesInputItemsJSON(items []ResponseItem) ([]json.RawMessage, error)

MarshalResponsesInputItemsJSON encodes replay/input items into Responses API request-shape JSON. Known item types are always serialized from structured fields instead of blindly replaying item.Raw, so stale output-shape payloads cannot poison later continuations.

func MarshalResponsesOutputItemJSON

func MarshalResponsesOutputItemJSON(item ResponseItem) json.RawMessage

MarshalResponsesOutputItemJSON encodes one result/output item into stable output-shape JSON.

func MarshalResponsesOutputItemsJSON

func MarshalResponsesOutputItemsJSON(items []ResponseItem) []json.RawMessage

MarshalResponsesOutputItemsJSON encodes output/result items into stable output-shape JSON shared by gateway HTTP/SSE/WS surfaces.

func MarshalResponsesWebsocketCreateJSON

func MarshalResponsesWebsocketCreateJSON(req *ResponsesRequest, generate *bool) ([]byte, error)

func MarshalToolArgumentsJSON

func MarshalToolArgumentsJSON(args map[string]any) string

func MessageUsageFromUsage

func MessageUsageFromUsage(usage Usage) *op.MessageUsage

func NormalizeServiceTier

func NormalizeServiceTier(value string) string

func OpMessageFromCanonical

func OpMessageFromCanonical(msg ConversationMessage) (op.Message, error)

func ParseResponsesFailureErrorJSON

func ParseResponsesFailureErrorJSON(raw string) error

func ParseRetryAfterHeaders

func ParseRetryAfterHeaders(headers http.Header) int64

func ParseToolArgumentsObject

func ParseToolArgumentsObject(raw string) map[string]any

func RenderCanonicalAPIResponseJSON

func RenderCanonicalAPIResponseJSON(resp *ProviderResponse) json.RawMessage

func RenderCanonicalStreamEventJSON

func RenderCanonicalStreamEventJSON(event ProviderEvent) json.RawMessage

func RenderResponsesAPIResponseJSON

func RenderResponsesAPIResponseJSON(result *ResponsesResult) json.RawMessage

func RenderResponsesAPIStreamEventJSON

func RenderResponsesAPIStreamEventJSON(event ResponsesStreamEvent, requestID string) json.RawMessage

func ResponseContentTexts

func ResponseContentTexts(parts []ResponseContentPart) []string

func ResponsesAPIServiceTier

func ResponsesAPIServiceTier(value string) (string, error)

func TruncateToolOutputForReplay

func TruncateToolOutputForReplay(content string) string

func TruncateToolOutputForReplayWithLimits

func TruncateToolOutputForReplayWithLimits(content string, maxLines int, maxBytes int) string

func WrapRetryError

func WrapRetryError(err error, statusCode int, code, message string, retryAfterMs int64) error

Types

type CanonicalAPIRequestPayload

type CanonicalAPIRequestPayload struct {
	Model              string              `json:"model"`
	Context            ConversationContext `json:"context"`
	Config             GenerationConfig    `json:"config"`
	PreviousResponseID string              `json:"previousResponseID,omitempty"`
	RequestID          string              `json:"requestID,omitempty"`
}

type CanonicalProvider

type CanonicalProvider interface {
	Capabilities() ProviderCapabilities
	CompleteCanonical(ctx context.Context, req *ProviderRequest) (*ProviderResponse, error)
	StreamCanonical(ctx context.Context, req *ProviderRequest) (*ProviderEventStream, error)
}

type CanonicalToolCall

type CanonicalToolCall = op.CanonicalToolCall

type CanonicalToolResult

type CanonicalToolResult = op.CanonicalToolResult

type CanonicalWebsocketCreatePayload

type CanonicalWebsocketCreatePayload struct {
	Type string `json:"type"`
	CanonicalAPIRequestPayload
}

type ContentBlock

type ContentBlock = op.ContentBlock

func CloneContentBlockPtr

func CloneContentBlockPtr(block *ContentBlock) *ContentBlock

type ContentBlockType

type ContentBlockType = op.ContentBlockType

type ConversationContext

type ConversationContext struct {
	SystemPrompt string                `json:"systemPrompt,omitempty"`
	Messages     []ConversationMessage `json:"messages,omitempty"`
	Tools        []ToolDefinition      `json:"tools,omitempty"`
}

type ConversationMessage

type ConversationMessage = op.ConversationMessage

func CanonicalMessagesFromOp

func CanonicalMessagesFromOp(messages []op.Message) []ConversationMessage

func CanonicalMessagesFromReplayableOp

func CanonicalMessagesFromReplayableOp(messages []op.Message) []ConversationMessage

func CloneConversationMessagePtr

func CloneConversationMessagePtr(msg *ConversationMessage) *ConversationMessage

func FinalizeStreamConversationMessage

func FinalizeStreamConversationMessage(partial *StreamConversationMessage) ConversationMessage

type ConversationRole

type ConversationRole = op.ConversationRole

type GenerationConfig

type GenerationConfig struct {
	Model             string          `json:"model,omitempty"`
	ServiceTier       string          `json:"serviceTier,omitempty"`
	MaxTokens         *int64          `json:"maxTokens,omitempty"`
	Temperature       *float64        `json:"temperature,omitempty"`
	ReasoningEffort   string          `json:"reasoningEffort,omitempty"`
	ReasoningEnabled  *bool           `json:"reasoningEnabled,omitempty"`
	ReasoningSummary  string          `json:"reasoningSummary,omitempty"`
	ToolChoice        json.RawMessage `json:"toolChoice,omitempty"`
	ParallelToolCalls *bool           `json:"parallelToolCalls,omitempty"`
	Include           []string        `json:"include,omitempty"`
	PromptCacheKey    string          `json:"promptCacheKey,omitempty"`
}

type ProviderCapabilities

type ProviderCapabilities struct {
	SupportsThinkingBlocks     bool
	SupportsToolCalls          bool
	SupportsParallelToolCalls  bool
	SupportsImages             bool
	SupportsStatelessReplay    bool
	SupportsPreviousResponseID bool
	SupportsCompaction         bool
	SupportsWebsocketStream    bool
}

func DefaultCapabilitiesForAPI

func DefaultCapabilitiesForAPI(api string) ProviderCapabilities

type ProviderEvent

type ProviderEvent struct {
	Type         ProviderEventType
	ContentIndex int
	Delta        string
	Content      string
	Block        *StreamContentBlock
	Partial      *StreamConversationMessage
	Response     *ProviderResponse
	Error        error
	Raw          json.RawMessage
}

func ParseCanonicalStreamEventJSON

func ParseCanonicalStreamEventJSON(raw []byte) (ProviderEvent, error)

type ProviderEventStream

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

func NewProviderEventStream

func NewProviderEventStream(buffer int) *ProviderEventStream

func (*ProviderEventStream) Close

func (s *ProviderEventStream) Close()

func (*ProviderEventStream) Emit

func (s *ProviderEventStream) Emit(event ProviderEvent) bool

func (*ProviderEventStream) Err

func (s *ProviderEventStream) Err() error

func (*ProviderEventStream) Event

func (*ProviderEventStream) Finish

func (s *ProviderEventStream) Finish(err error)

func (*ProviderEventStream) Next

func (s *ProviderEventStream) Next() bool

type ProviderEventType

type ProviderEventType string
const (
	EventCanonicalStart         ProviderEventType = "start"
	EventCanonicalTextStart     ProviderEventType = "text_start"
	EventCanonicalTextDelta     ProviderEventType = "text_delta"
	EventCanonicalTextEnd       ProviderEventType = "text_end"
	EventCanonicalThinkingStart ProviderEventType = "thinking_start"
	EventCanonicalThinkingDelta ProviderEventType = "thinking_delta"
	EventCanonicalThinkingEnd   ProviderEventType = "thinking_end"
	EventCanonicalToolCallStart ProviderEventType = "toolcall_start"
	EventCanonicalToolCallDelta ProviderEventType = "toolcall_delta"
	EventCanonicalToolCallEnd   ProviderEventType = "toolcall_end"
	EventCanonicalDone          ProviderEventType = "done"
	EventCanonicalError         ProviderEventType = "error"
)

type ProviderRequest

type ProviderRequest struct {
	Context            ConversationContext `json:"context"`
	Config             GenerationConfig    `json:"config"`
	PreviousResponseID string              `json:"previousResponseID,omitempty"`
	RequestID          string              `json:"requestID,omitempty"`
}

func DecodeCanonicalAPIRequestJSON

func DecodeCanonicalAPIRequestJSON(raw []byte) (string, *ProviderRequest, error)

func DecodeCanonicalAPIRequestPayload

func DecodeCanonicalAPIRequestPayload(payload CanonicalAPIRequestPayload) (string, *ProviderRequest, error)

func DecodeCanonicalWebsocketCreateJSON

func DecodeCanonicalWebsocketCreateJSON(raw []byte) (string, *ProviderRequest, error)

func PrepareCanonicalReplayForTarget

func PrepareCanonicalReplayForTarget(req *ProviderRequest, target ReplayTarget) *ProviderRequest

PrepareCanonicalReplayForTarget returns a request-only replay view for the target endpoint. Provider replay state is preserved only for the exact providerRef/API/model that produced it; cross-target history is downgraded to ordinary semantic context so provider-specific thinking/tool protocols cannot leak into a different endpoint.

type ProviderResponse

type ProviderResponse struct {
	Message    ConversationMessage `json:"message"`
	Usage      Usage               `json:"usage"`
	StopReason StopReason          `json:"stopReason,omitempty"`
}

func CloneProviderResponsePtr

func CloneProviderResponsePtr(resp *ProviderResponse) *ProviderResponse

func ParseCanonicalAPIResponseJSON

func ParseCanonicalAPIResponseJSON(raw []byte) (*ProviderResponse, error)

func ProviderResponseFromOpMessage

func ProviderResponseFromOpMessage(msg op.Message, usage Usage, stopReason StopReason) *ProviderResponse

func ProviderResponseFromResponsesResult

func ProviderResponseFromResponsesResult(result *ResponsesResult) *ProviderResponse

type ProviderState

type ProviderState = op.ProviderState

type ReplayTarget

type ReplayTarget struct {
	ProviderRef string
	Provider    string
	API         string
	Model       string
}

type ReplayableCanonicalMessagesResult

type ReplayableCanonicalMessagesResult struct {
	Messages             []ConversationMessage
	ContinuationRequired bool
}

func NormalizeReplayableCanonicalMessages

func NormalizeReplayableCanonicalMessages(messages []ConversationMessage) ReplayableCanonicalMessagesResult

type ReplayableOpMessagesResult

type ReplayableOpMessagesResult struct {
	Messages             []op.Message
	ContinuationRequired bool
}

func NormalizeReplayableOpMessages

func NormalizeReplayableOpMessages(messages []op.Message) ReplayableOpMessagesResult

type ResponseContentPart

type ResponseContentPart struct {
	Type     string
	Text     string
	ImageURL string
	Detail   string
}

type ResponseItem

type ResponseItem struct {
	Type             string
	Role             string
	ID               string
	Status           string
	CallID           string
	Name             string
	Arguments        string
	Content          []ResponseContentPart
	Summary          []ResponseSummaryPart
	EncryptedContent string
	OutputText       string
	OutputContent    []ResponseContentPart
	Raw              json.RawMessage
}

func ParseResponseItemRaw

func ParseResponseItemRaw(raw json.RawMessage) ResponseItem

type ResponseSummaryPart

type ResponseSummaryPart struct {
	Type string
	Text string
}

type ResponseTool

type ResponseTool struct {
	Type        string
	Name        string
	Description string
	Parameters  any
	Strict      *bool
	Raw         json.RawMessage
}

type ResponsesAPIRequestPayload

type ResponsesAPIRequestPayload struct {
	Model              string          `json:"model"`
	Instructions       string          `json:"instructions"`
	PreviousResponseID string          `json:"previous_response_id"`
	ServiceTier        string          `json:"service_tier"`
	Input              json.RawMessage `json:"input"`
	Tools              json.RawMessage `json:"tools"`
	Stream             *bool           `json:"stream"`
	MaxOutputTokens    *int64          `json:"max_output_tokens"`
	Temperature        *float64        `json:"temperature"`
	Reasoning          json.RawMessage `json:"reasoning"`
	ToolChoice         json.RawMessage `json:"tool_choice"`
	ParallelToolCalls  *bool           `json:"parallel_tool_calls"`
	Include            []string        `json:"include"`
	PromptCacheKey     string          `json:"prompt_cache_key"`
	Store              *bool           `json:"store"`
	Text               json.RawMessage `json:"text"`
}

ResponsesAPIRequestPayload is the wire-level JSON payload accepted by the OpenAI-compatible Responses HTTP API.

type ResponsesEventStream

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

func NewResponsesEventStream

func NewResponsesEventStream(buffer int) *ResponsesEventStream

func (*ResponsesEventStream) Close

func (s *ResponsesEventStream) Close()

func (*ResponsesEventStream) Emit

func (*ResponsesEventStream) Err

func (s *ResponsesEventStream) Err() error

func (*ResponsesEventStream) Event

func (*ResponsesEventStream) Finish

func (s *ResponsesEventStream) Finish(err error)

func (*ResponsesEventStream) Next

func (s *ResponsesEventStream) Next() bool

type ResponsesProvider

type ResponsesProvider interface {
	CompleteResponses(ctx context.Context, req *ResponsesRequest) (*ResponsesResult, error)
	StreamResponses(ctx context.Context, req *ResponsesRequest) (*ResponsesEventStream, error)
}

ResponsesProvider is the native Responses API surface used when callers need item-level protocol semantics instead of the canonical conversation surface.

type ResponsesReasoning

type ResponsesReasoning struct {
	Effort  string
	Summary string
}

type ResponsesRequest

type ResponsesRequest struct {
	Model              string
	Instructions       string
	PreviousResponseID string
	RequestID          string
	ServiceTier        string
	Input              []ResponseItem
	Tools              []ResponseTool
	ToolChoice         json.RawMessage
	ParallelToolCalls  *bool
	Reasoning          *ResponsesReasoning
	Store              *bool
	Stream             bool
	Include            []string
	PromptCacheKey     string
	Text               *ResponsesTextConfig
	Temperature        *float64
	MaxOutputTokens    *int64
}

func DecodeResponsesAPIRequestJSON

func DecodeResponsesAPIRequestJSON(raw []byte) (*ResponsesRequest, bool, error)

func DecodeResponsesAPIRequestPayload

func DecodeResponsesAPIRequestPayload(req ResponsesAPIRequestPayload) (*ResponsesRequest, bool, error)

type ResponsesResult

type ResponsesResult struct {
	ID          string
	ProviderRef string
	Model       string
	Status      string
	Output      []ResponseItem
	Usage       Usage
	StopReason  StopReason
}

func ParseResponsesResultJSON

func ParseResponsesResultJSON(raw []byte) (*ResponsesResult, error)

type ResponsesStreamEvent

type ResponsesStreamEvent struct {
	Type     string
	Delta    string
	Item     *ResponseItem
	Response *ResponsesResult
	Error    error
	Raw      json.RawMessage
}

func NewSyntheticResponsesCompletedEvent

func NewSyntheticResponsesCompletedEvent(result *ResponsesResult) ResponsesStreamEvent

func NewSyntheticResponsesCreatedEvent

func NewSyntheticResponsesCreatedEvent(responseID, model string) ResponsesStreamEvent

func NewSyntheticResponsesFailureEvent

func NewSyntheticResponsesFailureEvent(err error) ResponsesStreamEvent

func ParseResponsesStreamEventJSON

func ParseResponsesStreamEventJSON(raw []byte) (ResponsesStreamEvent, error)

type ResponsesTextConfig

type ResponsesTextConfig struct {
	Verbosity string
	FormatRaw json.RawMessage
}

type ResponsesWebsocketCreatePayload

type ResponsesWebsocketCreatePayload struct {
	Type     string `json:"type"`
	Generate *bool  `json:"generate"`
	ResponsesAPIRequestPayload
}

ResponsesWebsocketCreatePayload is the wire-level websocket create envelope used by the gateway websocket Responses surface.

type RetryError

type RetryError struct {
	Retryable    bool
	StatusCode   int
	Code         string
	Message      string
	RetryAfterMs int64
	Err          error
}

RetryError is the canonical transient-failure shape used across provider, runtime, and UI layers. It preserves the original error while surfacing the retry semantics the runtime needs.

func AsRetryError

func AsRetryError(err error) (*RetryError, bool)

func NormalizeRetryError

func NormalizeRetryError(err error) *RetryError

func (*RetryError) Error

func (e *RetryError) Error() string

func (*RetryError) Unwrap

func (e *RetryError) Unwrap() error

type StopReason

type StopReason = op.MessageStopReason

type StreamContentBlock

type StreamContentBlock struct {
	Type                ContentBlockType `json:"type"`
	Text                string           `json:"text,omitempty"`
	MimeType            string           `json:"mimeType,omitempty"`
	ImageData           string           `json:"imageData,omitempty"`
	TextSignature       string           `json:"textSignature,omitempty"`
	ThinkingReplayField string           `json:"thinkingReplayField,omitempty"`
	ThinkingSignature   string           `json:"thinkingSignature,omitempty"`
	ToolCall            *StreamToolCall  `json:"toolCall,omitempty"`
	EncryptedContent    string           `json:"encryptedContent,omitempty"`
	Raw                 json.RawMessage  `json:"raw,omitempty"`
}

func CloneStreamContentBlockPtr

func CloneStreamContentBlockPtr(block *StreamContentBlock) *StreamContentBlock

func StreamContentBlockFromCanonical

func StreamContentBlockFromCanonical(block ContentBlock) StreamContentBlock

type StreamConversationMessage

type StreamConversationMessage struct {
	Role          ConversationRole     `json:"role"`
	Content       []StreamContentBlock `json:"content,omitempty"`
	Timestamp     int64                `json:"timestamp,omitempty"`
	ProviderState *ProviderState       `json:"providerState,omitempty"`
	Raw           json.RawMessage      `json:"raw,omitempty"`
}

func StreamConversationMessageFromCanonical

func StreamConversationMessageFromCanonical(msg ConversationMessage) *StreamConversationMessage

type StreamToolCall

type StreamToolCall struct {
	ID               string          `json:"id"`
	Name             string          `json:"name"`
	Arguments        map[string]any  `json:"arguments,omitempty"`
	RawArguments     string          `json:"rawArguments,omitempty"`
	ThoughtSignature string          `json:"thoughtSignature,omitempty"`
	Complete         bool            `json:"complete,omitempty"`
	Raw              json.RawMessage `json:"raw,omitempty"`
}

type ThreadContextUsage

type ThreadContextUsage struct {
	Tokens        int64 `json:"tokens,omitempty"`
	ContextWindow int64 `json:"contextWindow,omitempty"`
	PercentMilli  int64 `json:"percentMilli,omitempty"`
	Known         bool  `json:"known,omitempty"`
}

type ThreadSnapshot

type ThreadSnapshot struct {
	Meta               op.ThreadMeta               `json:"meta"`
	Entries            []op.ThreadEntry            `json:"entries,omitempty"`
	EntryWindow        op.ThreadEntryWindow        `json:"entryWindow,omitempty"`
	Revision           string                      `json:"revision,omitempty"`
	RunStatus          op.ThreadRunStatus          `json:"runStatus,omitempty"`
	TailStatus         op.ThreadTailStatus         `json:"tailStatus,omitempty"`
	ContinuationReason op.ThreadContinuationReason `json:"continuationReason,omitempty"`
	QueuedMessages     op.ThreadQueueSnapshot      `json:"queuedMessages,omitempty"`
	MessageRecords     []op.MessageRecord          `json:"messageRecords,omitempty"`
	ChannelSummaries   []op.MessageChannelSummary  `json:"channelSummaries,omitempty"`
	ContextUsage       ThreadContextUsage          `json:"contextUsage,omitempty"`
}

type ToolDefinition

type ToolDefinition struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	Parameters  any             `json:"parameters,omitempty"`
	Strict      *bool           `json:"strict,omitempty"`
	Raw         json.RawMessage `json:"raw,omitempty"`
}

func CanonicalToolsFromOp

func CanonicalToolsFromOp(specs []op.ToolSpec) []ToolDefinition

type Usage

type Usage struct {
	InputTokens      int64 `json:"inputTokens,omitempty"`
	OutputTokens     int64 `json:"outputTokens,omitempty"`
	CacheReadTokens  int64 `json:"cacheReadTokens,omitempty"`
	CacheWriteTokens int64 `json:"cacheWriteTokens,omitempty"`
	TotalTokens      int64 `json:"totalTokens,omitempty"`
}

func (Usage) PromptTokens

func (u Usage) PromptTokens() int64

func (Usage) ResolvedTotalTokens

func (u Usage) ResolvedTotalTokens() int64

Directories

Path Synopsis
edge

Jump to

Keyboard shortcuts

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