recorder

package
v2.39.5 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 20 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Recorder

The recorder package defines a Recorder interface and supplementary types, as well as several implementations of the interface. A concrete recorder, like DRPCRecorder, is a Repository/Store for persisting information about interactions with an LLM that were intercepted by AI gateway.

Various Decorator Recorders are defined that add behaviour like logging and tracing without polluting the persistence layer. Decorator Recorders wrap other Recorders, like middleware.

To begin exploring the package, start from types.go, which defines the Recorder interface. Then, move on to the various implementations.

Decorators are composed with Chain, in chain.go, which takes them outermost first and returns a function to apply them to the concrete recorder that terminates the chain. Each decorating recorder has a corresponding Decorator constructor, such as WithLogging, defined alongside it.

Documentation

Index

Constants

View Source
const (
	InterceptionLogMarker = "interception log"
	MetadataUserAgentKey  = "request_user_agent"
)

The structured log contract for AI Gateway interception records. Customer SIEM pipelines select and parse on these values, so they are public API and must not change without a deprecation. They live here, rather than beside either emitter, because both the gateway and coderd emit this format and duplicated literals would let the two drift.

View Source
const (
	RecordTypeInterceptionStart = "interception_start"
	RecordTypeInterceptionEnd   = "interception_end"
	RecordTypeTokenUsage        = "token_usage"
	RecordTypePromptUsage       = "prompt_usage"
	RecordTypeToolUsage         = "tool_usage"
	RecordTypeModelThought      = "model_thought"
)

Values of the record_type field, one per Recorder method.

View Source
const (
	ThoughtSourceThinking         = "thinking"
	ThoughtSourceReasoningSummary = "reasoning_summary"
	ThoughtSourceCommentary       = "commentary"
)

Model thought source constants.

View Source
const DefaultAsyncTimeout = time.Second * 5

DefaultAsyncTimeout is the default timeout for asynchronous recordings.

View Source
const MetadataKeyServiceTier = "service_tier"

Variables

View Source
var ErrInvalidRecord = xerrors.New("invalid record")

ErrInvalidRecord reports a record that cannot be recorded as given. Callers receive it in place of a delegated call's error.

Functions

This section is empty.

Types

type AsyncRecorder

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

AsyncRecorder calls Recorder methods asynchronously, discarding any errors which may occur; wrap it in a LogRecorder to have those logged.

func NewAsyncRecorder

func NewAsyncRecorder(wrapped Recorder, timeout time.Duration) *AsyncRecorder

func (*AsyncRecorder) RecordInterception

func (*AsyncRecorder) RecordInterception(context.Context, *InterceptionRecord) error

RecordInterception must NOT be called asynchronously. If an interception cannot be recorded, the whole request should fail.

func (*AsyncRecorder) RecordInterceptionEnded

func (a *AsyncRecorder) RecordInterceptionEnded(ctx context.Context, req *InterceptionRecordEnded) error

func (*AsyncRecorder) RecordModelThought

func (a *AsyncRecorder) RecordModelThought(ctx context.Context, req *ModelThoughtRecord) error

func (*AsyncRecorder) RecordPromptUsage

func (a *AsyncRecorder) RecordPromptUsage(ctx context.Context, req *PromptUsageRecord) error

func (*AsyncRecorder) RecordTokenUsage

func (a *AsyncRecorder) RecordTokenUsage(ctx context.Context, req *TokenUsageRecord) error

func (*AsyncRecorder) RecordToolUsage

func (a *AsyncRecorder) RecordToolUsage(ctx context.Context, req *ToolUsageRecord) error

func (*AsyncRecorder) Wait

func (a *AsyncRecorder) Wait()

func (*AsyncRecorder) WithClient

func (a *AsyncRecorder) WithClient(client string)

func (*AsyncRecorder) WithInitiatorID

func (a *AsyncRecorder) WithInitiatorID(initiatorID string)

func (*AsyncRecorder) WithMetrics

func (a *AsyncRecorder) WithMetrics(m any)

func (*AsyncRecorder) WithModel

func (a *AsyncRecorder) WithModel(model string)

func (*AsyncRecorder) WithProvider

func (a *AsyncRecorder) WithProvider(provider string)

type DRPCRecorder

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

DRPCRecorder satisfies the Recorder interface and translates calls into dRPC calls to aibridgedserver.

func NewDRPCRecorder

func NewDRPCRecorder(clientFn func(context.Context) (proto.DRPCRecorderClient, error)) *DRPCRecorder

NewDRPCRecorder creates a DRPCRecorder. clientFn receives the context of the record call it serves. Each interception reads its authenticated API-key ID from that context rather than storing request identity on the recorder.

func (*DRPCRecorder) RecordInterception

func (t *DRPCRecorder) RecordInterception(ctx context.Context, req *InterceptionRecord) error

func (*DRPCRecorder) RecordInterceptionEnded

func (t *DRPCRecorder) RecordInterceptionEnded(ctx context.Context, req *InterceptionRecordEnded) error

func (*DRPCRecorder) RecordModelThought

func (t *DRPCRecorder) RecordModelThought(ctx context.Context, req *ModelThoughtRecord) error

func (*DRPCRecorder) RecordPromptUsage

func (t *DRPCRecorder) RecordPromptUsage(ctx context.Context, req *PromptUsageRecord) error

func (*DRPCRecorder) RecordTokenUsage

func (t *DRPCRecorder) RecordTokenUsage(ctx context.Context, req *TokenUsageRecord) error

func (*DRPCRecorder) RecordToolUsage

func (t *DRPCRecorder) RecordToolUsage(ctx context.Context, req *ToolUsageRecord) error

type DisabledRecords

type DisabledRecords struct {
	Interception      bool
	InterceptionEnded bool
	TokenUsage        bool
	PromptUsage       bool
	ToolUsage         bool
	ModelThought      bool
}

DisabledRecords selects the records a FilterRecorder drops.

type ErrorType added in v2.36.0

type ErrorType string

ErrorType categorizes the terminal upstream error observed when an interception fails. The empty value means the interception succeeded and no error should be recorded. Values must match the aibridge_interception_error_type Postgres enum.

const (
	// ErrorTypeBadRequest is a malformed or otherwise rejected request (HTTP 400).
	ErrorTypeBadRequest ErrorType = "bad_request"
	// ErrorTypeUnauthorized is an authentication or authorization failure (HTTP 401/403).
	ErrorTypeUnauthorized ErrorType = "unauthorized"
	// ErrorTypeRateLimited is an upstream rate-limit response (HTTP 429).
	ErrorTypeRateLimited ErrorType = "rate_limited"
	// ErrorTypeOverloaded is an upstream overloaded response (Anthropic's HTTP
	// 529 or OpenAI's HTTP 503).
	ErrorTypeOverloaded ErrorType = "overloaded"
	// ErrorTypeServerError is an upstream or gateway server error (HTTP 5xx).
	ErrorTypeServerError ErrorType = "server_error"
	// ErrorTypeTimeout is an upstream request timeout (HTTP 408).
	ErrorTypeTimeout ErrorType = "timeout"
	// ErrorTypeUnknown is any error that could not be categorized.
	ErrorTypeUnknown ErrorType = "unknown"
)

func ErrorTypeFromStatus added in v2.36.0

func ErrorTypeFromStatus(status int) ErrorType

ErrorTypeFromStatus maps a standard upstream HTTP status code to an ErrorType. Provider-specific statuses (e.g. Anthropic's 529) are handled by the provider before calling this. Unrecognized codes yield ErrorTypeUnknown.

type FilterRecorder

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

FilterRecorder wraps another Recorder and drops the records selected by a DisabledRecords, so that a deployment can keep some record types out of its database while the rest of the chain keeps working.

A dropped record is reported to the caller as recorded successfully. The caller produced the record before the deployment's choice not to keep it was known, and cannot act on that choice, so failing the call would fail the intercepted request for a record the deployment did not want.

It belongs below the LogRecorder, so that a dropped record is still logged. Note that this means a record can reach the logs without reaching the database; see LogRecorder, which logs each record's payload. Anything below FilterRecorder, including the spans of an enclosing TraceRecorder, never observes a dropped record.

func NewFilterRecorder

func NewFilterRecorder(disabled DisabledRecords, wrapped Recorder) *FilterRecorder

NewFilterRecorder creates a FilterRecorder. wrapped may be nil, in which case every record is dropped.

func (*FilterRecorder) RecordInterception

func (r *FilterRecorder) RecordInterception(ctx context.Context, req *InterceptionRecord) error

func (*FilterRecorder) RecordInterceptionEnded

func (r *FilterRecorder) RecordInterceptionEnded(ctx context.Context, req *InterceptionRecordEnded) error

func (*FilterRecorder) RecordModelThought

func (r *FilterRecorder) RecordModelThought(ctx context.Context, req *ModelThoughtRecord) error

func (*FilterRecorder) RecordPromptUsage

func (r *FilterRecorder) RecordPromptUsage(ctx context.Context, req *PromptUsageRecord) error

func (*FilterRecorder) RecordTokenUsage

func (r *FilterRecorder) RecordTokenUsage(ctx context.Context, req *TokenUsageRecord) error

func (*FilterRecorder) RecordToolUsage

func (r *FilterRecorder) RecordToolUsage(ctx context.Context, req *ToolUsageRecord) error

type InterceptionRecord

type InterceptionRecord struct {
	ID                    string
	InitiatorID           string
	Metadata              Metadata
	Model                 string
	Provider              string
	ProviderName          string
	StartedAt             time.Time
	ClientSessionID       *string
	Client                string
	UserAgent             string
	CorrelatingToolCallID *string
	// AgentFirewallSessionID is the UUID of the Agent Firewall session
	// that produced this request. Nil when the request did not pass
	// through Agent Firewall.
	AgentFirewallSessionID *string
	// AgentFirewallSequenceNumber is the monotonically increasing
	// sequence number assigned by Agent Firewall. Nil when the request
	// did not pass through Agent Firewall.
	AgentFirewallSequenceNumber *int32
	// CredentialKind is always set: either BYOK or centralized.
	CredentialKind credential.Kind
	// CredentialHint is only set for BYOK, where the key is known
	// from the request. Centralized uses key failover, so the hint
	// can only be determined at end-of-interception.
	CredentialHint string
}

type InterceptionRecordEnded

type InterceptionRecordEnded struct {
	ID      string
	EndedAt time.Time
	// CredentialHint is the hint observed at end-of-interception.
	// Only applied to the DB row for centralized; ignored for BYOK.
	CredentialHint string
	// ErrorType is the categorized terminal upstream error. Empty when the
	// interception succeeded.
	ErrorType ErrorType
	// ErrorMessage is the raw terminal upstream error message. Empty when the
	// interception succeeded.
	ErrorMessage string
}

type LogRecorder

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

LogRecorder optionally wraps another Recorder and logs every call. If the wrapped recorder is nil, calls are logged but not delegated on.

LogRecorder is the single place where calls to a Recorder are logged. Logs were taken from the recorders which logged them before, for backwards compatibility. A single failure therefore still produces two lines for most records. This is suboptimal, but a requirement for backwards compatibility.

func NewLogRecorder

func NewLogRecorder(logger slog.Logger, structured bool, wrapped Recorder) *LogRecorder

NewLogRecorder creates a LogRecorder which logs each record and then delegates it to wrapped. wrapped may be nil, in which case records are only logged. Interception identity is read from each call's actor context.

func (*LogRecorder) RecordInterception

func (r *LogRecorder) RecordInterception(ctx context.Context, req *InterceptionRecord) error

func (*LogRecorder) RecordInterceptionEnded

func (r *LogRecorder) RecordInterceptionEnded(ctx context.Context, req *InterceptionRecordEnded) error

func (*LogRecorder) RecordModelThought

func (r *LogRecorder) RecordModelThought(ctx context.Context, req *ModelThoughtRecord) error

func (*LogRecorder) RecordPromptUsage

func (r *LogRecorder) RecordPromptUsage(ctx context.Context, req *PromptUsageRecord) error

func (*LogRecorder) RecordTokenUsage

func (r *LogRecorder) RecordTokenUsage(ctx context.Context, req *TokenUsageRecord) error

func (*LogRecorder) RecordToolUsage

func (r *LogRecorder) RecordToolUsage(ctx context.Context, req *ToolUsageRecord) error

type Metadata

type Metadata map[string]any

type Middleware

type Middleware func(next Recorder) Recorder

Middleware wraps a Recorder in additional behavior, returning the wrapping Recorder. Each decorating recorder in this package has a corresponding Middleware constructor, such as WithLogging, which closes over that recorder's own dependencies so that decorators can be composed by ChainMiddleware.

func ChainMiddleware

func ChainMiddleware(middleware ...Middleware) Middleware

ChainMiddleware composes a slice of middleware into a single Middleware.

The example below wraps a recorder, which does no logging or tracing of its own in middleware that adds logging and tracing for every call. In the order provided, logging will happen first, then tracing, and then the call to the recorder.

middleware := ChainMiddleware(
	WithLogging(logger, true),
	WithTracing(tracer),
)

recorder := NewDRPCRecorder(clientFn)

wrappedRecorder := middleware(recorder)

Middleware are listed outermost first, so the last middleware wraps the recorder.

ChainMiddleware does not enforce ordering constraints between decorators; see the individual Decorator constructors for any position a decorator requires.

func WithLogging

func WithLogging(logger slog.Logger, structured bool) Middleware

WithLogging returns a Middleware which wraps a Recorder in a LogRecorder, for composition by ChainMiddleware.

func WithTracing

func WithTracing(tracer trace.Tracer) Middleware

WithTracing returns a [Decorator] which wraps a Recorder in a TraceRecorder, for composition by ChainMiddleware. As TraceRecorder documents, it belongs last in a chain, immediately above the recorder whose work its spans measure.

func WithValidation

func WithValidation(logger slog.Logger) Middleware

WithValidation returns a Middleware which wraps a Recorder in a ValidatingRecorder, for composition by ChainMiddleware.

func WithoutRecords

func WithoutRecords(disabled DisabledRecords) Middleware

WithoutRecords returns a Middleware which wraps a Recorder in a FilterRecorder, for composition by ChainMiddleware.

type ModelThoughtRecord

type ModelThoughtRecord struct {
	InterceptionID string
	Content        string
	Metadata       Metadata
	CreatedAt      time.Time
}

type PromptUsageRecord

type PromptUsageRecord struct {
	InterceptionID string
	MsgID          string
	Prompt         string
	Metadata       Metadata
	CreatedAt      time.Time
}

type Recorder

type Recorder interface {
	// RecordInterception records metadata about an interception with an upstream AI provider.
	RecordInterception(ctx context.Context, req *InterceptionRecord) error
	// RecordInterceptionEnded records that given interception has completed.
	RecordInterceptionEnded(ctx context.Context, req *InterceptionRecordEnded) error
	// RecordTokenUsage records the tokens used in an interception with an upstream AI provider.
	RecordTokenUsage(ctx context.Context, req *TokenUsageRecord) error
	// RecordPromptUsage records the prompts used in an interception with an upstream AI provider.
	RecordPromptUsage(ctx context.Context, req *PromptUsageRecord) error
	// RecordToolUsage records the tools used in an interception with an upstream AI provider.
	RecordToolUsage(ctx context.Context, req *ToolUsageRecord) error
	// RecordModelThought records model thoughts produced in an interception with an upstream AI provider.
	RecordModelThought(ctx context.Context, req *ModelThoughtRecord) error
}

Recorder describes all the possible usage information we need to capture during interactions with AI providers. Additionally, it introduces the concept of an "Interception", which includes information about which provider/model was used and by whom. All usage records should reference this Interception by ID.

type TokenUsageRecord

type TokenUsageRecord struct {
	InterceptionID string
	MsgID          string
	// ProviderModel is the model reported by the upstream response, which
	// may differ from the requested model when the provider resolves an
	// alias. Empty when the response does not report one.
	ProviderModel         string
	Input                 int64
	Output                int64
	CacheReadInputTokens  int64
	CacheWriteInputTokens int64
	// ExtraTokenTypes holds token types which *may* exist over and above input/output.
	// These should ultimately get merged into [Metadata], but it's useful to keep these
	// with their actual type (int64) since [Metadata] is a map[string]any.
	ExtraTokenTypes map[string]int64
	Metadata        Metadata
	CreatedAt       time.Time
}

type ToolArgs

type ToolArgs any

type ToolUsageRecord

type ToolUsageRecord struct {
	InterceptionID string
	MsgID          string
	Tool           string
	// ToolCallID is the correlation ID used to match a tool call to its
	// result (call_id in the Responses API, id in chat completions and
	// Anthropic messages). It is empty for hosted Responses tools (e.g.
	// web_search_call) which the provider executes internally.
	ToolCallID string
	// ItemID is the provider's unique ID for the output item that carried
	// the tool call. It is specific to the OpenAI Responses API, where an
	// output item has both an id and a call_id. It is empty for the chat
	// completions and Anthropic messages APIs, which have no separate item
	// ID concept.
	ItemID          string
	ServerURL       *string
	Args            ToolArgs
	Injected        bool
	InvocationError error
	Metadata        Metadata
	CreatedAt       time.Time
}

type TraceRecorder

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

TraceRecorder starts a span around each record before delegating it to a wrapped Recorder. If the wrapped recorder is nil, only the span is recorded.

It is the single place where records are traced. It belongs immediately above the recorder whose work the spans measure, so that they do not also cover the logging done by an enclosing LogRecorder.

func NewTraceRecorder

func NewTraceRecorder(tracer trace.Tracer, wrapped Recorder) *TraceRecorder

NewTraceRecorder creates a TraceRecorder which traces each record and then delegates it to wrapped. wrapped may be nil, in which case records are only traced.

func (*TraceRecorder) RecordInterception

func (r *TraceRecorder) RecordInterception(ctx context.Context, req *InterceptionRecord) (outErr error)

func (*TraceRecorder) RecordInterceptionEnded

func (r *TraceRecorder) RecordInterceptionEnded(ctx context.Context, req *InterceptionRecordEnded) (outErr error)

func (*TraceRecorder) RecordModelThought

func (r *TraceRecorder) RecordModelThought(ctx context.Context, req *ModelThoughtRecord) (outErr error)

func (*TraceRecorder) RecordPromptUsage

func (r *TraceRecorder) RecordPromptUsage(ctx context.Context, req *PromptUsageRecord) (outErr error)

func (*TraceRecorder) RecordTokenUsage

func (r *TraceRecorder) RecordTokenUsage(ctx context.Context, req *TokenUsageRecord) (outErr error)

func (*TraceRecorder) RecordToolUsage

func (r *TraceRecorder) RecordToolUsage(ctx context.Context, req *ToolUsageRecord) (outErr error)

type ValidatingRecorder

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

ValidatingRecorder refuses records whose timestamp is unset, so a record that would be persisted in year one, skewing budget periods, retention and the sessions timeline, fails where it was produced rather than after a round trip to coderd.

Only timestamps are checked. Every other property of a record is the database's to enforce, so that this recorder cannot diverge from it.

It belongs below the logging middleware, so that a refused record is logged with its payload, and above any middleware that drops records, so that a record's validity does not depend on the deployment's record policy.

Refusal is not equally visible per record type: an interception is recorded synchronously and its error fails the intercepted request, while every other record is dispatched through AsyncRecorder, which discards errors. This recorder therefore logs each refusal itself.

func NewValidatingRecorder

func NewValidatingRecorder(logger slog.Logger, wrapped Recorder) *ValidatingRecorder

NewValidatingRecorder creates a ValidatingRecorder which delegates valid records to wrapped. wrapped may be nil, in which case valid records are discarded.

func (*ValidatingRecorder) RecordInterception

func (r *ValidatingRecorder) RecordInterception(ctx context.Context, req *InterceptionRecord) error

func (*ValidatingRecorder) RecordInterceptionEnded

func (r *ValidatingRecorder) RecordInterceptionEnded(ctx context.Context, req *InterceptionRecordEnded) error

func (*ValidatingRecorder) RecordModelThought

func (r *ValidatingRecorder) RecordModelThought(ctx context.Context, req *ModelThoughtRecord) error

func (*ValidatingRecorder) RecordPromptUsage

func (r *ValidatingRecorder) RecordPromptUsage(ctx context.Context, req *PromptUsageRecord) error

func (*ValidatingRecorder) RecordTokenUsage

func (r *ValidatingRecorder) RecordTokenUsage(ctx context.Context, req *TokenUsageRecord) error

func (*ValidatingRecorder) RecordToolUsage

func (r *ValidatingRecorder) RecordToolUsage(ctx context.Context, req *ToolUsageRecord) error

Jump to

Keyboard shortcuts

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