observers

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: BSD-2-Clause Imports: 16 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.

Documentation

Overview

Package observers provides pipeline observers: components that watch the frames flowing through a pipeline without modifying it. They derive turn, latency and startup metrics, report the conversation's speaking lifecycle, the function calls it makes, the failures it runs into and what each service spent and consumed, or log the stream. Register them via pipeline.WorkerConfig.Observers.

Every handover between two processors is reported, not only what reaches the ends of the pipeline, so an observer sees where each frame came from. Each observer here is safe for concurrent use: a pipeline's processors each run on their own goroutine.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DebugFrameFilter added in v0.1.0

type DebugFrameFilter struct {
	// Frame is an instance of the frame type to log; its type is what is
	// matched, not its contents.
	Frame frames.Frame
	// Match, when set, logs the frame only where the processor at Endpoint
	// satisfies it. Leave it nil to log the frame wherever it travels.
	Match func(processor.Processor) bool
	// Endpoint is the end of the handover Match decides on.
	Endpoint FrameEndpoint
}

DebugFrameFilter narrows what a DebugLog observer reports to one kind of frame, optionally only where one end of the handover is a particular kind of processor.

type DebugLog added in v0.1.0

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

DebugLog logs the frames going by with their contents, for working out what a pipeline is actually doing. Every exported field of a frame is rendered, so it serves any frame type without knowing anything about it.

func NewDebugLog added in v0.1.0

func NewDebugLog(cfg DebugLogConfig) *DebugLog

NewDebugLog builds a DebugLog observer.

func (*DebugLog) OnPushFrame added in v0.1.0

func (o *DebugLog) OnPushFrame(data processor.FramePushed)

OnPushFrame implements processor.Observer.

type DebugLogConfig added in v0.1.0

type DebugLogConfig struct {
	// Logger is the destination; slog.Default() when nil.
	Logger *slog.Logger
	// Frames selects what to log. An empty list logs every frame, which on a
	// real pipeline is a great many.
	Frames []DebugFrameFilter
	// ExcludeFields names the frame fields left out of the log. A nil slice
	// leaves out the binary payloads (Audio, Image, Images); an empty non-nil
	// slice leaves out nothing.
	ExcludeFields []string
}

DebugLogConfig configures a DebugLog observer.

type ErrorConfig added in v0.2.0

type ErrorConfig struct {
	// MaxFrames is unused.
	//
	// Deprecated: the observer is told about each frame once, so it keeps no
	// window of the frames it has seen.
	MaxFrames int
	// Now reads the current time. Nil uses time.Now. Supplying one lets a test
	// place failures without waiting.
	Now func() time.Time
	// OnError is called for each error, as an ErrorEvent.
	OnError func(e ErrorEvent)
}

ErrorConfig configures an Errors observer.

type ErrorEvent added in v0.2.0

type ErrorEvent struct {
	// Message is what went wrong, in the words of the processor that failed.
	Message string
	// Category is why it failed, drawn from [errors.Category] and independent of
	// the provider that failed: rejected credentials, an unreachable service, a
	// malformed request and so on.
	Category errs.Category
	// ExceptionType is the type of the error behind the failure, where one
	// caused it, and "" where none did. Failures group by this where a message,
	// carrying the particulars of a single occurrence, is too specific to group
	// by.
	ExceptionType string
	// Processor is the name of the processor that raised the error.
	Processor string
	// ProcessorUsable reports whether that processor can still do its job. A
	// processor that cannot keeps failing for as long as it is given work, so
	// this separates a bad minute from the end of a capability.
	ProcessorUsable bool
	// Timestamp is the wall-clock time of the failure.
	Timestamp time.Time
}

ErrorEvent is one failure, as the processor that raised it described it.

type Errors added in v0.2.0

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

Errors reports each error a pipeline raises, once, where it is raised.

Errors travel upstream from the processor that raised them, and not all of them reach the end of that journey: a processor that answers for a failure itself (a service switcher that fails over to its next service, say) stops the error there. This observer reads each error where it is raised, so a session's failure history holds the ones that were recovered from as well as the ones that surfaced.

An error is reported at its origin rather than where it ends up, and named for the processor that raised it rather than the one that passed it along.

func NewErrors added in v0.2.0

func NewErrors(cfg ErrorConfig) *Errors

NewErrors builds an Errors observer.

func (*Errors) ObserveEveryPush added in v0.3.0

func (o *Errors) ObserveEveryPush() bool

ObserveEveryPush implements processor.EveryPushObserver: an error is reported once, on its first push.

func (*Errors) OnPushFrame added in v0.2.0

func (o *Errors) OnPushFrame(data processor.FramePushed)

OnPushFrame implements processor.Observer. It reports an error frame. The first push of an error comes from the processor that failed.

type FrameEndpoint added in v0.1.0

type FrameEndpoint int

FrameEndpoint selects which end of a handover a filter decides on.

const (
	// SourceEndpoint decides on the processor pushing the frame.
	SourceEndpoint FrameEndpoint = iota
	// DestinationEndpoint decides on the processor receiving it.
	DestinationEndpoint
)

type FunctionCallConfig added in v0.2.0

type FunctionCallConfig struct {
	// MaxFrames is unused.
	//
	// Deprecated: the observer is told about each frame once, so it keeps no
	// window of the frames it has seen.
	MaxFrames int
	// IncludeArguments reports the arguments a call was made with. Nil leaves it
	// on: they are small, and they are the reason a call is worth reading at all.
	IncludeArguments *bool
	// IncludeResults reports what a call returned. Nil leaves it off: a result is
	// whatever a provider decided to return, which can be anything at all.
	IncludeResults *bool
	// Now reads the current time. Nil uses time.Now. Supplying one lets a test
	// place moments without waiting.
	Now func() time.Time
	// OnFunctionCallEvent is called for each moment, as a FunctionCallEvent.
	OnFunctionCallEvent func(e FunctionCallEvent)
}

FunctionCallConfig configures a FunctionCalls observer.

type FunctionCallEvent added in v0.2.0

type FunctionCallEvent struct {
	// Kind is what happened to the call.
	Kind FunctionCallEventKind
	// FunctionName is the name of the function.
	FunctionName string
	// ToolCallID is the model's identifier for this call, unique within a
	// conversation.
	ToolCallID string
	// Timestamp is the wall-clock time of the moment.
	Timestamp time.Time
	// GroupID identifies the calls the model asked for in one response, which run
	// together. Set when the call goes in progress.
	GroupID string
	// Blocking reports whether the conversation waited for this call. A call that
	// does not block is answered later through a developer message, while the
	// model carries on talking. Set when the call goes in progress, and nil
	// everywhere else.
	Blocking *bool
	// Arguments is what the model passed to the function, when the observer is
	// reporting arguments. Set both when the call starts and when it goes in
	// progress, since a call can be reported at either moment without the other.
	Arguments json.RawMessage
	// StartedAt is when the call started, on the moment it goes in progress, so
	// the wait between the two reads from one record. The zero value means the
	// call started before the observer was watching.
	StartedAt time.Time
	// InProgressAt is when the call went in progress, on the moment that settles
	// it, so the time it ran reads from one record. The zero value means it began
	// running before the observer was watching.
	InProgressAt time.Time
	// Result is what the handler returned, when the observer is reporting
	// results.
	Result string
	// Error is what went wrong, on a call whose handler failed.
	Error string
}

FunctionCallEvent is one moment in the life of a function call.

The moments that open a call describe it; the moment that settles it describes what became of it. Each names the call, so they read as a sequence without any of them repeating the others.

type FunctionCallEventKind added in v0.2.0

type FunctionCallEventKind string

FunctionCallEventKind is where a function call has got to.

A call starts when the model asks for it and is in progress once it is running, which are two moments rather than one: calls run one at a time unless the service was built to run them in parallel, so a call can wait in between, and a call still waiting when the conversation moves on never runs at all.

A call settles in one of four ways: it returned, its handler failed, it ran past its deadline, or it was canceled, by an interruption or by the model asking for it.

const (
	FunctionCallStarted    FunctionCallEventKind = "function_call_started"
	FunctionCallInProgress FunctionCallEventKind = "function_call_in_progress"
	FunctionCallCompleted  FunctionCallEventKind = "function_call_completed"
	FunctionCallFailed     FunctionCallEventKind = "function_call_failed"
	FunctionCallTimedOut   FunctionCallEventKind = "function_call_timed_out"
	FunctionCallCanceled   FunctionCallEventKind = "function_call_canceled"
)

The moments in the life of a function call.

type FunctionCallMetrics added in v0.1.0

type FunctionCallMetrics struct {
	// FunctionName is the name of the tool that was called.
	FunctionName string
	// StartTime is the wall-clock time the call started at.
	StartTime time.Time
	// Duration is the time from the call starting to its result arriving.
	Duration time.Duration
}

FunctionCallMetrics is how long one tool call took to run.

type FunctionCalls added in v0.2.0

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

FunctionCalls reports each function call a conversation makes, from start to outcome.

A function call is the one thing a bot does rather than says, and the part of a turn whose duration belongs to the application's own code. A call is reported at each moment it reaches rather than summarized once it is over, because the moments can be far apart and a call need not reach all of them: one waiting its turn to run is dropped if the conversation moves on, and one the conversation does not wait for can settle long after the turn that asked for it.

Arguments and results are where a call holds whatever the conversation was about, so each is a choice. Arguments travel by default and results do not.

func NewFunctionCalls added in v0.2.0

func NewFunctionCalls(cfg FunctionCallConfig) *FunctionCalls

NewFunctionCalls builds a FunctionCalls observer.

func (*FunctionCalls) ObserveEveryPush added in v0.3.0

func (o *FunctionCalls) ObserveEveryPush() bool

ObserveEveryPush implements processor.EveryPushObserver: a moment is reported once, on the first push of the frame that represents it.

func (*FunctionCalls) OnPushFrame added in v0.2.0

func (o *FunctionCalls) OnPushFrame(data processor.FramePushed)

OnPushFrame implements processor.Observer. It reports the moments a frame represents.

type LLMLog added in v0.1.0

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

LLMLog logs what a language-model service was given and what it produced: the context it was asked to answer, the tokens it generated, the bounds of each response, and the tool calls it made along with their results.

Only frames pushed to or from a model service are reported, so the same frame types traveling elsewhere in the pipeline are left alone.

func NewLLMLog added in v0.1.0

func NewLLMLog(cfg LLMLogConfig) *LLMLog

NewLLMLog builds an LLMLog observer.

func (*LLMLog) OnPushFrame added in v0.1.0

func (o *LLMLog) OnPushFrame(data processor.FramePushed)

OnPushFrame implements processor.Observer.

type LLMLogConfig added in v0.1.0

type LLMLogConfig struct {
	// Logger is the destination; slog.Default() when nil.
	Logger *slog.Logger
}

LLMLogConfig configures an LLMLog observer.

type LatencyBreakdown added in v0.1.0

type LatencyBreakdown struct {
	// TTFB is what each service took to produce anything at all, in the order
	// the measurements were reported.
	TTFB []TTFBBreakdown
	// TextAggregation is the first text-aggregation measurement of the cycle,
	// which is what grouping the model's tokens into sentences cost before
	// synthesis could start. It is nil when none was reported.
	TextAggregation *TextAggregationBreakdown
	// UserTurnStart is when the user's turn ended in the audio: the moment the
	// speech itself stopped, before the detector had confirmed it. The zero
	// value means no VAD stop was observed.
	UserTurnStart time.Time
	// UserTurn is how long releasing the turn took from that moment: the
	// detector's silence window, the transcriber finalizing, and any wait on an
	// end-of-turn analyzer. It is nil when the turn was never released, which is
	// what a pipeline with no turn analyzer looks like.
	UserTurn *time.Duration
	// FunctionCalls is how long each tool call of the cycle took. It is empty
	// when the reply made none.
	FunctionCalls []FunctionCallMetrics
	// Contributions are the named parts of the interval, in chronological order,
	// summing to the measured latency. A part is listed only if it happened, so
	// a bot without turn completion has no marker or wait entries.
	Contributions []LatencyContribution
	// MeasuredFrom is where the interval was anchored, so a greeting is not
	// compared with a turn. It is MeasuredFromNothing on a breakdown carrying no
	// contributions.
	MeasuredFrom MeasuredFrom
	// Total is the measured interval, which the contributions sum to.
	Total time.Duration
}

LatencyBreakdown accounts for one user-to-bot cycle: what each service in the pipeline contributed to the delay the listener heard.

It is collected between the user falling silent and the bot starting to speak, and only when the pipeline collects metrics at all: the measurements come from the MetricsFrames the services emit, which they only emit when asked to.

func (LatencyBreakdown) TurnContributionLines added in v0.2.0

func (b LatencyBreakdown) TurnContributionLines(byCost bool) []string

TurnContributionLines formats the contributions for logging, one per line plus a total.

One breakdown covers one user-to-bot cycle, so these lines describe a single turn, or, for the first thing the bot says, the wait before it from the pipeline being ready with a client on it, which the total line names.

byCost orders by duration, largest first, rather than in the order things happened. It is what to ask for when the question is what to optimize rather than what the turn did.

It returns nothing when no contributions were collected.

type LatencyConfig

type LatencyConfig struct {
	// MaxFrames is unused.
	//
	// Deprecated: the observer is told about each frame once, so it keeps no
	// window of the frames it has seen.
	MaxFrames int
	// MinContribution is the shortest stretch reported in its own right; 0 uses
	// 5ms. Anything shorter is a frame hop rather than work worth naming, so it
	// is rolled into the single pipeline contribution. Set it negative to list
	// every stretch, individual frame hops included.
	MinContribution time.Duration
	// Now reads the current time. Nil uses time.Now. Supplying one lets a test
	// drive a cycle without waiting out the intervals it describes.
	Now func() time.Time
	// OnLatency is called with the time from the user stopping speaking to the
	// bot starting: the user-perceived response latency.
	OnLatency func(d time.Duration)
	// OnBreakdown is called with the per-service account of the same cycle,
	// alongside every latency the observer reports. It is empty of measurements
	// unless the pipeline collects metrics.
	OnBreakdown func(b LatencyBreakdown)
	// OnFirstBotSpeechLatency is called once, with the time from the client
	// connecting to the bot first speaking. It is not called at all when the
	// user speaks first: the figure means the greeting was slow, and there is no
	// greeting to measure once the conversation has started without one.
	OnFirstBotSpeechLatency func(d time.Duration)
}

LatencyConfig configures a UserBotLatency observer.

type LatencyContribution added in v0.2.0

type LatencyContribution struct {
	// Key is a stable identifier for this part of a turn. Unlike Label, it is
	// safe to group on: it survives the label being reworded.
	Key string
	// Label is what the time was spent on.
	Label string
	// Owner is what spent it: a processor name, or a "config:" tag naming the
	// setting that governs it.
	Owner string
	// OwnerKind is what kind of thing the owner is.
	OwnerKind LatencyOwnerKind
	// StartTime is when this part started.
	StartTime time.Time
	// Duration is how long it took.
	Duration time.Duration
}

LatencyContribution is one named part of the user-to-bot interval.

Contributions account for the whole interval, so their durations sum to the measured latency. Unlike a TTFB, which reports what a service spent once it was asked, a contribution can also name time no service is measuring: the silence a VAD waits out, the tokens a turn-completion marker occupies before any speakable text, or a hold while the pipeline waits for the user to finish a sentence.

type LatencyOwnerKind added in v0.2.0

type LatencyOwnerKind string

LatencyOwnerKind is what kind of thing a contribution's owner is.

Grouping on this answers where a turn's time went without matching on the owner's name: a service that could be swapped, a setting the bot chose, the bot's own code, or the pipeline between them.

const (
	OwnerService  LatencyOwnerKind = "service"
	OwnerSetting  LatencyOwnerKind = "setting"
	OwnerBot      LatencyOwnerKind = "bot"
	OwnerPipeline LatencyOwnerKind = "pipeline"
)

The kinds of thing that spend a turn's time.

type MeasuredFrom added in v0.2.0

type MeasuredFrom string

MeasuredFrom is where a measured interval was anchored.

A greeting is timed from the client connecting, a turn from the user falling silent, so a partial interval is never mistaken for a whole one.

const (
	// MeasuredFromNothing is the zero value, on a breakdown carrying no
	// contributions.
	MeasuredFromNothing         MeasuredFrom = ""
	MeasuredFromUserSilence     MeasuredFrom = "user_silence"
	MeasuredFromClientConnected MeasuredFrom = "client_connected"
)

The anchors an interval can be measured from.

type MetricsLog added in v0.1.0

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

MetricsLog logs the measurements the pipeline reports: what each service took to answer, how much it was given, and what it billed.

func NewMetricsLog added in v0.1.0

func NewMetricsLog(cfg MetricsLogConfig) *MetricsLog

NewMetricsLog builds a MetricsLog observer.

func (*MetricsLog) ObserveEveryPush added in v0.3.0

func (o *MetricsLog) ObserveEveryPush() bool

ObserveEveryPush implements processor.EveryPushObserver: a metrics frame is logged once, on its first push.

func (*MetricsLog) OnPushFrame added in v0.1.0

func (o *MetricsLog) OnPushFrame(data processor.FramePushed)

OnPushFrame implements processor.Observer.

type MetricsLogConfig added in v0.1.0

type MetricsLogConfig struct {
	// Logger is the destination; slog.Default() when nil.
	Logger *slog.Logger
	// Include selects the kinds of measurement to log, given as instances of
	// the frames.MetricsData types wanted. An empty list logs every kind.
	Include []frames.MetricsData
}

MetricsLogConfig configures a MetricsLog observer.

type ProcessorStartupTiming added in v0.1.0

type ProcessorStartupTiming struct {
	// ProcessorName is the name of the processor.
	ProcessorName string
	// StartOffset is how long after the StartFrame entered the pipeline this
	// processor began starting.
	StartOffset time.Duration
	// Duration is what the processor cost to get ready: its setup and its start
	// together. It connects while it is set up, and starting is whatever is left
	// to do once it has.
	Duration time.Duration
	// SetupDuration is how long the processor's setup took, which is the part of
	// Duration spent connecting.
	SetupDuration time.Duration
	// StartDuration is how long the processor spent on the StartFrame, which is
	// the rest of Duration: whatever getting ready still needed once the
	// processor had connected.
	StartDuration time.Duration
}

ProcessorStartupTiming is what one processor cost to start.

type ServiceLatencyKind added in v0.2.0

type ServiceLatencyKind string

ServiceLatencyKind is which measurement of a service's own time a record carries.

const (
	LatencyTTFB  ServiceLatencyKind = "ttfb"
	LatencyTTFA  ServiceLatencyKind = "ttfa"
	LatencyTTFAT ServiceLatencyKind = "ttfat"
)

The waits a service reports.

type ServiceLatencyRecord added in v0.2.0

type ServiceLatencyRecord struct {
	// Kind is which wait was measured.
	Kind ServiceLatencyKind
	// Processor is the name of the processor that reported it.
	Processor string
	// Model is the model the processor was using, "" where it names none.
	Model string
	// Timestamp is the wall-clock time the measurement was observed at.
	Timestamp time.Time
	// Duration is the measurement itself.
	Duration time.Duration
	// TTFB is the time to first byte the measurement builds on, on the kinds
	// that report one. It is that same measurement rather than another one, so
	// do not add it to Duration.
	TTFB time.Duration
	// LeadingSilence is the silence at the head of the first audio, on the time
	// to first audible sample.
	LeadingSilence time.Duration
	// ThinkingTime is the time between a model's first output and its first
	// answer token, on the time to first answer token.
	ThinkingTime time.Duration
}

ServiceLatencyRecord is one measurement of how long a service took.

type ServiceMetrics added in v0.2.0

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

ServiceMetrics reports each metric a service publishes as its own record.

Services report metrics as they finish a piece of work, and this observer turns each one into a record: what was measured, which processor and model reported it, and when. Nothing is summed, so a consumer groups the records by turn, session or model as it needs, and a session that ends abruptly still leaves behind everything that happened before it did. A turn that runs two inferences reports two records, and a consumer that wants a total groups them itself: summing here would lose the grain, and a total held in memory is lost with the process holding it.

What a service made someone wait for is here; what it did with its own time is not. Processing time, text aggregation and end-of-turn predictions are all deliberately absent: aggregation already appears as a span in LatencyBreakdown, and the other two describe how work was done rather than what it cost the person waiting.

func NewServiceMetrics added in v0.2.0

func NewServiceMetrics(cfg ServiceMetricsConfig) *ServiceMetrics

NewServiceMetrics builds a ServiceMetrics observer.

func (*ServiceMetrics) ObserveEveryPush added in v0.3.0

func (o *ServiceMetrics) ObserveEveryPush() bool

ObserveEveryPush implements processor.EveryPushObserver: a frame's metrics are reported once, on its first push.

func (*ServiceMetrics) OnPushFrame added in v0.2.0

func (o *ServiceMetrics) OnPushFrame(data processor.FramePushed)

OnPushFrame implements processor.Observer. It reports the metrics a frame carries, the first time that frame is seen: every processor that passes it along reports it.

Metrics travel in one direction, so a frame is identified by its id alone.

type ServiceMetricsConfig added in v0.2.0

type ServiceMetricsConfig struct {
	// MaxFrames is unused.
	//
	// Deprecated: the observer is told about each frame once, so it keeps no
	// window of the frames it has seen.
	MaxFrames int
	// Now reads the current time. Nil uses time.Now. Supplying one lets a test
	// place records without waiting.
	Now func() time.Time
	// OnServiceLatency is called for each measurement of a service's own time.
	OnServiceLatency func(r ServiceLatencyRecord)
	// OnServiceUsage is called for each report of what a service consumed.
	OnServiceUsage func(r ServiceUsageRecord)
}

ServiceMetricsConfig configures a ServiceMetrics observer.

type ServiceUsageKind added in v0.2.0

type ServiceUsageKind string

ServiceUsageKind is which kind of service consumed something.

const (
	UsageSTT ServiceUsageKind = "stt"
	UsageLLM ServiceUsageKind = "llm"
	UsageTTS ServiceUsageKind = "tts"
)

The kinds of service that report usage.

type ServiceUsageRecord added in v0.2.0

type ServiceUsageRecord struct {
	// Kind is which kind of service reported.
	Kind ServiceUsageKind
	// Processor is the name of the processor that reported it.
	Processor string
	// Model is the model the processor was using, "" where it names none.
	Model string
	// Timestamp is the wall-clock time the usage was observed at.
	Timestamp time.Time

	// AudioSeconds is the audio transcribed, for speech-to-text.
	AudioSeconds float64
	// Characters is the characters synthesized, for text-to-speech.
	Characters int

	// PromptTokens is the tokens in the prompt, for an LLM.
	PromptTokens int64
	// CompletionTokens is the tokens generated.
	CompletionTokens int64
	// TotalTokens is the tokens in the prompt and the completion together.
	TotalTokens int64
	// CacheReadTokens is the prompt tokens served from cache.
	CacheReadTokens *int64
	// CacheCreationTokens is the prompt tokens written to cache.
	CacheCreationTokens *int64
	// ReasoningTokens is the tokens spent reasoning before answering.
	ReasoningTokens *int64
	// InputAudioTokens is the audio tokens in the prompt.
	InputAudioTokens *int64
	// OutputAudioTokens is the audio tokens generated.
	OutputAudioTokens *int64
	// CacheReadAudioTokens is the audio prompt tokens served from cache.
	CacheReadAudioTokens *int64
	// InputTextTokens is the text tokens in the prompt, where the model reports
	// a per-modality breakdown.
	InputTextTokens *int64
	// OutputTextTokens is the text tokens generated, where the model reports a
	// per-modality breakdown.
	OutputTextTokens *int64
}

ServiceUsageRecord is what one service consumed doing a piece of work.

A field is set only where the kind of service reports it, so an LLM record carries token counts and a text-to-speech record carries characters. The counts a service may leave unreported are pointers, because a count nobody measured must not read as a measured zero to whoever is adding up a bill.

type Speaking added in v0.2.0

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

Speaking reports the speaking lifecycle of a conversation.

A conversation is a sequence of people taking the floor and occasionally taking it from each other. Every moment is reported as it happens, and the moments that close a stretch of speech name where it began, so an interval reads whole from one record: a stretch whose closing moment never arrives stays open rather than quietly joining itself to the next one.

What a turn is stays with the reader. A turn built here would freeze one definition into every record, where the moments themselves can be grouped again later, differently, over the same history.

func NewSpeaking added in v0.2.0

func NewSpeaking(cfg SpeakingConfig) *Speaking

NewSpeaking builds a Speaking observer.

func (*Speaking) ObserveEveryPush added in v0.3.0

func (o *Speaking) ObserveEveryPush() bool

ObserveEveryPush implements processor.EveryPushObserver: a moment is reported once, on the first push of the frame that represents it.

func (*Speaking) OnPushFrame added in v0.2.0

func (o *Speaking) OnPushFrame(data processor.FramePushed)

OnPushFrame implements processor.Observer. It reports the moment a frame represents.

type SpeakingConfig added in v0.2.0

type SpeakingConfig struct {
	// MaxFrames is unused.
	//
	// Deprecated: the observer is told about each frame once, so it keeps no
	// window of the frames it has seen.
	MaxFrames int
	// Now reads the current time. Nil uses time.Now. Supplying one lets a test
	// place moments without waiting.
	Now func() time.Time
	// OnSpeechEvent is called for each moment, as a SpeechEvent.
	OnSpeechEvent func(e SpeechEvent)
}

SpeakingConfig configures a Speaking observer.

type SpeechEvent added in v0.2.0

type SpeechEvent struct {
	// Kind is what happened, to whom, and at which layer.
	Kind SpeechEventKind
	// Timestamp is the wall-clock time of the moment itself. Speech is timed to
	// when it began and ended, not to when the detector confirmed it, so an
	// interval drawn from these matches what was said.
	Timestamp time.Time
	// StartedAt is when the matching stretch of speech began, on the moments
	// that end one, so a stretch reads as an interval without pairing it with
	// the moment that opened it. The zero value means the stretch began before
	// the observer was watching.
	StartedAt time.Time
}

SpeechEvent is one moment in the conversation's speaking lifecycle.

type SpeechEventKind added in v0.2.0

type SpeechEventKind string

SpeechEventKind is what happened, to whom, and at which layer.

The user appears at two layers, and they answer different questions. UserSpeech* is the speech itself, as the voice activity detector heard it: speech that never becomes a turn (a cough, a false start, a pause mid-sentence) appears only here. UserTurn* is the turn strategy's ruling on that speech, which is what the rest of the pipeline acts on, and follows the speech by however long the ruling took.

const (
	UserSpeechStarted SpeechEventKind = "user_speech_started"
	UserSpeechStopped SpeechEventKind = "user_speech_stopped"
	UserTurnStarted   SpeechEventKind = "user_turn_started"
	UserTurnStopped   SpeechEventKind = "user_turn_stopped"
	BotSpeechStarted  SpeechEventKind = "bot_speech_started"
	BotSpeechStopped  SpeechEventKind = "bot_speech_stopped"
	Interruption      SpeechEventKind = "interruption"
)

The moments a conversation is made of.

type StartupTiming

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

StartupTiming measures what starting a pipeline costs, processor by processor.

A processor does its startup work while handling the StartFrame: connecting to a provider, authenticating, loading a model. The observer times the gap between that frame reaching the processor and the processor passing it on, which is exactly that work, and reports the lot once the pipeline is up.

It reports separately on the transport, which is the other half of how long a call takes to become answerable: how long after the pipeline started the bot joined the session, and how long until the first client did.

func NewStartupTiming

func NewStartupTiming(cfg StartupTimingConfig) *StartupTiming

NewStartupTiming builds a StartupTiming observer.

func (*StartupTiming) OnPipelineSetupStarted added in v0.1.0

func (o *StartupTiming) OnPipelineSetupStarted(at time.Time)

OnPipelineSetupStarted implements processor.SetupStartedObserver. Processors connect while they are being set up, so startup begins here rather than at the StartFrame.

func (*StartupTiming) OnPipelineStarted added in v0.1.0

func (o *StartupTiming) OnPipelineStarted()

OnPipelineStarted implements processor.PipelineStartedObserver. The pipeline being up is what says every processor has started, so it is where the report is made.

func (*StartupTiming) OnProcessFrame added in v0.1.0

func (o *StartupTiming) OnProcessFrame(data processor.FrameProcessed)

OnProcessFrame implements processor.ProcessObserver. It records the StartFrame reaching a processor, which is where that processor's startup begins.

func (*StartupTiming) OnProcessorSetup added in v0.1.0

func (o *StartupTiming) OnProcessorSetup(data processor.ProcessorSetUp)

OnProcessorSetup implements processor.SetupObserver. It records what a processor's setup cost, which is the part of getting ready it spends connecting.

func (*StartupTiming) OnPushFrame added in v0.1.0

func (o *StartupTiming) OnPushFrame(data processor.FramePushed)

OnPushFrame implements processor.Observer. It closes the measurement a processor opened, and watches for the transport's connection milestones.

type StartupTimingConfig added in v0.1.0

type StartupTimingConfig struct {
	// Track selects the processors to measure. When nil every processor is
	// measured except the pipeline plumbing: the pipelines themselves, and the
	// sources they wrap the head of their chains in.
	Track func(processor.Processor) bool
	// OnStartupTimingReport is called once, when the pipeline has started, with
	// what each processor cost. It is not called when nothing was measured.
	OnStartupTimingReport func(r StartupTimingReport)
	// OnTransportTimingReport is called once, when the first client connects,
	// with how long the transport took to get there.
	OnTransportTimingReport func(r TransportTimingReport)
}

StartupTimingConfig configures a StartupTiming observer.

type StartupTimingReport added in v0.1.0

type StartupTimingReport struct {
	// StartTime is the wall-clock time at which the pipeline began setting up.
	StartTime time.Time
	// TotalDuration is the wall-clock time from the pipeline starting to set up
	// until it had started. Processors are set up concurrently, so it is the
	// span rather than the sum of what each of them cost. It is SetupPhase and
	// StartPhase back to back.
	TotalDuration time.Duration
	// SetupPhase is how long getting every processor ready took. Setting up runs
	// concurrently, so the longest single piece of work decides this rather than
	// their sum.
	SetupPhase time.Duration
	// StartPhase is how long the StartFrame took to travel the pipeline. It
	// reaches processors one after another, so what each spends on it adds up.
	StartPhase time.Duration
	// ProcessorTimings is what each processor cost, in the order the StartFrame
	// left them.
	ProcessorTimings []ProcessorStartupTiming
}

StartupTimingReport is what every measured processor cost to start.

type TTFBBreakdown added in v0.1.0

type TTFBBreakdown struct {
	// Processor is the name of the processor that reported it.
	Processor string
	// Model is the model it is attributed to, "" when unknown.
	Model string
	// StartTime is the wall-clock time the measurement started at.
	StartTime time.Time
	// Duration is the measured time to first byte.
	Duration time.Duration
}

TTFBBreakdown is one time-to-first-byte measurement, placed on the timeline of the reply it belongs to.

type TextAggregationBreakdown added in v0.1.0

type TextAggregationBreakdown struct {
	// Processor is the name of the processor that reported it.
	Processor string
	// StartTime is the wall-clock time the measurement started at.
	StartTime time.Time
	// Duration is the measured aggregation time.
	Duration time.Duration
}

TextAggregationBreakdown is one text-aggregation measurement, placed on the timeline of the reply it belongs to.

type TranscriptionLog added in v0.1.0

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

TranscriptionLog logs what a speech-to-text service heard, final transcripts and interim ones alike. Only what a transcriber produced is reported, so a transcript arriving from somewhere else is left alone.

func NewTranscriptionLog added in v0.1.0

func NewTranscriptionLog(cfg TranscriptionLogConfig) *TranscriptionLog

NewTranscriptionLog builds a TranscriptionLog observer.

func (*TranscriptionLog) OnPushFrame added in v0.1.0

func (o *TranscriptionLog) OnPushFrame(data processor.FramePushed)

OnPushFrame implements processor.Observer.

type TranscriptionLogConfig added in v0.1.0

type TranscriptionLogConfig struct {
	// Logger is the destination; slog.Default() when nil.
	Logger *slog.Logger
}

TranscriptionLogConfig configures a TranscriptionLog observer.

type TransportTimingReport added in v0.1.0

type TransportTimingReport struct {
	// StartTime is the wall-clock time at which the pipeline began setting up.
	StartTime time.Time
	// BotConnected is how long after the pipeline began setting up the bot
	// itself joined
	// the session. It is nil on a transport that never reports the bot joining,
	// which is every transport that is not an SFU.
	BotConnected *time.Duration
	// ClientConnected is how long after the pipeline began setting up the first
	// remote participant connected.
	ClientConnected time.Duration
}

TransportTimingReport is how long the transport took to reach the points at which a conversation can actually happen.

type TurnTrace added in v0.1.0

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

TurnTrace traces a conversation and its turns. The conversation span opens with the pipeline and lasts the whole session; each turn opens a span beneath it, and the service spans of that turn nest under it in turn, so one session is one trace shaped like the conversation it recorded.

It observes only the pipeline start; the turns themselves are reported to it by a TurnTracking observer, and the response latency by a UserBotLatency observer, through TurnStarted, TurnEnded and LatencyMeasured.

func NewTurnTrace added in v0.1.0

func NewTurnTrace(cfg TurnTraceConfig) *TurnTrace

NewTurnTrace builds a TurnTrace observer.

func (*TurnTrace) CurrentTurnContext added in v0.2.0

func (o *TurnTrace) CurrentTurnContext() trace.SpanContext

CurrentTurnContext is the span context of the turn being traced, for a caller creating a span beneath it. The zero value means no turn is open.

func (*TurnTrace) EndConversation added in v0.1.0

func (o *TurnTrace) EndConversation()

EndConversation closes the conversation span, and any turn still open with it. The task calls it when the pipeline has stopped. A nil observer — a task that is not tracing — has nothing to close.

func (*TurnTrace) LatencyMeasured added in v0.1.0

func (o *TurnTrace) LatencyMeasured(d time.Duration)

LatencyMeasured records the user-perceived response latency on the turn it was measured in. Wire it to a UserBotLatency observer's OnLatency.

func (*TurnTrace) OnPushFrame added in v0.1.0

func (o *TurnTrace) OnPushFrame(data processor.FramePushed)

OnPushFrame implements processor.Observer. The conversation span opens on the StartFrame rather than with the first turn, so whatever a bot does before the user speaks — a greeting, a flow initializing — is part of the conversation.

func (*TurnTrace) StartConversation added in v0.1.0

func (o *TurnTrace) StartConversation(id string)

StartConversation opens the conversation span under id, generating one when id is empty. The task calls it before the pipeline runs, and the StartFrame handler above calls it for an observer wired up by hand. Whichever comes first opens the span; the other finds it open and returns. A nil observer (a task that is not tracing) has nothing to open.

func (*TurnTrace) TurnContext added in v0.2.0

func (o *TurnTrace) TurnContext(turn int) trace.SpanContext

TurnContext is the span context of the given turn, for a caller creating a span beneath a turn that may already have ended. The zero value means the turn was never traced.

func (*TurnTrace) TurnEnded added in v0.1.0

func (o *TurnTrace) TurnEnded(turn int, d time.Duration, interrupted bool)

TurnEnded closes the span for a turn, recording how long it ran and whether it was cut short. Wire it to a TurnTracking observer's OnTurnEnded.

func (*TurnTrace) TurnStarted added in v0.1.0

func (o *TurnTrace) TurnStarted(turn int)

TurnStarted opens the span for a turn. Wire it to a TurnTracking observer's OnTurnStarted.

type TurnTraceConfig added in v0.1.0

type TurnTraceConfig struct {
	// Tracing is the pipeline's tracing context, which the observer writes as
	// the conversation and its turns begin and end. Required: it is what the
	// services read to parent their spans to the turn being spoken.
	Tracing *tracing.TracingContext
	// ConversationID names the conversation; empty generates one.
	ConversationID string
	// Attributes are set on the conversation span on top of the ones the
	// observer sets itself, and are where the keys a trace backend reads from
	// the root span belong (a session id, a user id, tags).
	Attributes []attribute.KeyValue
}

TurnTraceConfig configures a TurnTrace observer.

type TurnTracking

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

TurnTracking tracks conversational turns. The first turn starts with the pipeline; a turn ends when the bot finishes speaking (after TurnEndTimeout) or is interrupted by the user, at which point the next turn starts.

A turn is timed on the pipeline clock, from the frame that opened it to the frame that closed it. A turn ended by the timeout is therefore measured to the moment the bot fell silent, not to the moment the timer fired: the wait exists to tell a pause apart from an ending, and it is not part of the turn.

func NewTurnTracking

func NewTurnTracking(cfg TurnTrackingConfig) *TurnTracking

NewTurnTracking builds a TurnTracking observer.

func (*TurnTracking) Cleanup added in v0.3.0

func (o *TurnTracking) Cleanup(context.Context) error

Cleanup cancels the pending turn-end timer. It implements processor.CleanupObserver.

The pipeline can be torn down before this observer receives its EndFrame or CancelFrame, and the timer would then fire on a finished pipeline, ending a turn after the run, while its callback keeps the pipeline in memory.

func (*TurnTracking) ObserveEveryPush added in v0.3.0

func (o *TurnTracking) ObserveEveryPush() bool

ObserveEveryPush implements processor.EveryPushObserver: a frame is counted once, on its first push.

func (*TurnTracking) OnPushFrame added in v0.1.0

func (o *TurnTracking) OnPushFrame(data processor.FramePushed)

OnPushFrame implements processor.Observer.

func (*TurnTracking) OnTurnEnded added in v0.1.0

func (o *TurnTracking) OnTurnEnded(fn func(turn int, duration time.Duration, interrupted bool))

OnTurnEnded adds a listener called when a turn ends, alongside the one the config carries and any added before it.

type TurnTrackingConfig

type TurnTrackingConfig struct {
	// MaxFrames is unused.
	//
	// Deprecated: the observer is told about each frame once, so it keeps no
	// window of the frames it has seen.
	MaxFrames int
	// TurnEndTimeout is how long after the bot stops speaking a turn ends; 0 uses
	// 2.5s. The delay lets a turn survive a brief gap between bot utterances (an
	// HTTP TTS boundary, a function call) without splitting into two turns.
	TurnEndTimeout time.Duration
	// OnTurnStarted is called when a turn begins, with the 1-based turn number.
	OnTurnStarted func(turn int)
	// OnTurnEnded is called when a turn ends, with the turn number, its duration,
	// and whether it was cut short by an interruption.
	OnTurnEnded func(turn int, duration time.Duration, interrupted bool)
}

TurnTrackingConfig configures a TurnTracking observer.

type UserBotLatency

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

UserBotLatency measures the response latency of each turn: the gap between the user stopping speaking and the bot starting. Alongside each measurement it reports a LatencyBreakdown accounting for where that time went, and it reports separately on the first thing the bot says after a client connects.

It watches downstream frames only. A frame broadcast in both directions is therefore counted once, on the way down.

func NewUserBotLatency

func NewUserBotLatency(cfg LatencyConfig) *UserBotLatency

NewUserBotLatency builds a UserBotLatency observer.

func (*UserBotLatency) ObserveEveryPush added in v0.3.0

func (o *UserBotLatency) ObserveEveryPush() bool

ObserveEveryPush implements processor.EveryPushObserver: a frame is counted once, on its first push.

func (*UserBotLatency) OnPipelineStarted added in v0.2.0

func (o *UserBotLatency) OnPipelineStarted()

OnPipelineStarted implements processor.PipelineStartedObserver. The StartFrame has reached every processor by now, which is where the startup report stops measuring.

func (*UserBotLatency) OnPushFrame added in v0.1.0

func (o *UserBotLatency) OnPushFrame(data processor.FramePushed)

OnPushFrame implements processor.Observer.

Jump to

Keyboard shortcuts

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