obs

package
v1.261203.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: MPL-2.0 Imports: 22 Imported by: 0 modules, 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.

Documentation

Overview

Package obs provides a unified observability layer for Go applications, integrating structured logging, metrics, and distributed tracing via OpenTelemetry.

It offers simple, high-level APIs to initialize and use telemetry components without exposing underlying complexity. Ideal for microservices and cloud-native apps.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContextWithRequestID added in v0.260827.1

func ContextWithRequestID(ctx context.Context, id string) context.Context

ContextWithRequestID returns a child context carrying the correlation id. Request-scoped code logs via logrus.WithContext(ctx); the MultiLogger hook reads the id back with RequestIDFromContext to route the entry to the model_request source and stamp it with the id.

func LevelForStatus added in v0.260924.1

func LevelForStatus(statusCode int) logrus.Level

LevelForStatus maps an HTTP status code to the log severity it deserves: a 5xx is a server-side failure (Error), a 4xx is a client/provider-side rejection worth noticing but not alarming on (Warn), and everything else is routine (Info). Shared by anything that logs one line per HTTP response — the access log and the upstream-call log — so status-to-level thresholds live in one place instead of being redefined per call site.

func RequestIDFromContext added in v0.260827.1

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext returns the correlation id stored in ctx, or "".

func SessionShort added in v0.260514.1

func SessionShort(sid typ.SessionID) (short, source string)

SessionShort returns a privacy-safe 16-hex-char identifier and source label for a session. Returns ("", "") when the session is empty.

Types

type ActionType

type ActionType = string

ActionType represents the type of action performed

const (
	ActionAddProvider    ActionType = "add_provider"
	ActionDeleteProvider ActionType = "delete_provider"
	ActionUpdateProvider ActionType = "update_provider"
	ActionStartServer    ActionType = "start_server"
	ActionStopServer     ActionType = "stop_server"
	ActionRestartServer  ActionType = "restart_server"
	ActionGenerateToken  ActionType = "generate_token"
	ActionUpdateDefaults ActionType = "update_defaults"
	ActionFetchModels    ActionType = "fetch_models"
)

type BatchProcessor added in v0.260514.1

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

BatchProcessor batches Records and forwards them to a RecordExporter on a periodic ticker or when the batch reaches maxBatch size.

Emit is non-blocking: if the internal queue is full the record is dropped and a counter is incremented.

func NewBatchProcessor added in v0.260514.1

func NewBatchProcessor(exporter RecordExporter, opts BatchProcessorOptions) *BatchProcessor

NewBatchProcessor creates a BatchProcessor and starts its background worker.

func (*BatchProcessor) Emit added in v0.260514.1

func (bp *BatchProcessor) Emit(r *Record)

Emit enqueues r for export. Drops the record (incrementing the dropped counter) if the internal queue is full.

func (*BatchProcessor) ForceFlush added in v0.260514.1

func (bp *BatchProcessor) ForceFlush(ctx context.Context) error

ForceFlush triggers an immediate export of any pending records and waits for it.

func (*BatchProcessor) Shutdown added in v0.260514.1

func (bp *BatchProcessor) Shutdown(ctx context.Context) error

Shutdown stops the ticker, drains the queue, exports remaining records, then shuts down the exporter.

type BatchProcessorOptions added in v0.260514.1

type BatchProcessorOptions struct {
	// QueueSize is the capacity of the internal channel (default 1024).
	QueueSize int
	// MaxBatch is the maximum number of records per Export call (default 256).
	MaxBatch int
	// FlushInterval is how often the worker drains the queue (default 5s).
	FlushInterval time.Duration
}

BatchProcessorOptions configures a BatchProcessor.

type CASFileExporter added in v0.260514.1

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

CASFileExporter implements RecordExporter with content-addressed storage:

  1. Slim-ifies every Record (large sub-values replaced by $ref pointers).
  2. Writes new blobs atomically (tmp+rename) under {baseDir}/blobs/.
  3. Appends SlimRecords to per-session JSONL files.

CASFileExporter is NOT goroutine-safe; it must be driven by a single goroutine (the BatchProcessor worker).

func NewCASFileExporter added in v0.260514.1

func NewCASFileExporter(baseDir string) (*CASFileExporter, error)

NewCASFileExporter creates a CASFileExporter rooted at baseDir and populates the in-memory blob set by scanning existing blobs.

func (*CASFileExporter) Export added in v0.260514.1

func (e *CASFileExporter) Export(_ context.Context, records []*Record) error

Export processes a batch of Records.

func (*CASFileExporter) Shutdown added in v0.260514.1

func (e *CASFileExporter) Shutdown(_ context.Context) error

Shutdown flushes and closes all open session files.

type GzipFileExporter added in v0.260514.1

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

GzipFileExporter implements RecordExporter by appending one gzip member per batch to a per-session .jsonl.gz file. Records are emitted with all bodies inlined (no $ref / blob extraction).

On-disk layout:

{baseDir}/{scenario}/sessions/{YYYY-MM-DD}/{session}.jsonl.gz

Multiple gzip members concatenated in the same file remain a valid gzip stream; standard tools (zcat, gzip -d, gzip.Reader with Multistream(true)) decompress them transparently.

func NewGzipFileExporter added in v0.260514.1

func NewGzipFileExporter(baseDir string) *GzipFileExporter

NewGzipFileExporter creates an exporter rooted at baseDir.

func (*GzipFileExporter) Export added in v0.260514.1

func (e *GzipFileExporter) Export(_ context.Context, records []*Record) error

Export groups records by session path and appends one gzip member per session.

func (*GzipFileExporter) Shutdown added in v0.260514.1

func (e *GzipFileExporter) Shutdown(_ context.Context) error

Shutdown is a no-op; GzipFileExporter holds no persistent state.

type LogEntry added in v0.260827.1

type LogEntry struct {
	Time    time.Time              `json:"time"`
	Level   string                 `json:"level"`
	Message string                 `json:"message"`
	Source  string                 `json:"source,omitempty"` // Log source identification
	Fields  map[string]interface{} `json:"fields,omitempty"`
}

LogEntry represents a structured log entry for JSON output

type LogSource added in v0.260827.1

type LogSource string

LogSource identifies the source of a log entry for routing decisions

const (
	// LogSourceHTTP indicates logs from HTTP requests
	LogSourceHTTP LogSource = "http"
	// LogSourceSystem indicates logs from the application/system
	LogSourceSystem LogSource = "system"
	// LogSourceAction indicates logs from user actions/operations
	LogSourceAction LogSource = "action"
	// LogSourceSmartRouting indicates logs from smart routing rule evaluation
	LogSourceSmartRouting LogSource = "smart_routing"
	// LogSourceModelRequest indicates request-scoped logs from the model
	// request pipeline (protocol conversion, upstream client calls). These
	// are correlated by a request_id field rather than by transport path.
	LogSourceModelRequest LogSource = "model_request"
	// LogSourceUnknown indicates unknown log source
	LogSourceUnknown LogSource = "unknown"
)

type MemoryLogHook added in v0.260827.1

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

MemoryLogHook is a logrus hook that stores log entries in an in-memory circular buffer.

func NewMemoryLogHook added in v0.260827.1

func NewMemoryLogHook(maxEntries int) *MemoryLogHook

NewMemoryLogHook creates a new memory log hook with the specified maximum capacity.

func (*MemoryLogHook) AddWriter added in v0.260827.1

func (h *MemoryLogHook) AddWriter(w io.Writer)

AddWriter adds a writer for tee output functionality.

func (*MemoryLogHook) Capacity added in v1.261022.2

func (h *MemoryLogHook) Capacity() int

Capacity is the configured number of entries the ring can retain.

func (*MemoryLogHook) Clear added in v0.260827.1

func (h *MemoryLogHook) Clear()

Clear removes all log entries.

func (*MemoryLogHook) Fire added in v0.260827.1

func (h *MemoryLogHook) Fire(entry *logrus.Entry) error

Fire processes each log entry.

func (*MemoryLogHook) GetEntries added in v0.260827.1

func (h *MemoryLogHook) GetEntries() []*logrus.Entry

GetEntries returns all log entries in chronological order.

func (*MemoryLogHook) GetEntriesByLevel added in v0.260827.1

func (h *MemoryLogHook) GetEntriesByLevel(level logrus.Level) []*logrus.Entry

GetEntriesByLevel returns log entries matching the specified level.

func (*MemoryLogHook) GetEntriesByLevelRange added in v0.260827.1

func (h *MemoryLogHook) GetEntriesByLevelRange(minLevel, maxLevel logrus.Level) []*logrus.Entry

GetEntriesByLevelRange returns log entries within the specified level range.

func (*MemoryLogHook) GetEntriesSince added in v0.260827.1

func (h *MemoryLogHook) GetEntriesSince(since time.Time) []*logrus.Entry

GetEntriesSince returns log entries after the specified time.

func (*MemoryLogHook) GetLatest added in v0.260827.1

func (h *MemoryLogHook) GetLatest(n int) []*logrus.Entry

GetLatest returns the newest N log entries.

func (*MemoryLogHook) Levels added in v0.260827.1

func (h *MemoryLogHook) Levels() []logrus.Level

Levels returns the log levels this hook processes.

func (*MemoryLogHook) Size added in v0.260827.1

func (h *MemoryLogHook) Size() int

Size returns the current number of stored log entries.

type MemorySinkConfig added in v0.260827.1

type MemorySinkConfig struct {
	MaxEntries int // Maximum entries to keep in memory (default varies by source)
}

MemorySinkConfig holds configuration for a memory sink

type MultiExporter added in v0.260514.1

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

MultiExporter fans Export and Shutdown calls out to multiple RecordExporters. One exporter failing does not prevent the others from running; the first non-nil error is returned.

func NewMultiExporter added in v0.260514.1

func NewMultiExporter(exporters ...RecordExporter) *MultiExporter

NewMultiExporter aggregates the given exporters behind a single RecordExporter interface. Nil exporters are skipped.

func (*MultiExporter) Export added in v0.260514.1

func (m *MultiExporter) Export(ctx context.Context, records []*Record) error

Export forwards records to every registered exporter.

func (*MultiExporter) Shutdown added in v0.260514.1

func (m *MultiExporter) Shutdown(ctx context.Context) error

Shutdown closes every registered exporter.

type MultiLogger added in v0.260827.1

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

MultiLogger writes logs to multiple outputs: text, JSON, and memory. Text logs are for human readability, JSON logs for persistence, and memory for quick API access.

Architecture:

┌─────────────────────────────────────────────────────────┐
│                     MultiLogger                         │
│  ┌────────────┐  ┌────────────┐  ┌──────────────────┐  │
│  │    Text    │  │    JSON    │  │  Memory Sinks    │  │
│  │   Output   │  │   Output   │  │  (by source)     │  │
│  └────────────┘  └────────────┘  ├──────────────────┤  │
│                                   │ HTTP (1000)      │  │
│                                   │ System (500)     │  │
│                                   │ Action (100)     │  │
│                                   └──────────────────┘  │
└─────────────────────────────────────────────────────────┘

Usage:

// Get the main multi logger
logger := obs.NewMultiLogger(config)

// Get a scoped logger for specific use case
actionLogger := logger.WithSource(obs.LogSourceAction)
actionLogger.LogAction("add_provider", details, true, "success")

// Or get the underlying logrus logger for custom use
httpLogger := logger.GetLogrusLogger(obs.LogSourceHTTP)
httpLogger.WithField("path", "/api/test").Info("request processed")

func NewMultiLogger added in v0.260827.1

func NewMultiLogger(cfg *MultiLoggerConfig) (*MultiLogger, error)

NewMultiLogger creates a new multi-mode logger

func (*MultiLogger) Close added in v0.260827.1

func (m *MultiLogger) Close() error

Close closes the logger

func (*MultiLogger) GetJSONLogPath added in v0.260827.1

func (m *MultiLogger) GetJSONLogPath() string

GetJSONLogPath returns the path to the JSON log file

func (*MultiLogger) GetLevel added in v0.260827.1

func (m *MultiLogger) GetLevel() logrus.Level

GetLevel returns the current minimum log level

func (*MultiLogger) GetLogrusLogger added in v0.260827.1

func (m *MultiLogger) GetLogrusLogger(source LogSource) *logrus.Logger

GetLogrusLogger returns a logrus.Logger instance that writes to this MultiLogger with the specified source. The logger is cached for performance.

Example:

logger := multiLogger.GetLogrusLogger(LogSourceHTTP)
logger.WithField("path", "/api/test").Info("request processed")

func (*MultiLogger) GetMemorySink added in v0.260827.1

func (m *MultiLogger) GetMemorySink(source LogSource) *MemoryLogHook

GetMemorySink returns the memory sink for the specified source, creating it if necessary. Returns nil if the source has no memory sink configured.

func (*MultiLogger) ReadJSONLogs added in v0.260827.1

func (m *MultiLogger) ReadJSONLogs(limit int) ([]LogEntry, error)

ReadJSONLogs reads log entries from the JSON log file with optional filtering

func (*MultiLogger) ReadJSONLogsBySource added in v0.260827.1

func (m *MultiLogger) ReadJSONLogsBySource(limit int, allowed ...LogSource) ([]LogEntry, error)

ReadJSONLogsBySource reads recent log entries from the JSON log file keeping only entries whose source is in the allowed set. An empty/absent source on a legacy entry is treated as LogSourceSystem. Reading stops once limit matching entries are collected.

func (*MultiLogger) ReadJSONLogsFiltered added in v1.261022.2

func (m *MultiLogger) ReadJSONLogsFiltered(limit int, keep func(LogEntry) bool) ([]LogEntry, error)

ReadJSONLogsFiltered applies keep before the limit across the active file and rotated history, so unrelated logs do not consume a view's window.

func (*MultiLogger) SetLevel added in v0.260827.1

func (m *MultiLogger) SetLevel(level logrus.Level)

SetLevel sets the minimum log level for all loggers

func (*MultiLogger) WithSource added in v0.260827.1

func (m *MultiLogger) WithSource(source LogSource) *ScopedLogger

WithSource returns a scoped logger for the specified source. This provides a convenient API for logging with a specific source.

Example:

actionLogger := logger.WithSource(LogSourceAction)
actionLogger.LogAction("add_provider", details, true, "success")

func (*MultiLogger) Write added in v0.260827.1

func (m *MultiLogger) Write(p []byte) (n int, err error)

Write implements io.Writer for text output

func (*MultiLogger) WriteEntry added in v0.260827.1

func (m *MultiLogger) WriteEntry(entry *logrus.Entry) error

WriteEntry writes a structured log entry to the JSON log and memory sink

type MultiLoggerConfig added in v0.260827.1

type MultiLoggerConfig struct {
	// Text log config (for humans)
	TextLogPath    string
	TextMaxSize    int // MB
	TextMaxBackups int
	TextMaxAge     int // days
	TextCompress   bool

	// JSON log config (for frontend/API)
	JSONLogPath    string
	JSONMaxSize    int // MB (small, for recent logs only)
	JSONMaxBackups int // small number, we only keep recent
	JSONMaxAge     int // days

	// Memory sink config (optional, uses defaults if not specified)
	MemorySinkConfig map[LogSource]MemorySinkConfig
}

MultiLoggerConfig holds configuration for multi-mode logging

func DefaultMultiLoggerConfig added in v0.260827.1

func DefaultMultiLoggerConfig(configDir string) *MultiLoggerConfig

DefaultMultiLoggerConfig returns default configuration

type MultiLoggerHook added in v0.260827.1

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

MultiLoggerHook is a logrus hook that writes to the multi-mode logger This is used for global logrus integration (e.g., main application logs)

func NewMultiLoggerHook added in v0.260827.1

func NewMultiLoggerHook(logger *MultiLogger, levels []logrus.Level) *MultiLoggerHook

NewMultiLoggerHook creates a new multi logger hook for global use Use this for adding the MultiLogger to the global logrus instance

func (*MultiLoggerHook) Fire added in v0.260827.1

func (h *MultiLoggerHook) Fire(entry *logrus.Entry) error

Fire processes each log entry, writing it to the JSON log

func (*MultiLoggerHook) Levels added in v0.260827.1

func (h *MultiLoggerHook) Levels() []logrus.Level

Levels returns the log levels this hook processes

type Record added in v0.260514.1

type Record struct {
	Timestamp  time.Time
	RequestID  string
	SessionID  string // sha256(raw session value)[:16], empty when unknown
	SessionSrc string // "user" | "hdr" | "ip" | ""
	Provider   string
	Scenario   string
	Model      string

	// Provider connection details for debugging
	APIStyle string `json:"api_style,omitempty"` // Provider API style (e.g., "openai", "anthropic")
	BaseURL  string `json:"base_url,omitempty"`  // Provider base URL

	OriginalRequest    *RecordRequest
	TransformedRequest *RecordRequest
	ProviderResponse   *RecordResponse
	FinalResponse      *RecordResponse

	Duration time.Duration
	Err      string
	Steps    []string
}

Record is the canonical data model for one LLM request/response cycle. Construct it on the hot path and pass to Sink.Emit; the only cost is a non-blocking channel send.

type RecordExporter added in v0.260514.1

type RecordExporter interface {
	Export(ctx context.Context, records []*Record) error
	Shutdown(ctx context.Context) error
}

RecordExporter is called by BatchProcessor with a slice of Records to persist.

type RecordMode

type RecordMode string

RecordMode carries the recording selection: a comma-separated set of capture points (typ.RecordingPoint), or a legacy enum value. "" means disabled. The obs layer treats it as opaque enabled/disabled — capture-point filtering happens in the recorder (see typ.ParseRecordingMode).

const (
	// Legacy enum values from the pre point-set model. Kept because stored
	// configs and tests still pass them; they normalize to point sets at the
	// recorder boundary (typ.ParseRecordingMode).
	RecordModeRequestOnly           RecordMode = "request"                 // → upstream_request
	RecordModeRequestResponse       RecordMode = "request_response"        // → upstream_request,final_response
	RecordModeStagedRequestResponse RecordMode = "staged_request_response" // → client_request,upstream_request,final_response
)

type RecordProcessor added in v0.260514.1

type RecordProcessor interface {
	Emit(r *Record)
	ForceFlush(ctx context.Context) error
	Shutdown(ctx context.Context) error
}

RecordProcessor is the OTel-shaped hot-path interface. Emit must be non-blocking; callers on the request goroutine must not be delayed.

type RecordRequest

type RecordRequest struct {
	Method  string                 `json:"method"`
	URL     string                 `json:"url"`
	Headers map[string]string      `json:"headers"`
	Body    map[string]interface{} `json:"body,omitempty"`
}

RecordRequest represents the HTTP request details. Kept for callers that build RecordRequest directly (e.g. client/record_roundtripper.go).

type RecordResponse

type RecordResponse struct {
	StatusCode   int                    `json:"status_code"`
	Headers      map[string]string      `json:"headers"`
	Body         map[string]interface{} `json:"body,omitempty"`
	IsStreaming  bool                   `json:"is_streaming,omitempty"`
	StreamChunks []string               `json:"-"`
}

RecordResponse represents the HTTP response details.

type ResolveOpts added in v0.260514.1

type ResolveOpts struct {
	// AllowMissingBlobs replaces missing blob refs with {"_missing_blob":"sha256:..."}
	// instead of returning an error.
	AllowMissingBlobs bool
}

ResolveOpts controls how missing blobs are handled during resolution.

type ScopedLogger added in v0.260827.1

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

ScopedLogger provides a convenient API for logging with a specific source

func (*ScopedLogger) ClearMemory added in v0.260827.1

func (s *ScopedLogger) ClearMemory()

ClearMemory clears all log entries from memory for this scope

func (*ScopedLogger) GetLogrusLogger added in v0.260827.1

func (s *ScopedLogger) GetLogrusLogger() *logrus.Logger

GetLogrusLogger returns the logrus logger for this scope

func (*ScopedLogger) GetMemoryEntries added in v0.260827.1

func (s *ScopedLogger) GetMemoryEntries() []*logrus.Entry

GetMemoryEntries returns all log entries from memory for this scope

func (*ScopedLogger) GetMemoryLatest added in v0.260827.1

func (s *ScopedLogger) GetMemoryLatest(n int) []*logrus.Entry

GetMemoryLatest returns the newest N log entries from memory for this scope

func (*ScopedLogger) GetMemorySink added in v0.260827.1

func (s *ScopedLogger) GetMemorySink() *MemoryLogHook

GetMemorySink returns the memory sink for this scope

func (*ScopedLogger) LogAction added in v0.260827.1

func (s *ScopedLogger) LogAction(action string, details map[string]interface{}, success bool, message string)

LogAction logs a user action with structured data This is a convenience method for logging user actions to the action source

Parameters:

  • action: The action type (e.g., "add_provider", "delete_provider")
  • details: Additional details about the action (can be nil)
  • success: Whether the action was successful
  • message: A human-readable message about the action

type SessionIterator added in v0.260514.1

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

SessionIterator iterates over SlimRecords in a session JSONL file.

func WalkSession added in v0.260514.1

func WalkSession(baseDir, scenario, sessionShort string) (*SessionIterator, error)

WalkSession opens the JSONL file for the given scenario and session short ID under baseDir and returns an iterator.

func (*SessionIterator) Next added in v0.260514.1

func (it *SessionIterator) Next() (*SlimRecord, error)

Next advances the iterator and returns the next SlimRecord. Returns (nil, nil) at EOF.

type Sink

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

Sink manages recording of LLM request/response cycles. All writes are batched asynchronously; Emit is non-blocking.

func NewSink

func NewSink(baseDir string, mode RecordMode, opts ...SinkOption) *Sink

NewSink creates a new Sink backed by the OTel-shaped batch pipeline. Returns nil when recording is disabled (empty mode or baseDir).

Default exporter: GzipFileExporter (one gzip member per batch, per-session .jsonl.gz files). Pass WithCASExporter() to additionally write content-addressed slim JSONL + blobs.

func (*Sink) Close

func (s *Sink) Close()

Close drains pending records and shuts down the pipeline.

func (*Sink) Emit added in v0.260514.1

func (s *Sink) Emit(r *Record)

Emit enqueues r for asynchronous export. The call is non-blocking.

func (*Sink) ForceFlush added in v0.260531.1

func (s *Sink) ForceFlush(ctx context.Context) error

ForceFlush drains any pending records by delegating to the underlying processor. Used by tests that need a synchronisation point before inspecting exported records.

func (*Sink) GetBaseDir

func (s *Sink) GetBaseDir() string

GetBaseDir returns the recording root directory.

func (*Sink) GetMode added in v0.260514.1

func (s *Sink) GetMode() RecordMode

GetMode returns the configured RecordMode, or "" when the sink is nil.

func (*Sink) IsEnabled

func (s *Sink) IsEnabled() bool

IsEnabled returns whether recording is active.

func (*Sink) RecordWithScenario

func (s *Sink) RecordWithScenario(provider, model, scenario string, req *RecordRequest, resp *RecordResponse, duration time.Duration, err error)

RecordWithScenario builds a single-stage Record (original request + final response) and emits it. Used by client-side roundtrippers that don't go through the transform pipeline. Server-side code should construct a *Record directly and call Emit.

type SinkOption added in v0.260514.1

type SinkOption func(*sinkConfig)

SinkOption customises Sink construction. Apply via NewSink(baseDir, mode, opts...).

func WithCASExporter added in v0.260514.1

func WithCASExporter() SinkOption

WithCASExporter appends a CASFileExporter to the default gzip exporter. Records are written twice (once gzipped, once as content-addressed slim JSONL + blobs) — useful for cross-session analysis or replay tooling.

func WithExporters added in v0.260514.1

func WithExporters(exporters ...RecordExporter) SinkOption

WithExporters replaces the Sink's default exporter list entirely. Useful for tests and for plugging in future exporters (SQLite, OTLP, remote collectors).

type SlimHTTPData added in v0.260514.1

type SlimHTTPData struct {
	Method      string            `json:"method,omitempty"`
	URL         string            `json:"url,omitempty"`
	Headers     map[string]string `json:"headers,omitempty"`
	StatusCode  int               `json:"status_code,omitempty"`
	Body        interface{}       `json:"body,omitempty"`
	IsStreaming bool              `json:"is_streaming,omitempty"`
}

SlimHTTPData mirrors RecordRequest / RecordResponse with a body that may contain {"$ref":"sha256:<hex>"} markers instead of large inline values.

type SlimRecord added in v0.260514.1

type SlimRecord struct {
	V         int    `json:"v"` // schema version = 3
	Timestamp string `json:"ts"`
	RequestID string `json:"rid"`

	SessionID  string `json:"sid,omitempty"`
	SessionSrc string `json:"sid_src,omitempty"`

	Provider string `json:"provider,omitempty"`
	Scenario string `json:"scenario,omitempty"`
	Model    string `json:"model,omitempty"`

	OriginalRequest    *SlimHTTPData `json:"original_request,omitempty"`
	TransformedRequest *SlimHTTPData `json:"transformed_request,omitempty"`
	ProviderResponse   *SlimHTTPData `json:"provider_response,omitempty"`
	FinalResponse      *SlimHTTPData `json:"final_response,omitempty"`

	DurationMs int64  `json:"duration_ms"`
	Error      string `json:"error,omitempty"`

	Steps []string `json:"transform_steps,omitempty"`
}

SlimRecord is the JSON-serializable slim form stored in session JSONL files. Large values are replaced by {"$ref":"sha256:<hex>"} pointers into the blob store.

func FullRecord added in v0.260514.1

func FullRecord(r *Record) *SlimRecord

FullRecord returns a SlimRecord-shaped value with all fields inlined and no $ref extraction. Used by exporters that don't dedup (e.g. GzipFileExporter).

func ResolveRecord added in v0.260514.1

func ResolveRecord(baseDir string, slim *SlimRecord, opts ResolveOpts) (*SlimRecord, error)

ResolveRecord expands all {"$ref":"sha256:<hash>"} markers in a SlimRecord by loading the corresponding blobs from baseDir.

func SlimifyRecord added in v0.260514.1

func SlimifyRecord(r *Record, knownBlobs map[string]struct{}) (*SlimRecord, map[string][]byte)

SlimifyRecord converts a Record to a SlimRecord by replacing large JSON sub-values with content-addressed $ref pointers.

knownBlobs is the set of hashes already on disk; only new blobs are returned in the second return value (hash → serialised JSON bytes).

Jump to

Keyboard shortcuts

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