agentobs

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package agentobs provides generic agent observability interfaces for use with Opik.

This package defines generic event types and interfaces that allow agent frameworks to send observability data to Opik without depending on specific framework implementations. It is designed to be imported by agent framework integrations while keeping opik-go free of framework-specific dependencies.

Core Types

AgentEvent represents a generic agent lifecycle event with type, timestamp, session/trace/span identifiers, and arbitrary data. Framework integrations convert their native events into AgentEvent before sending to Opik.

TraceManager manages the lifecycle of Opik traces associated with agent sessions, including automatic cleanup of stale traces and correlation of spans within traces.

Utilities

The package includes utilities for common observability tasks:

  • ExtractMedia extracts media references from message content
  • Sanitize removes internal markers and sensitive content
  • SanitizeMap recursively sanitizes map data structures

Usage

Framework integrations should:

  1. Convert framework-specific events to AgentEvent
  2. Use TraceManager to manage trace lifecycle
  3. Use Sanitize to clean content before sending to Opik
  4. Use ExtractMedia to extract attachments from message content

Example:

manager, _ := agentobs.NewTraceManager(client, agentobs.TraceManagerConfig{
    StaleTimeout: 5 * time.Minute,
})
defer manager.Close()

// On session creation
trace, _ := manager.StartTrace(ctx, "session-123", "my-agent")

// On message
event := agentobs.AgentEvent{
    Type:      agentobs.EventMessageReceived,
    SessionID: "session-123",
    Data: map[string]any{
        "content": agentobs.Sanitize(content, agentobs.DefaultSanitizeConfig()),
    },
}

Index

Constants

This section is empty.

Variables

View Source
var SanitizeKeys = []string{
	"password",
	"passwd",
	"secret",
	"api_key",
	"apikey",
	"access_token",
	"auth_token",
	"bearer",
	"authorization",
	"credentials",
	"private_key",
}

SanitizeKeys is a list of keys that should have their values redacted.

Functions

func RemoveEmptyStrings

func RemoveEmptyStrings(data map[string]any) map[string]any

RemoveEmptyStrings removes empty string values from a map.

func Sanitize

func Sanitize(content string, cfg SanitizeConfig) string

Sanitize removes internal markers, metadata blocks, and sensitive content from the input string according to the provided configuration.

func SanitizeMap

func SanitizeMap(data map[string]any, cfg SanitizeConfig) map[string]any

SanitizeMap recursively sanitizes all string values in a map.

func SanitizeMapKeys

func SanitizeMapKeys(data map[string]any) map[string]any

SanitizeMapKeys redacts values for sensitive keys in a map.

func StripMedia

func StripMedia(content string) string

StripMedia removes media references from content, replacing them with placeholders.

Types

type AgentEvent

type AgentEvent struct {
	// Type identifies the kind of event.
	Type EventType `json:"type"`

	// Timestamp is when the event occurred.
	Timestamp time.Time `json:"timestamp"`

	// SessionID identifies the agent session this event belongs to.
	SessionID string `json:"session_id,omitempty"`

	// TraceID is the Opik trace ID for correlation.
	TraceID string `json:"trace_id,omitempty"`

	// SpanID is the Opik span ID for this specific event.
	SpanID string `json:"span_id,omitempty"`

	// ParentSpanID is the parent span ID for nested operations.
	ParentSpanID string `json:"parent_span_id,omitempty"`

	// Data contains event-specific payload.
	// The structure depends on the event type.
	Data map[string]any `json:"data,omitempty"`
}

AgentEvent represents a generic agent lifecycle event. Framework integrations convert their native events into this generic format.

func NewEvent

func NewEvent(eventType EventType) AgentEvent

NewEvent creates a new AgentEvent with the given type and current timestamp.

func (AgentEvent) GetBool

func (e AgentEvent) GetBool(key string) bool

GetBool returns a bool value from Data, or false if not found or not a bool.

func (AgentEvent) GetMap

func (e AgentEvent) GetMap(key string) map[string]any

GetMap returns a map value from Data, or nil if not found or not a map.

func (AgentEvent) GetString

func (e AgentEvent) GetString(key string) string

GetString returns a string value from Data, or empty string if not found or not a string.

func (AgentEvent) WithData

func (e AgentEvent) WithData(key string, value any) AgentEvent

WithData sets a data field and returns the event.

func (AgentEvent) WithDataMap

func (e AgentEvent) WithDataMap(data map[string]any) AgentEvent

WithDataMap merges a map into the event data and returns the event.

func (AgentEvent) WithParentSpan

func (e AgentEvent) WithParentSpan(parentSpanID string) AgentEvent

WithParentSpan sets the parent span ID and returns the event.

func (AgentEvent) WithSession

func (e AgentEvent) WithSession(sessionID string) AgentEvent

WithSession sets the session ID and returns the event.

func (AgentEvent) WithTrace

func (e AgentEvent) WithTrace(traceID, spanID string) AgentEvent

WithTrace sets the trace and span IDs and returns the event.

type AgentObserver

type AgentObserver interface {
	// OnEvent processes an agent event.
	// The implementation should translate the event to the appropriate
	// backend-specific operations (e.g., creating traces, spans, etc.)
	OnEvent(ctx context.Context, event AgentEvent) error

	// Flush ensures all pending events are sent to the backend.
	Flush(ctx context.Context) error

	// Close releases resources and stops the observer.
	Close() error
}

AgentObserver defines the interface for agent observability backends. Implementations receive generic agent events and translate them to backend-specific telemetry data.

type EventFilter

type EventFilter func(event AgentEvent) bool

EventFilter defines a function that filters events. Returns true if the event should be processed, false to skip.

func FilterByEventType

func FilterByEventType(types ...EventType) EventFilter

FilterByEventType creates a filter that only passes specified event types.

func FilterBySessionID

func FilterBySessionID(sessionID string) EventFilter

FilterBySessionID creates a filter that only passes events for a specific session.

func FilterExcludeEventType

func FilterExcludeEventType(types ...EventType) EventFilter

FilterExcludeEventType creates a filter that excludes specified event types.

func FilterHasSessionID

func FilterHasSessionID() EventFilter

FilterHasSessionID filters to events that have a session ID.

func FilterHasTraceID

func FilterHasTraceID() EventFilter

FilterHasTraceID filters to events that have a trace ID.

type EventType

type EventType string

EventType defines the type of agent lifecycle event.

const (
	// EventSessionCreated indicates a new agent session was created.
	EventSessionCreated EventType = "session.created"

	// EventSessionUpdated indicates an existing session was updated.
	EventSessionUpdated EventType = "session.updated"

	// EventSessionClosed indicates a session was explicitly closed.
	EventSessionClosed EventType = "session.closed"

	// EventMessageReceived indicates a user message was received.
	EventMessageReceived EventType = "message.received"

	// EventMessageSent indicates an assistant message was sent.
	EventMessageSent EventType = "message.sent"

	// EventToolCalled indicates a tool invocation started.
	EventToolCalled EventType = "tool.called"

	// EventToolCompleted indicates a tool invocation completed.
	EventToolCompleted EventType = "tool.completed"

	// EventSubagentStarted indicates a subagent was spawned.
	EventSubagentStarted EventType = "subagent.started"

	// EventSubagentCompleted indicates a subagent completed its task.
	EventSubagentCompleted EventType = "subagent.completed"

	// EventJobExecuted indicates a scheduled job was executed.
	EventJobExecuted EventType = "job.executed"

	// EventError indicates an error occurred.
	EventError EventType = "error"
)

Event type constants matching common agent framework events.

func (EventType) String

func (e EventType) String() string

String returns the string representation of the event type.

type FilteredObserver

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

FilteredObserver wraps an observer with event filtering.

func NewFilteredObserver

func NewFilteredObserver(observer AgentObserver, filters ...EventFilter) *FilteredObserver

NewFilteredObserver creates an observer that only processes events matching all provided filters.

func (*FilteredObserver) Close

func (f *FilteredObserver) Close() error

Close delegates to the underlying observer.

func (*FilteredObserver) Flush

func (f *FilteredObserver) Flush(ctx context.Context) error

Flush delegates to the underlying observer.

func (*FilteredObserver) OnEvent

func (f *FilteredObserver) OnEvent(ctx context.Context, event AgentEvent) error

OnEvent processes the event if it passes all filters.

type MediaRef

type MediaRef struct {
	// Type is the media type (image, audio, video, document, etc.)
	Type string `json:"type"`

	// MimeType is the MIME type of the media.
	MimeType string `json:"mime_type,omitempty"`

	// Source indicates where the media came from (url, file, data, markdown).
	Source string `json:"source"`

	// URL is the media URL if applicable.
	URL string `json:"url,omitempty"`

	// Data contains inline data (e.g., base64-decoded bytes).
	Data []byte `json:"data,omitempty"`

	// Alt is the alt text or description if available.
	Alt string `json:"alt,omitempty"`

	// Original is the original reference string as found in content.
	Original string `json:"original,omitempty"`
}

MediaRef represents a media reference extracted from content.

func ExtractMedia

func ExtractMedia(content string) []MediaRef

ExtractMedia extracts all media references from content. It recognizes:

  • Markdown images: ![alt](url)
  • Data URLs: data:mime/type;base64,...
  • media: protocol: media:mime/type:base64data
  • file:// URLs: file:///path/to/file
  • HTTP URLs with media extensions

func ExtractMediaFromMap

func ExtractMediaFromMap(data map[string]any) []MediaRef

ExtractMediaFromMap extracts media from string values in a map.

type MultiObserver

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

MultiObserver broadcasts events to multiple observers.

func NewMultiObserver

func NewMultiObserver(observers ...AgentObserver) *MultiObserver

NewMultiObserver creates an observer that sends events to all provided observers.

func (*MultiObserver) Close

func (m *MultiObserver) Close() error

Close closes all observers.

func (*MultiObserver) Flush

func (m *MultiObserver) Flush(ctx context.Context) error

Flush flushes all observers.

func (*MultiObserver) OnEvent

func (m *MultiObserver) OnEvent(ctx context.Context, event AgentEvent) error

OnEvent sends the event to all observers. Returns the first error encountered, but continues sending to remaining observers.

type NoOpObserver

type NoOpObserver struct{}

NoOpObserver is an observer that does nothing. Useful for testing or disabling observability.

func (NoOpObserver) Close

func (NoOpObserver) Close() error

Close does nothing.

func (NoOpObserver) Flush

func (NoOpObserver) Flush(_ context.Context) error

Flush does nothing.

func (NoOpObserver) OnEvent

OnEvent does nothing.

type SanitizeConfig

type SanitizeConfig struct {
	// RemoveInternalMarkers removes framework-specific internal markers.
	RemoveInternalMarkers bool

	// RemoveMetadataBlocks removes metadata blocks like <system-reminder>.
	RemoveMetadataBlocks bool

	// RemoveSecrets removes patterns that look like secrets or API keys.
	RemoveSecrets bool

	// RemoveAnsiCodes removes ANSI escape codes from terminal output.
	RemoveAnsiCodes bool

	// MaxLength truncates content exceeding this length (0 = no limit).
	MaxLength int

	// CustomPatterns are additional regex patterns to remove.
	CustomPatterns []*regexp.Regexp
}

SanitizeConfig configures content sanitization behavior.

func DefaultSanitizeConfig

func DefaultSanitizeConfig() SanitizeConfig

DefaultSanitizeConfig returns a SanitizeConfig with sensible defaults.

type Span

type Span interface {
	// ID returns the span ID.
	ID() string

	// TraceID returns the parent trace ID.
	TraceID() string

	// Name returns the span name.
	Name() string

	// End ends the span with optional output.
	End(ctx context.Context, output any, err error) error

	// CreateChildSpan creates a child span.
	CreateChildSpan(ctx context.Context, name string, spanType string, input any) (Span, error)
}

Span represents a span within a trace.

type Trace

type Trace interface {
	// ID returns the trace ID.
	ID() string

	// Name returns the trace name.
	Name() string

	// End ends the trace with optional output.
	End(ctx context.Context, output any) error

	// Update updates the trace metadata.
	Update(ctx context.Context, metadata map[string]any) error

	// CreateSpan creates a new span within this trace.
	CreateSpan(ctx context.Context, name string, spanType string, input any) (Span, error)
}

Trace represents a trace in the observability backend.

type TraceClient

type TraceClient interface {
	// CreateTrace creates a new trace.
	CreateTrace(ctx context.Context, name string, input any, tags []string) (Trace, error)

	// IsTracingEnabled returns whether tracing is active.
	IsTracingEnabled() bool
}

TraceClient is the interface that trace providers must implement. This allows the TraceManager to work with different backends.

type TraceManager

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

TraceManager manages the lifecycle of traces associated with agent sessions.

func NewTraceManager

func NewTraceManager(client TraceClient, opts ...TraceManagerOption) *TraceManager

NewTraceManager creates a new TraceManager.

func (*TraceManager) ActiveSessionIDs

func (tm *TraceManager) ActiveSessionIDs() []string

ActiveSessionIDs returns the session IDs with active traces.

func (*TraceManager) ActiveTraceCount

func (tm *TraceManager) ActiveTraceCount() int

ActiveTraceCount returns the number of active traces.

func (*TraceManager) Close

func (tm *TraceManager) Close() error

Close stops the manager and closes all active traces.

func (*TraceManager) EndSpan

func (tm *TraceManager) EndSpan(ctx context.Context, sessionID string, output any, spanErr error) error

EndSpan ends the current span for a session.

func (*TraceManager) EndSpanByID

func (tm *TraceManager) EndSpanByID(ctx context.Context, sessionID, spanID string, output any, spanErr error) error

EndSpanByID ends a specific span by its ID.

func (*TraceManager) EndTrace

func (tm *TraceManager) EndTrace(ctx context.Context, sessionID string, output any) error

EndTrace ends a trace and removes it from management.

func (*TraceManager) ExtractMedia

func (tm *TraceManager) ExtractMedia(content string) []MediaRef

ExtractMedia extracts media references if configured.

func (*TraceManager) GetCurrentSpan

func (tm *TraceManager) GetCurrentSpan(sessionID string) Span

GetCurrentSpan returns the current span for a session.

func (*TraceManager) GetTrace

func (tm *TraceManager) GetTrace(sessionID string) *TraceState

GetTrace returns the trace state for a session.

func (*TraceManager) SanitizeContent

func (tm *TraceManager) SanitizeContent(content string) string

SanitizeContent sanitizes content if configured.

func (*TraceManager) SanitizeData

func (tm *TraceManager) SanitizeData(data map[string]any) map[string]any

SanitizeData sanitizes map data if configured.

func (*TraceManager) StartSpan

func (tm *TraceManager) StartSpan(ctx context.Context, sessionID, spanName, spanType string, input any) (Span, error)

StartSpan creates a new span within a session's trace.

func (*TraceManager) StartTrace

func (tm *TraceManager) StartTrace(ctx context.Context, sessionID string, agentName string, input any) (*TraceState, error)

StartTrace creates a new trace for a session.

func (*TraceManager) TouchTrace

func (tm *TraceManager) TouchTrace(sessionID string)

TouchTrace updates the last activity for a session's trace.

type TraceManagerConfig

type TraceManagerConfig struct {
	// StaleTimeout is how long a trace can be inactive before being closed.
	// Default: 5 minutes.
	StaleTimeout time.Duration

	// SweepInterval is how often to check for stale traces.
	// Default: 1 minute.
	SweepInterval time.Duration

	// DefaultTags are applied to all traces.
	DefaultTags []string

	// ProjectName is the default Opik project name.
	ProjectName string

	// SanitizeContent enables content sanitization.
	// Default: true.
	SanitizeContent bool

	// SanitizeConfig is the sanitization configuration.
	// Used when SanitizeContent is true.
	SanitizeConfig SanitizeConfig

	// ExtractMedia enables media extraction from content.
	// Default: true.
	ExtractMedia bool

	// TraceNamePrefix is prepended to trace names.
	// Default: "agent.session."
	TraceNamePrefix string
}

TraceManagerConfig configures the TraceManager behavior.

func DefaultTraceManagerConfig

func DefaultTraceManagerConfig() TraceManagerConfig

DefaultTraceManagerConfig returns a TraceManagerConfig with sensible defaults.

func (*TraceManagerConfig) ApplyOptions

func (cfg *TraceManagerConfig) ApplyOptions(opts ...TraceManagerOption)

ApplyOptions applies functional options to a config.

type TraceManagerOption

type TraceManagerOption func(*TraceManagerConfig)

TraceManagerOption is a functional option for TraceManagerConfig.

func WithDefaultTags

func WithDefaultTags(tags ...string) TraceManagerOption

WithDefaultTags sets the default tags for all traces.

func WithMediaExtraction

func WithMediaExtraction(enabled bool) TraceManagerOption

WithMediaExtraction enables or disables media extraction.

func WithProjectName

func WithProjectName(name string) TraceManagerOption

WithProjectName sets the default project name.

func WithSanitization

func WithSanitization(enabled bool) TraceManagerOption

WithSanitization enables or disables content sanitization.

func WithSanitizeConfig

func WithSanitizeConfig(sanitizeCfg SanitizeConfig) TraceManagerOption

WithSanitizeConfig sets the sanitization configuration.

func WithStaleTimeout

func WithStaleTimeout(d time.Duration) TraceManagerOption

WithStaleTimeout sets the stale trace timeout.

func WithSweepInterval

func WithSweepInterval(d time.Duration) TraceManagerOption

WithSweepInterval sets the sweep interval for stale trace cleanup.

func WithTraceNamePrefix

func WithTraceNamePrefix(prefix string) TraceManagerOption

WithTraceNamePrefix sets the prefix for trace names.

type TraceState

type TraceState struct {
	Trace        Trace
	SessionID    string
	LastActivity time.Time
	OpenSpans    map[string]Span // spanID -> Span
	SpanStack    []string        // Stack of span IDs for nesting
	// contains filtered or unexported fields
}

TraceState holds the state of an active trace.

func NewTraceState

func NewTraceState(trace Trace, sessionID string) *TraceState

NewTraceState creates a new trace state.

func (*TraceState) CurrentSpan

func (ts *TraceState) CurrentSpan() Span

CurrentSpan returns the current (top) span without removing it.

func (*TraceState) GetSpan

func (ts *TraceState) GetSpan(spanID string) Span

GetSpan returns a span by ID.

func (*TraceState) HasOpenSpans

func (ts *TraceState) HasOpenSpans() bool

HasOpenSpans returns true if there are open spans.

func (*TraceState) IsStale

func (ts *TraceState) IsStale(timeout time.Duration) bool

IsStale returns true if the trace has been inactive longer than timeout.

func (*TraceState) OpenSpanCount

func (ts *TraceState) OpenSpanCount() int

OpenSpanCount returns the number of open spans.

func (*TraceState) PopSpan

func (ts *TraceState) PopSpan() Span

PopSpan removes and returns the top span from the stack.

func (*TraceState) PushSpan

func (ts *TraceState) PushSpan(span Span)

PushSpan adds a span to the stack.

func (*TraceState) RemoveSpan

func (ts *TraceState) RemoveSpan(spanID string) Span

RemoveSpan removes a specific span by ID.

func (*TraceState) Touch

func (ts *TraceState) Touch()

Touch updates the last activity timestamp.

Jump to

Keyboard shortcuts

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