pipeline

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: BSD-2-Clause Imports: 30 Imported by: ? 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 pipeline connects frame processors into a chain and drives them.

A Pipeline links a sequence of processors between a source and a sink. A Task runs a pipeline for one session: it sends the StartFrame, pushes frames, and shuts the pipeline down on an EndFrame or CancelFrame. A Runner runs a Task and ends it on an interrupt signal.

Example

A pipeline is a chain of processors, and a worker runs it. Frames queued on the worker enter at the head; an EndFrame ends the run once everything before it has gone through.

package main

import (
	"context"
	"fmt"

	"github.com/gojargo/jargo/frames"
	"github.com/gojargo/jargo/pipeline"
	"github.com/gojargo/jargo/processor"
	"github.com/gojargo/jargo/workers"
)

// printer prints the text of every TextFrame and passes every frame on.
type printer struct {
	*processor.Base
}

func newPrinter() *printer {
	p := &printer{}
	p.Base = processor.New("Printer", p)
	return p
}

func (p *printer) ProcessFrame(ctx context.Context, f frames.Frame, dir processor.Direction) error {
	if err := p.Base.ProcessFrame(ctx, f, dir); err != nil {
		return err
	}
	if t, ok := f.(*frames.TextFrame); ok {
		fmt.Println(t.Text)
	}
	return p.PushFrame(ctx, f, dir)
}

// A pipeline is a chain of processors, and a worker runs it. Frames queued on
// the worker enter at the head; an EndFrame ends the run once everything
// before it has gone through.
func main() {
	worker := pipeline.NewWorker(pipeline.New(newPrinter()), pipeline.WorkerConfig{})
	worker.QueueFrames([]frames.Frame{
		frames.NewTextFrame("Hello"),
		frames.NewTextFrame("world"),
		frames.NewEndFrame(),
	})
	if err := worker.Run(context.Background(), workers.Params{}); err != nil {
		fmt.Println("error:", err)
	}
}
Output:
Hello
world

Index

Examples

Constants

View Source
const (
	// EventFrameReachedUpstream fires for a frame reaching the start of the
	// pipeline that ReachedUpstreamFilter selects, carrying that frame.
	EventFrameReachedUpstream = "on_frame_reached_upstream"
	// EventFrameReachedDownstream fires for a frame reaching the end of the
	// pipeline that ReachedDownstreamFilter selects, carrying that frame.
	EventFrameReachedDownstream = "on_frame_reached_downstream"
	// EventHeartbeatTimeout fires when no heartbeat has reached the end of the
	// pipeline within the monitor timeout, and again every interval for as long
	// as the silence lasts. It carries nothing.
	EventHeartbeatTimeout = "on_heartbeat_timeout"
	// EventIdleTimeout fires when the pipeline has gone idle, before it is
	// canceled. It carries nothing.
	EventIdleTimeout = "on_idle_timeout"
	// EventPipelineStarted fires once the StartFrame has traveled the whole
	// pipeline, meaning every processor is up, carrying that frame.
	EventPipelineStarted = "on_pipeline_started"
	// EventPipelineFinished fires once the pipeline has reached a terminal
	// state, carrying the frame that ended it: an EndFrame, a StopFrame or a
	// CancelFrame. It fires for a CancelFrame even when the frame never arrived
	// and the wait timed out, so a caller always hears the run end.
	EventPipelineFinished = "on_pipeline_finished"
	// EventPipelineFlushed fires when a flush has made its whole trip through
	// this worker's pipeline, so every frame queued ahead of it has been
	// processed, carrying the flush's last probe. Its FlushID tells flushes
	// apart; start one with FlushWithProbe to know it beforehand. It fires for a
	// PipelineFlushFrame queued directly too, and, for a probe that crossed in
	// from another worker, on the worker that answered it.
	EventPipelineFlushed = "on_pipeline_flushed"
	// EventPipelineTimeout fires when a frame the worker was waiting on never
	// reached the end of the pipeline: the StartFrame within StartTimeout, or a
	// CancelFrame within CancelTimeout. Handlers receive the worker and that
	// frame. Nothing else tells an application its pipeline never came up.
	EventPipelineTimeout = "on_pipeline_timeout"
	// EventSetupTimeout fires when the processors did not all finish being set
	// up within SetupTimeout. Handlers receive the worker.
	EventSetupTimeout = "on_setup_timeout"
	// EventPipelineError fires for every error frame reaching the start of the
	// pipeline, fatal or not, carrying that frame. A fatal one also cancels the
	// worker, after the handlers have run.
	EventPipelineError = "on_pipeline_error"
)

The events a pipeline worker raises, on top of the ones every worker raises.

View Source
const EventServiceSwitched = "on_service_switched"

EventServiceSwitched is raised by a switcher strategy whenever the active service changes, with the service now active. Every handler attached runs, asynchronously, off the frame path that made the switch.

View Source
const FlushNoProgressTimeout = 5 * time.Second

FlushNoProgressTimeout is how long a flush waits with nothing happening before it gives up. It bounds the quiet, not the flush: a pipeline that keeps working keeps the wait alive however long it takes.

Variables

View Source
var ErrFlushNoProgress = errors.New("pipeline flush gave up with nothing happening")

ErrFlushNoProgress is returned by Flush when the pipeline went quiet without the probe coming back.

Functions

func AnyFrame added in v0.1.0

func AnyFrame(frames.Frame) bool

AnyFrame is a filter selecting every frame, for a caller that really does want to watch the whole stream. Prefer FrameTypes: a handler that runs on every frame runs on the goroutine the frame arrived on, so it is on the path of everything the pipeline does.

func FrameTypes added in v0.1.0

func FrameTypes(exemplars ...frames.Frame) func(frames.Frame) bool

FrameTypes returns a filter selecting frames of the type of one of the exemplars, or of a type built on it. An exemplar is read for its type alone and never enters a pipeline, so an empty literal is enough:

pipeline.FrameTypes(&frames.TTSStoppedFrame{}, &frames.BotStoppedSpeakingFrame{})

A frame whose type embeds an exemplar's is selected too: naming TextFrame selects LLM tokens and transcriptions. A filter cannot name an interface; write the predicate directly for that:

func(f frames.Frame) bool { _, ok := f.(frames.SystemFrame); return ok }

func Or added in v0.1.0

func Or(a, b func(frames.Frame) bool) func(frames.Frame) bool

Or returns a filter selecting whatever either filter selects. A nil filter means nothing was set rather than everything was, so combining with one returns the other.

Types

type BaseSwitcherStrategy added in v1.0.0

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

BaseSwitcherStrategy keeps a switcher's services and the one that is active, and switches nowhere on its own: HandleFrame and HandleError return nil. A strategy embeds it and overrides either, calling SetActiveIfAvailable to switch.

func NewBaseSwitcherStrategy added in v1.0.0

func NewBaseSwitcherStrategy(self SwitcherStrategy, services []processor.Processor) *BaseSwitcherStrategy

NewBaseSwitcherStrategy builds the base of a strategy choosing between services, the first of which starts active. self is the strategy embedding it, which EventServiceSwitched names as its source; nil names the base.

func (*BaseSwitcherStrategy) ActiveService added in v1.0.0

func (b *BaseSwitcherStrategy) ActiveService() processor.Processor

ActiveService implements SwitcherStrategy.

func (*BaseSwitcherStrategy) Events added in v1.0.0

func (b *BaseSwitcherStrategy) Events() *event.Registry

Events implements SwitcherStrategy.

func (*BaseSwitcherStrategy) HandleError added in v1.0.0

HandleError does nothing: the base switches on no error.

func (*BaseSwitcherStrategy) HandleFrame added in v1.0.0

HandleFrame does nothing: the base switches on no frame.

func (*BaseSwitcherStrategy) Services added in v1.0.0

func (b *BaseSwitcherStrategy) Services() []processor.Processor

Services implements SwitcherStrategy.

func (*BaseSwitcherStrategy) SetActiveIfAvailable added in v1.0.0

func (b *BaseSwitcherStrategy) SetActiveIfAvailable(target frames.ServiceTarget) processor.Processor

SetActiveIfAvailable activates target if it is one of the strategy's services, and returns it, or nil if it did not switch. A target it does not manage is left alone, since the request was meant for another switcher. A service that can no longer do its job is refused: making it active would only route work to something that cannot handle it. Bring it back with its own SetUsable first, once whatever stopped it working has been dealt with.

func (*BaseSwitcherStrategy) UsableServices added in v1.0.0

func (b *BaseSwitcherStrategy) UsableServices() []processor.Processor

UsableServices are the services that can still be given work, in order.

type FrameOrder added in v0.1.0

type FrameOrder int

FrameOrder is the order a SyncParallelPipeline pushes the output of one input frame in, once every branch has produced it.

const (
	// FrameOrderArrival pushes frames in the order they arrive from any branch.
	// It is the zero value, and so the default.
	FrameOrderArrival FrameOrder = iota
	// FrameOrderPipeline pushes frames in branch order: everything the first
	// branch produced, then the second, and so on. Use it when the order between
	// branches matters, to keep an image ahead of the audio that goes with it.
	FrameOrderPipeline
)

type LLMMember added in v0.1.0

type LLMMember interface {
	processor.Processor
	// SyncToolHandlers brings the service's tool registry into line with the
	// toolset a conversation advertises.
	SyncToolHandlers(ctx context.Context, tools frames.ToolsSchema)
	// RegisterFunction records a handler for a tool the model may call.
	RegisterFunction(name string, h llm.FunctionCallHandler, opts ...llm.RegisterOption)
}

LLMMember is what an LLM switcher needs of each language model service it manages. The LLM service base satisfies it, so any service built on that base can be a member.

type LLMSwitcher added in v0.1.0

type LLMSwitcher struct {
	*ServiceSwitcher
	// contains filtered or unexported fields
}

LLMSwitcher routes the conversation through one of several language model services at a time, so a call can move to a stronger model when it gets hard, or to another provider when one stops answering.

It is a ServiceSwitcher that also keeps the members in step on the things a conversation carries rather than the pipeline: the tools it advertises and the handlers registered for them. An inactive model sits behind a closed filter and would otherwise never see them, and would then be out of step with what the model is told it can call the moment it becomes active.

func NewLLMSwitcher added in v0.1.0

func NewLLMSwitcher(llms []LLMMember, newStrategy StrategyFunc) (*LLMSwitcher, error)

NewLLMSwitcher builds a switcher over llms, the first of which starts active, choosing between them with the strategy newStrategy builds. A nil newStrategy switches only when asked.

func (*LLMSwitcher) ActiveLLM added in v0.1.0

func (s *LLMSwitcher) ActiveLLM() LLMMember

ActiveLLM is the language model service currently in use.

func (*LLMSwitcher) LLMService added in v0.2.0

func (s *LLMSwitcher) LLMService()

LLMService marks the switcher as a language-model service.

It is what the rest of the pipeline talks to in place of one, and frames from the active service leave through the switcher's own PushFrame, so without this nothing arriving from an LLM looks like it came from an LLM. The observer that logs what a model was given and what it produced was silent for every pipeline built on a switcher, which is every pipeline with a failover chain.

func (*LLMSwitcher) LLMs added in v0.1.0

func (s *LLMSwitcher) LLMs() []LLMMember

LLMs are the language model services the switcher manages.

func (*LLMSwitcher) ProcessFrame added in v0.1.0

func (s *LLMSwitcher) ProcessFrame(ctx context.Context, f frames.Frame, dir processor.Direction) error

ProcessFrame keeps every member's tool handlers in step with the conversation.

Only the active service receives the conversation, so it alone would pick up the handlers the advertised tools carry. The others are synced here, from outside the branches, so whichever becomes active next already knows how to answer what the model may call.

func (*LLMSwitcher) RegisterFunction added in v0.1.0

func (s *LLMSwitcher) RegisterFunction(
	name string, h llm.FunctionCallHandler, opts ...llm.RegisterOption,
)

RegisterFunction records a handler on every member, active or not, so a tool keeps working across a switch.

func (*LLMSwitcher) RunInference added in v0.1.0

func (s *LLMSwitcher) RunInference(
	ctx context.Context, convo *frames.LLMContext, opts llm.InferenceOptions,
) (string, bool, error)

RunInference answers a conversation once on the active service, off to the side of the pipeline. It reports false if the active service cannot answer off-pipeline.

type ParallelPipeline

type ParallelPipeline struct {
	*processor.Base
	// contains filtered or unexported fields
}

ParallelPipeline runs several sub-pipelines, the branches, concurrently. Every frame entering the parallel pipeline is fanned out to all branches, and frames emerging from the branches are merged back out. A frame that more than one branch forwards unchanged escapes only once: the merge deduplicates by frame id.

Lifecycle frames (StartFrame, EndFrame and CancelFrame) are synchronized. On one of those the parallel pipeline pauses its own frame handling and lets a single copy continue only once every branch has processed it, buffering any other frames a branch emits in the meantime (flushing them after a StartFrame, before an EndFrame or CancelFrame). Three things go wrong without this:

  • StartFrame: a fast branch completing first would let processors in the other branches receive frames before their StartFrame.
  • EndFrame: an EndFrame escaping from a fast branch would shut downstream processors down while a slower branch still had output to flush.
  • CancelFrame: the Task waits for the CancelFrame to reach the pipeline sink, so one escaping early would make it consider cancellation complete while slower branches were still running.

A ParallelPipeline is itself a processor, so it nests inside a Pipeline.

The deduplication set holds the frames that escaped the parallel pipeline weakly: a frame nothing holds any more cannot come back out of a branch, so its entry goes with it, and the set stays as large as the frames in flight.

func NewParallel

func NewParallel(branches ...[]processor.Processor) (*ParallelPipeline, error)

NewParallel builds a ParallelPipeline from one or more branches, each a list of processors connected in order. It returns an error if no branch is given.

func (*ParallelPipeline) Cleanup

func (p *ParallelPipeline) Cleanup(ctx context.Context) error

Cleanup cleans up the parallel pipeline and every branch.

func (*ParallelPipeline) EntryProcessors added in v0.1.0

func (p *ParallelPipeline) EntryProcessors() []processor.Processor

EntryProcessors returns the branches: a frame entering the parallel pipeline is fanned out to all of them.

func (*ParallelPipeline) ProcessFrame

func (p *ParallelPipeline) ProcessFrame(ctx context.Context, f frames.Frame, dir processor.Direction) error

ProcessFrame fans a frame out to every branch. For a lifecycle frame it first arms the synchronization counter and pauses its own frame handling, so nothing else is fanned out until the last branch reports the frame back and the sink resumes it.

func (*ParallelPipeline) Processors added in v0.1.0

func (p *ParallelPipeline) Processors() []processor.Processor

Processors returns the branches.

func (*ParallelPipeline) ProcessorsWithMetrics added in v0.1.0

func (p *ParallelPipeline) ProcessorsWithMetrics() []processor.Processor

ProcessorsWithMetrics returns the processors across every branch that report metrics.

func (*ParallelPipeline) Setup

Setup sets up the parallel pipeline and every branch.

type Params added in v0.1.0

type Params struct {
	// AudioInSampleRate is the StartFrame input sample rate; default 16000.
	AudioInSampleRate int
	// AudioOutSampleRate is the StartFrame output sample rate; default 24000.
	AudioOutSampleRate int
	// EnableExpressiveConversation is whether the agent takes part in an
	// expressive conversation (alpha). TTS services then read the expression
	// tags an LLM writes into its reply instead of speaking them.
	EnableExpressiveConversation bool
	// ExpressionPolicy is which expression tags the LLMs are offered and when
	// to use them, with expressive conversation on. Nil offers every tag the
	// TTS service performs among the core ones, with no guidance. Part of
	// expressive conversation (alpha).
	ExpressionPolicy *expressive.ExpressionPolicy
	// EnableMetrics enables performance-metrics collection across the pipeline.
	EnableMetrics bool
	// EnableUsageMetrics enables usage-metrics collection (e.g. LLM token usage)
	// across the pipeline.
	EnableUsageMetrics bool
	// StartMetadata is carried on the StartFrame, where every processor sees it
	// at setup. It is for the values a whole session is stamped with, a call id
	// or a tenant say, that a processor or an observer needs and the framework
	// knows nothing about.
	StartMetadata map[string]any
	// ReportOnlyInitialTTFB reports each service's first time-to-first-byte and
	// no more, for a consumer who wants the figure the call opened with rather
	// than one per turn. It only applies when EnableMetrics is set.
	ReportOnlyInitialTTFB bool
	// SendInitialEmptyMetrics sends a zeroed MetricsFrame for every processor
	// that reports metrics once the pipeline is ready, so a consumer knows which
	// processors to expect metrics from before any have been measured; nil
	// defaults to true. It only applies when EnableMetrics is set.
	SendInitialEmptyMetrics *bool
	// EnableHeartbeats sends a heartbeat through the pipeline at a fixed
	// interval and reports when one stops coming out the far end, which is how a
	// caller tells a pipeline that is quiet from one that is stuck.
	EnableHeartbeats bool
	// HeartbeatPeriod is how often a heartbeat is sent; zero defaults to one
	// second. It only applies when EnableHeartbeats is set.
	HeartbeatPeriod time.Duration
	// HeartbeatMonitorTimeout is how long to go without a heartbeat reaching the
	// end of the pipeline before saying so; zero defaults to ten seconds. It only
	// applies when EnableHeartbeats is set.
	HeartbeatMonitorTimeout time.Duration
}

Params is what the pipeline itself is told when it starts: the values that ride on the StartFrame and reach every processor at setup. Anything about the worker rather than the pipeline belongs in WorkerConfig.

type Pipeline

type Pipeline struct {
	*processor.Base
	// contains filtered or unexported fields
}

Pipeline is a linear chain of processors. It wraps the chain with a source and a sink so frames can be fed in and observed at the edges, and is itself a processor, so pipelines can nest.

func New

func New(procs ...processor.Processor) *Pipeline

New builds a Pipeline from procs, connected in order. Frames pushed out of the chain's source and sink are forwarded to the pipeline's own neighbors.

func (*Pipeline) Cleanup

func (p *Pipeline) Cleanup(ctx context.Context) error

Cleanup cleans up the pipeline and every processor in the chain.

func (*Pipeline) EntryProcessors added in v0.1.0

func (p *Pipeline) EntryProcessors() []processor.Processor

EntryProcessors returns the source, which every frame entering the pipeline reaches first.

func (*Pipeline) ProcessFrame

func (p *Pipeline) ProcessFrame(ctx context.Context, f frames.Frame, dir processor.Direction) error

ProcessFrame routes a frame into the chain: downstream frames enter at the source, upstream frames enter at the sink.

func (*Pipeline) Processors added in v0.1.0

func (p *Pipeline) Processors() []processor.Processor

Processors returns the chain, source and sink included.

func (*Pipeline) ProcessorsWithMetrics added in v0.1.0

func (p *Pipeline) ProcessorsWithMetrics() []processor.Processor

ProcessorsWithMetrics returns the processors in the chain that report metrics, including those inside a nested pipeline.

func (*Pipeline) Setup

func (p *Pipeline) Setup(ctx context.Context, s processor.Setup) error

Setup sets up the pipeline and every processor in the chain.

type ProcessorUnusablePolicy added in v0.1.0

type ProcessorUnusablePolicy string

ProcessorUnusablePolicy is what a pipeline worker does when a processor can no longer do its job.

An unusable processor keeps failing for as long as the pipeline keeps using it, so the pipeline has to decide whether it is still worth running.

const (
	// UnusableContinue reports the error and keeps running. The application
	// decides what to do, by failing over to another provider for instance. It
	// is the zero value, and so the default.
	UnusableContinue ProcessorUnusablePolicy = ""
	// UnusableEnd ends the pipeline gracefully, letting queued frames drain
	// first.
	UnusableEnd ProcessorUnusablePolicy = "end"
	// UnusableCancel cancels the pipeline immediately, abandoning queued frames.
	UnusableCancel ProcessorUnusablePolicy = "cancel"
)

The policies a worker can take on an unusable processor.

type ServiceSwitcher

type ServiceSwitcher struct {
	*ParallelPipeline
	// contains filtered or unexported fields
}

ServiceSwitcher routes the pipeline through one of several interchangeable services at a time. Every service is started and kept warm, but only the active one receives data; the rest are gated off.

It is a ParallelPipeline: each service becomes a branch wrapped in a pair of filters that pass lifecycle frames (so every service stays ready) but gate everything else on whether that service is active. What leaves the switcher is decided on the way out, which is where the copies the gating produces are dropped so the rest of the pipeline sees one service, not several.

Two kinds of frame are exceptions to the gating. A settings update addressed to a member service reaches it whether or not it is in use, and one marked ReachInactiveServices reaches every member, so whichever service becomes active later is already configured. And metadata from a service outside the switcher reaches every member, so a member that reads another service's metadata has it when it becomes active. It travels on once, from the active member, as it would through that service alone. A switcher is only as dead as its last service, so its own usability is a reading of theirs rather than a state of its own.

func NewServiceSwitcher

func NewServiceSwitcher(
	services []processor.Processor, newStrategy StrategyFunc,
) (*ServiceSwitcher, error)

NewServiceSwitcher builds a switcher over services, the first of which starts active, choosing between them with the strategy newStrategy builds. A nil newStrategy switches only when asked.

func (*ServiceSwitcher) ActiveService

func (s *ServiceSwitcher) ActiveService() processor.Processor

ActiveService is the service currently in use.

func (*ServiceSwitcher) ProcessFrame added in v0.1.0

func (s *ServiceSwitcher) ProcessFrame(ctx context.Context, f frames.Frame, dir processor.Direction) error

ProcessFrame steers the switcher on the frames that ask it to, and hands every settings update, and metadata from outside, to the member services the gating would otherwise keep it from.

func (*ServiceSwitcher) PushFrame added in v0.1.0

func (s *ServiceSwitcher) PushFrame(ctx context.Context, f frames.Frame, dir processor.Direction) error

PushFrame decides what leaves the switcher.

The branches are copies of one another as far as the rest of the pipeline is concerned, so what escapes has to be the active service's alone: its metadata, its settings update, its errors. It is also where a non-fatal error from the active service reaches the strategy, which is what drives failover.

func (*ServiceSwitcher) Services added in v0.1.0

func (s *ServiceSwitcher) Services() []processor.Processor

Services are the services the switcher manages.

func (*ServiceSwitcher) SetUsable added in v0.1.0

func (s *ServiceSwitcher) SetUsable(ctx context.Context, usable bool)

SetUsable ignores an attempt to set this switcher's usability directly.

A switcher has no usability of its own to set: what it reports is a reading of its services. Bring an individual service back with its own SetUsable, which brings the switcher back with it.

func (*ServiceSwitcher) Strategy added in v0.1.0

func (s *ServiceSwitcher) Strategy() SwitcherStrategy

Strategy is the strategy choosing between the switcher's services.

func (*ServiceSwitcher) Usable added in v0.1.0

func (s *ServiceSwitcher) Usable() bool

Usable reports whether any of the switched services can still be given work.

A switcher is only as dead as its last service: it can keep doing its job by moving work to a different one, so it reports itself unusable only once none of them can do theirs. This is a reading of the services rather than a state of its own, so bringing a service back with SetUsable brings the switcher back too, and calling that on the switcher itself does nothing. The switcher raises EventUsableChanged for itself as the reading moves, so watching it is enough to hear about the services it holds.

type StrategyFunc added in v0.1.0

type StrategyFunc func(services []processor.Processor) SwitcherStrategy

StrategyFunc builds a strategy over a set of services. A switcher is given the constructor rather than a built strategy, so the strategy is always paired with the services the switcher actually manages.

type SwitcherStrategy

type SwitcherStrategy interface {

	// Services are the services the strategy chooses between.
	Services() []processor.Processor
	// UsableServices are the services that can still be given work, in order.
	UsableServices() []processor.Processor
	// ActiveService is the service currently in use.
	ActiveService() processor.Processor
	// HandleFrame acts on a frame that steers the switcher, returning the
	// service it switched to, or nil if it did not switch. A frame it does not
	// act on travels on, so another switcher can have its turn.
	HandleFrame(f frames.Frame, dir processor.Direction) processor.Processor
	// HandleError reacts to a non-fatal error from the active service,
	// returning the service it switched to, or nil if it did not switch.
	//
	// It is called for every non-fatal error the active service reports,
	// whether or not the service can carry on from it, so the strategy decides
	// which errors are worth switching away from. ErrorFrame.Source.Usable()
	// tells a service that is finished from one having a bad moment.
	HandleError(ef *frames.ErrorFrame) processor.Processor
	// Events is where the strategy reports what it does: it raises
	// EventServiceSwitched whenever the active service changes.
	Events() *event.Registry
	// contains filtered or unexported methods
}

SwitcherStrategy decides which of a switcher's services is active and when that changes. Build one with a StrategyFunc.

Two are supplied: NewManualStrategy switches only when asked, and NewFailoverStrategy additionally moves on when the active service reports an error. For anything else, embed *BaseSwitcherStrategy and override HandleFrame or HandleError.

func NewFailoverStrategy added in v0.1.0

func NewFailoverStrategy(services []processor.Processor) SwitcherStrategy

NewFailoverStrategy builds a strategy that switches to the next service when the active one reports a non-fatal error, and can still be switched by hand. The failed service stays in the list and can be switched back to.

func NewManualStrategy added in v0.1.0

func NewManualStrategy(services []processor.Processor) SwitcherStrategy

NewManualStrategy builds a strategy that changes the active service only on an explicit request. The first service starts active.

type SyncFrame added in v0.1.0

type SyncFrame struct {
	frames.BaseControlFrame
}

SyncFrame is the sentinel sent in behind a frame to detect when a branch has finished with it. Frames are handled in order, so a SyncFrame coming out of a branch means everything that branch produced for the preceding frame has come out already.

func NewSyncFrame added in v0.1.0

func NewSyncFrame() *SyncFrame

NewSyncFrame builds a SyncFrame.

type SyncParallelPipeline added in v0.1.0

type SyncParallelPipeline struct {
	*processor.Base
	// contains filtered or unexported fields
}

SyncParallelPipeline runs several sub-pipelines, the branches, and holds the output of each input frame until every branch has finished producing it. For each frame it:

  1. sends the frame into every branch,
  2. sends a SyncFrame in behind it,
  3. waits for every branch to produce its SyncFrame, which means all the output for that input is ready,
  4. releases the collected frames, deduplicated by frame id since the same frame can come out of more than one branch.

The last processor of each branch has to be synchronous for this to work: the SyncFrame only means the branch is done because frames are handled in order.

System frames skip the mechanism and pass straight through, since they are meant to race ahead of data frames. A system frame also lands in the branch queues on its way through; every frame is pushed once, so the copies that come out later are dropped.

An EndFrame is its own sentinel: everything a branch produces before it is released, and the EndFrame itself is pushed once, after every branch's output.

Use it where output has to stay together, for instance an image and the speech describing it. Where branches are independent, ParallelPipeline is the lighter choice.

func NewSyncParallel added in v0.1.0

func NewSyncParallel(order FrameOrder, branches ...[]processor.Processor) (*SyncParallelPipeline, error)

NewSyncParallel builds a SyncParallelPipeline from one or more branches, each a list of processors connected in order, pushing output in the given order. It returns an error if no branch is given.

func (*SyncParallelPipeline) Cleanup added in v0.1.0

func (p *SyncParallelPipeline) Cleanup(ctx context.Context) error

Cleanup cleans up the sync parallel pipeline and every branch.

func (*SyncParallelPipeline) EntryProcessors added in v0.1.0

func (p *SyncParallelPipeline) EntryProcessors() []processor.Processor

EntryProcessors returns the branch sources, which a frame entering the sync parallel pipeline is handed to directly.

func (*SyncParallelPipeline) ProcessFrame added in v0.1.0

ProcessFrame sends a frame through every branch and releases the output once they have all finished with it.

func (*SyncParallelPipeline) Processors added in v0.1.0

func (p *SyncParallelPipeline) Processors() []processor.Processor

Processors returns the branches.

func (*SyncParallelPipeline) ProcessorsWithMetrics added in v0.1.0

func (p *SyncParallelPipeline) ProcessorsWithMetrics() []processor.Processor

ProcessorsWithMetrics returns the processors across every branch that report metrics.

func (*SyncParallelPipeline) Setup added in v0.1.0

Setup sets up the sync parallel pipeline and every branch.

type Worker added in v0.1.0

type Worker struct {
	*workers.Base
	// contains filtered or unexported fields
}

Worker runs a pipeline for a single session. It drives the lifecycle: it sends the StartFrame, waits for the pipeline to be ready, pushes queued frames, and shuts the pipeline down once an EndFrame or CancelFrame has traveled all the way through.

func NewWorker added in v0.1.0

func NewWorker(pipe processor.Processor, cfg WorkerConfig) *Worker

NewWorker wraps pipe in a Worker. pipe is usually a *Pipeline but may be any processor.

func (*Worker) ActivateWorker added in v0.1.0

func (t *Worker) ActivateWorker(ctx context.Context, workerName string, opts workers.ActivateOptions)

ActivateWorker activates another worker by name, draining this pipeline when handing over.

Deactivating this worker before its pipeline drains would let the target start producing while this worker's output is still in flight, and both would arrive interleaved. A worker that stays active is handing nothing over, so it does not wait: the first activation of a session would otherwise wait on the very worker it is about to wake. One that stays active and wants to drain anyway can call Flush before this.

func (*Worker) AddObserver added in v0.1.0

func (t *Worker) AddObserver(o processor.Observer)

AddObserver registers an observer while the pipeline runs, for something built after the task that wants to watch the frames going by. It watches from here on; what already happened is not replayed. Adding an observer that is already registered, here or through WorkerConfig.Observers, does nothing.

func (*Worker) AddReachedDownstreamFilter added in v0.1.0

func (t *Worker) AddReachedDownstreamFilter(f func(frames.Frame) bool)

AddReachedDownstreamFilter widens the downstream filter to select what f selects as well, so two consumers of the same task can each ask for their own frames without knowing about each other.

func (*Worker) AddReachedUpstreamFilter added in v0.1.0

func (t *Worker) AddReachedUpstreamFilter(f func(frames.Frame) bool)

AddReachedUpstreamFilter widens the upstream filter to select what f selects as well. See AddReachedDownstreamFilter.

func (*Worker) AppResources added in v0.5.0

func (t *Worker) AppResources() any

AppResources implements processor.PipelineWorker: what the application shares across the session, as WorkerConfig.AppResources gave it.

func (*Worker) Bridged added in v0.1.0

func (t *Worker) Bridged() bool

Bridged reports whether this worker's pipeline is on the bus, which is announced when the worker becomes ready so the others know it can be fed.

func (*Worker) Cancel added in v0.1.0

func (t *Worker) Cancel(ctx context.Context, reason string)

Cancel stops this worker's pipeline immediately by queueing a CancelFrame. It does nothing once the worker has finished.

It replaces the plain worker's cancel, which asks every worker in the session to stop: a pipeline worker stops by driving a frame through its own pipeline, so that each processor is told in turn. Call Base.Cancel for the session-wide one.

func (*Worker) Capabilities added in v0.3.0

func (t *Worker) Capabilities() capabilities.BotCapabilities

Capabilities is what the bot does in this session.

It is derived from the media the pipeline's transports send and receive and from Params.EnableMetrics, with WorkerConfig.Capabilities applied on top. A field no transport reports is nil (unknown). RTVI sends this to the client in bot-ready.

func (*Worker) End added in v0.1.0

func (t *Worker) End(ctx context.Context, reason string)

End asks for the session to end gracefully, draining this pipeline first, so that whatever the worker has already pushed reaches the end of the pipeline rather than being cut off wherever it happened to be.

func (*Worker) Flush added in v0.1.0

func (t *Worker) Flush(ctx context.Context) error

Flush waits for the pipeline to drain: it queues a PipelineFlushFrame probe down to the sink, then pushes a new probe back up to the source and a third down to the sink again, and blocks until that last one arrives. By then every frame queued ahead of the flush has been processed, along with anything a processor started by pushing upstream. Use it to let the pipeline settle, after an interruption say, before injecting new work.

The first probe goes on the worker's queue, behind whatever is already waiting there, so a frame handed to QueueFrame just before this call is covered too.

It returns ctx.Err() if ctx is done first, and ErrFlushNoProgress if the pipeline goes quiet for FlushNoProgressTimeout without the probe coming back. Progress is a frame reaching this worker's sink, or a report from the pipeline answering the probe once it has crossed into another worker. A pipeline still working keeps the wait alive; one that is stuck, or that nobody will answer, gives up after that much quiet.

The pipeline raises EventPipelineFlushed as the flush settles.

func (*Worker) FlushWithProbe added in v0.7.0

func (t *Worker) FlushWithProbe(ctx context.Context, probe *frames.PipelineFlushFrame) error

FlushWithProbe is Flush pushing probe, so the caller knows its FlushID before the flush starts, to match it in EventPipelineFlushed say. Its Done and Origin are set here, because the flush waits on Done and other workers report progress to Origin. A nil probe is a new one.

func (*Worker) HandleWorkerCancel added in v0.1.0

func (t *Worker) HandleWorkerCancel(ctx context.Context, m *bus.CancelWorkerMessage)

HandleWorkerCancel cancels the pipeline once the children have been told. See HandleWorkerEnd.

func (*Worker) HandleWorkerEnd added in v0.1.0

func (t *Worker) HandleWorkerEnd(ctx context.Context, m *bus.EndWorkerMessage)

HandleWorkerEnd ends the pipeline once the children have ended.

The end is driven through the pipeline as an EndFrame rather than stopping the worker where it stands, so every processor is told in turn and the worker is finished only once the frame has drained out the far end.

func (*Worker) HasFinished added in v0.1.0

func (t *Worker) HasFinished() bool

HasFinished reports whether the task has finished running.

func (*Worker) OnBusMessage added in v0.1.0

func (t *Worker) OnBusMessage(ctx context.Context, m bus.Message)

OnBusMessage handles the messages a pipeline worker acts on itself, after the handling every worker does.

A request to speak becomes a frame in this worker's pipeline. A pipeline with no speech in it simply lets the frame through.

The bus delivers from a goroutine of its own, which belongs to no session, so the message is handled through this worker's loop, as one step among the session's tasks.

func (*Worker) QueueFrame added in v0.1.0

func (t *Worker) QueueFrame(f frames.Frame, dir ...processor.Direction)

QueueFrame queues a frame to be pushed through the pipeline. The direction is optional and defaults to downstream, which enters at the start of the pipeline; pass processor.Upstream to enter at the end instead, which is how a caller replies to something the pipeline sent it. Only the first direction is read.

func (*Worker) QueueFrames added in v0.1.0

func (t *Worker) QueueFrames(fs []frames.Frame, dir ...processor.Direction)

QueueFrames queues several frames, in order. See QueueFrame for the direction.

func (*Worker) RTVI added in v0.1.0

func (t *Worker) RTVI() *rtvi.Processor

RTVI is the processor a client talks to, whether this worker added it or the pipeline already carried one. It is nil when the worker runs without RTVI.

func (*Worker) RemoveObserver added in v0.1.0

func (t *Worker) RemoveObserver(o processor.Observer)

RemoveObserver stops reporting to an observer registered earlier. It has stopped by the time this returns, so whatever the observer holds may be released. Removing one that was never registered does nothing.

An observer may remove itself from one of its own callbacks. It cannot wait for itself, so it is told nothing more once that callback returns.

func (*Worker) Run added in v0.1.0

func (t *Worker) Run(ctx context.Context, _ workers.Params) error

Run sets up the pipeline and drives it until an EndFrame or CancelFrame completes its journey through the pipeline, or ctx is canceled. It then cleans up the pipeline. Run blocks until the pipeline has finished.

The task manager in params is not used. A pipeline is a session, and a session runs its tasks on a loop of its own rather than on the one the runner shares among its workers: WorkerConfig.TaskManager, or one the worker builds. The worker owns it, and so reports its dangling tasks itself.

func (*Worker) SetReachedDownstreamFilter added in v0.1.0

func (t *Worker) SetReachedDownstreamFilter(f func(frames.Frame) bool)

SetReachedDownstreamFilter replaces the filter selecting which frames reaching the end of the pipeline are reported.

func (*Worker) SetReachedUpstreamFilter added in v0.1.0

func (t *Worker) SetReachedUpstreamFilter(f func(frames.Frame) bool)

SetReachedUpstreamFilter replaces the filter selecting which frames reaching the start of the pipeline are reported.

func (*Worker) StopWhenDone added in v0.1.0

func (t *Worker) StopWhenDone()

StopWhenDone schedules the pipeline to stop once all queued frames have been processed, by queueing an EndFrame.

func (*Worker) Tracing added in v0.1.0

func (t *Worker) Tracing() *tracing.Context

Tracing is the session's tracing state: the conversation span the trace hangs from and the turn being spoken. It is nil unless the task traces, and is what the processors are given at setup so their spans land under the right turn.

func (*Worker) TrackFlushProbe added in v0.1.0

func (t *Worker) TrackFlushProbe(f *frames.PipelineFlushFrame)

TrackFlushProbe records a probe from another worker that this pipeline is answering, so progress is reported back to whoever is waiting on it.

It is called by whatever brings the probe into this pipeline, since only that knows it is really coming in: every worker on the bus sees the frame, but most of them have nowhere to put it.

func (*Worker) TurnTrace added in v0.1.0

func (t *Worker) TurnTrace() *observers.TurnTrace

TurnTrace is the observer writing the conversation and turn spans. It is nil unless the task traces.

func (*Worker) TurnTracker added in v0.1.0

func (t *Worker) TurnTracker() processor.TurnTracker

TurnTracker follows the conversation's turns, for a processor that has to know where a turn ended. It is nil when the worker is not tracking turns. It implements processor.PipelineWorker.

func (*Worker) TurnTracking added in v0.1.0

func (t *Worker) TurnTracking() *observers.TurnTracking

TurnTracking is the observer following the conversation's turns. It is nil only when turn tracking has been turned off.

func (*Worker) WorkerRunner added in v1.1.0

func (t *Worker) WorkerRunner() any

WorkerRunner implements processor.WorkerRunnerHost.

type WorkerConfig added in v0.1.0

type WorkerConfig struct {
	// Name is what other workers address this one by. Empty names it after its
	// type, which suits a worker taking no part in worker-to-worker messaging.
	Name string
	// TypeName is the kind of worker an unnamed one is named after; empty is
	// PipelineWorker. A worker built on this one gives its own.
	TypeName string
	// Active reports whether the worker starts active; nil defaults to true.
	Active *bool
	// Params is what the pipeline is told when it starts.
	Params Params
	// Clock is the pipeline clock; a system clock is used when nil.
	Clock clock.Clock
	// AppResources is whatever the application wants to share across a session,
	// a database handle or an HTTP client say. It is passed by reference and
	// never read by the framework. A processor reaches it through its setup's
	// PipelineWorker, and a tool handler through FunctionCallParams.AppResources.
	AppResources any
	// CancelTimeout bounds the wait for a CancelFrame to travel the pipeline;
	// zero defaults to 20 seconds. Canceling is what a caller reaches for when
	// something has already gone wrong, so it must not be the thing that hangs:
	// a processor wedged somewhere would otherwise hold the shutdown open for
	// good. Reaching the timeout gives up on the frame and finishes the run. An
	// EndFrame is not bounded this way, since a graceful shutdown is expected to
	// flush whatever is in flight however long that takes.
	CancelTimeout time.Duration
	// SetupTimeout bounds the wait for every processor to finish being set up;
	// zero defaults to 20 seconds. A processor connects while it is set up, so
	// one that never connects would otherwise leave the run waiting on it with
	// nothing to time it out. Reaching the timeout abandons setting up, raises
	// EventSetupTimeout and tears down whatever came up, so Run returns rather
	// than hanging.
	SetupTimeout time.Duration
	// StartTimeout bounds the wait for the StartFrame to reach the end of the
	// pipeline; zero defaults to 20 seconds. A processor that blocks while
	// handling it leaves the pipeline half-started, and nothing pushed in
	// afterwards would be processed, so reaching the timeout raises
	// EventPipelineTimeout and tears the pipeline down.
	StartTimeout time.Duration
	// IdleTimeout is how long the pipeline may go without any of the frames
	// IdleTimeoutFrames selects before it counts as idle; zero defaults to five
	// minutes and a negative value turns idle detection off.
	IdleTimeout time.Duration
	// IdleTimeoutFrames selects the frames that count as the pipeline being
	// busy; nil pairs the VAD-only UserSpeakingFrame with the turn and
	// transcription frames a provider-driven pipeline reports instead. The
	// StartFrame always counts, so the first stretch is measured from the
	// pipeline coming up.
	IdleTimeoutFrames func(frames.Frame) bool
	// CancelOnIdleTimeout cancels the worker once the pipeline has gone idle;
	// nil defaults to true. Setting it false reports the idle pipeline and
	// leaves it running, and goes on reporting each further stretch of quiet.
	CancelOnIdleTimeout *bool
	// CancelRunnerOnIdleTimeout also cancels the runner, and with it every other
	// root worker, when the pipeline goes idle; nil defaults to true. It only
	// applies when CancelOnIdleTimeout is set: opting out of canceling this
	// worker opts out of canceling the rest. Set it false for a worker running
	// beside others that should see itself out without taking them with it.
	CancelRunnerOnIdleTimeout *bool
	// ProcessorUnusablePolicy says what to do when a processor reports an error
	// that leaves it unable to do its job, a service whose API key was rejected
	// being the case in point. The zero value continues, leaving the decision to
	// the EventPipelineError handlers.
	ProcessorUnusablePolicy ProcessorUnusablePolicy
	// ReachedDownstreamFilter selects which frames reaching the end of the
	// pipeline are reported. Nil selects nothing, so a handler without a filter
	// is never called; that is the default because a handler on every frame sits
	// on the path of everything the pipeline does. Use AnyFrame to watch the
	// whole stream anyway.
	ReachedDownstreamFilter func(frames.Frame) bool
	// ReachedUpstreamFilter selects which frames reaching the start of the
	// pipeline are reported. Nil selects nothing. See ReachedDownstreamFilter.
	ReachedUpstreamFilter func(frames.Frame) bool
	// Observers watch every frame reaching either end of the pipeline.
	Observers []processor.Observer
	// EnableTurnTracking follows the conversation's turns; nil defaults to true.
	// It applies whether or not the worker traces, since where the turns fell is
	// worth knowing either way; see Worker.TurnTracking. Tracing hangs off it, so
	// turning it off turns tracing off too: there would be nothing to hang the
	// turn spans from.
	EnableTurnTracking *bool
	// EnableTracing opens a span for the conversation and one for each turn
	// beneath it, and gives the processors the tracing context their own spans
	// hang from, so a session is one trace shaped like the conversation it
	// recorded. It needs a TracerProvider installed (see telemetry/tracing);
	// without one the spans are no-ops.
	EnableTracing bool
	// ConversationID names the traced conversation; empty generates one.
	ConversationID string
	// AdditionalSpanAttributes are set on the conversation span, on top of the
	// ones the worker sets itself. They are where the keys a trace backend reads
	// from the root span belong: a session id, a user id, tags.
	AdditionalSpanAttributes []attribute.KeyValue
	// Bridged puts the pipeline on the bus: what comes out of either end is
	// copied across, and what arrives from another worker is injected back in.
	//
	// Nil leaves the pipeline to itself. An empty but non-nil slice takes frames
	// from every bridge, and naming bridges takes them only from those. A
	// bridged worker is how one worker's pipeline feeds another's.
	Bridged []string
	// ExcludeFrames are frame types that never cross the bus, on top of the
	// lifecycle frames, which never do. It only applies to a bridged worker.
	ExcludeFrames []frames.Frame
	// HandleFlushFrame reports whether this worker answers a flush probe,
	// bouncing it at the sink and completing it there on its return. Nil
	// defaults to whether the pipeline is unbridged, so a worker wired into
	// someone else's topology leaves the probe to travel on and be completed by
	// the pipeline that owns the transport.
	//
	// A bridged worker with no such peer never completes a flush, and every
	// Flush call on it waits out its no-progress timeout.
	HandleFlushFrame *bool
	// EnableRTVI puts an RTVI processor at the head of the pipeline, and its
	// observer alongside the others, so a client is told what the session is
	// doing without the pipeline having to be built for it. Nil, the default,
	// adds it unless the pipeline is bridged: a bridged worker has no client of
	// its own, and its RTVI would report every frame a second time as it
	// crosses the bridge.
	//
	// A pipeline that already contains one keeps its own, and the observer for
	// it must be given in Observers. Set it false for a pipeline with no client
	// on the other end.
	EnableRTVI *bool
	// CheckDanglingTasks warns, when the worker finishes, about the tasks still
	// running on its task manager; nil enables it.
	CheckDanglingTasks *bool
	// TaskManager creates and cancels the session's tasks, and its loop runs
	// them; nil builds one on a loop of the worker's own. A manager given here
	// is the caller's: the worker does not close its loop, and workers sharing
	// one take turns on that loop.
	TaskManager *tasks.Manager
	// RTVIProcessor is the processor to add when RTVI is enabled and the
	// pipeline does not already contain one; nil builds a default one.
	RTVIProcessor *rtvi.Processor
	// RTVIObserverParams configures the observer added alongside it, which the
	// processor builds (see rtvi.Processor.CreateObserver).
	RTVIObserverParams *rtvi.ObserverParams
	// Capabilities is what the bot does, for fields the pipeline cannot show.
	// Its known fields replace the ones derived from the pipeline's transports
	// and parameters. See Worker.Capabilities.
	Capabilities capabilities.BotCapabilities
}

WorkerConfig configures a Worker: how it drives its pipeline, and how it takes part in a session alongside the other workers.

Directories

Path Synopsis
Package capabilities describes what a bot does in a session, reported so clients can configure themselves.
Package capabilities describes what a bot does in a session, reported so clients can configure themselves.
Package jobcontext describes the long-running work one worker asks another for: how such a job ends, and the error a job carries when it is cut short.
Package jobcontext describes the long-running work one worker asks another for: how such a job ends, and the error a job carries when it is cut short.
Package llmwithbackend pairs a conversational frontend LLM with a backend that does the work it hands off.
Package llmwithbackend pairs a conversational frontend LLM with a backend that does the work it hands off.

Jump to

Keyboard shortcuts

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