gateway

package
v0.1.64 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package gateway contains transport-independent gateway use cases.

Index

Constants

View Source
const (
	AttemptKindPrimary  = "primary"
	AttemptKindFailover = "failover"
	AttemptKindRetry    = "retry"
)

Variables

This section is empty.

Functions

func ApplyResolvedSelector

func ApplyResolvedSelector(model, providerHint *string, resolution *core.RequestModelResolution)

ApplyResolvedSelector updates request model/provider fields to the resolved selector.

func ApplyWorkflowContextOverrides

func ApplyWorkflowContextOverrides(ctx context.Context, workflow *core.Workflow)

ApplyWorkflowContextOverrides applies request-origin-specific policy changes.

func ApplyWorkflowPolicy

func ApplyWorkflowPolicy(ctx context.Context, workflow *core.Workflow, resolver WorkflowPolicyResolver, selector core.WorkflowSelector) error

ApplyWorkflowPolicy applies the first matching workflow policy to workflow.

func CloneChatRequestForSelector

func CloneChatRequestForSelector(req *core.ChatRequest, selector core.ModelSelector) *core.ChatRequest

CloneChatRequestForSelector clones a chat request for a concrete selector.

func CloneChatRequestForStreamUsage

func CloneChatRequestForStreamUsage(req *core.ChatRequest) *core.ChatRequest

CloneChatRequestForStreamUsage clones chat stream options before usage mutation.

func CloneResponsesRequestForSelector

func CloneResponsesRequestForSelector(req *core.ResponsesRequest, selector core.ModelSelector) *core.ResponsesRequest

CloneResponsesRequestForSelector clones a Responses request for a concrete selector.

func FirstNonEmpty

func FirstNonEmpty(values ...string) string

FirstNonEmpty returns the first non-empty trimmed string.

func IsNativeBatchResultsPending

func IsNativeBatchResultsPending(
	ctx context.Context,
	nativeRouter core.NativeBatchRoutableProvider,
	providerType, providerBatchID string,
	err error,
) (bool, *core.BatchResponse)

IsNativeBatchResultsPending reports whether a provider 404 means results are still pending.

func IsTerminalBatchStatus

func IsTerminalBatchStatus(status string) bool

IsTerminalBatchStatus reports whether status is terminal.

func LogBatchUsageFromBatchResults

func LogBatchUsageFromBatchResults(
	stored *batchstore.StoredBatch,
	result *core.BatchResultsResponse,
	fallbackRequestID string,
	usageLogger usage.LoggerInterface,
	pricingResolver usage.PricingResolver,
) bool

LogBatchUsageFromBatchResults writes per-item usage from batch results once.

func MergeStoredBatchFromUpstream

func MergeStoredBatchFromUpstream(stored *batchstore.StoredBatch, upstream *core.BatchResponse)

MergeStoredBatchFromUpstream applies sparse upstream refresh fields to a stored batch.

func NormalizeWorkflowPolicyError

func NormalizeWorkflowPolicyError(err error) error

NormalizeWorkflowPolicyError converts policy lookup failures into gateway errors.

func ProviderNameFromWorkflow

func ProviderNameFromWorkflow(workflow *core.Workflow) string

ProviderNameFromWorkflow returns the resolved configured provider name.

func ProviderTypeFromWorkflow

func ProviderTypeFromWorkflow(workflow *core.Workflow) string

ProviderTypeFromWorkflow returns the workflow provider type.

func QualifyExecutedModel

func QualifyExecutedModel(workflow *core.Workflow, model, providerName string) string

QualifyExecutedModel returns the public executed model selector.

func QualifyModelWithProvider

func QualifyModelWithProvider(model, providerName string) string

QualifyModelWithProvider prefixes a model with providerName when needed.

func ResolveExecutionSelector

func ResolveExecutionSelector(
	ctx context.Context,
	provider core.RoutableProvider,
	resolver ModelResolver,
	requested core.RequestedModelSelector,
) (core.ModelSelector, bool, error)

ResolveExecutionSelector applies explicit and provider-owned selector resolution. ctx carries the effective request user path so a resolver that implements UserPathModelResolver can apply user_path-scoped redirects.

func ResolveRequestModelWithAuthorizer

func ResolveRequestModelWithAuthorizer(
	ctx context.Context,
	provider core.RoutableProvider,
	resolver ModelResolver,
	authorizer ModelAuthorizer,
	requested core.RequestedModelSelector,
) (*core.RequestModelResolution, error)

ResolveRequestModelWithAuthorizer resolves and validates a requested selector.

func ResolvedModelFromWorkflow

func ResolvedModelFromWorkflow(workflow *core.Workflow, fallback string) string

ResolvedModelFromWorkflow returns the resolved model or fallback.

func ResolvedProviderName

func ResolvedProviderName(provider core.RoutableProvider, selector core.ModelSelector, fallback string) string

ResolvedProviderName returns the configured provider instance name for a selector.

func ResolvedWorkflowProviderName

func ResolvedWorkflowProviderName(resolution *core.RequestModelResolution) string

ResolvedWorkflowProviderName returns the configured provider name recorded in a resolution.

func ResponseProviderType

func ResponseProviderType(fallback, responseProvider string) string

ResponseProviderType returns responseProvider when set, otherwise fallback.

func SanitizePublicBatchMetadata

func SanitizePublicBatchMetadata(metadata map[string]string) map[string]string

SanitizePublicBatchMetadata removes gateway-private metadata keys.

func ShouldAttemptFailover

func ShouldAttemptFailover(err error) bool

ShouldAttemptFailover reports whether err should trigger translated failover.

func TranslatedWorkflow

func TranslatedWorkflow(
	ctx context.Context,
	requestID string,
	endpoint core.EndpointDescriptor,
	resolution *core.RequestModelResolution,
	policyResolver WorkflowPolicyResolver,
) (*core.Workflow, error)

TranslatedWorkflow builds a translated execution workflow for a resolved model.

func WithAttemptObserver

func WithAttemptObserver(ctx context.Context, observe AttemptObserver) context.Context

WithAttemptObserver registers an observer notified after each failed attempt. It is independent of (and additive to) the attempt recorder.

func WithAttemptRecorder

func WithAttemptRecorder(ctx context.Context) context.Context

WithAttemptRecorder ensures ctx carries a request-scoped attempt recorder.

func WorkflowProviderNameForType

func WorkflowProviderNameForType(provider core.RoutableProvider, providerType string) string

WorkflowProviderNameForType maps a provider type to its configured provider name when available.

Types

type AttemptObserver

type AttemptObserver func()

AttemptObserver is invoked after a failed provider attempt is recorded, so the audit/live layer can surface it before the overall request finishes (e.g. a failed primary while failover is still in flight).

type AttemptRecorder

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

func AttemptRecorderFromContext

func AttemptRecorderFromContext(ctx context.Context) *AttemptRecorder

type BatchConfig

type BatchConfig struct {
	Provider                             core.RoutableProvider
	ModelResolver                        ModelResolver
	ModelAuthorizer                      ModelAuthorizer
	InputFileProviderResolver            BatchInputFileProviderResolver
	WorkflowPolicyResolver               WorkflowPolicyResolver
	BatchRequestPreparer                 BatchRequestPreparer
	BatchStore                           batchstore.Store
	CleanupPreparedBatchInputFile        func(context.Context, string, string)
	CleanupStoredBatchRewrittenInputFile func(context.Context, *batchstore.StoredBatch) bool
	UsageLogger                          usage.LoggerInterface
	PricingResolver                      usage.PricingResolver
	BudgetEnforcer                       func(context.Context) error
}

BatchConfig configures native batch orchestration.

type BatchCreateResult

type BatchCreateResult struct {
	Batch        *core.BatchResponse
	Workflow     *core.Workflow
	ProviderType string
}

BatchCreateResult is the result of creating a native batch.

type BatchExecutionSelection

type BatchExecutionSelection struct {
	ProviderType string
	Selector     core.WorkflowSelector
}

BatchExecutionSelection captures the provider and workflow selector for a native batch.

func DetermineBatchExecutionSelectionWithAuthorizerAndInputFileResolver

func DetermineBatchExecutionSelectionWithAuthorizerAndInputFileResolver(
	ctx context.Context,
	provider core.RoutableProvider,
	resolver ModelResolver,
	authorizer ModelAuthorizer,
	inputFileProviderResolver BatchInputFileProviderResolver,
	req *core.BatchRequest,
) (BatchExecutionSelection, error)

DetermineBatchExecutionSelectionWithAuthorizerAndInputFileResolver resolves and authorizes native batch items, using file ownership metadata for file-backed batches when no explicit provider hint is supplied.

type BatchInputFileProviderResolver

type BatchInputFileProviderResolver interface {
	ResolveBatchInputFileProvider(ctx context.Context, fileID string) (providerType string, ok bool, err error)
}

BatchInputFileProviderResolver resolves provider ownership for an uploaded batch input file.

type BatchListParams

type BatchListParams struct {
	Limit int
	After string
}

BatchListParams contains native batch list pagination options.

type BatchMeta

type BatchMeta struct {
	RequestID string
	Endpoint  core.EndpointDescriptor
	Workflow  *core.Workflow
}

BatchMeta carries transport-derived metadata into native batch use cases.

type BatchOrchestrator

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

BatchOrchestrator owns native batch lifecycle behavior independent of HTTP.

func NewBatchOrchestrator

func NewBatchOrchestrator(cfg BatchConfig) *BatchOrchestrator

NewBatchOrchestrator creates a native batch orchestrator.

func (*BatchOrchestrator) Cancel

func (o *BatchOrchestrator) Cancel(ctx context.Context, id string) (*BatchResult, error)

Cancel cancels an upstream native batch and persists refreshed state.

func (*BatchOrchestrator) Create

Create creates a native provider batch and persists the gateway batch mapping.

func (*BatchOrchestrator) Delete added in v0.1.53

func (o *BatchOrchestrator) Delete(ctx context.Context, id string) (*BatchResult, error)

Delete removes an ended batch from the upstream provider (when its batch API supports deletion) and from the gateway store. Batches still processing must be canceled first, matching the Anthropic Message Batches contract.

func (*BatchOrchestrator) Get

Get refreshes and returns a stored batch.

func (*BatchOrchestrator) List

List returns gateway-tracked batches.

func (*BatchOrchestrator) Results

func (o *BatchOrchestrator) Results(ctx context.Context, id, fallbackRequestID string) (*BatchResultsResult, error)

Results returns native batch output items and persists result/usage refreshes.

type BatchRequestPreparer

type BatchRequestPreparer interface {
	PrepareBatchRequest(ctx context.Context, providerType string, req *core.BatchRequest) (*core.BatchRewriteResult, error)
}

BatchRequestPreparer rewrites a native batch request before provider submission. This keeps batch-specific policy out of provider decorators.

type BatchResult

type BatchResult struct {
	Batch        *core.BatchResponse
	ProviderType string
}

BatchResult is the result of a single batch lifecycle operation.

type BatchResultsResult

type BatchResultsResult struct {
	Response     *core.BatchResultsResponse
	ProviderType string
}

BatchResultsResult is the result of retrieving batch output items.

type ChatCompletionResult

type ChatCompletionResult struct {
	Response *core.ChatResponse
	Meta     ExecutionMeta
}

ChatCompletionResult is the non-streaming chat completion result.

type EmbeddingResult

type EmbeddingResult struct {
	Response *core.EmbeddingResponse
	Meta     ExecutionMeta
}

EmbeddingResult is the embeddings result.

type ExecutionMeta

type ExecutionMeta struct {
	ProviderType  string
	ProviderName  string
	Model         string
	FailoverModel string
	UsedFailover  bool
}

ExecutionMeta describes the concrete route used for provider execution.

type FailoverResolver

type FailoverResolver interface {
	ResolveFailovers(resolution *core.RequestModelResolution, op core.Operation) []core.ModelSelector
}

FailoverResolver resolves alternate concrete model selectors for a translated request after the primary selector has already been resolved.

type InferenceConfig

type InferenceConfig struct {
	Provider                 core.RoutableProvider
	ModelResolver            ModelResolver
	ModelAuthorizer          ModelAuthorizer
	WorkflowPolicyResolver   WorkflowPolicyResolver
	FailoverResolver         FailoverResolver
	TranslatedRequestPatcher TranslatedRequestPatcher
	UsageLogger              usage.LoggerInterface
	PricingResolver          usage.PricingResolver
	RouteGate                RouteGate
	GuardrailsHash           string
}

InferenceConfig configures translated inference orchestration.

type InferenceOrchestrator

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

InferenceOrchestrator owns translated inference workflow resolution, request patching, provider dispatch, failover, usage logging, and cache metadata.

func NewInferenceOrchestrator

func NewInferenceOrchestrator(cfg InferenceConfig) *InferenceOrchestrator

NewInferenceOrchestrator creates a translated inference orchestrator.

func (*InferenceOrchestrator) CanFastPathStreamingChatPassthrough

func (o *InferenceOrchestrator) CanFastPathStreamingChatPassthrough(workflow *core.Workflow, req *core.ChatRequest) bool

CanFastPathStreamingChatPassthrough reports whether a streaming chat request can bypass translation.

func (*InferenceOrchestrator) DispatchChatCompletion

func (o *InferenceOrchestrator) DispatchChatCompletion(
	ctx context.Context,
	workflow *core.Workflow,
	req *core.ChatRequest,
) (*core.ChatResponse, string, string, string, bool, error)

DispatchChatCompletion executes a non-streaming chat request without usage side effects.

func (*InferenceOrchestrator) DispatchEmbeddings

func (o *InferenceOrchestrator) DispatchEmbeddings(
	ctx context.Context,
	workflow *core.Workflow,
	req *core.EmbeddingRequest,
) (*core.EmbeddingResponse, string, string, error)

DispatchEmbeddings executes an embeddings request without usage side effects.

func (*InferenceOrchestrator) DispatchResponses

DispatchResponses executes a non-streaming Responses request without usage side effects.

func (*InferenceOrchestrator) ExecuteChatCompletion

func (o *InferenceOrchestrator) ExecuteChatCompletion(ctx context.Context, workflow *core.Workflow, req *core.ChatRequest, requestID, endpoint string) (*ChatCompletionResult, error)

ExecuteChatCompletion executes a non-streaming chat request and records usage on success.

func (*InferenceOrchestrator) ExecuteEmbeddings

func (o *InferenceOrchestrator) ExecuteEmbeddings(ctx context.Context, workflow *core.Workflow, req *core.EmbeddingRequest, requestID, endpoint string) (*EmbeddingResult, error)

ExecuteEmbeddings executes an embeddings request and records usage on success.

func (*InferenceOrchestrator) ExecuteResponses

func (o *InferenceOrchestrator) ExecuteResponses(ctx context.Context, workflow *core.Workflow, req *core.ResponsesRequest, requestID, endpoint string) (*ResponsesResult, error)

ExecuteResponses executes a non-streaming Responses API request and records usage on success.

func (*InferenceOrchestrator) FailoverSelectors

func (o *InferenceOrchestrator) FailoverSelectors(workflow *core.Workflow) []core.ModelSelector

FailoverSelectors returns failover selectors for a translated workflow.

func (*InferenceOrchestrator) LogUsage

func (o *InferenceOrchestrator) LogUsage(
	ctx context.Context,
	workflow *core.Workflow,
	model, providerType, providerName string,
	extractFn func(*core.ModelPricing) *usage.UsageEntry,
)

LogUsage writes one non-streaming usage entry when usage is enabled.

func (*InferenceOrchestrator) PrepareChatRequest

func (o *InferenceOrchestrator) PrepareChatRequest(ctx context.Context, req *core.ChatRequest, meta RequestMeta) (*PreparedChatRequest, error)

PrepareChatRequest resolves workflow/model policy and applies translated request patching.

func (*InferenceOrchestrator) PrepareEmbeddingRequest

func (o *InferenceOrchestrator) PrepareEmbeddingRequest(ctx context.Context, req *core.EmbeddingRequest, meta RequestMeta) (*PreparedEmbeddingRequest, error)

PrepareEmbeddingRequest resolves workflow/model policy for an embeddings request.

func (*InferenceOrchestrator) PrepareResponsesRequest

func (o *InferenceOrchestrator) PrepareResponsesRequest(ctx context.Context, req *core.ResponsesRequest, meta RequestMeta) (*PreparedResponsesRequest, error)

PrepareResponsesRequest resolves workflow/model policy and applies translated request patching.

func (*InferenceOrchestrator) ProviderTypeForSelector

func (o *InferenceOrchestrator) ProviderTypeForSelector(selector core.ModelSelector, fallback string) string

ProviderTypeForSelector returns the provider type for a selector.

func (*InferenceOrchestrator) ResolveChatRoute

func (o *InferenceOrchestrator) ResolveChatRoute(workflow *core.Workflow, req *core.ChatRequest) (*core.ChatRequest, string, string, string)

ResolveChatRoute returns the provider route and the request to send for chat streams.

func (*InferenceOrchestrator) ShouldEnforceReturningUsageData

func (o *InferenceOrchestrator) ShouldEnforceReturningUsageData() bool

ShouldEnforceReturningUsageData reports whether streams should request usage chunks.

func (*InferenceOrchestrator) StreamChatCompletion

func (o *InferenceOrchestrator) StreamChatCompletion(ctx context.Context, workflow *core.Workflow, req *core.ChatRequest) (*StreamResult, error)

StreamChatCompletion opens a chat SSE stream. Stream usage is recorded by the caller's stream observer.

func (*InferenceOrchestrator) StreamResponses

func (o *InferenceOrchestrator) StreamResponses(ctx context.Context, workflow *core.Workflow, req *core.ResponsesRequest) (*StreamResult, error)

StreamResponses opens a Responses API SSE stream. Stream usage is recorded by the caller's stream observer.

func (*InferenceOrchestrator) WithCacheRequestContext

func (o *InferenceOrchestrator) WithCacheRequestContext(ctx context.Context, workflow *core.Workflow) context.Context

WithCacheRequestContext injects workflow and guardrails cache metadata into ctx.

type ModelAuthorizer

type ModelAuthorizer interface {
	ValidateModelAccess(ctx context.Context, selector core.ModelSelector) error
	AllowsModel(ctx context.Context, selector core.ModelSelector) bool
	FilterPublicModels(ctx context.Context, models []core.Model) []core.Model
}

ModelAuthorizer validates request-scoped access to concrete models.

type ModelResolver

type ModelResolver interface {
	ResolveModel(requested core.RequestedModelSelector) (core.ModelSelector, bool, error)
}

ModelResolver resolves raw request selectors into concrete model selectors before provider execution.

type PreparedChatRequest

type PreparedChatRequest struct {
	Context  context.Context
	Request  *core.ChatRequest
	Workflow *core.Workflow
}

PreparedChatRequest is a translated chat request ready for cache lookup or execution.

type PreparedEmbeddingRequest

type PreparedEmbeddingRequest struct {
	Context  context.Context
	Request  *core.EmbeddingRequest
	Workflow *core.Workflow
}

PreparedEmbeddingRequest is a translated embeddings request ready for execution.

type PreparedResponsesRequest

type PreparedResponsesRequest struct {
	Context  context.Context
	Request  *core.ResponsesRequest
	Workflow *core.Workflow
}

PreparedResponsesRequest is a translated Responses request ready for cache lookup or execution.

type ProviderAttempt

type ProviderAttempt struct {
	Seq          int
	Kind         string
	ProviderType string
	ProviderName string
	Model        string
	StatusCode   int
	Success      bool
	ErrorType    string
	ErrorCode    string
	ErrorMessage string
	StartedAt    time.Time
	DurationNs   int64
	// ResponseBody and ResponseHeaders hold the raw upstream error response for
	// a failed attempt. They are persisted only when audit body/header logging
	// is enabled; the audit layer parses and redacts them before storage.
	ResponseBody    []byte
	ResponseHeaders http.Header
}

ProviderAttempt describes one external provider call made while serving a logical request. It is intentionally storage-agnostic; server/audit layers decide how to persist it.

func AttemptsFromContext

func AttemptsFromContext(ctx context.Context) []ProviderAttempt

type RequestMeta

type RequestMeta struct {
	RequestID string
	Endpoint  core.EndpointDescriptor
	Workflow  *core.Workflow
}

RequestMeta carries transport-derived metadata into gateway use cases.

type ResponsesResult

type ResponsesResult struct {
	Response *core.ResponsesResponse
	Meta     ExecutionMeta
}

ResponsesResult is the non-streaming Responses API result.

type RouteGate

type RouteGate interface {
	RouteAvailable(providerName, model string) bool
}

RouteGate reports whether a provider/model route currently has rate-limit capacity. Failover uses it to skip saturated targets; admission at the handler layer stays the authoritative check.

type StreamResult

type StreamResult struct {
	Stream io.ReadCloser
	Meta   ExecutionMeta
}

StreamResult is a provider SSE stream plus route metadata for observers.

type TranslatedRequestPatcher

type TranslatedRequestPatcher interface {
	PatchChatRequest(ctx context.Context, req *core.ChatRequest) (*core.ChatRequest, error)
	PatchResponsesRequest(ctx context.Context, req *core.ResponsesRequest) (*core.ResponsesRequest, error)
}

TranslatedRequestPatcher applies request-level transforms for translated routes after workflow resolution has resolved the concrete execution selector.

type UserPathModelResolver

type UserPathModelResolver interface {
	ResolveModelForUserPath(ctx context.Context, requested core.RequestedModelSelector) (core.ModelSelector, bool, error)
}

UserPathModelResolver is an optional ModelResolver that resolves with awareness of the effective request user path, so a redirect (alias) can be scoped to specific user_paths and fall through to the literal model name for callers that do not match. Resolvers that do not implement it are resolved unscoped via ResolveModel.

type WorkflowPolicyResolver

type WorkflowPolicyResolver interface {
	Match(selector core.WorkflowSelector) (*core.ResolvedWorkflowPolicy, error)
}

WorkflowPolicyResolver matches persisted workflow versions for requests.

Jump to

Keyboard shortcuts

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