sdk

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 27, 2026 License: AGPL-3.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNotImplemented = errors.New("capability not implemented")

Functions

func ServeFromEnv

func ServeFromEnv(service *Service) error

func ServeUnix

func ServeUnix(ctx context.Context, socketPath string, service *Service) error

Types

type AuthenticateRequest

type AuthenticateRequest struct {
	Context  CallContext       `json:"context"`
	Headers  map[string]string `json:"headers"`
	SourceIP string            `json:"source_ip"`
	Method   string            `json:"method"`
	Path     string            `json:"path"`
}

type AuthenticateResponse

type AuthenticateResponse struct {
	Allow       bool         `json:"allow"`
	Identity    Identity     `json:"identity"`
	DenyReason  string       `json:"deny_reason,omitempty"`
	Diagnostics []Diagnostic `json:"diagnostics,omitempty"`
}

type Authenticator

type Authenticator interface {
	Authenticate(context.Context, AuthenticateRequest) (AuthenticateResponse, error)
}

type CacheLookupRequest

type CacheLookupRequest struct {
	Context  CallContext `json:"context"`
	Identity Identity    `json:"identity"`
	CacheKey string      `json:"cache_key"`
	Policy   CachePolicy `json:"policy"`
}

type CacheLookupResponse

type CacheLookupResponse struct {
	Hit      bool           `json:"hit"`
	Response CachedResponse `json:"response,omitempty"`
	CacheID  string         `json:"cache_id,omitempty"`
}

type CachePolicy

type CachePolicy struct {
	TTLMillis int64             `json:"ttl_ms,omitempty"`
	Semantic  bool              `json:"semantic,omitempty"`
	Vary      map[string]string `json:"vary,omitempty"`
}

type CacheStoreRequest

type CacheStoreRequest struct {
	Context  CallContext    `json:"context"`
	Identity Identity       `json:"identity"`
	CacheKey string         `json:"cache_key"`
	Response CachedResponse `json:"response"`
	Policy   CachePolicy    `json:"policy"`
}

type CachedResponse

type CachedResponse struct {
	Response ChatCompletionResponse `json:"response"`
	Usage    Usage                  `json:"usage,omitempty"`
}

type CallContext

type CallContext struct {
	RequestID      string
	TenantID       string
	Deadline       time.Time
	TraceContext   map[string]string
	GatewayVersion string
	PluginInstance string
}

type CapabilityDescriptor

type CapabilityDescriptor struct {
	Type    CapabilityType `json:"type"`
	Name    string         `json:"name"`
	Version string         `json:"version"`
}

type CapabilityType

type CapabilityType string
const (
	CapabilityAuthenticator         CapabilityType = "authenticator"
	CapabilityAuthorizer            CapabilityType = "authorizer"
	CapabilityRateLimiter           CapabilityType = "rate_limiter"
	CapabilityRouter                CapabilityType = "router"
	CapabilityUpstreamProvider      CapabilityType = "upstream_provider"
	CapabilityCacheProvider         CapabilityType = "cache_provider"
	CapabilityObserver              CapabilityType = "observer"
	CapabilityPromptProvider        CapabilityType = "prompt_provider"
	CapabilityCostProvider          CapabilityType = "cost_provider"
	CapabilityModelRegistryProvider CapabilityType = "model_registry_provider"
)

type ChatChoice

type ChatChoice struct {
	Index        int         `json:"index"`
	Message      ChatMessage `json:"message,omitempty"`
	Delta        ChatMessage `json:"delta,omitempty"`
	FinishReason string      `json:"finish_reason,omitempty"`
}

type ChatCompletionChunk

type ChatCompletionChunk struct {
	ID      string       `json:"id"`
	Object  string       `json:"object"`
	Created int64        `json:"created"`
	Model   string       `json:"model"`
	Choices []ChatChoice `json:"choices"`
}

type ChatCompletionRequest

type ChatCompletionRequest struct {
	Model       string         `json:"model"`
	Messages    []ChatMessage  `json:"messages"`
	Stream      bool           `json:"stream,omitempty"`
	Temperature *float64       `json:"temperature,omitempty"`
	MaxTokens   *int64         `json:"max_tokens,omitempty"`
	Tools       any            `json:"tools,omitempty"`
	ToolChoice  any            `json:"tool_choice,omitempty"`
	Metadata    any            `json:"metadata,omitempty"`
	Extra       map[string]any `json:"-"`
}

type ChatCompletionResponse

type ChatCompletionResponse struct {
	ID      string           `json:"id"`
	Object  string           `json:"object"`
	Created int64            `json:"created"`
	Model   string           `json:"model"`
	Choices []ChatChoice     `json:"choices"`
	Usage   map[string]int64 `json:"usage,omitempty"`
}

type ChatMessage

type ChatMessage struct {
	Role       string     `json:"role"`
	Content    any        `json:"content"`
	Name       string     `json:"name,omitempty"`
	ToolCallID string     `json:"tool_call_id,omitempty"`
	ToolCalls  []ToolCall `json:"tool_calls,omitempty"`
}

type CommitUsageRequest

type CommitUsageRequest struct {
	Context  CallContext `json:"context"`
	Identity Identity    `json:"identity"`
	Usage    Usage       `json:"usage"`
}

type ConfigureRequest

type ConfigureRequest struct {
	Context         CallContext
	ConfigJSON      string
	ResolvedSecrets map[string]string
}

type ConfigureResponse

type ConfigureResponse struct{ Diagnostics []Diagnostic }

type Configurer

type Configurer interface {
	Configure(context.Context, map[string]any, map[string]string) error
}

type DataPermissions

type DataPermissions struct {
	ReadPrompt     bool `json:"read_prompt"`
	ReadResponse   bool `json:"read_response"`
	ModifyRequest  bool `json:"modify_request"`
	ModifyResponse bool `json:"modify_response"`
	ReadHeaders    bool `json:"read_headers"`
}

type Diagnostic

type Diagnostic struct {
	Severity string            `json:"severity"`
	Code     string            `json:"code"`
	Message  string            `json:"message"`
	Details  map[string]string `json:"details,omitempty"`
}

type GatewayEvent

type GatewayEvent struct {
	EventID           string            `json:"event_id"`
	RequestID         string            `json:"request_id"`
	TenantID          string            `json:"tenant_id,omitempty"`
	EventType         string            `json:"event_type"`
	TimestampUnixNano int64             `json:"timestamp_unix_nano"`
	Properties        map[string]string `json:"properties,omitempty"`
	Usage             Usage             `json:"usage,omitempty"`
	Error             map[string]string `json:"error,omitempty"`
}

type GetConfigSchemaRequest

type GetConfigSchemaRequest struct{}

type GetConfigSchemaResponse

type GetConfigSchemaResponse struct{ SchemaJSON string }

type GetMetadataRequest

type GetMetadataRequest struct{}

type HandshakeRequest

type HandshakeRequest struct {
	GatewayVersion            string
	SupportedProtocolVersions []int
}

type HandshakeResponse

type HandshakeResponse struct {
	SelectedProtocolVersion int
	PluginName              string
	PluginVersion           string
	Diagnostics             []Diagnostic
}

type HealthRequest

type HealthRequest struct{}

type HealthResponse

type HealthResponse struct {
	State       string
	Diagnostics []Diagnostic
}

type Identity

type Identity struct {
	Subject    string            `json:"subject"`
	TenantID   string            `json:"tenant_id"`
	Groups     []string          `json:"groups,omitempty"`
	Claims     map[string]string `json:"claims,omitempty"`
	AuthMethod string            `json:"auth_method"`
}

type InvokeCancelRequest added in v0.2.0

type InvokeCancelRequest struct {
	StreamID uint64 `json:"stream_id"`
}

type InvokeCancelResponse added in v0.2.0

type InvokeCancelResponse struct{}

type InvokeNextRequest added in v0.2.0

type InvokeNextRequest struct {
	StreamID uint64 `json:"stream_id"`
}

type InvokeNextResponse added in v0.2.0

type InvokeNextResponse struct {
	Chunk ResponseChunk `json:"chunk,omitempty"`
	EOF   bool          `json:"eof,omitempty"`
}

type InvokeRequest

type InvokeRequest struct {
	Context       CallContext           `json:"context"`
	Identity      Identity              `json:"identity"`
	ProviderModel string                `json:"provider_model"`
	Request       ChatCompletionRequest `json:"request"`
	Properties    map[string]string     `json:"properties,omitempty"`
}

type InvokeStartResponse added in v0.2.0

type InvokeStartResponse struct {
	StreamID uint64 `json:"stream_id"`
}

type Metadata

type Metadata struct {
	Name         string                 `json:"name"`
	Version      string                 `json:"version"`
	Homepage     string                 `json:"homepage,omitempty"`
	Capabilities []CapabilityDescriptor `json:"capabilities"`
	Permissions  Permissions            `json:"permissions"`
}

type ModelInfo

type ModelInfo struct {
	ID                string            `json:"id"`
	Object            string            `json:"object,omitempty"`
	OwnedBy           string            `json:"owned_by,omitempty"`
	ProviderInstance  string            `json:"provider_instance,omitempty"`
	ProviderModel     string            `json:"provider_model,omitempty"`
	ContextWindow     int64             `json:"context_window,omitempty"`
	SupportsStreaming bool              `json:"supports_streaming,omitempty"`
	SupportsTools     bool              `json:"supports_tools,omitempty"`
	SupportsJSONMode  bool              `json:"supports_json_mode,omitempty"`
	SupportsVision    bool              `json:"supports_vision,omitempty"`
	Region            string            `json:"region,omitempty"`
	Healthy           bool              `json:"healthy"`
	Properties        map[string]string `json:"properties,omitempty"`
}

type Observer

type Observer interface {
	Emit(context.Context, []GatewayEvent) error
}

type Permissions

type Permissions struct {
	OutboundHosts []string        `json:"outbound_hosts"`
	SecretNames   []string        `json:"secret_names"`
	Data          DataPermissions `json:"data"`
}

type PromptProvider

type PromptProvider interface {
	ResolvePrompt(context.Context, PromptResolveRequest) (PromptResolveResponse, error)
}

type PromptResolveRequest

type PromptResolveRequest struct {
	Context   CallContext       `json:"context"`
	Identity  Identity          `json:"identity"`
	PromptRef string            `json:"prompt_ref"`
	Version   string            `json:"version,omitempty"`
	Variables map[string]string `json:"variables,omitempty"`
}

type PromptResolveResponse

type PromptResolveResponse struct {
	Messages        []ChatMessage     `json:"messages"`
	ResolvedVersion string            `json:"resolved_version,omitempty"`
	Properties      map[string]string `json:"properties,omitempty"`
}

type RateLimitCheckRequest

type RateLimitCheckRequest struct {
	Context               CallContext       `json:"context"`
	Identity              Identity          `json:"identity"`
	Model                 string            `json:"model"`
	EstimatedInputTokens  int64             `json:"estimated_input_tokens"`
	RequestedOutputTokens int64             `json:"requested_output_tokens"`
	Properties            map[string]string `json:"properties,omitempty"`
}

type RateLimitCheckResponse

type RateLimitCheckResponse struct {
	Decision     string         `json:"decision"`
	DenyReason   string         `json:"deny_reason,omitempty"`
	RetryAfterMS int64          `json:"retry_after_ms,omitempty"`
	State        RateLimitState `json:"state,omitempty"`
}

type RateLimitState

type RateLimitState struct {
	RequestLimit       int64   `json:"request_limit,omitempty"`
	RequestRemaining   int64   `json:"request_remaining,omitempty"`
	TokenLimit         int64   `json:"token_limit,omitempty"`
	TokenRemaining     int64   `json:"token_remaining,omitempty"`
	BudgetLimitUSD     float64 `json:"budget_limit_usd,omitempty"`
	BudgetRemainingUSD float64 `json:"budget_remaining_usd,omitempty"`
	ResetUnixNano      int64   `json:"reset_unix_nano,omitempty"`
}

type RequestConstraints

type RequestConstraints struct {
	AllowedModels       []string `json:"allowed_models,omitempty"`
	MaxOutputTokens     int64    `json:"max_output_tokens,omitempty"`
	MaxEstimatedCostUSD float64  `json:"max_estimated_cost_usd,omitempty"`
	AllowedRegions      []string `json:"allowed_regions,omitempty"`
}

type RequestSummary

type RequestSummary struct {
	Operation            string            `json:"operation"`
	RequestedModel       string            `json:"requested_model"`
	EstimatedInputTokens int64             `json:"estimated_input_tokens"`
	Properties           map[string]string `json:"properties,omitempty"`
}

type ResponseChunk

type ResponseChunk struct {
	Chunk *ChatCompletionChunk `json:"chunk,omitempty"`
	Usage *Usage               `json:"usage,omitempty"`
	Error *UpstreamError       `json:"error,omitempty"`
}

type RouteCandidate

type RouteCandidate struct {
	ProviderInstance         string            `json:"provider_instance"`
	ProviderModel            string            `json:"provider_model"`
	LogicalModel             string            `json:"logical_model"`
	Weight                   int               `json:"weight"`
	Region                   string            `json:"region,omitempty"`
	Healthy                  bool              `json:"healthy"`
	EstimatedCostPer1KInput  float64           `json:"estimated_cost_per_1k_input,omitempty"`
	EstimatedCostPer1KOutput float64           `json:"estimated_cost_per_1k_output,omitempty"`
	Properties               map[string]string `json:"properties,omitempty"`
}

type RouteRequest

type RouteRequest struct {
	Context        CallContext        `json:"context"`
	Identity       Identity           `json:"identity"`
	RequestedModel string             `json:"requested_model"`
	Request        RequestSummary     `json:"request"`
	Candidates     []RouteCandidate   `json:"candidates"`
	Constraints    RequestConstraints `json:"constraints,omitempty"`
}

type RouteResponse

type RouteResponse struct {
	Routes      []SelectedRoute `json:"routes"`
	Reason      string          `json:"reason,omitempty"`
	Diagnostics []Diagnostic    `json:"diagnostics,omitempty"`
}

type Router

type Router interface {
	Route(context.Context, RouteRequest) (RouteResponse, error)
}

type SelectedRoute

type SelectedRoute struct {
	ProviderInstance string            `json:"provider_instance"`
	ProviderModel    string            `json:"provider_model"`
	Priority         int               `json:"priority"`
	Properties       map[string]string `json:"properties,omitempty"`
}

type Service

type Service struct {
	Metadata Metadata
	Schema   string

	Configurer       Configurer
	Authenticator    Authenticator
	RateLimiter      RateLimiter
	Router           Router
	UpstreamProvider UpstreamProvider
	CacheProvider    CacheProvider
	Observer         Observer
	PromptProvider   PromptProvider
	// contains filtered or unexported fields
}

func (*Service) Authenticate

func (s *Service) Authenticate(req AuthenticateRequest, resp *AuthenticateResponse) error

func (*Service) CacheLookup

func (s *Service) CacheLookup(req CacheLookupRequest, resp *CacheLookupResponse) error

func (*Service) CacheStore

func (s *Service) CacheStore(req CacheStoreRequest, resp *struct{}) error

func (*Service) CheckRateLimit

func (s *Service) CheckRateLimit(req RateLimitCheckRequest, resp *RateLimitCheckResponse) error

func (*Service) CommitUsage

func (s *Service) CommitUsage(req CommitUsageRequest, resp *struct{}) error

func (*Service) Configure

func (s *Service) Configure(req ConfigureRequest, resp *ConfigureResponse) error

func (*Service) Emit

func (s *Service) Emit(events []GatewayEvent, resp *struct{}) error

func (*Service) GetConfigSchema

func (s *Service) GetConfigSchema(req GetConfigSchemaRequest, resp *GetConfigSchemaResponse) error

func (*Service) GetMetadata

func (s *Service) GetMetadata(req GetMetadataRequest, resp *Metadata) error

func (*Service) Handshake

func (s *Service) Handshake(req HandshakeRequest, resp *HandshakeResponse) error

func (*Service) Health

func (s *Service) Health(req HealthRequest, resp *HealthResponse) error

func (*Service) InvokeCancel added in v0.2.0

func (s *Service) InvokeCancel(req InvokeCancelRequest, resp *InvokeCancelResponse) error

InvokeCancel aborts an in-flight stream. The gateway calls this when its own context is cancelled (client disconnect, deadline). The producer's context is cancelled, which propagates to the upstream HTTP request, which closes the chunk channel. Any in-flight InvokeNext returns EOF.

func (*Service) InvokeNext added in v0.2.0

func (s *Service) InvokeNext(req InvokeNextRequest, resp *InvokeNextResponse) error

InvokeNext returns the next chunk on a stream, blocking until one arrives. When the producer has finished, the channel is closed and InvokeNext returns with EOF=true (one final empty response). The caller is expected to keep calling until EOF.

func (*Service) InvokeStart added in v0.2.0

func (s *Service) InvokeStart(req InvokeRequest, resp *InvokeStartResponse) error

InvokeStart spins up a streaming upstream call. It returns immediately with a stream ID; the caller pulls chunks via InvokeNext until eof=true. The producer goroutine runs the plugin's UpstreamProvider.Invoke, which writes chunks to a buffered channel as they arrive — when that function returns, the SDK closes the channel so any waiting InvokeNext observes EOF.

func (*Service) ListModels

func (s *Service) ListModels(req struct{}, resp *[]ModelInfo) error

func (*Service) ResolvePrompt

func (s *Service) ResolvePrompt(req PromptResolveRequest, resp *PromptResolveResponse) error

func (*Service) Route

func (s *Service) Route(req RouteRequest, resp *RouteResponse) error

func (*Service) Shutdown

func (s *Service) Shutdown(req ShutdownRequest, resp *ShutdownResponse) error

type ShutdownRequest

type ShutdownRequest struct{}

type ShutdownResponse

type ShutdownResponse struct{}

type ToolCall added in v0.2.0

type ToolCall struct {
	Index    int              `json:"index,omitempty"`
	ID       string           `json:"id,omitempty"`
	Type     string           `json:"type,omitempty"`
	Function ToolCallFunction `json:"function,omitempty"`
}

type ToolCallFunction added in v0.2.0

type ToolCallFunction struct {
	Name      string `json:"name,omitempty"`
	Arguments string `json:"arguments,omitempty"`
}

type UpstreamError

type UpstreamError struct {
	Code        string `json:"code"`
	Message     string `json:"message"`
	HTTPStatus  int    `json:"http_status"`
	Retryable   bool   `json:"retryable"`
	RateLimited bool   `json:"rate_limited"`
}

type UpstreamProvider

type UpstreamProvider interface {
	Invoke(ctx context.Context, req InvokeRequest, out chan<- ResponseChunk) error
	ListModels(ctx context.Context) ([]ModelInfo, error)
}

UpstreamProvider streams response chunks for an upstream call. The plugin owns `out`: it must send each chunk as it becomes available and then return (the SDK closes the channel for it). Errors that should surface on the in-flight request must be emitted as a ResponseChunk{Error: ...} rather than returned, so the gateway records the failure on the originating request. Returning a non-nil error fails the InvokeStart RPC itself — use it only for setup failures (validation, missing config) that happen before any chunks have been produced.

type Usage

type Usage struct {
	ProviderInstance string  `json:"provider_instance,omitempty"`
	ProviderModel    string  `json:"provider_model,omitempty"`
	InputTokens      int64   `json:"input_tokens,omitempty"`
	OutputTokens     int64   `json:"output_tokens,omitempty"`
	TotalTokens      int64   `json:"total_tokens,omitempty"`
	CostUSD          float64 `json:"cost_usd,omitempty"`
}

Jump to

Keyboard shortcuts

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