Documentation
¶
Overview ¶
Package stage provides the reactive streams architecture for pipeline execution.
A pipeline is a directed acyclic graph of stages. Each stage runs in its own goroutine, reads StreamElement values from an input channel, and writes StreamElement values to an output channel. A StreamElement carries one unit of data (text, audio, video, an image, a message, or a tool call) together with metadata and an optional error.
Building and running ¶
PipelineBuilder assembles stages into a graph with Chain, Connect, Branch and Merge, and Build validates it. StreamPipeline.Execute starts the stages and returns the output channel. StreamPipeline.ExecuteSync runs the pipeline to completion and returns an ExecutionResult. PipelineConfig sets channel buffering, the execution and idle timeouts, and the graceful shutdown timeout.
Stage kinds ¶
Every stage implements Stage. A stage with several upstream edges also implements MultiInputStage, and a stage that routes elements to named downstream outputs implements MultiOutputStage. StageType describes whether a stage transforms, accumulates, generates, sinks or is bidirectional.
The package supplies stages for prompt assembly and templating, context building and compaction, provider calls and tool execution, state store load and save, recording, speech, text-to-speech and voice activity handling, audio pacing and resampling, and media extraction, conversion and composition.
Failure ¶
The first stage error ends the turn. The pipeline does not cancel the other stages. It sends the error in-band to the failed stage's downstream stages as an error element, and they pass it on instead of acting on the incomplete turn. The error reaches the caller as the last element on the output channel. A provider error arrives as the provider stage emitted it. The error of any other stage arrives as a *StageError, which unwraps to the stage's own error. ExecuteSync returns the error alongside the result.
Package layout ¶
Most stages are implemented in packages under stage/internal, one per subsystem (core, provider, duplex, voice, media, persist, cue and others). This package re-exports their API under the names documented here: types as aliases, functions as wrappers, and errors and constants as variables and constants of the same value. Import this package; the internal packages cannot be imported from outside it.
Index ¶
- Constants
- Variables
- func BatchEmbeddingTexts(texts []string, batchSize int) [][]string
- func BudgetTokensFor(p providers.Provider) int
- func CosineSimilarity(a, b []float32) float64
- func DescribeCapabilities(stage Stage) string
- func ExcludeFromModelContext(msgs []types.Message) []types.Message
- func IsTranscriptMessage(elem *StreamElement) bool
- func ModelContextMask(msgs []types.Message) []bool
- func NewCompositionStepExecutor(deps CompositionExecutorDeps) engine.StepExecutor
- func NewFileSchemaResolver(configDir string) func(path string) (json.RawMessage, error)
- func NormalizeEmbedding(embedding []float32) []float32
- func PrewarmClips(ctx context.Context, cache cueclip.Cache, svc tts.Service, voice string, ...) error
- func PutElement(elem *StreamElement)
- func ResetIdleFromContext(ctx context.Context)
- func ValidateCapabilities(stages []Stage, edges map[string][]string)
- type AudioCapability
- type AudioData
- type AudioFormat
- type AudioPacingStage
- type AudioResampleConfig
- type AudioResampleStage
- type AudioTurnConfig
- type AudioTurnStage
- type BaseStage
- type BlockedMessage
- type BlockedMessageFunc
- type BroadcastRouter
- type ByOriginalIndex
- type CallRateLimitError
- type CallRateWindow
- type Capabilities
- type CompactResult
- type CompactionContext
- type CompactionRule
- type CompactionStrategy
- type CompositionExecutorDeps
- type CompositionRecorder
- func (r *CompositionRecorder) CompositionMetadata() map[string]any
- func (r *CompositionRecorder) RecordBranch(id, taken string)
- func (r *CompositionRecorder) RecordParallel(id string, branches []engine.NamedOutput)
- func (r *CompositionRecorder) RecordStepCompleted(id, kind string, input, output json.RawMessage, attempt int, err error)
- func (r *CompositionRecorder) RecordStepStarted(id, kind string, input json.RawMessage)
- func (r *CompositionRecorder) Reset()
- func (r *CompositionRecorder) SetEmitter(em *events.Emitter)
- func (r *CompositionRecorder) Snapshot() *CompositionSnapshot
- type CompositionSnapshot
- type CompositionStage
- type CompositionStepRecord
- type ContentRouter
- type ContentType
- type ContextAssemblyConfig
- type ContextAssemblyStage
- type ContextBuilderPolicy
- type ContextBuilderStage
- type ContextCompactor
- type Cue
- type CueKind
- type CueOptions
- type DebugStage
- type DropStrategy
- type DuplexProviderStage
- func NewDuplexProviderStage(provider providers.StreamInputSupport, ...) *DuplexProviderStage
- func NewDuplexProviderStageWithEmitter(provider providers.StreamInputSupport, ...) *DuplexProviderStage
- func NewDuplexProviderStageWithTurnState(provider providers.StreamInputSupport, ...) *DuplexProviderStage
- type DuplexToolConfig
- type ElementMetadata
- type EndInputter
- type ExecutionResult
- type ExecutionTrace
- type FilterStage
- type FormatCapable
- type FrameExtractionMode
- type FrameRateLimitConfig
- type FrameRateLimitStage
- type FrameSelectionStrategy
- type FramesToMessageConfig
- type FramesToMessageStage
- type Handoff
- type HandoffCall
- type HashRouter
- type HeardReplies
- type ImageData
- type ImagePreprocessConfig
- type ImagePreprocessStage
- type ImageResizeStage
- type ImageResizeStageConfig
- type IncrementalSaveConfig
- type IncrementalSaveStage
- type MapStage
- type MaxRoundsError
- type MediaComposeConfig
- type MediaComposeStage
- type MediaConvertConfig
- type MediaConvertStage
- type MediaExternalizerConfig
- type MediaExternalizerStage
- type MediaExtractConfig
- type MediaExtractInfo
- type MediaExtractStage
- type MemoryExtractionStage
- type MemoryRetrievalStage
- type MergeStage
- type MessageBroadcastStage
- type MetricsStage
- type MultiInputStage
- type MultiOutputStage
- type PassthroughStage
- type PipelineBuilder
- func (b *PipelineBuilder) AddStage(stage Stage) *PipelineBuilder
- func (b *PipelineBuilder) Branch(fromStage string, toStages ...string) *PipelineBuilder
- func (b *PipelineBuilder) Build() (*StreamPipeline, error)
- func (b *PipelineBuilder) Chain(stages ...Stage) *PipelineBuilder
- func (b *PipelineBuilder) Clone() *PipelineBuilder
- func (b *PipelineBuilder) Connect(fromStage, toStage string) *PipelineBuilder
- func (b *PipelineBuilder) Merge(into string, from ...string) *PipelineBuilder
- func (b *PipelineBuilder) WithConfig(config *PipelineConfig) *PipelineBuilder
- func (b *PipelineBuilder) WithEventEmitter(emitter *events.Emitter) *PipelineBuilder
- type PipelineConfig
- func (c *PipelineConfig) Validate() error
- func (c *PipelineConfig) WithChannelBufferSize(size int) *PipelineConfig
- func (c *PipelineConfig) WithExecutionTimeout(timeout time.Duration) *PipelineConfig
- func (c *PipelineConfig) WithGracefulShutdownTimeout(timeout time.Duration) *PipelineConfig
- func (c *PipelineConfig) WithIdleTimeout(timeout time.Duration) *PipelineConfig
- func (c *PipelineConfig) WithMaxConcurrentPipelines(maxPipelines int) *PipelineConfig
- func (c *PipelineConfig) WithPrioritizeElements(prioritize bool) *PipelineConfig
- type PlayoutHoldStage
- type Priority
- type PriorityChannel
- type PromptAssemblyStage
- type ProviderBudgetedCompaction
- type ProviderConfig
- type ProviderStage
- func NewProviderStage(provider providers.Provider, toolRegistry *tools.Registry, ...) *ProviderStage
- func NewProviderStageWithEmitter(provider providers.Provider, toolRegistry *tools.Registry, ...) *ProviderStage
- func NewProviderStageWithHooks(provider providers.Provider, toolRegistry *tools.Registry, ...) *ProviderStage
- func NewProviderStageWithTurnState(provider providers.Provider, toolRegistry *tools.Registry, ...) *ProviderStage
- type QuerySourceType
- type RandomRouter
- type RealtimeChainConfig
- type RealtimeHold
- type RealtimePacing
- type RealtimeSlot
- type ReasoningDelta
- type RecordingPosition
- type RecordingStage
- type RecordingStageConfig
- type RelevanceConfig
- type Response
- type ResponseVADConfig
- type ResponseVADStage
- type RoundRobinRouter
- type RouterFunc
- type RouterStage
- type RoutingRule
- type STTStage
- type STTStageConfig
- type ScoredMessage
- type ScoredMessages
- type Stage
- type StageError
- type StageFunc
- type StageMetrics
- type StageType
- type StateStoreLoadStage
- type StreamElement
- func GetAudioElement(audio *AudioData) *StreamElement
- func GetElement() *StreamElement
- func GetEndOfStreamElement() *StreamElement
- func GetErrorElement(err error) *StreamElement
- func GetImageElement(image *ImageData) *StreamElement
- func GetMessageElement(msg *types.Message) *StreamElement
- func GetTextElement(text string) *StreamElement
- func GetVideoElement(video *VideoData) *StreamElement
- func NewAudioElement(audio *AudioData) StreamElement
- func NewEndOfStreamElement() StreamElement
- func NewEndOfTurnElement() StreamElement
- func NewErrorElement(err error) StreamElement
- func NewImageElement(image *ImageData) StreamElement
- func NewInterruptElement() StreamElement
- func NewMessageElement(msg *types.Message) StreamElement
- func NewTextElement(text string) StreamElement
- func NewVideoElement(video *VideoData) StreamElement
- func StreamMediaToElement(media *providers.StreamMediaData) StreamElement
- type StreamExecution
- type StreamHoldConfig
- type StreamPipeline
- func (p *StreamPipeline) Execute(ctx context.Context, input <-chan StreamElement) (<-chan StreamElement, error)
- func (p *StreamPipeline) ExecuteSync(ctx context.Context, input ...StreamElement) (*ExecutionResult, error)
- func (p *StreamPipeline) RunsToolCalls() bool
- func (p *StreamPipeline) Shutdown(ctx context.Context) error
- func (p *StreamPipeline) Start(ctx context.Context, input <-chan StreamElement) (*StreamExecution, error)
- type StructuredOutputMode
- type TTSConfig
- type TTSService
- type TTSStage
- type TTSStageWithInterruption
- type TTSStageWithInterruptionConfig
- type TemplateStage
- type TokenBudgetConfig
- type TokenBudgetStage
- type ToolCallRecorder
- type ToolCallRunner
- type ToolLoading
- type ToolLoadingMode
- type ToolOfferHistory
- type TranscriptReorderStage
- type Transcription
- type TruncationStrategy
- type TurnState
- type VariableProviderStage
- func NewVariableProviderStage(variableProviders ...variables.Provider) *VariableProviderStage
- func NewVariableProviderStageWithVars(staticVars map[string]string, variableProviders []variables.Provider) *VariableProviderStage
- func NewVariableProviderStageWithVarsAndTurnState(staticVars map[string]string, variableProviders []variables.Provider, ...) *VariableProviderStage
- type VideoData
- type VideoFramesInfo
- type VideoToFramesConfig
- type VideoToFramesStage
- type WeightedRouter
- type WorkflowStateResolver
Examples ¶
Constants ¶
const ( // DefaultChannelBufferSize is the default buffer size for channels between stages. // For text pipelines, 32 provides adequate buffering. // For audio pipelines at ~50 chunks/sec, consider using DefaultAudioChannelBufferSize. DefaultChannelBufferSize = 32 // DefaultAudioChannelBufferSize is the recommended buffer size for audio pipelines. // At 50 chunks/sec, 64 buffers provide ~1.3 seconds of buffering to absorb jitter. DefaultAudioChannelBufferSize = 64 // DefaultMaxConcurrentPipelines is the default maximum number of concurrent pipeline executions. DefaultMaxConcurrentPipelines = 100 // DefaultExecutionTimeoutSeconds is the default execution timeout in seconds. // Set to 0 (disabled). IdleTimeout is the primary liveness check. DefaultExecutionTimeoutSeconds = 0 // DefaultIdleTimeoutSeconds is the default idle timeout in seconds. // The timer resets on each activity signal (stream chunk, round, tool // completion) and is held open while tool calls are in flight. DefaultIdleTimeoutSeconds = 30 // DefaultGracefulShutdownTimeoutSeconds is the default graceful shutdown timeout in seconds. DefaultGracefulShutdownTimeoutSeconds = 10 )
const ( // DefaultFrameInterval is the default time between extracted frames. DefaultFrameInterval = media.DefaultFrameInterval // DefaultTargetFPS is the default target frame rate. DefaultTargetFPS = media.DefaultTargetFPS // DefaultMaxFrames is the default maximum frames to extract. DefaultMaxFrames = media.DefaultMaxFrames // DefaultOutputFormat is the default output image format. DefaultOutputFormat = media.DefaultOutputFormat // OutputFormatPNG is the PNG output format. OutputFormatPNG = media.OutputFormatPNG // DefaultOutputQuality is the default JPEG quality. DefaultOutputQuality = media.DefaultOutputQuality // DefaultFFmpegPath is the default path to FFmpeg. DefaultFFmpegPath = media.DefaultFFmpegPath // DefaultFFmpegTimeout is the default FFmpeg execution timeout. DefaultFFmpegTimeout = media.DefaultFFmpegTimeout // DefaultFramesCompletionTimeout is the default timeout for frame accumulation. DefaultFramesCompletionTimeout = media.DefaultFramesCompletionTimeout // DefaultMaxFramesPerMessage is the default max frames in composed message. // It is providers.MaxMediaItems, the most media parts a provider loads for // one message, so a frames message at the default is never refused for // carrying too many images. DefaultMaxFramesPerMessage = media.DefaultMaxFramesPerMessage )
Default configuration values.
const ( // DefaultMaxMessages is the maximum number of messages retained when no // explicit context window is configured. Older non-system messages are // discarded to prevent unbounded context growth. DefaultMaxMessages = 200 // DefaultWarningThreshold is the message count above which a warning is // logged when no context window or token budget is configured. DefaultWarningThreshold = 100 )
const BlockedMessageDetail = provider.BlockedMessageDetail
BlockedMessageDetail is the ValidationResult.Details key that records the text a BlockedMessageFunc chose for a firing, when it chose one. The guardrail's own replacement, if any, stays under its own key.
const ( // DefaultBudgetTokens is the default context window budget for compaction. DefaultBudgetTokens = compaction.DefaultBudgetTokens )
const ( // DefaultCompletionTimeout is the default timeout for waiting for all message parts. DefaultCompletionTimeout = media.DefaultCompletionTimeout )
Default configuration values.
const ( // DefaultFrameRateLimitFPS is the default target frame rate. // 1 FPS is suitable for most LLM vision scenarios. DefaultFrameRateLimitFPS = media.DefaultFrameRateLimitFPS )
Default frame rate limit configuration constants.
const SchemaUnappliedMetaKey = provider.SchemaUnappliedMetaKey
SchemaUnappliedMetaKey marks an assistant message that a configured ResponseFormat was NOT applied to, so its content is the loop's unconstrained answer rather than schema-shaped output. The value says why.
Two causes reach it: the re-ask failed at the provider, or the tool loop exhausted its rounds and never produced a final turn to constrain.
Exported because detecting it is a caller's decision. Returning prose is the right trade against losing a completed tool loop's work, but only if the caller can tell it happened. An unmarked fallback is indistinguishable from a model that answered in prose, which is the unobservable-success failure this whole mode exists to remove.
const TextInputTurnSource = duplex.TextInputTurnSource
TextInputTurnSource is the StreamElement.Source of the element that carries a realtime session's typed user turn: text sent to the session with no Message (SendText), which DuplexProviderStage turns into a user message of the conversation and emits between the assistant's replies. The element is for the stages that persist and record the conversation; the SDK does not pass it on to the caller, who sent the text.
Variables ¶
var ( // ErrPipelineShuttingDown is returned when attempting to execute a pipeline that is shutting down. ErrPipelineShuttingDown = core.ErrPipelineShuttingDown // ErrOutputTruncated ends the output of a turn that ran but lost output: // Shutdown abandoned the execution and the reader fell behind, so elements // were dropped (see StreamPipeline.Shutdown). Unlike ErrPipelineShuttingDown, // the turn did run, so its side effects may have happened. ErrOutputTruncated = core.ErrOutputTruncated // ErrShutdownTimeout is returned when pipeline shutdown times out. ErrShutdownTimeout = core.ErrShutdownTimeout // ErrExecutionTimeout is the cause of a stage failure the pipeline's // ExecutionTimeout produced. The turn's error wraps both it and // context.DeadlineExceeded. ErrExecutionTimeout = core.ErrExecutionTimeout // ErrInvalidPipeline is returned when building an invalid pipeline. ErrInvalidPipeline = core.ErrInvalidPipeline // ErrCyclicDependency is returned when the pipeline DAG contains cycles. ErrCyclicDependency = core.ErrCyclicDependency // ErrStageNotFound is returned when a referenced stage doesn't exist. ErrStageNotFound = core.ErrStageNotFound // ErrDuplicateStageName is returned when multiple stages have the same name. ErrDuplicateStageName = core.ErrDuplicateStageName // ErrNoStages is returned when trying to build a pipeline with no stages. ErrNoStages = core.ErrNoStages // ErrCompositionToolNeedsApproval is returned when a tool an agent step of // a composition called is held for approval (CompositionExecutorDeps. // ApprovalChecker). A step cannot suspend for the approval, so it fails // rather than run the tool unapproved. ErrCompositionToolNeedsApproval = core.ErrCompositionToolNeedsApproval // ErrInvalidChannelBufferSize is returned for invalid buffer size. ErrInvalidChannelBufferSize = core.ErrInvalidChannelBufferSize // ErrInvalidMaxConcurrentPipelines is returned for invalid max concurrent pipelines. ErrInvalidMaxConcurrentPipelines = core.ErrInvalidMaxConcurrentPipelines // ErrInvalidExecutionTimeout is returned for invalid execution timeout. ErrInvalidExecutionTimeout = core.ErrInvalidExecutionTimeout // ErrInvalidGracefulShutdownTimeout is returned for invalid graceful shutdown timeout. ErrInvalidGracefulShutdownTimeout = core.ErrInvalidGracefulShutdownTimeout // ErrInvalidIdleTimeout is returned for invalid idle timeout. ErrInvalidIdleTimeout = core.ErrInvalidIdleTimeout // ErrFFmpegNotFound is returned when FFmpeg binary cannot be found. ErrFFmpegNotFound = core.ErrFFmpegNotFound // ErrFFmpegFailed is returned when FFmpeg execution fails. ErrFFmpegFailed = core.ErrFFmpegFailed // ErrFFmpegTimeout is returned when FFmpeg execution times out. ErrFFmpegTimeout = core.ErrFFmpegTimeout // ErrInvalidVideoFormat is returned when video cannot be processed. ErrInvalidVideoFormat = core.ErrInvalidVideoFormat // ErrNoFramesExtracted is returned when FFmpeg produces no output frames. ErrNoFramesExtracted = core.ErrNoFramesExtracted // ErrVideoDataRequired is returned when video data is required but missing. ErrVideoDataRequired = core.ErrVideoDataRequired // ErrFanInNotSupported is returned when a stage has multiple upstream edges but // does not implement MultiInputStage. ErrFanInNotSupported = core.ErrFanInNotSupported // ErrDuplicateFanInEdge is returned when a stage receives multiple edges from // the same upstream stage, creating a duplicate input source. ErrDuplicateFanInEdge = core.ErrDuplicateFanInEdge // ErrTurnStateRequired is returned by Build when a TemplateStage or // PromptAssemblyStage has no TurnState. Those stages share the loaded and // rendered system prompt through TurnState; without one they do nothing and // the provider receives an empty system prompt. Construct them with // NewTemplateStageWithTurnState / NewPromptAssemblyStageWithTurnState. ErrTurnStateRequired = core.ErrTurnStateRequired )
Common errors
var ( // ErrRealtimeChainProvider is returned when the provider stage is nil or // dropped. ErrRealtimeChainProvider = errors.New("realtime chain: a provider stage is required") // ErrRealtimeChainSlot is returned for a slot name the chain does not have, // or a nil stage inserted after a slot. ErrRealtimeChainSlot = errors.New("realtime chain: invalid slot") // ErrRealtimeChainPacing is returned for a RealtimePacing value the chain // does not have. ErrRealtimeChainPacing = errors.New("realtime chain: unknown pacing mode") )
Errors returned by NewRealtimeChain.
var ErrIdleTimeout = core.ErrIdleTimeout
ErrIdleTimeout is returned (via context.Cause) when the pipeline idle timeout fires because no activity was detected within the configured duration.
var ErrMaxRoundsExceeded = core.ErrMaxRoundsExceeded
ErrMaxRoundsExceeded matches, with errors.Is, a turn the provider stage ended because the model was still calling tools when the tool loop reached its round limit. Unlike a provider's own error it carries nothing secret, and it is recoverable: the model was working, and another message lets it continue. errors.As with *MaxRoundsError gives the limit.
var ErrSessionBoundSource = cue.ErrSessionBoundSource
ErrSessionBoundSource is PrewarmClips' error for a clip source that needs a live session: a provider's own out-of-band audio renders only inside a session, so it cannot be pre-warmed.
var ErrTemplateUnresolved = core.ErrTemplateUnresolved
ErrTemplateUnresolved is returned by TemplateStage when the system prompt references a variable nothing supplied. The turn fails and the error reaches the caller wrapped in a *StageError, so errors.Is matches it. The stage does not send the unrendered template to the model.
var ErrVoicePrewarmedByAnotherService = cue.ErrVoicePrewarmedByAnotherService
ErrVoicePrewarmedByAnotherService is PrewarmClips' error for a text already pre-warmed for the voice and format from another TTS service: a session with no TTS service plays one service's clips per voice, so a second service's is refused rather than mixed in.
Functions ¶
func BatchEmbeddingTexts ¶
BatchEmbeddingTexts splits texts into batches of the given size. Useful for respecting embedding provider batch limits.
func BudgetTokensFor ¶ added in v2.13.0
BudgetTokensFor returns p's context window, or DefaultBudgetTokens when it reports none.
func CosineSimilarity ¶
CosineSimilarity computes the cosine similarity between two embedding vectors. Returns a value between -1.0 and 1.0, where:
- 1.0 means vectors are identical in direction
- 0.0 means vectors are orthogonal (unrelated)
- -1.0 means vectors are opposite
For text embeddings, values typically range from 0.0 to 1.0, with higher values indicating greater semantic similarity.
Returns 0.0 if vectors have different lengths, are empty, or have zero magnitude.
func DescribeCapabilities ¶
DescribeCapabilities returns a human-readable description of a stage's capabilities. Useful for debugging and logging.
func ExcludeFromModelContext ¶ added in v2.22.0
ExcludeFromModelContext returns msgs without what never goes back to a model, the messages ModelContextMask marks: interrupted replies (types.ExcludeInterrupted), blocked input turns (the canned reply marked Meta[types.MetaBlockedInput] and the user message it answered), and each message marked Meta[types.MetaExcludedFromModel]. A transcript keeps both; any path that builds model context from one (a carry-forward summary, a host's own summarizer) passes it through this first. msgs is returned as-is when it holds neither.
func IsTranscriptMessage ¶ added in v2.22.0
func IsTranscriptMessage(elem *StreamElement) bool
IsTranscriptMessage reports whether the save stage stores elem's Message in the transcript: a message this pipeline produced (not history loaded from the store, a summary or a retrieved message) that is not held for playout. A held Message is stored from its PlayoutRelease element instead. A stage after the save stage counts these to know how far the transcript reaches.
func ModelContextMask ¶ added in v2.22.0
ModelContextMask reports, for each message of msgs, whether ExcludeFromModelContext leaves it out: an interrupted reply (but not what a caller heard of one, types.Message.IsHeardPrefix), a message of a blocked input turn, or one marked Meta[types.MetaExcludedFromModel]. It returns nil when it leaves none out. A host that rebuilds a history from another copy of it uses the mask to keep what the transcript holds out of model context out of it still.
func NewCompositionStepExecutor ¶
func NewCompositionStepExecutor(deps CompositionExecutorDeps) engine.StepExecutor
NewCompositionStepExecutor returns an engine.StepExecutor that runs prompt/agent steps as sub-pipelines and tool steps via the registry.
func NewFileSchemaResolver ¶
func NewFileSchemaResolver(configDir string) func(path string) (json.RawMessage, error)
NewFileSchemaResolver returns a resolver that reads a schema file path relative to configDir (absolute paths are used as-is). An empty path resolves to (nil, nil) ("no schema"), matching CompositionExecutorDeps.SchemaResolver's contract.
func NormalizeEmbedding ¶
NormalizeEmbedding normalizes an embedding vector to unit length. This can improve similarity comparisons by ensuring all vectors have the same magnitude.
func PrewarmClips ¶ added in v2.22.0
func PrewarmClips(ctx context.Context, cache cueclip.Cache, svc tts.Service, voice string, format cueclip.Format, texts []string) error
PrewarmClips renders texts with the TTS service svc into cache, so a session started later plays them with no render. voice is the session's voice name: the clips are keyed by the service voice whose ID or name matches it, ignoring case (the service's default voice when none does), exactly as a session in that voice looks them up. format is the session's output format (PCM16 mono; a zero SampleRate is 24 kHz). A nil cache is the process-wide default.
Each clip is also kept under the session voice alone, so a session with no TTS service configured (a test, an arena run, a host that warms a directory offline) plays it too. That is skipped, with a warning, when the service has no voice matching voice. Pre-warm one TTS service per voice and format: a text already kept for the voice with another service's audio returns ErrVoicePrewarmedByAnotherService.
Each text renders once, through the same trimming, fade, resampling and process-wide single-flight a session uses, a few at a time. A text the service fails is named in the returned error; the others are still cached. svc must render PCM; nil, or a live session's audio, is session-bound and returns ErrSessionBoundSource.
func PutElement ¶
func PutElement(elem *StreamElement)
PutElement returns a StreamElement to the pool for reuse. The element is reset before being returned to the pool to prevent data leaks. After calling PutElement, the caller must not use the element again.
func ResetIdleFromContext ¶
ResetIdleFromContext extracts the idle reset function from the context and calls it. This is a no-op if no idle timeout is configured.
func ValidateCapabilities ¶
ValidateCapabilities checks format compatibility between connected stages. It logs warnings for potential mismatches but does not return errors, as format compatibility can often only be fully determined at runtime.
This function is called during pipeline building to provide early feedback about potential issues.
Types ¶
type AudioCapability ¶
type AudioCapability = core.AudioCapability
AudioCapability describes audio format requirements for a stage.
type AudioFormat ¶
type AudioFormat = core.AudioFormat
AudioFormat represents the encoding format of audio data.
const ( // AudioFormatPCM16 is 16-bit PCM encoding AudioFormatPCM16 AudioFormat = core.AudioFormatPCM16 // AudioFormatFloat32 is 32-bit floating point encoding AudioFormatFloat32 AudioFormat = core.AudioFormatFloat32 // AudioFormatOpus is Opus codec encoding AudioFormatOpus AudioFormat = core.AudioFormatOpus // AudioFormatMP3 is MP3 encoding AudioFormatMP3 AudioFormat = core.AudioFormatMP3 // AudioFormatAAC is AAC encoding AudioFormatAAC AudioFormat = core.AudioFormatAAC )
type AudioPacingStage ¶
type AudioPacingStage = voice.AudioPacingStage
AudioPacingStage paces audio chunks toward downstream stages so they are forwarded at roughly real-time rate, smoothing bursty producers (e.g. file readers) into a steady stream that real-provider VAD and local sinks can consume without buffer overrun or premature turn-end.
func NewAudioPacingStage ¶
func NewAudioPacingStage() *AudioPacingStage
NewAudioPacingStage creates a new audio pacing stage with the default preroll (defaultPrerollChunks chunks forwarded immediately before pacing kicks in) and the canonical name "audio-pacing".
Use NewNamedAudioPacingStage when wiring two instances in the same pipeline (input + output direction); the pipeline builder rejects duplicate stage names.
func NewNamedAudioPacingStage ¶
func NewNamedAudioPacingStage(name string) *AudioPacingStage
NewNamedAudioPacingStage is like NewAudioPacingStage but lets the caller pick the stage name. Necessary when two pacing stages coexist in the same pipeline (e.g. one for the input audio path, one for the output). The pipeline builder treats stage names as unique IDs and would reject a second "audio-pacing".
type AudioResampleConfig ¶
type AudioResampleConfig = voice.AudioResampleConfig
AudioResampleConfig contains configuration for the audio resampling stage.
func DefaultAudioResampleConfig ¶
func DefaultAudioResampleConfig() AudioResampleConfig
DefaultAudioResampleConfig returns sensible defaults for audio resampling.
type AudioResampleStage ¶
type AudioResampleStage = voice.AudioResampleStage
AudioResampleStage resamples audio data to a target sample rate. This is useful for normalizing audio from different sources (TTS, files) to match provider requirements.
This is a Transform stage: audio element → resampled audio element (1:1)
func NewAudioResampleStage ¶
func NewAudioResampleStage(config AudioResampleConfig) *AudioResampleStage
NewAudioResampleStage creates a new audio resampling stage.
type AudioTurnConfig ¶
type AudioTurnConfig = voice.AudioTurnConfig
AudioTurnConfig configures the AudioTurnStage.
func DefaultAudioTurnConfig ¶
func DefaultAudioTurnConfig() AudioTurnConfig
DefaultAudioTurnConfig returns sensible defaults for AudioTurnStage.
type AudioTurnStage ¶
type AudioTurnStage = voice.AudioTurnStage
AudioTurnStage detects voice activity and accumulates audio into complete turns. It outputs complete audio utterances when the user stops speaking.
This stage consolidates: - Voice Activity Detection (VAD) - Turn boundary detection - Audio accumulation - Interruption detection (shared with TTSStageWithInterruption)
This is an Accumulate stage: N audio chunks → 1 audio utterance
func NewAudioTurnStage ¶
func NewAudioTurnStage(config AudioTurnConfig) (*AudioTurnStage, error)
NewAudioTurnStage creates a new audio turn stage.
type BaseStage ¶
BaseStage provides common functionality for stage implementations. Stages can embed this to reduce boilerplate.
func NewBaseStage ¶
NewBaseStage creates a new BaseStage with the given name and type.
type BlockedMessage ¶ added in v2.22.0
type BlockedMessage = provider.BlockedMessage
BlockedMessage is a guardrail firing whose message is about to replace a turn, as a BlockedMessageFunc is given it.
type BlockedMessageFunc ¶ added in v2.22.0
type BlockedMessageFunc = provider.BlockedMessageFunc
BlockedMessageFunc chooses the text of a blocked message: what replaces the turn, is shown to the caller, stored, and spoken by a cue. An empty return keeps b.Text, as does a panic. On a realtime session (DuplexProviderStage) it is given at most the cue stage's OnDemandBudget (1.5s by default; its ctx is canceled then) before b.Text is used, so it cannot stall the session's output.
type BroadcastRouter ¶
type BroadcastRouter struct {
BaseStage
// contains filtered or unexported fields
}
BroadcastRouter sends each element to ALL registered outputs. Useful for fan-out scenarios where all consumers need every element.
func NewBroadcastRouter ¶
func NewBroadcastRouter(name string) *BroadcastRouter
NewBroadcastRouter creates a router that broadcasts to all outputs.
func (*BroadcastRouter) Process ¶
func (r *BroadcastRouter) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process broadcasts each element to all outputs.
func (*BroadcastRouter) RegisterOutput ¶
func (r *BroadcastRouter) RegisterOutput(name string, output chan<- StreamElement)
RegisterOutput registers an output channel with a name.
type ByOriginalIndex ¶
type ByOriginalIndex = compaction.ByOriginalIndex
ByOriginalIndex sorts ScoredMessages by their original index (ascending).
type CallRateLimitError ¶ added in v2.17.0
type CallRateLimitError = provider.CallRateLimitError
CallRateLimitError is the refusal of a call over ToolPolicy.MaxCallsPerMinute. Its message is what the model is told in place of the call's result.
type CallRateWindow ¶ added in v2.17.0
type CallRateWindow = provider.CallRateWindow
CallRateWindow enforces ToolPolicy.MaxCallsPerMinute. For each conversation and tool, it counts the calls admitted to run in the last minute. A call is checked against the limit, and counted, only when it is admitted (Admit):
- a call the provider stage runs is admitted immediately before the stage executes it;
- a call held for approval is admitted when the host approves it;
- a call its executor defers (ToolStatusPending, such as a client tool) is admitted when the host uses its result.
A call that is refused, rejected, abandoned or never answered is never counted. Nothing is reserved, so nothing is left to give back. The cost is that a held or deferred call is checked late: a human may approve a call that then hits the limit, and a client may run a call whose result is then refused.
The stage admits a call through tools.Registry.ExecuteAsyncAdmitted, after the registry's own checks pass (the tool exists, its arguments are valid, the registry's rate limit allows it), so a call those refuse is never counted. A call its executor defers without running it (tools.DeferringExecutor, as the SDK's client executor does for a client tool with no handler) is never admitted at dispatch, so a round's deferred calls never take each other's room. For an executor that cannot say, a deferred call is known only when the executor returns: the stage takes its admission back then. While such an executor runs, the call counts, so another call to the same tool in the same round can be refused for the limit in that moment.
A provider stage holds one window (ProviderConfig.CallRate, or its own), so the window spans every turn of a conversation the stage runs. Safe for concurrent use: a round's calls are admitted in parallel.
tools.WithRateLimit is the other sliding window, and a different limit. It is one per registry, shared by its children, counts every conversation's calls to a tool together under a fixed limit, and refuses with tools.ErrRateLimitExceeded. This one is keyed on the conversation, takes the limit of the policy in force for each call, drops idle conversations (its keys are unbounded, the registry's are tool names), and is also used by the host for calls that run outside the stage.
func NewCallRateWindow ¶ added in v2.17.0
func NewCallRateWindow() *CallRateWindow
NewCallRateWindow returns an empty window.
type Capabilities ¶
type Capabilities = core.Capabilities
Capabilities describes what a stage accepts or produces.
func AnyCapabilities ¶
func AnyCapabilities() Capabilities
AnyCapabilities returns capabilities that accept any content type.
func AudioCapabilities ¶
func AudioCapabilities(formats []AudioFormat, sampleRates, channels []int) Capabilities
AudioCapabilities returns capabilities for audio content with optional format constraints.
func MessageCapabilities ¶
func MessageCapabilities() Capabilities
MessageCapabilities returns capabilities for message content.
func TextCapabilities ¶
func TextCapabilities() Capabilities
TextCapabilities returns capabilities for text-only content.
type CompactResult ¶
type CompactResult = compaction.CompactResult
CompactResult contains the output of a compaction pass.
type CompactionContext ¶
type CompactionContext = compaction.CompactionContext
CompactionContext provides read-only context to rules.
type CompactionRule ¶
type CompactionRule = compaction.CompactionRule
CompactionRule transforms individual messages during compaction. Rules are applied in order to each compactable message outside the pinned window. The first rule whose CanFold returns true wins.
func CollapsePairs ¶
func CollapsePairs() CompactionRule
CollapsePairs returns a compaction rule that collapses superseded assistant→tool message pairs. A pair is superseded when the same tool name and arguments appear in a later tool result.
func FoldToolResults ¶
func FoldToolResults() CompactionRule
FoldToolResults returns the default compaction rule that folds large tool result messages into compact summaries.
type CompactionStrategy ¶
type CompactionStrategy = compaction.CompactionStrategy
CompactionStrategy is the top-level interface for context compaction. Called by ProviderStage between tool loop rounds. Implementations must be safe for concurrent use if the provider stage is used concurrently across conversations (each conversation has its own message slice).
type CompositionExecutorDeps ¶
type CompositionExecutorDeps struct {
PromptRegistry *prompt.Registry
// Provider runs every prompt/agent step, unless ResolveProvider is set.
Provider providers.Provider
// ResolveProvider, when set, picks the provider for each prompt/agent step
// (the step's provider key, else its prompt's, else the default).
// Optional; without it every step runs on Provider.
ResolveProvider func(step *composition.Step) (providers.Provider, error)
ToolRegistry *tools.Registry
Emitter *events.Emitter
// HookRegistry holds the hooks every step runs, unless StepHookRegistry
// gives a step its own.
HookRegistry *hooks.Registry
// StepHookRegistry, when set, gives the hooks a prompt or agent step runs
// for its prompt task: the host's hooks with that prompt's own validators,
// as an opened prompt runs them. A nil return means HookRegistry.
StepHookRegistry func(promptTask string) *hooks.Registry
BaseVariables map[string]string
// PromptDeclarations maps prompt tasks to their pack declarations, for
// provider hooks inside each step (see ProviderConfig.PromptDeclarations).
PromptDeclarations map[string]*packspec.Prompt
// SchemaResolver maps a step's output_schema path to JSON-schema bytes for
// structured output. nil (or a nil return) means no ResponseFormat is set.
// Plan 3 supplies the real resolver from the pack/config dir.
SchemaResolver func(path string) (json.RawMessage, error)
// BaseMetadata is merged into each sub-pipeline's ProviderRequestMetadata
// alongside composition_step_id. Arena uses this to propagate mock_scenario_id
// so per-step mock responses are keyed against the right scenario.
BaseMetadata map[string]interface{}
// ParentTurnState is the enclosing turn's state, read only for its
// TurnIndex and ConversationID. Each step gets a fresh TurnState (its
// prompt, tools and system prompt are the step's, not the turn's), but
// two things must survive the boundary. Without the turn number every
// step reports turn 1 and no guardrail event inside a composition can be
// placed against the transcript. Without the conversation ID the step's
// calls count under no conversation in CallRate. Optional.
ParentTurnState *TurnState
// SkipContentValidation is ProviderConfig.SkipContentValidation for every
// prompt and agent step. False validates.
SkipContentValidation bool
// ToolPolicy is the host's tool policy, the base of every prompt and agent
// step's (see stepToolPolicy). Nil: the step's bounds alone.
ToolPolicy *pipeline.ToolPolicy
// ApprovalChecker is the conversation's human-in-the-loop approval gate
// (ProviderConfig.ApprovalChecker). A tool call it holds inside an agent
// step fails the step with ErrCompositionToolNeedsApproval, so the tool
// never runs unapproved. Nil: no tool needs approval.
ApprovalChecker tools.ApprovalChecker
// ApprovalGate is the conversation's approval gate when it can refuse a
// call (ProviderConfig.ApprovalGate). It takes the place of
// ApprovalChecker: a call it holds fails the step as above, and a call it
// refuses does not run.
ApprovalGate tools.ApprovalGate
// CallRate is the enclosing conversation's call-rate window
// (ProviderConfig.CallRate). Every step's provider stage counts in it, so
// ToolPolicy.MaxCallsPerMinute spans the composition's steps and turns.
// Nil: each step execution gets a window of its own.
CallRate *CallRateWindow
// Caller is who the conversation acts for (ProviderConfig.Caller). Tool
// steps hand it to the registry, and every prompt and agent step's
// provider stage puts it on its tool calls and tool hook requests. The
// zero value means none was set.
Caller types.Caller
// BlockedMessage chooses the text a guardrail's block replaces a prompt or
// agent step's reply with (ProviderConfig.BlockedMessage). Nil keeps the
// guardrail's message.
BlockedMessage BlockedMessageFunc
}
CompositionExecutorDeps carries the runtime collaborators a composition step needs to execute. Injected once; reused for every step of every Execute call.
type CompositionRecorder ¶
type CompositionRecorder struct {
// contains filtered or unexported fields
}
CompositionRecorder captures per-step composition execution data for Arena observability. Populated during a single engine.Execute (RecordStepStarted and RecordStepCompleted may fire from parallel-branch goroutines, hence the mutex) and read afterward via CompositionMetadata. Reset() is called at the start of each turn. An optional Emitter (set via SetEmitter) receives composition.* events; all map mutations occur under the mutex but the emitter is called outside the lock to avoid holding it across emit from concurrent branches.
func NewCompositionRecorder ¶
func NewCompositionRecorder() *CompositionRecorder
NewCompositionRecorder returns an empty recorder.
func (*CompositionRecorder) CompositionMetadata ¶
func (r *CompositionRecorder) CompositionMetadata() map[string]any
CompositionMetadata returns a flat snapshot for the eval metadata bridge. The returned maps are copies safe to read after the next Reset().
func (*CompositionRecorder) RecordBranch ¶
func (r *CompositionRecorder) RecordBranch(id, taken string)
RecordBranch implements engine.Recorder.
func (*CompositionRecorder) RecordParallel ¶
func (r *CompositionRecorder) RecordParallel(id string, branches []engine.NamedOutput)
RecordParallel implements engine.Recorder.
func (*CompositionRecorder) RecordStepCompleted ¶
func (r *CompositionRecorder) RecordStepCompleted(id, kind string, input, output json.RawMessage, attempt int, err error)
RecordStepCompleted implements engine.Recorder.
func (*CompositionRecorder) RecordStepStarted ¶
func (r *CompositionRecorder) RecordStepStarted(id, kind string, input json.RawMessage)
RecordStepStarted implements engine.Recorder.
func (*CompositionRecorder) Reset ¶
func (r *CompositionRecorder) Reset()
Reset clears all recorded data (called per turn). Does NOT clear the emitter.
func (*CompositionRecorder) SetEmitter ¶
func (r *CompositionRecorder) SetEmitter(em *events.Emitter)
SetEmitter wires an Emitter so the recorder publishes composition.* events. Safe to call concurrently; replaces any emitter already set.
func (*CompositionRecorder) Snapshot ¶
func (r *CompositionRecorder) Snapshot() *CompositionSnapshot
Snapshot returns an ordered, richer per-turn view of the composition execution for report rendering. The returned value is a deep copy safe to read after the next Reset(). Returns nil when no steps, branches, or parallel entries have been recorded (e.g. immediately after Reset).
type CompositionSnapshot ¶
type CompositionSnapshot struct {
Steps []CompositionStepRecord `json:"steps"`
Branches map[string]string `json:"branches,omitempty"`
Parallel map[string]string `json:"parallel,omitempty"`
}
CompositionSnapshot is an ordered, richer per-turn view of composition execution for report rendering. It is attached to the assistant message Meta by CompositionStage so that JSON (and future HTML) reports can surface the step-graph trace without touching the assertion-bridge maps.
type CompositionStage ¶
type CompositionStage struct {
// contains filtered or unexported fields
}
CompositionStage runs a composition to completion as a single pipeline stage: it reads the turn's input element, executes the composition's step DAG via the engine, and emits one assistant element carrying the structured output.
func NewCompositionStage ¶
func NewCompositionStage(name string, comp *composition.Composition, deps CompositionExecutorDeps) *CompositionStage
NewCompositionStage builds a CompositionStage from a composition spec and the runtime collaborators its steps need.
func NewCompositionStageWithRecorder ¶
func NewCompositionStageWithRecorder( name string, comp *composition.Composition, deps CompositionExecutorDeps, rec *CompositionRecorder, ) *CompositionStage
NewCompositionStageWithRecorder builds a CompositionStage that records step-level execution data via rec for Arena observability. rec.Reset() is called before each composition execution so that each turn's metadata is independent. A nil rec is equivalent to calling NewCompositionStage.
func (*CompositionStage) Name ¶
func (s *CompositionStage) Name() string
Name returns the stage name.
func (*CompositionStage) Process ¶
func (s *CompositionStage) Process(ctx context.Context, in <-chan StreamElement, out chan<- StreamElement) error
Process reads the first non-history message element as the composition input (its message Content bytes are the input JSON), runs the composition, and emits one assistant element whose Content is the composition's structured output. History elements (elem.Meta.FromHistory == true), non-message/EndOfStream elements, and any elements after the first live message are forwarded unchanged.
func (*CompositionStage) Type ¶
func (s *CompositionStage) Type() StageType
Type reports this as a transform stage.
type CompositionStepRecord ¶
type CompositionStepRecord struct {
ID string `json:"id"`
Kind string `json:"kind"`
Attempt int `json:"attempt"`
Output json.RawMessage `json:"output,omitempty"`
}
CompositionStepRecord is one entry in a CompositionSnapshot, capturing the completion order, kind, retry attempt, and output of a single step.
type ContentRouter ¶
type ContentRouter struct {
BaseStage
// contains filtered or unexported fields
}
ContentRouter routes elements to different outputs based on predicate rules. Rules are evaluated in order; the first matching rule determines the destination. Elements that don't match any rule are dropped with a warning log.
func NewContentRouter ¶
func NewContentRouter(name string, rules ...RoutingRule) *ContentRouter
NewContentRouter creates a new content-aware router with the given rules.
func (*ContentRouter) Process ¶
func (r *ContentRouter) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process routes elements based on the configured rules.
func (*ContentRouter) RegisterOutput ¶
func (r *ContentRouter) RegisterOutput(name string, output chan<- StreamElement)
RegisterOutput registers an output channel with a name. This must be called before Process() to set up routing destinations.
type ContentType ¶
type ContentType = core.ContentType
ContentType describes the type of content a stage handles.
const ( // ContentTypeAny indicates the stage accepts any content type. ContentTypeAny ContentType = core.ContentTypeAny // ContentTypeText indicates text content. ContentTypeText ContentType = core.ContentTypeText // ContentTypeAudio indicates audio content. ContentTypeAudio ContentType = core.ContentTypeAudio // ContentTypeVideo indicates video content. ContentTypeVideo ContentType = core.ContentTypeVideo // ContentTypeImage indicates image content. ContentTypeImage ContentType = core.ContentTypeImage // ContentTypeMessage indicates a complete message. ContentTypeMessage ContentType = core.ContentTypeMessage // ContentTypeToolCall indicates a tool invocation. ContentTypeToolCall ContentType = core.ContentTypeToolCall )
type ContextAssemblyConfig ¶
type ContextAssemblyConfig struct {
// StateStoreConfig for accessing the store.
StateStoreConfig *rtpipeline.StateStoreConfig
// RecentMessages is the number of recent messages to include (hot window).
// Zero or negative means 20.
RecentMessages int
// MessageIndex for semantic retrieval of relevant older messages.
// When nil, only the hot window and summaries are used.
MessageIndex statestore.MessageIndex
// RetrievalTopK is the number of results to retrieve from the message index.
// Zero or negative disables retrieval.
RetrievalTopK int
// MaxMessages is the hard cap on total messages retained when no explicit
// context window is set. System messages at the start are always preserved.
// Zero or negative means DefaultMaxMessages (200).
MaxMessages int
// WarningThreshold is the message count above which a warning is logged
// when no context window or token budget is configured.
// Zero or negative means DefaultWarningThreshold (100).
WarningThreshold int
// HasTokenBudget indicates whether a token budget stage is configured
// downstream. When true, the large-conversation warning is suppressed
// because the token budget stage handles overflow.
HasTokenBudget bool
// HasContextWindow indicates whether an explicit context window (hot
// window) size was set by the caller. When false and messages exceed
// MaxMessages, automatic truncation is applied.
HasContextWindow bool
}
ContextAssemblyConfig configures the ContextAssemblyStage.
type ContextAssemblyStage ¶
type ContextAssemblyStage struct {
BaseStage
// contains filtered or unexported fields
}
ContextAssemblyStage loads a subset of conversation history using efficient partial reads (MessageReader) instead of loading the full state. It assembles context from three tiers: summaries, semantically retrieved messages, and the most recent messages (hot window).
When the store doesn't implement MessageReader, it falls back to loading all history via Store.Load (same behavior as StateStoreLoadStage).
func NewContextAssemblyStage ¶
func NewContextAssemblyStage(config *ContextAssemblyConfig) *ContextAssemblyStage
NewContextAssemblyStage creates a new context assembly stage.
func NewContextAssemblyStageWithTurnState ¶
func NewContextAssemblyStageWithTurnState( config *ContextAssemblyConfig, turnState *TurnState, ) *ContextAssemblyStage
NewContextAssemblyStageWithTurnState creates a context assembly stage that publishes ConversationID/UserID onto the supplied TurnState.
func (*ContextAssemblyStage) Process ¶
func (s *ContextAssemblyStage) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process loads context tiers and emits them before the current input.
type ContextBuilderPolicy ¶
type ContextBuilderPolicy struct {
TokenBudget int
ReserveForOutput int
Strategy TruncationStrategy
CacheBreakpoints bool
// RelevanceConfig for TruncateLeastRelevant strategy.
// Required when using TruncateLeastRelevant; must include EmbeddingProvider.
RelevanceConfig *RelevanceConfig
// Summarizer for TruncateSummarize strategy.
// When set, messages that exceed the budget are compressed into summaries
// rather than dropped. Required when using TruncateSummarize.
Summarizer statestore.Summarizer
// TokenCounter provides token counting for budget management.
// If nil, a default heuristic counter is used with ModelFamilyDefault ratio (1.35).
// Use tokenizer.NewTokenCounterForModel(modelName) to create a model-aware counter.
TokenCounter tokenizer.TokenCounter
}
ContextBuilderPolicy defines token budget and truncation behavior.
type ContextBuilderStage ¶
type ContextBuilderStage struct {
BaseStage
// contains filtered or unexported fields
}
ContextBuilderStage manages token budget and truncates messages if needed.
This stage ensures the conversation context fits within the LLM's token budget by applying truncation strategies when messages exceed the limit.
Token budget calculation:
available = TokenBudget - ReserveForOutput - systemPromptTokens
Truncation strategies (TruncationStrategy):
- TruncateOldest: removes oldest messages first (keeps most recent context)
- TruncateLeastRelevant: removes least relevant messages (requires RelevanceConfig with EmbeddingProvider)
- TruncateSummarize: replaces older messages with a summary from the policy's Summarizer (falls back to TruncateOldest without one)
- TruncateFail: returns error if budget exceeded (strict mode)
Whatever the strategy, the truncated history starts at a user message and keeps a tool call only with all of its results. When the budget cannot fit any user message (the current turn does not fit), the stage returns an error rather than send a request with no question in it.
Configuration (ContextBuilderPolicy):
- TokenBudget: total tokens allowed (0 = unlimited, pass-through mode)
- ReserveForOutput: tokens reserved for LLM response
- Strategy: truncation strategy to apply
- CacheBreakpoints: enable prompt caching hints
Metadata set on the emitted elements:
- Meta.ContextTruncated: true if truncation was applied
- Meta.EnableCacheBreakpoints: true if policy.CacheBreakpoints is set
An unrecognized Strategy truncates like TruncateOldest.
This is an Accumulate stage: N input elements produce N (possibly fewer) output elements.
func NewContextBuilderStage ¶
func NewContextBuilderStage(policy *ContextBuilderPolicy) *ContextBuilderStage
NewContextBuilderStage creates a context builder stage with no TurnState wired. Useful for tests; production callers should use NewContextBuilderStageWithTurnState so the system prompt is available for token-budget accounting.
func NewContextBuilderStageWithTurnState ¶
func NewContextBuilderStageWithTurnState(policy *ContextBuilderPolicy, turnState *TurnState) *ContextBuilderStage
NewContextBuilderStageWithTurnState creates a context builder stage that reads the system prompt from the shared *TurnState.
func (*ContextBuilderStage) Process ¶
func (s *ContextBuilderStage) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process enforces token budget and truncates messages if needed.
type ContextCompactor ¶
type ContextCompactor = compaction.ContextCompactor
ContextCompactor is the default CompactionStrategy. It applies rules in order to fold stale messages until context is under the token budget. Deterministic, zero LLM calls.
type CueKind ¶ added in v2.22.0
CueKind says what a cue is for.
const CueGuardrailMessage CueKind = core.CueGuardrailMessage
CueGuardrailMessage is a guardrail's message, spoken when it cuts a reply or blocks typed input.
type CueOptions ¶ added in v2.22.0
type CueOptions = cue.CueOptions
CueOptions configures the cue stage NewDuplexCueStage builds.
type DebugStage ¶
type DebugStage struct {
BaseStage
// contains filtered or unexported fields
}
DebugStage logs StreamElements for debugging pipeline state. Useful for development and troubleshooting.
func NewDebugStage ¶
func NewDebugStage(stageName string) *DebugStage
NewDebugStage creates a debug stage that logs elements at a specific pipeline location.
func (*DebugStage) Process ¶
func (s *DebugStage) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process logs each element as it passes through (passthrough transform).
type DropStrategy ¶
type DropStrategy = media.DropStrategy
DropStrategy defines how frames are dropped when rate limiting.
const ( // DropStrategyKeepLatest keeps the most recent frame and drops older ones. // This ensures the model sees the most current state. DropStrategyKeepLatest DropStrategy = media.DropStrategyKeepLatest // DropStrategyUniform attempts to keep frames uniformly distributed. // This provides a more representative sampling across time. DropStrategyUniform DropStrategy = media.DropStrategyUniform )
type DuplexProviderStage ¶
type DuplexProviderStage = duplex.DuplexProviderStage
DuplexProviderStage handles bidirectional streaming through a session. It forwards elements from input to the provider's session and forwards responses from the session to output.
This stage is PROVIDER-AGNOSTIC. Provider-specific behaviors (interruptions, reconnection, protocol quirks) are handled BY the provider internally.
System Prompt Handling: The first element received may contain a system prompt in metadata["system_prompt"]. This is sent to the session via SendSystemContext() before processing audio/text.
Response Accumulation: Streaming providers send text/audio responses in chunks. This stage accumulates content across chunks and creates a Message on turn completion (FinishReason).
Session Closure: When the session closes unexpectedly, any accumulated content is emitted as a partial response. The executor is responsible for session recreation if needed.
This is a Bidirectional stage: input elements ⟷ session ⟷ output elements
func NewDuplexProviderStage ¶
func NewDuplexProviderStage(provider providers.StreamInputSupport, baseConfig *providers.StreamingInputConfig) *DuplexProviderStage
NewDuplexProviderStage creates a new duplex provider stage. The session is created lazily when the first element arrives. Prefer NewDuplexProviderStageWithTurnState in production so the system prompt is sourced from the per-Turn shared state.
func NewDuplexProviderStageWithEmitter ¶
func NewDuplexProviderStageWithEmitter(provider providers.StreamInputSupport, baseConfig *providers.StreamingInputConfig, emitter *events.Emitter) *DuplexProviderStage
NewDuplexProviderStageWithEmitter creates a new duplex provider stage with event emission support. The stage emits audio.input and audio.output events through it for session recording.
func NewDuplexProviderStageWithTurnState ¶
func NewDuplexProviderStageWithTurnState(provider providers.StreamInputSupport, baseConfig *providers.StreamingInputConfig, emitter *events.Emitter, turnState *TurnState) *DuplexProviderStage
NewDuplexProviderStageWithTurnState creates a new duplex provider stage that sources system_prompt from the shared *TurnState. The emitter remains optional.
type DuplexToolConfig ¶ added in v2.22.0
type DuplexToolConfig = duplex.DuplexToolConfig
DuplexToolConfig is what a DuplexProviderStage's tool calls run with, as the matching ProviderConfig fields are for ProviderStage.
type ElementMetadata ¶
type ElementMetadata = core.ElementMetadata
ElementMetadata is the typed schema for per-element coordination data. Unlike TurnState (which is per-Turn-invariant), fields here genuinely differ between elements within the same Turn.
Only data that differs between elements of the same Turn belongs here.
type EndInputter ¶
type EndInputter = duplex.EndInputter
EndInputter is an optional interface for sessions that support explicit end-of-input signaling. This is primarily used by mock sessions to trigger responses after all audio has been sent.
type ExecutionResult ¶
type ExecutionResult struct {
Messages []types.Message // All messages in the conversation
Response *Response // The final response
Trace ExecutionTrace // Execution trace
CostInfo types.CostInfo // Cost information
PendingTools []tools.PendingToolExecution // Tool calls suspended awaiting out-of-band completion
Metadata map[string]interface{} // Additional metadata
}
ExecutionResult represents the final result of a pipeline execution. This matches the existing pipeline.ExecutionResult for compatibility.
type ExecutionTrace ¶
ExecutionTrace captures execution history (for compatibility).
type FilterStage ¶
type FilterStage = core.FilterStage
FilterStage filters elements based on a predicate function.
func NewFilterStage ¶
func NewFilterStage(name string, predicate func(StreamElement) bool) *FilterStage
NewFilterStage creates a new filter stage.
type FormatCapable ¶
type FormatCapable = core.FormatCapable
FormatCapable is an optional interface that stages can implement to declare their input/output format requirements. Stages that don't implement this are treated as accepting/producing any format.
type FrameExtractionMode ¶
type FrameExtractionMode = media.FrameExtractionMode
FrameExtractionMode defines how frames are selected from video.
const ( // FrameExtractionInterval extracts frames at fixed time intervals. FrameExtractionInterval FrameExtractionMode = media.FrameExtractionInterval // FrameExtractionKeyframes extracts only keyframes (I-frames). FrameExtractionKeyframes FrameExtractionMode = media.FrameExtractionKeyframes // FrameExtractionFPS extracts at a specific frame rate. FrameExtractionFPS FrameExtractionMode = media.FrameExtractionFPS )
type FrameRateLimitConfig ¶
type FrameRateLimitConfig = media.FrameRateLimitConfig
FrameRateLimitConfig configures the FrameRateLimitStage behavior.
func DefaultFrameRateLimitConfig ¶
func DefaultFrameRateLimitConfig() FrameRateLimitConfig
DefaultFrameRateLimitConfig returns sensible defaults for frame rate limiting.
type FrameRateLimitStage ¶
type FrameRateLimitStage = media.FrameRateLimitStage
FrameRateLimitStage drops frames to maintain a target frame rate. This is useful for high-FPS video feeds (e.g., 30fps webcam) that need to be reduced to a rate suitable for LLM processing (e.g., 1fps).
This is a Transform stage that may drop elements (N:M where M <= N).
func NewFrameRateLimitStage ¶
func NewFrameRateLimitStage(config FrameRateLimitConfig) *FrameRateLimitStage
NewFrameRateLimitStage creates a new frame rate limiting stage.
type FrameSelectionStrategy ¶
type FrameSelectionStrategy = media.FrameSelectionStrategy
FrameSelectionStrategy defines how frames are selected when limiting.
const ( // FrameSelectionUniform selects frames uniformly distributed across the video. FrameSelectionUniform FrameSelectionStrategy = media.FrameSelectionUniform // FrameSelectionFirst selects the first N frames. FrameSelectionFirst FrameSelectionStrategy = media.FrameSelectionFirst // FrameSelectionLast selects the last N frames. FrameSelectionLast FrameSelectionStrategy = media.FrameSelectionLast )
type FramesToMessageConfig ¶
type FramesToMessageConfig = media.FramesToMessageConfig
FramesToMessageConfig configures the FramesToMessageStage behavior.
func DefaultFramesToMessageConfig ¶
func DefaultFramesToMessageConfig() FramesToMessageConfig
DefaultFramesToMessageConfig returns sensible defaults for frame composition.
type FramesToMessageStage ¶
type FramesToMessageStage = media.FramesToMessageStage
FramesToMessageStage collects extracted frames and composes them into Messages. Elements are correlated by video ID from VideoToFramesStage metadata.
Input: StreamElements with Image and video_frames metadata Output: StreamElement with Message containing composed image Parts[]
Non-frame elements (those without video_frames metadata) are passed through unchanged.
This is an Accumulate stage (N:1 fan-in pattern).
func NewFramesToMessageStage ¶
func NewFramesToMessageStage(config FramesToMessageConfig) *FramesToMessageStage
NewFramesToMessageStage creates a new frame composition stage.
type Handoff ¶
Handoff describes the prompt and tool set the workflow's current state needs.
It states what the turn should be running. It does not record that something changed: the stage compares it against what the turn is actually running and swaps only on a mismatch. A pipeline re-execution (HITL resume, deferred client tool) re-runs PromptAssemblyStage, which resets the turn's prompt to the state the pipeline was built for, so a "did a transition happen this run" signal is unobservable by then, while a "what should be running" signal self-corrects.
type HandoffCall ¶ added in v2.13.0
type HandoffCall = provider.HandoffCall
HandoffCall is what the current state's prompt runs on: its provider and its sampling parameters (prompt.Registry.CallParameters).
type HashRouter ¶
type HashRouter struct {
BaseStage
// contains filtered or unexported fields
}
HashRouter routes elements based on consistent hashing of a key. This ensures elements with the same key always go to the same destination.
func NewHashRouter ¶
func NewHashRouter(name string, outputNames []string, keyFunc func(StreamElement) string) *HashRouter
NewHashRouter creates a router that uses consistent hashing. The keyFunc extracts a key from each element (e.g., session ID). Elements with the same key always route to the same destination.
func (*HashRouter) Process ¶
func (r *HashRouter) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process routes elements based on hash of key.
func (*HashRouter) RegisterOutput ¶
func (r *HashRouter) RegisterOutput(name string, output chan<- StreamElement)
RegisterOutput registers an output channel with a name.
type HeardReplies ¶ added in v2.22.0
type HeardReplies = heard.HeardReplies
HeardReplies carries what the caller heard of a cut reply from a cascaded voice pipeline's speech-out stage (TTSStageWithInterruption) back to its provider stage, so the model's next turn goes on from what was heard, as a realtime model goes on from the reply its provider truncated to it.
The provider stage keeps the conversation's history itself and wrote the whole reply into it; the speech-out stage, downstream, is the one that knows how much of it played. Share one HeardReplies between the two (ProviderConfig.HeardReplies, TTSStageWithInterruptionConfig.HeardReplies): the speech-out stage records each reply it cut, and the provider stage swaps it into its history before the next turn. A nil *HeardReplies does nothing.
func NewHeardReplies ¶ added in v2.22.0
func NewHeardReplies() *HeardReplies
NewHeardReplies returns an empty HeardReplies.
type ImageData ¶
ImageData carries image data with metadata. Supports externalization to avoid holding large data in memory.
type ImagePreprocessConfig ¶
type ImagePreprocessConfig = media.ImagePreprocessConfig
ImagePreprocessConfig contains configuration for the image preprocessing stage.
func DefaultImagePreprocessConfig ¶
func DefaultImagePreprocessConfig() ImagePreprocessConfig
DefaultImagePreprocessConfig returns sensible defaults for image preprocessing.
type ImagePreprocessStage ¶
type ImagePreprocessStage = media.ImagePreprocessStage
ImagePreprocessStage preprocesses images in messages before sending to providers. This stage processes images directly within Message.Parts[].Media, performing operations like resizing, format conversion, and size optimization.
This is a Transform stage: message with images → message with processed images (1:1)
func NewImagePreprocessStage ¶
func NewImagePreprocessStage(config ImagePreprocessConfig) *ImagePreprocessStage
NewImagePreprocessStage creates a new image preprocessing stage.
type ImageResizeStage ¶
type ImageResizeStage = media.ImageResizeStage
ImageResizeStage resizes images to fit within configured dimensions. This is useful for reducing image sizes before sending to providers or for normalizing images from different sources.
This is a Transform stage: image element → resized image element (1:1)
func NewImageResizeStage ¶
func NewImageResizeStage(config ImageResizeStageConfig) *ImageResizeStage
NewImageResizeStage creates a new image resizing stage.
type ImageResizeStageConfig ¶
type ImageResizeStageConfig = media.ImageResizeStageConfig
ImageResizeStageConfig is an alias for runtime/media's ImageResizeConfig. This provides stage-specific naming while avoiding code duplication.
func DefaultImageResizeStageConfig ¶
func DefaultImageResizeStageConfig() ImageResizeStageConfig
DefaultImageResizeStageConfig returns sensible defaults for image resizing.
type IncrementalSaveConfig ¶
type IncrementalSaveConfig = persist.IncrementalSaveConfig
IncrementalSaveConfig configures the IncrementalSaveStage.
type IncrementalSaveStage ¶
type IncrementalSaveStage = persist.IncrementalSaveStage
IncrementalSaveStage saves only new messages from the current turn using MessageAppender, avoiding the full load+replace+save cycle. When the store doesn't implement MessageAppender, it loads the state, appends the new messages and writes it back through BulkWriter. A store that implements neither makes the stage return an error.
func NewIncrementalSaveStage ¶
func NewIncrementalSaveStage(config *IncrementalSaveConfig) *IncrementalSaveStage
NewIncrementalSaveStage creates a new incremental save stage.
func NewIncrementalSaveStageWithTurnState ¶
func NewIncrementalSaveStageWithTurnState(config *IncrementalSaveConfig, turnState *TurnState) *IncrementalSaveStage
NewIncrementalSaveStageWithTurnState creates an incremental save stage that also merges TurnState.ProviderRequestMetadata into the persisted state on the fallback fullSave path.
type MapStage ¶
MapStage transforms elements using a mapping function.
Example ¶
ExampleMapStage demonstrates using a map stage to transform elements.
package main
import (
"context"
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/pipeline/stage"
"github.com/AltairaLabs/PromptKit/runtime/v2/types"
)
func main() {
// Create a map stage that uppercases text
uppercaseStage := stage.NewMapStage("uppercase", func(elem stage.StreamElement) (stage.StreamElement, error) {
if elem.Message != nil {
msg := *elem.Message
msg.Content = "TRANSFORMED: " + msg.Content
elem.Message = &msg
}
return elem, nil
})
// Build pipeline
pipeline, _ := stage.NewPipelineBuilder().
Chain(uppercaseStage).
Build()
// Execute
input := make(chan stage.StreamElement, 1)
input <- stage.NewMessageElement(&types.Message{
Role: "user",
Content: "hello",
})
close(input)
output, _ := pipeline.Execute(context.Background(), input)
for elem := range output {
if elem.Message != nil {
fmt.Printf("%s\n", elem.Message.Content)
}
}
}
Output: TRANSFORMED: hello
func NewMapStage ¶
func NewMapStage(name string, mapFunc func(StreamElement) (StreamElement, error)) *MapStage
NewMapStage creates a new map stage.
type MaxRoundsError ¶ added in v2.14.0
type MaxRoundsError = core.MaxRoundsError
MaxRoundsError is the error the provider stage returns when the tool loop reaches its round limit. It wraps ErrMaxRoundsExceeded.
type MediaComposeConfig ¶
type MediaComposeConfig = media.MediaComposeConfig
MediaComposeConfig configures the MediaComposeStage behavior.
func DefaultMediaComposeConfig ¶
func DefaultMediaComposeConfig() MediaComposeConfig
DefaultMediaComposeConfig returns sensible defaults for media composition.
type MediaComposeStage ¶
type MediaComposeStage = media.MediaComposeStage
MediaComposeStage collects processed media and composes back into messages. Elements are correlated by message ID from MediaExtractStage metadata.
Input: StreamElements with Image or Video and extract metadata Output: StreamElement with Message containing composed Parts[]
Non-media elements (those without extract metadata) are passed through unchanged.
This is an Accumulate stage (N:1 fan-in pattern).
func NewMediaComposeStage ¶
func NewMediaComposeStage(config MediaComposeConfig) *MediaComposeStage
NewMediaComposeStage creates a new media composition stage.
type MediaConvertConfig ¶
type MediaConvertConfig = media.MediaConvertConfig
MediaConvertConfig configures the MediaConvertStage behavior.
func DefaultMediaConvertConfig ¶
func DefaultMediaConvertConfig() MediaConvertConfig
DefaultMediaConvertConfig returns sensible defaults for media conversion.
type MediaConvertStage ¶
type MediaConvertStage = media.MediaConvertStage
MediaConvertStage converts media content to match target format requirements. This is useful for normalizing media from various sources to match provider capabilities.
This is a Transform stage: element → converted element (1:1)
func NewMediaConvertStage ¶
func NewMediaConvertStage(config *MediaConvertConfig) *MediaConvertStage
NewMediaConvertStage creates a new media conversion stage.
type MediaExternalizerConfig ¶
type MediaExternalizerConfig struct {
Enabled bool
StorageService storage.MediaStorageService
SizeThresholdKB int64
DefaultPolicy string
RunID string
SessionID string
ConversationID string
}
MediaExternalizerConfig configures media externalization behavior.
type MediaExternalizerStage ¶
type MediaExternalizerStage struct {
BaseStage
// contains filtered or unexported fields
}
MediaExternalizerStage externalizes large media content to external storage.
When messages contain large inline media (images, audio, video), this stage moves the data to external storage and replaces it with a storage reference. This reduces memory usage and allows for media lifecycle management.
Behavior:
- Skipped if Enabled=false or no StorageService configured
- Only externalizes media exceeding SizeThresholdKB (base64 size)
- Preserves media.StorageReference if already externalized
- Clears media.Data after successful externalization
Configuration:
- Enabled: master switch for externalization
- SizeThresholdKB: minimum size to externalize (0 = externalize all)
- StorageService: where to store media (S3, GCS, local filesystem, etc.)
- DefaultPolicy: retention policy name for stored media
This is a Transform stage: each input element produces one output element.
func NewMediaExternalizerStage ¶
func NewMediaExternalizerStage(config *MediaExternalizerConfig) *MediaExternalizerStage
NewMediaExternalizerStage creates a media externalizer stage.
func (*MediaExternalizerStage) Process ¶
func (s *MediaExternalizerStage) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process externalizes media from messages if they exceed size threshold.
type MediaExtractConfig ¶
type MediaExtractConfig = media.MediaExtractConfig
MediaExtractConfig configures the MediaExtractStage behavior.
func DefaultMediaExtractConfig ¶
func DefaultMediaExtractConfig() MediaExtractConfig
DefaultMediaExtractConfig returns sensible defaults for media extraction.
type MediaExtractInfo ¶
type MediaExtractInfo = core.MediaExtractInfo
MediaExtractInfo is the typed payload for media-extraction correlation.
type MediaExtractStage ¶
type MediaExtractStage = media.MediaExtractStage
MediaExtractStage extracts media from messages into individual StreamElements. This enables batch processing of images/videos through separate pipeline stages.
Input: StreamElement with Message containing Parts[] Output: Multiple StreamElements with Image or Video, preserving correlation metadata
For messages without media, the element is passed through unchanged.
This is a Transform stage with fan-out behavior (1 message → N media elements).
func NewMediaExtractStage ¶
func NewMediaExtractStage(config MediaExtractConfig) *MediaExtractStage
NewMediaExtractStage creates a new media extraction stage.
type MemoryExtractionStage ¶
type MemoryExtractionStage = persist.MemoryExtractionStage
MemoryExtractionStage extracts memories from the conversation after the provider responds. Runs late in the pipeline (before state persist). Calls Extractor.Extract() with the conversation messages and saves results via Store.Save().
No-op passthrough when extractor is nil.
func NewMemoryExtractionStage ¶
func NewMemoryExtractionStage(extractor memory.Extractor, store memory.Store, scope map[string]string) *MemoryExtractionStage
NewMemoryExtractionStage creates an extraction stage.
type MemoryRetrievalStage ¶
type MemoryRetrievalStage = persist.MemoryRetrievalStage
MemoryRetrievalStage injects relevant memories into the conversation context. Accumulates messages from input elements, then calls Retriever.RetrieveContext() once the input channel closes and writes the formatted memory context onto TurnState.Variables["memory_context"] for the template stage to consume.
It MUST be placed before TemplateStage. That stage is the single render point, and a variable written after it renders is invisible: the prompt reaches the model with {{memory_context}} unresolved while retrieval reports success.
No-op passthrough when retriever or turnState is nil.
func NewMemoryRetrievalStage ¶
func NewMemoryRetrievalStage(retriever memory.Retriever, store memory.Store, scope map[string]string) *MemoryRetrievalStage
NewMemoryRetrievalStage creates a retrieval stage.
func NewMemoryRetrievalStageWithTurnState ¶
func NewMemoryRetrievalStageWithTurnState(retriever memory.Retriever, store memory.Store, scope map[string]string, turnState *TurnState) *MemoryRetrievalStage
NewMemoryRetrievalStageWithTurnState creates a retrieval stage that publishes its formatted memory context onto the supplied TurnState.
type MergeStage ¶
type MergeStage struct {
BaseStage
// contains filtered or unexported fields
}
MergeStage merges multiple input channels into a single output channel. This enables fan-in patterns where multiple stages feed into one.
This is an Accumulate stage type that handles multiple inputs (N:1 merge).
func NewMergeStage ¶
func NewMergeStage(name string, inputCount int) *MergeStage
NewMergeStage creates a new merge stage that merges N inputs into 1 output.
func (*MergeStage) Process ¶
func (s *MergeStage) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process implements the Stage interface (single input). For merge stage, this is not typically used - use ProcessMultiple instead.
func (*MergeStage) ProcessMultiple ¶
func (s *MergeStage) ProcessMultiple( ctx context.Context, inputs []<-chan StreamElement, output chan<- StreamElement, ) error
ProcessMultiple processes multiple input channels and merges them into one output. This is a special method for merge stages that differs from the standard Process signature.
type MessageBroadcastStage ¶
type MessageBroadcastStage = persist.MessageBroadcastStage
MessageBroadcastStage publishes message.created on the EventBus for each new complete message that streams through it, and forwards every element unchanged.
This is the live route for messages: asynchronous, lossy, binary stripped. It suits a consumer watching a conversation unfold, such as a TUI, an SSE relay or a log tail. It needs no EventStore and no state store, so it works on any pipeline that has an emitter.
RecordingStage is the fidelity route for the same event type: synchronous, lossless, full binary, opt-in, straight to an EventStore. Both build their payload with events.NewMessageCreatedData, so they carry the same data for the same message except Parts.
No binary data reaches the bus, whether or not recording is on. A subscriber gets the message text, along with MIME type, dimensions, size and URL references for any media, and never the media itself.
The bus is lossy under burst, so a live view can miss a message. The state store remains the source of truth for the transcript.
Index is transcript-absolute, and history is never re-published, so a subscriber sees each message once at the position the persisted transcript will hold it. Two details make that work:
The counter is local to each Process call, never a field on the stage. A pipeline is built once and re-executed per turn, and stage objects are shared across concurrent Execute calls. Counting per execution is correct because the provider re-emits the whole accumulated transcript on every turn.
History is detected by Message.Source, not by Meta.FromHistory. ProviderStage rebuilds every message with NewMessageElement, which produces a zero Meta, so element metadata does not survive to any stage downstream of the provider. Source travels with the message value. IncrementalSaveStage uses the same predicate for the same question.
Placement: the stage must sit where it observes every message element, in transcript order, within a single Process call. The pipeline is a DAG (PipelineBuilder offers Branch, Merge and Connect, and RouterStage does selective fan-out), and nothing enforces this.
Downstream of every message producer. Assistant messages are created by ProviderStage, by CompositionStage (which replaces ProviderStage for composition states), and by the media-compose and video-frame stages. A message routed down a branch this stage is not on is never published.
On an order-preserving path. Index is the element's position in the stream this call saw. It is transcript-absolute because the provider re-emits the accumulated transcript in order down a linear chain. MergeStage spawns a goroutine per input, so downstream of a fan-in the interleaving, and therefore Index, is nondeterministic. Completeness survives a merge; ordering does not.
The stage does not need to be adjacent to the save stage. The SDK builder places it immediately before that sink so a message broadcasts as soon as it exists.
The bus delivers to each subscriber in publish order. Index is still the reliable way to reassemble a transcript: it stays correct when a subscriber's queue overflows and drops an event, or when the stage sits downstream of a fan-in that interleaves elements.
func NewMessageBroadcastStage ¶
func NewMessageBroadcastStage(emitter *events.Emitter) *MessageBroadcastStage
NewMessageBroadcastStage creates a message broadcast stage. A nil emitter makes the stage an inert pass-through.
type MetricsStage ¶
type MetricsStage struct {
BaseStage
// contains filtered or unexported fields
}
MetricsStage wraps another stage and collects metrics about its performance. This is a transparent wrapper that doesn't modify element flow.
func NewMetricsStage ¶
func NewMetricsStage(wrappedStage Stage) *MetricsStage
NewMetricsStage wraps a stage with metrics collection.
func (*MetricsStage) GetMetrics ¶
func (s *MetricsStage) GetMetrics() StageMetrics
GetMetrics returns the collected metrics.
func (*MetricsStage) Process ¶
func (s *MetricsStage) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process implements the Stage interface with metrics collection.
type MultiInputStage ¶
type MultiInputStage = core.MultiInputStage
MultiInputStage is a Stage that consumes multiple upstream input channels (fan-in / N:1 merge). The pipeline calls ProcessMultiple instead of Process when the stage has more than one upstream edge. Like Process, the stage MUST close output when all inputs are drained.
type MultiOutputStage ¶
type MultiOutputStage = core.MultiOutputStage
MultiOutputStage is a Stage that routes elements to named downstream outputs (selective fan-out / 1:N routing). The pipeline registers one channel per downstream edge via RegisterOutput before Process runs; the stage routes each element to the appropriate registered output(s) and MUST close them when done.
Single-Execute caveat: RegisterOutput is called on the stage instance (e.g. RouterStage.outputs) fresh on every StreamPipeline.Execute() call, since the per-Execute edge channels live for the duration of that Execute() only. A pipeline containing a MultiOutputStage is therefore only safe for a single (or strictly sequential, non-concurrent) Execute() call. Concurrent Execute() calls on the same pipeline would race registering and routing through the stage's shared output registry. The long-running duplex streaming session, which calls Execute once, is the intended use. Callers that reuse one *StreamPipeline across concurrent Execute() calls (e.g. the unary Send() path) must not include a MultiOutputStage in that pipeline.
type PassthroughStage ¶
type PassthroughStage = core.PassthroughStage
PassthroughStage is a simple stage that passes all elements through unchanged. Useful for testing or as a placeholder.
func NewPassthroughStage ¶
func NewPassthroughStage(name string) *PassthroughStage
NewPassthroughStage creates a new passthrough stage.
type PipelineBuilder ¶
type PipelineBuilder struct {
// contains filtered or unexported fields
}
PipelineBuilder constructs a pipeline DAG. It provides methods for creating linear chains and branching topologies.
Example ¶
ExamplePipelineBuilder demonstrates building a simple linear pipeline.
package main
import (
"context"
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/pipeline/stage"
"github.com/AltairaLabs/PromptKit/runtime/v2/types"
)
func main() {
// Create some simple stages
inputStage := stage.NewPassthroughStage("input")
processStage := stage.NewPassthroughStage("process")
outputStage := stage.NewPassthroughStage("output")
// Build a linear pipeline
pipeline, err := stage.NewPipelineBuilder().
Chain(inputStage, processStage, outputStage).
Build()
if err != nil {
fmt.Printf("Error building pipeline: %v\n", err)
return
}
// Create input channel with a message
input := make(chan stage.StreamElement, 1)
input <- stage.NewMessageElement(&types.Message{
Role: "user",
Content: "Hello, world!",
})
close(input)
// Execute pipeline
ctx := context.Background()
output, err := pipeline.Execute(ctx, input)
if err != nil {
fmt.Printf("Error executing pipeline: %v\n", err)
return
}
// Consume output
for elem := range output {
if elem.Message != nil {
fmt.Printf("Received message: %s\n", elem.Message.Content)
}
}
}
Output: Received message: Hello, world!
Example (WithConfig) ¶
ExamplePipelineBuilder_withConfig demonstrates building a pipeline with custom configuration.
package main
import (
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/pipeline/stage"
)
func main() {
// Create custom config
config := stage.DefaultPipelineConfig().
WithChannelBufferSize(32)
// Build pipeline with config
pipeline, err := stage.NewPipelineBuilderWithConfig(config).
Chain(
stage.NewPassthroughStage("stage1"),
stage.NewPassthroughStage("stage2"),
).
Build()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Pipeline created with %d stages\n", 2)
_ = pipeline
}
Output: Pipeline created with 2 stages
func NewPipelineBuilder ¶
func NewPipelineBuilder() *PipelineBuilder
NewPipelineBuilder creates a new PipelineBuilder with default configuration.
func NewPipelineBuilderWithConfig ¶
func NewPipelineBuilderWithConfig(config *PipelineConfig) *PipelineBuilder
NewPipelineBuilderWithConfig creates a new PipelineBuilder with custom configuration.
func (*PipelineBuilder) AddStage ¶
func (b *PipelineBuilder) AddStage(stage Stage) *PipelineBuilder
AddStage adds a stage to the builder without connecting it. This is useful when building complex topologies manually.
func (*PipelineBuilder) Branch ¶
func (b *PipelineBuilder) Branch(fromStage string, toStages ...string) *PipelineBuilder
Branch creates multiple outgoing connections from a single stage. The downstream stages share stage B's output channel and compete for it: each element goes to whichever downstream stage reads it first, not to all of them. To deliver every element to every branch, make the branching stage a BroadcastRouter: the pipeline gives each stage downstream of a router its own channel, and the router closes them all when it returns.
Example:
pipeline, err := NewPipelineBuilder().
Chain(NewStageA(), NewStageB()).
Branch("stageB", "stageC", "stageD"). // each element of B's output goes to C or D
Build()
func (*PipelineBuilder) Build ¶
func (b *PipelineBuilder) Build() (*StreamPipeline, error)
Build constructs the pipeline from the builder's configuration. It validates the pipeline structure and returns an error if invalid: no stages (ErrNoStages), an invalid PipelineConfig, a duplicate stage name (ErrDuplicateStageName), an edge to an unknown stage (ErrStageNotFound), a cycle (ErrCyclicDependency), a duplicate edge (ErrDuplicateFanInEdge), a fan-in stage that does not implement MultiInputStage (ErrFanInNotSupported), or a TemplateStage or PromptAssemblyStage without a TurnState (ErrTurnStateRequired, wrapped in ErrInvalidPipeline).
func (*PipelineBuilder) Chain ¶
func (b *PipelineBuilder) Chain(stages ...Stage) *PipelineBuilder
Chain creates a linear chain of stages. This is the most common pattern: stage1 -> stage2 -> stage3. Each stage's output is connected to the next stage's input.
Example:
pipeline, err := NewPipelineBuilder().
Chain(
NewStageA(),
NewStageB(),
NewStageC(),
).
Build()
func (*PipelineBuilder) Clone ¶
func (b *PipelineBuilder) Clone() *PipelineBuilder
Clone creates a deep copy of the builder.
func (*PipelineBuilder) Connect ¶
func (b *PipelineBuilder) Connect(fromStage, toStage string) *PipelineBuilder
Connect creates a directed edge from one stage to another. The output of fromStage will be connected to the input of toStage.
func (*PipelineBuilder) Merge ¶
func (b *PipelineBuilder) Merge(into string, from ...string) *PipelineBuilder
Merge wires multiple upstream stages into a single downstream fan-in node. The target stage must implement MultiInputStage (e.g. MergeStage).
func (*PipelineBuilder) WithConfig ¶
func (b *PipelineBuilder) WithConfig(config *PipelineConfig) *PipelineBuilder
WithConfig sets the pipeline configuration.
func (*PipelineBuilder) WithEventEmitter ¶
func (b *PipelineBuilder) WithEventEmitter(emitter *events.Emitter) *PipelineBuilder
WithEventEmitter sets the event emitter for the pipeline.
type PipelineConfig ¶
type PipelineConfig struct {
// ChannelBufferSize controls buffering between stages.
// Smaller values = lower latency but more backpressure.
// Larger values = higher throughput but more memory usage.
// Default: 32
ChannelBufferSize int
// MaxConcurrentPipelines limits how many executions of one pipeline run at
// once. When the limit is reached, Execute waits for a running execution to
// finish. It returns the context's error if ctx ends first, and
// ErrPipelineShuttingDown if Shutdown is called first. Zero means no limit.
// Validate rejects negative values. Build reads it, so changing it later
// has no effect on a built pipeline.
// Default: 100
MaxConcurrentPipelines int
// PrioritizeElements makes each stage read its input in priority order: a
// higher-priority element queued behind lower-priority ones is delivered
// first, and elements of equal priority keep the order they were sent in.
// Up to ChannelBufferSize elements wait in each stage's priority queue.
//
// With it a control element can overtake content sent before it: an
// EndOfTurn or EndOfStream (PriorityCritical) can reach a stage ahead of
// the turn's text or audio. Enable it only when every stage tolerates that.
// The streaming provider stage does not: it fires a turn on EndOfTurn, so
// an EndOfTurn ahead of the turn's messages fires nothing and holds the
// messages for the next turn. False (the default) delivers every element
// in the order it was sent, whatever its priority.
PrioritizeElements bool
// ExecutionTimeout sets a hard maximum duration for a single pipeline execution.
// This is a safety ceiling. Prefer IdleTimeout for liveness detection.
// Set to 0 to disable (default).
ExecutionTimeout time.Duration
// IdleTimeout sets the maximum duration of inactivity before the pipeline is
// canceled. The timer resets on each streaming chunk, round completion, and
// tool completion, and is held open for as long as tool calls are running.
// A tool in flight is not an idle pipeline, and slow tools are bounded by
// their own TimeoutMs instead. Set to 0 to disable.
// Default: 30 seconds.
IdleTimeout time.Duration
// GracefulShutdownTimeout sets the maximum time to wait for in-flight executions during shutdown.
// Default: 10 seconds
GracefulShutdownTimeout time.Duration
// ProviderBinding, when non-nil, is attached to the execution context so
// checks can resolve the LOGICAL provider names their pack declared
// (evals.BindingFromContext). The host owns the mapping; the pipeline only
// carries it.
ProviderBinding evals.ProviderBinding
// InferenceRegistry, when non-nil, is attached to the execution
// context (via inference.WithRegistry) so stages and downstream
// consumers resolve inference providers with inference.FromContext.
InferenceRegistry *inference.Registry
// ClassifyRegistry is ignored.
//
// Deprecated: use InferenceRegistry. Kept only for v2 compatibility;
// removed in v3.
ClassifyRegistry *classify.Registry
}
PipelineConfig defines configuration options for pipeline execution.
func DefaultPipelineConfig ¶
func DefaultPipelineConfig() *PipelineConfig
DefaultPipelineConfig returns a PipelineConfig with sensible defaults.
func (*PipelineConfig) Validate ¶
func (c *PipelineConfig) Validate() error
Validate checks if the configuration is valid.
func (*PipelineConfig) WithChannelBufferSize ¶
func (c *PipelineConfig) WithChannelBufferSize(size int) *PipelineConfig
WithChannelBufferSize sets the channel buffer size.
func (*PipelineConfig) WithExecutionTimeout ¶
func (c *PipelineConfig) WithExecutionTimeout(timeout time.Duration) *PipelineConfig
WithExecutionTimeout sets the execution timeout.
func (*PipelineConfig) WithGracefulShutdownTimeout ¶
func (c *PipelineConfig) WithGracefulShutdownTimeout(timeout time.Duration) *PipelineConfig
WithGracefulShutdownTimeout sets the graceful shutdown timeout.
func (*PipelineConfig) WithIdleTimeout ¶
func (c *PipelineConfig) WithIdleTimeout(timeout time.Duration) *PipelineConfig
WithIdleTimeout sets the idle timeout.
func (*PipelineConfig) WithMaxConcurrentPipelines ¶
func (c *PipelineConfig) WithMaxConcurrentPipelines(maxPipelines int) *PipelineConfig
WithMaxConcurrentPipelines sets the maximum number of concurrent pipeline executions.
func (*PipelineConfig) WithPrioritizeElements ¶ added in v2.17.0
func (c *PipelineConfig) WithPrioritizeElements(prioritize bool) *PipelineConfig
WithPrioritizeElements sets whether stages read their input in priority order.
type PlayoutHoldStage ¶ added in v2.22.0
type PlayoutHoldStage = duplex.PlayoutHoldStage
PlayoutHoldStage keeps a realtime reply out of the transcript until the caller has heard it. A realtime model sends a reply's audio faster than it plays, so the reply completes long before the caller has heard it, and a caller who barges in while it plays hears only part of it.
The stage estimates playout from the audio it forwards (audio.Playout, the estimate the realtime providers use to cut their own copy of the reply). It assumes the audio is played in real time as it arrives, so it belongs only in a pipeline that plays to a listener (the SDK wires it for a paced speaker or WithPlayoutTracking).
When a reply that has audio completes, its Message is held: the element still goes on at once, marked Meta.PlayoutHeld (and stamped with the time it was held) so the transcript stages (recording, message broadcast, memory, save) skip it, and every Message after it is held too, so the transcript keeps its order. When the audio has played out, each held Message is released unchanged on a Meta.PlayoutRelease element. When the caller barges in (an element marked Meta.Interrupted) or the session ends first (input closed or the context canceled), a reply not fully heard is released with its full text and FinishReason, plus Meta heard_ms, audio_ms, played_fraction and playout_cut. The text is not cut: the providers' audio transcripts carry no timing, so what the caller heard cannot be mapped to words.
A reply cut while it still arrives (an Interrupt element: a guardrail's cut, marked safety, or a barge-in the provider reported as the reply's end) is not held: its Message records what was heard before the cut, with playout_cut guardrail or barge-in.
A reply without audio, with nothing held ahead of it, passes unchanged.
func NewPlayoutHoldStage ¶ added in v2.22.0
func NewPlayoutHoldStage() *PlayoutHoldStage
NewPlayoutHoldStage creates a playout hold stage.
type Priority ¶
Priority defines the scheduling priority for stream elements. PriorityChannel delivers higher priority elements first. The channels between pipeline stages deliver elements in the order they were sent, whatever their priority, unless PipelineConfig.PrioritizeElements is set.
const ( // PriorityLow is for non-critical data like logs or metrics PriorityLow Priority = core.PriorityLow // PriorityNormal is the default priority for most elements PriorityNormal Priority = core.PriorityNormal // PriorityHigh is for real-time audio/video that requires low latency PriorityHigh Priority = core.PriorityHigh // PriorityCritical is for control signals, errors, and system messages PriorityCritical Priority = core.PriorityCritical )
type PriorityChannel ¶
type PriorityChannel struct {
// contains filtered or unexported fields
}
PriorityChannel is a channel that supports priority-based element delivery. Higher priority elements are delivered before lower priority elements, and elements of equal priority in the order they were sent. With PipelineConfig.PrioritizeElements set, each stage reads its input through one.
func NewPriorityChannel ¶
func NewPriorityChannel(capacity int) *PriorityChannel
NewPriorityChannel creates a new priority channel with the given capacity.
func (*PriorityChannel) Close ¶
func (pc *PriorityChannel) Close()
Close closes the priority channel.
func (*PriorityChannel) Len ¶
func (pc *PriorityChannel) Len() int
Len returns the current number of elements in the channel.
func (*PriorityChannel) Receive ¶
func (pc *PriorityChannel) Receive(ctx context.Context) (StreamElement, bool, error)
Receive receives the highest priority element from the channel. Blocks if the channel is empty, until an element arrives, the channel is closed, or ctx ends.
func (*PriorityChannel) Send ¶
func (pc *PriorityChannel) Send(ctx context.Context, elem StreamElement) error
Send sends an element to the priority channel. Blocks if the channel is at capacity, until there is room or ctx ends. A priority outside PriorityLow..PriorityCritical is treated as the nearest of the two.
type PromptAssemblyStage ¶
type PromptAssemblyStage struct {
BaseStage
// contains filtered or unexported fields
}
PromptAssemblyStage loads and assembles prompts from the prompt registry. It populates TurnState (Template, AllowedTools, Validators) on its first iteration; downstream stages read from TurnState.
func NewPromptAssemblyStage ¶
func NewPromptAssemblyStage( promptRegistry *prompt.Registry, taskType string, baseVariables map[string]string, ) *PromptAssemblyStage
NewPromptAssemblyStage creates a prompt assembly stage with no TurnState wired. Such a stage loads the template and has nowhere to publish it, so PipelineBuilder.Build rejects it with ErrTurnStateRequired; use NewPromptAssemblyStageWithTurnState in a pipeline so downstream stages can read the loaded template.
func NewPromptAssemblyStageWithTurnState ¶
func NewPromptAssemblyStageWithTurnState( promptRegistry *prompt.Registry, taskType string, baseVariables map[string]string, turnState *TurnState, ) *PromptAssemblyStage
NewPromptAssemblyStageWithTurnState creates a stage that publishes the loaded template, allowed tools, and validator configs onto the supplied TurnState before forwarding the first element.
func (*PromptAssemblyStage) Process ¶
func (s *PromptAssemblyStage) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process loads the prompt template and populates TurnState. It does not render the template (TemplateStage does) and does not set variables (VariableProviderStage does). All input elements are forwarded unchanged.
The template is loaded when the first element arrives, so the turn's variables (TurnState.Variables, which VariableProviderStage publishes before it forwards anything) are known: a fragment whose name a variable chooses resolves from them, whichever source set the variable.
func (*PromptAssemblyStage) WithModel ¶ added in v2.13.0
func (s *PromptAssemblyStage) WithModel(model string) *PromptAssemblyStage
WithModel sets the model of the provider that runs this prompt, so the prompt's model_overrides entry for it applies. Returns the stage.
type ProviderBudgetedCompaction ¶ added in v2.13.0
type ProviderBudgetedCompaction = compaction.ProviderBudgetedCompaction
ProviderBudgetedCompaction is a CompactionStrategy whose budget follows the provider a round runs on. ForProvider returns the strategy for p.
type ProviderConfig ¶
type ProviderConfig = provider.ProviderConfig
ProviderConfig contains configuration for the provider stage.
type ProviderStage ¶
type ProviderStage = provider.ProviderStage
ProviderStage executes LLM calls and handles tool execution.
With ProviderConfig.Streaming unset it runs in request/response mode: it reads its input to the end, calls the model, runs the tool loop, and emits the resulting messages. With Streaming set it fires on each EndOfTurn element and stays open for the next turn.
In request/response mode a failed call makes the stage emit the error as an error element and return it, so the caller receives the provider's error as the provider returned it, not wrapped in a *StageError. A tool loop that reaches its round limit ends the same way with a *MaxRoundsError. In streaming mode a failed turn emits the error element and the stage stays open for the next turn. If an upstream stage failed the turn, the stage forwards that failure and does not call the model.
func NewProviderStage ¶
func NewProviderStage(provider providers.Provider, toolRegistry *tools.Registry, toolPolicy *pipeline.ToolPolicy, config *ProviderConfig) *ProviderStage
NewProviderStage creates a new provider stage for request/response mode.
func NewProviderStageWithEmitter ¶
func NewProviderStageWithEmitter(provider providers.Provider, toolRegistry *tools.Registry, toolPolicy *pipeline.ToolPolicy, config *ProviderConfig, emitter *events.Emitter) *ProviderStage
NewProviderStageWithEmitter creates a new provider stage with event emission support. The stage emits provider.call.started, provider.call.completed, and provider.call.failed events through it for observability and session recording.
func NewProviderStageWithHooks ¶
func NewProviderStageWithHooks(provider providers.Provider, toolRegistry *tools.Registry, toolPolicy *pipeline.ToolPolicy, config *ProviderConfig, emitter *events.Emitter, hookRegistry *hooks.Registry) *ProviderStage
NewProviderStageWithHooks creates a provider stage with event emission and hook support. The hookRegistry enables synchronous interception of provider calls, streaming chunks, and tool execution. Pass nil for no hooks (zero overhead).
func NewProviderStageWithTurnState ¶
func NewProviderStageWithTurnState(provider providers.Provider, toolRegistry *tools.Registry, toolPolicy *pipeline.ToolPolicy, config *ProviderConfig, emitter *events.Emitter, hookRegistry *hooks.Registry, turnState *TurnState) *ProviderStage
NewProviderStageWithTurnState creates a provider stage that sources system_prompt, allowed_tools, and provider-bound metadata from the shared *TurnState. Pass nil for ad-hoc / test usage where TurnState is not wired.
type QuerySourceType ¶
type QuerySourceType string
QuerySourceType defines how to construct the relevance query.
const ( // QuerySourceLastUser uses the last user message as the query QuerySourceLastUser QuerySourceType = "last_user" // QuerySourceLastN concatenates the last N messages as the query QuerySourceLastN QuerySourceType = "last_n" // QuerySourceCustom uses a custom query string QuerySourceCustom QuerySourceType = "custom" )
type RandomRouter ¶
type RandomRouter struct {
BaseStage
// contains filtered or unexported fields
}
RandomRouter distributes elements randomly across outputs.
func NewRandomRouter ¶
func NewRandomRouter(name string, outputNames []string) *RandomRouter
NewRandomRouter creates a router that distributes elements randomly.
func (*RandomRouter) Process ¶
func (r *RandomRouter) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process distributes elements randomly.
func (*RandomRouter) RegisterOutput ¶
func (r *RandomRouter) RegisterOutput(name string, output chan<- StreamElement)
RegisterOutput registers an output channel with a name.
type RealtimeChainConfig ¶ added in v2.22.0
type RealtimeChainConfig struct {
// Cue configures the cue stage: the TTS service that voices its clips and
// the cache that keeps them.
Cue CueOptions
// ReorderInputTranscript adds the transcript reorder stage, for a provider
// that delivers the caller's transcript after the reply (OpenAI Realtime).
ReorderInputTranscript bool
// InputTranscriptPlaceholder is the caller text the reorder stage writes
// for a turn that ends with no transcript; empty leaves the turn out.
InputTranscriptPlaceholder string
// PlayoutHold adds the playout hold stage, for a pipeline whose reply
// audio is played to a listener in real time.
PlayoutHold bool
// RecordingStore, when set, adds an output recording stage writing to it
// with Recording (its Position set to RecordingPositionOutput).
RecordingStore events.EventStore
// Recording configures the output recording stage.
Recording RecordingStageConfig
// AudioTap, MemoryExtraction and Save are host-built stages placed in
// their slots; nil (typed or untyped) leaves the slot empty.
AudioTap Stage
MemoryExtraction Stage
Save Stage
// MessageBroadcast, when set, adds a MessageBroadcastStage publishing
// each completed message on it.
MessageBroadcast *events.Emitter
// Pacing selects the output audio pacing stage; a value other than the
// RealtimePacing constants is an error.
Pacing RealtimePacing
// After inserts stages directly after a slot, in the order given. A slot
// that is empty or dropped still places its stages where it would be.
After map[RealtimeSlot][]Stage
// Drop removes the stage in each named slot. The provider slot cannot be
// dropped.
Drop []RealtimeSlot
}
RealtimeChainConfig is what a host varies in the realtime chain. The zero value builds the provider stage followed by the cue stage.
type RealtimeHold ¶ added in v2.22.0
type RealtimeHold = provider.RealtimeHold
RealtimeHold is how a realtime session holds a spoken reply for the output guardrails that hold it (StreamHoldConfig.Realtime).
const ( // RealtimeHoldOff holds nothing: the reply plays as it arrives, and the // guardrails judge its text as it streams and once it completes, as they // do without a hold. The default. RealtimeHoldOff RealtimeHold = provider.RealtimeHoldOff // RealtimeHoldTurn holds the whole reply, audio and transcript, until the // completed reply passes, then releases it at once. RealtimeHoldTurn RealtimeHold = provider.RealtimeHoldTurn // RealtimeHoldSegment holds the reply's audio and transcript a segment at // a time: a segment's audio is released once the guardrails passed the // transcript that covers it. A turn guardrail still holds the whole reply. RealtimeHoldSegment RealtimeHold = provider.RealtimeHoldSegment )
type RealtimePacing ¶ added in v2.22.0
type RealtimePacing int
RealtimePacing selects the output audio pacing stage of the realtime chain.
const ( // RealtimePacingNone adds no pacing stage: the reply audio leaves the // chain as fast as the provider sends it. For a consumer with no realtime // speaker to protect. RealtimePacingNone RealtimePacing = iota // RealtimePacingFlushOnCut paces the reply audio to real time and drops // the queued audio of a reply that is cut (AudioPacingStage.WithFlushOnCut). // For a pipeline that plays to a listener who can barge in. RealtimePacingFlushOnCut // RealtimePacingPlayThrough paces the reply audio to real time and plays a // cut reply's queued audio out. RealtimePacingPlayThrough )
type RealtimeSlot ¶ added in v2.22.0
type RealtimeSlot string
RealtimeSlot names a position in the realtime chain NewRealtimeChain builds. A host inserts its own stages after a slot (RealtimeChainConfig.After) and removes the stage in a slot (RealtimeChainConfig.Drop) by its name.
const ( // RealtimeSlotProvider holds the DuplexProviderStage. It is always present. RealtimeSlotProvider RealtimeSlot = "provider" // RealtimeSlotCue holds the cue stage (NewDuplexCueStage). Present unless // dropped. RealtimeSlotCue RealtimeSlot = "cue" // RealtimeSlotTranscriptReorder holds the TranscriptReorderStage, when // RealtimeChainConfig.ReorderInputTranscript is set. RealtimeSlotTranscriptReorder RealtimeSlot = "transcript-reorder" // RealtimeSlotPlayoutHold holds the PlayoutHoldStage, when // RealtimeChainConfig.PlayoutHold is set. RealtimeSlotPlayoutHold RealtimeSlot = "playout-hold" // RealtimeSlotRecording holds the output RecordingStage, when // RealtimeChainConfig.RecordingStore is set. RealtimeSlotRecording RealtimeSlot = "recording" // RealtimeSlotAudioTap holds RealtimeChainConfig.AudioTap. RealtimeSlotAudioTap RealtimeSlot = "audio-tap" // RealtimeSlotMemoryExtraction holds RealtimeChainConfig.MemoryExtraction. RealtimeSlotMemoryExtraction RealtimeSlot = "memory-extraction" // RealtimeSlotMessageBroadcast holds the MessageBroadcastStage, when // RealtimeChainConfig.MessageBroadcast is set. RealtimeSlotMessageBroadcast RealtimeSlot = "message-broadcast" // RealtimeSlotSave holds RealtimeChainConfig.Save. RealtimeSlotSave RealtimeSlot = "save" // RealtimeSlotPacing holds the output AudioPacingStage, named // "audio-pacing-output", when RealtimeChainConfig.Pacing is not // RealtimePacingNone. RealtimeSlotPacing RealtimeSlot = "pacing" )
The slots of the realtime chain, in chain order.
type ReasoningDelta ¶
type ReasoningDelta = core.ReasoningDelta
ReasoningDelta is a non-content stream element payload carrying incremental model reasoning for live display. It is never persisted as content and never sent to the model on future turns.
type RecordingPosition ¶
type RecordingPosition = persist.RecordingPosition
RecordingPosition indicates where in the pipeline the recording stage is placed.
const ( // RecordingPositionInput records elements entering the pipeline (user input). RecordingPositionInput RecordingPosition = persist.RecordingPositionInput // RecordingPositionOutput records elements leaving the pipeline (agent output). RecordingPositionOutput RecordingPosition = persist.RecordingPositionOutput )
type RecordingStage ¶
type RecordingStage = persist.RecordingStage
RecordingStage captures pipeline elements as events for session recording. It observes elements flowing through without modifying them.
Writes synchronously to the EventStore. Slow disk applies back-pressure to upstream, so recording correctness takes priority over pipeline throughput. Where that trade-off is wrong, pass a buffered events.EventStore implementation.
Routing: this stage writes directly to the EventStore and never touches the EventBus. It does not use events.Emitter; it builds each Event itself.
It is not the only producer of message.created. MessageBroadcastStage publishes the same event on the bus for live consumers, such as a TUI or an SSE relay. The two differ in one way:
- this route retains full binary, because its purpose is lossless replay;
- the bus route strips content parts to metadata, so blobs stay out of observability.
Both build the payload with events.NewMessageCreatedData so nothing else can drift. This stage is opt-in (it exists only when a RecordingConfig and an EventStore are both set), but the live route is not, so a consumer without recording still sees messages.
Replayed history is counted for position but not re-recorded: the load stage runs ahead of this one, so history flows through every turn, and appending it again would make an N-turn recording hold turn 1 N times. Each message is recorded once, on the turn it was new.
func NewRecordingStage ¶
func NewRecordingStage(store events.EventStore, config RecordingStageConfig) *RecordingStage
NewRecordingStage creates a new recording stage.
type RecordingStageConfig ¶
type RecordingStageConfig = persist.RecordingStageConfig
RecordingStageConfig configures the recording stage behavior.
func DefaultRecordingStageConfig ¶
func DefaultRecordingStageConfig() RecordingStageConfig
DefaultRecordingStageConfig returns sensible defaults.
type RelevanceConfig ¶
type RelevanceConfig struct {
// EmbeddingProvider generates embeddings for similarity scoring.
// Required for relevance-based truncation. With none, truncation fails with an
// error. If the embedding call fails, truncation falls back to TruncateOldest.
EmbeddingProvider providers.EmbeddingProvider
// MinRecentMessages always keeps the N most recent messages
// regardless of relevance score. Zero or negative means 3.
MinRecentMessages int
// AlwaysKeepSystemRole keeps all system role messages regardless of score.
AlwaysKeepSystemRole bool
// SimilarityThreshold is the minimum score to consider a message relevant (0.0-1.0).
// Messages that are not protected and score below it are dropped. Zero disables
// the threshold.
SimilarityThreshold float64
// QuerySource determines what text to compare messages against. Empty
// means QuerySourceLastUser.
QuerySource QuerySourceType
// LastNCount is the number of messages to use when QuerySource is QuerySourceLastN.
// Zero or negative means 3.
LastNCount int
// CustomQuery is the query text when QuerySource is QuerySourceCustom.
CustomQuery string
// CacheEmbeddings reuses message embeddings across truncation calls, so a
// message whose text has not changed is not embedded again. Each call
// embeds only the texts (messages and query) it has no vector for.
//
// Vectors are keyed on a hash of the embedded text plus the embedding
// provider's ID and model, never on position: an edited message is
// re-embedded, and a reordered one is not. The cache belongs to the
// ContextBuilderStage, so it lasts as long as the stage (one conversation in
// the SDK), and after each call it keeps only that call's vectors, so it
// never holds more than one truncation's worth. It is safe for concurrent
// use. False (the zero value) embeds every message on every truncation.
CacheEmbeddings bool
}
RelevanceConfig configures embedding-based relevance truncation. Used when TruncationStrategy is TruncateLeastRelevant.
type Response ¶
type Response struct {
Role string
Content string
Parts []types.ContentPart
ToolCalls []types.MessageToolCall
FinalResponse string
}
Response represents a response message (for compatibility with existing pipeline).
type ResponseVADConfig ¶
type ResponseVADConfig = voice.ResponseVADConfig
ResponseVADConfig configures the ResponseVADStage.
func DefaultResponseVADConfig ¶
func DefaultResponseVADConfig() ResponseVADConfig
DefaultResponseVADConfig returns sensible defaults for ResponseVADStage.
type ResponseVADStage ¶
type ResponseVADStage = voice.ResponseVADStage
ResponseVADStage monitors response audio for silence and delays EndOfStream until actual silence is detected. This decouples turn completion from provider signaling (e.g., Gemini's turnComplete) which may arrive before all audio chunks have been received.
This stage: 1. Passes through all elements immediately (audio, text, messages) 2. When EndOfStream is received from upstream, starts monitoring for silence 3. Only emits EndOfStream downstream when VAD confirms sustained silence 4. Has a max wait timeout to prevent indefinite blocking 5. Emits a held EndOfStream at once when the next turn's EndOfStream arrives
This is a Transform stage with buffering: it may hold EndOfStream temporarily.
func NewResponseVADStage ¶
func NewResponseVADStage(config ResponseVADConfig) (*ResponseVADStage, error)
NewResponseVADStage creates a new response VAD stage.
type RoundRobinRouter ¶
type RoundRobinRouter struct {
BaseStage
// contains filtered or unexported fields
}
RoundRobinRouter distributes elements across outputs in sequence.
func NewRoundRobinRouter ¶
func NewRoundRobinRouter(name string, outputNames []string) *RoundRobinRouter
NewRoundRobinRouter creates a router that cycles through outputs sequentially.
func (*RoundRobinRouter) Process ¶
func (r *RoundRobinRouter) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process distributes elements in round-robin fashion.
func (*RoundRobinRouter) RegisterOutput ¶
func (r *RoundRobinRouter) RegisterOutput(name string, output chan<- StreamElement)
RegisterOutput registers an output channel with a name.
type RouterFunc ¶
type RouterFunc func(elem *StreamElement) []string
RouterFunc determines which output channel(s) to route an element to. Returns a slice of output names. Empty slice means drop the element.
type RouterStage ¶
type RouterStage struct {
BaseStage
// contains filtered or unexported fields
}
RouterStage routes elements to different output channels based on a routing function. This enables conditional branching and dynamic routing in the pipeline.
This is a special stage type that supports multiple outputs (1:N routing).
func NewRouterStage ¶
func NewRouterStage(name string, routerFunc RouterFunc) *RouterStage
NewRouterStage creates a new router stage with the given routing function.
func (*RouterStage) Process ¶
func (s *RouterStage) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process implements the Stage interface. Routes each element to appropriate output channel(s) based on routing function.
func (*RouterStage) RegisterOutput ¶
func (s *RouterStage) RegisterOutput(name string, output chan<- StreamElement)
RegisterOutput registers an output channel with a name. This must be called before Process() to set up routing destinations.
type RoutingRule ¶
type RoutingRule struct {
// Name identifies this rule for logging/debugging.
Name string
// Predicate returns true if the element should be routed to this rule's output.
Predicate func(StreamElement) bool
// Output is the destination name for matching elements.
Output string
}
RoutingRule defines a predicate-based routing rule.
func RouteAudio ¶
func RouteAudio(output string, format AudioFormat) RoutingRule
RouteAudio creates a routing rule for audio elements with specific format.
func RouteContentType ¶
func RouteContentType(output string, ct ContentType) RoutingRule
RouteContentType creates a routing rule for elements of a specific content type.
func RouteWhen ¶
func RouteWhen(output string, predicate func(StreamElement) bool) RoutingRule
RouteWhen creates a routing rule with the given predicate.
type STTStage ¶
STTStage transcribes audio to text using a speech-to-text service.
This is a Transform stage: audio element → text element (1:1)
func NewSTTStage ¶
func NewSTTStage(service base.STTProvider, config STTStageConfig) *STTStage
NewSTTStage creates a new STT stage. The service parameter accepts any base.STTProvider implementation. The legacy stt.Service interface embeds base.STTProvider, so existing callers that pass an stt.Service remain compatible without changes.
func NewSTTStageWithEmitter ¶
func NewSTTStageWithEmitter(service base.STTProvider, config STTStageConfig, emitter *events.Emitter) *STTStage
NewSTTStageWithEmitter creates an STT stage that publishes an EventAudioTranscription for each completed transcription.
The event type and its payload (events.AudioTranscriptionData) were declared and already consumed (session export writes transcriptions out as subtitles, and annotated sessions query them by type), but nothing produced them, so subscribers waited forever and both consumers saw an empty set. Applications wanting a live transcript had to thread their own callback through the stage graph instead.
The emitter is optional; NewSTTStage remains the no-events constructor.
type STTStageConfig ¶
type STTStageConfig = voice.STTStageConfig
STTStageConfig configures the STTStage.
func DefaultSTTStageConfig ¶
func DefaultSTTStageConfig() STTStageConfig
DefaultSTTStageConfig returns sensible defaults.
type ScoredMessage ¶
type ScoredMessage = compaction.ScoredMessage
ScoredMessage pairs a message with its relevance score and metadata. Used during relevance-based truncation to track which messages to keep.
type ScoredMessages ¶
type ScoredMessages = compaction.ScoredMessages
ScoredMessages is a sortable slice of ScoredMessage.
type Stage ¶
Stage is a processing unit in the pipeline DAG. Unlike traditional middleware, stages explicitly declare their I/O characteristics and operate on channels of StreamElements, enabling true streaming execution.
Stages read from an input channel, process elements, and write to an output channel. The stage MUST close the output channel when done (or when input closes).
Example implementation:
type ExampleStage struct {
name string
}
func (s *ExampleStage) Name() string {
return s.name
}
func (s *ExampleStage) Type() StageType {
return StageTypeTransform
}
func (s *ExampleStage) Process(ctx context.Context, input <-chan StreamElement, output chan<- StreamElement) error {
defer close(output)
for elem := range input {
// Process element
processedElem := s.transform(elem)
// Write to output
select {
case output <- processedElem:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}
func NewDuplexCueStage ¶ added in v2.22.0
func NewDuplexCueStage(duplex *DuplexProviderStage, opts CueOptions) Stage
NewDuplexCueStage creates the stage that speaks cues for duplex's realtime session: a guardrail's message, when a guardrail cuts a spoken reply or blocks typed input. It goes directly after duplex in the pipeline, ahead of transcript reordering, playout tracking, recording and pacing, which treat its audio as reply audio (marked Meta.CueAudio). Every element goes on unchanged and in order; after one carrying a Cue the stage plays the cue's clip, PCM16 mono at the reply audio's rate, in chunks of 100ms.
When duplex creates its session the stage learns the session's voice and output rate and starts rendering the messages of duplex's guardrails. Clips come from the first source that renders them: the session's own out-of-band audio (providers.OutOfBandSpeaker, OpenAI Realtime), in its exact voice and outside the conversation; then opts.Voice; then, with no Voice, the clips pre-warmed for the session's voice; then a built-in earcon (a short tone). The session's audio is checked against the text by its transcript (case, punctuation and spacing aside) and asked for once more on a miss before the text falls to the next source. Clips are kept in opts.Cache under their source and voice, so only the first session of a source and voice renders them.
While a clip renders, reply output waits behind it for at most 1.5s; past that the earcon plays in its place, and the clip is kept for the next cue. A cut (barge-in) while it renders drops the cue. A session whose replies are not spoken gets no cue audio; one that does not report its output audio (providers.OutputAudioReporter) renders PCM16 at 24 kHz in the voice service's default voice.
func NewRealtimeChain ¶ added in v2.22.0
func NewRealtimeChain(provider *DuplexProviderStage, cfg RealtimeChainConfig) ([]Stage, error)
NewRealtimeChain returns the stages of a realtime (duplex) pipeline from the provider stage on, in the order every host runs them:
provider, cue, transcript-reorder, playout-hold, recording, audio-tap, memory-extraction, message-broadcast, save, pacing
The cue stage directly follows the provider, ahead of the stages that treat its audio as reply audio. The transcript reorder stage runs before everything that reads the transcript, the playout hold before everything that records what was heard, and pacing last, so the bookkeeping stages run at full speed while the reply reaches a realtime speaker at playback rate.
The host puts its own front stages (prompt assembly, input recording, resampling, client-side turn detection) ahead of the returned stages and chains them with a PipelineBuilder.
Build one chain per provider stage. The cue stage plays the provider's cues, so each call that succeeds rewires them: to the cue stage it returns, or to none when the cue slot is dropped. A chain built earlier for the same provider then plays none. A call that returns an error changes nothing.
A nil stage, typed or untyped, in AudioTap, MemoryExtraction or Save leaves the slot empty; in After it is an error.
func WithNamePrefix ¶
WithNamePrefix returns s renamed to "<prefix>_<name>", so the same stage constructors can be instantiated once per branch in a single pipeline.
PipelineBuilder.Build rejects duplicate stage names, so a fan-out that runs identical sub-chains (one audio track per speaker on a two-party call, one per camera, one per tenant) must give each branch's stages distinct names. Without a shared helper, every consumer re-derives the same wrapper by embedding Stage and overriding Name().
An empty prefix returns s unchanged, which is the single-branch case: the constructors' natural names are already unique and no wrapper is warranted.
The original stage is not mutated, so the same instance can be wrapped more than once. Wrapping shares the underlying stage, including any state it holds. Branches needing independent state must construct separate stages.
type StageError ¶
type StageError = core.StageError
StageError wraps an error with stage information. The pipeline delivers a failed stage's error to the caller as a *StageError, except for an error the stage already emitted as an error element before returning it, which the caller receives as emitted. errors.Is and errors.As see through it to the stage's error.
func NewStageError ¶
func NewStageError(stageName string, stageType StageType, err error) *StageError
NewStageError creates a new StageError.
type StageFunc ¶
StageFunc is a functional adapter that allows using a function as a Stage. This is useful for simple transformations without defining a new type.
func NewStageFunc ¶
func NewStageFunc(name string, stageType StageType, fn func(context.Context, <-chan StreamElement, chan<- StreamElement) error) *StageFunc
NewStageFunc creates a new functional stage.
type StageMetrics ¶
type StageMetrics struct {
StageName string
ElementsIn int64
ElementsOut int64
ElementsErrored int64
TotalLatency time.Duration
MinLatency time.Duration
MaxLatency time.Duration
AvgLatency time.Duration
LastUpdated time.Time
// contains filtered or unexported fields
}
StageMetrics contains performance metrics for a stage.
func NewStageMetrics ¶
func NewStageMetrics(stageName string) *StageMetrics
NewStageMetrics creates a new metrics collector for a stage.
func (*StageMetrics) GetMetrics ¶
func (m *StageMetrics) GetMetrics() StageMetrics
GetMetrics returns a copy of the current metrics (thread-safe).
func (*StageMetrics) RecordElement ¶
func (m *StageMetrics) RecordElement(latency time.Duration, hasError bool)
RecordElement records metrics for a processed element.
type StageType ¶
StageType defines the processing model of a stage.
const ( // StageTypeTransform performs 1:1 or 1:N element transformation. // Each input element produces one or more output elements. // Examples: validation, prompt assembly, text formatting. StageTypeTransform StageType = core.StageTypeTransform // StageTypeAccumulate performs N:1 accumulation. // Multiple input elements are collected and combined into one output element. // Examples: VAD buffering, message accumulation. StageTypeAccumulate StageType = core.StageTypeAccumulate // StageTypeGenerate performs 0:N generation. // Generates output elements without consuming input (or consumes once then generates many). // Examples: LLM streaming response, TTS generation. StageTypeGenerate StageType = core.StageTypeGenerate // StageTypeSink is a terminal stage (N:0). // Consumes input elements but produces no output. // Examples: state store save, metrics collection, logging. StageTypeSink StageType = core.StageTypeSink // StageTypeBidirectional supports full duplex communication. // Both reads from input and writes to output concurrently. // Examples: WebSocket session, duplex provider. StageTypeBidirectional StageType = core.StageTypeBidirectional )
type StateStoreLoadStage ¶
type StateStoreLoadStage struct {
BaseStage
// contains filtered or unexported fields
}
StateStoreLoadStage loads conversation history from state store.
func NewStateStoreLoadStage ¶
func NewStateStoreLoadStage(config *pipeline.StateStoreConfig) *StateStoreLoadStage
NewStateStoreLoadStage creates a new state store load stage.
func NewStateStoreLoadStageWithTurnState ¶
func NewStateStoreLoadStageWithTurnState(config *pipeline.StateStoreConfig, turnState *TurnState) *StateStoreLoadStage
NewStateStoreLoadStageWithTurnState creates a state store load stage that publishes ConversationID/UserID onto the supplied TurnState.
func (*StateStoreLoadStage) Process ¶
func (s *StateStoreLoadStage) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process loads conversation history and emits it before current input.
type StreamElement ¶
type StreamElement = core.StreamElement
StreamElement is the unit of data flowing through the pipeline. It can carry different types of content and supports backpressure. Each element should contain at most one content type.
Example ¶
ExampleStreamElement demonstrates creating different types of stream elements.
package main
import (
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/pipeline/stage"
"github.com/AltairaLabs/PromptKit/runtime/v2/types"
)
func main() {
// Text element
textElem := stage.NewTextElement("Hello")
fmt.Printf("Text element: %v\n", *textElem.Text)
// Message element
msgElem := stage.NewMessageElement(&types.Message{
Role: "user",
Content: "Hello",
})
fmt.Printf("Message element: %s\n", msgElem.Message.Content)
// Error element
errElem := stage.NewErrorElement(fmt.Errorf("test error"))
fmt.Printf("Error element: %v\n", errElem.Error)
}
Output: Text element: Hello Message element: Hello Error element: test error
func GetAudioElement ¶
func GetAudioElement(audio *AudioData) *StreamElement
GetAudioElement retrieves a StreamElement from the pool and initializes it with audio data. This is a pooled alternative to NewAudioElement.
func GetElement ¶
func GetElement() *StreamElement
GetElement retrieves a StreamElement from the pool or creates a new one. The returned element has been through Reset. Callers should call PutElement once they are done with the element.
func GetEndOfStreamElement ¶
func GetEndOfStreamElement() *StreamElement
GetEndOfStreamElement retrieves a StreamElement from the pool and marks it as end-of-stream. This is a pooled alternative to NewEndOfStreamElement.
func GetErrorElement ¶
func GetErrorElement(err error) *StreamElement
GetErrorElement retrieves a StreamElement from the pool and initializes it with an error. This is a pooled alternative to NewErrorElement.
func GetImageElement ¶
func GetImageElement(image *ImageData) *StreamElement
GetImageElement retrieves a StreamElement from the pool and initializes it with image data. This is a pooled alternative to NewImageElement.
func GetMessageElement ¶
func GetMessageElement(msg *types.Message) *StreamElement
GetMessageElement retrieves a StreamElement from the pool and initializes it with a message. This is a pooled alternative to NewMessageElement.
func GetTextElement ¶
func GetTextElement(text string) *StreamElement
GetTextElement retrieves a StreamElement from the pool and initializes it with text content. This is a pooled alternative to NewTextElement.
func GetVideoElement ¶
func GetVideoElement(video *VideoData) *StreamElement
GetVideoElement retrieves a StreamElement from the pool and initializes it with video data. This is a pooled alternative to NewVideoElement.
func NewAudioElement ¶
func NewAudioElement(audio *AudioData) StreamElement
NewAudioElement creates a new StreamElement with audio data.
func NewEndOfStreamElement ¶
func NewEndOfStreamElement() StreamElement
NewEndOfStreamElement creates a new StreamElement marking end of stream.
func NewEndOfTurnElement ¶
func NewEndOfTurnElement() StreamElement
NewEndOfTurnElement marks the end of one conversational turn's input within a still-open stream. Distinct from NewEndOfStreamElement (session over): the streaming provider stage fires its tool loop on EndOfTurn and stays open for the next turn.
func NewErrorElement ¶
func NewErrorElement(err error) StreamElement
NewErrorElement creates a new StreamElement with an error.
func NewImageElement ¶
func NewImageElement(image *ImageData) StreamElement
NewImageElement creates a new StreamElement with image data.
func NewInterruptElement ¶
func NewInterruptElement() StreamElement
NewInterruptElement signals barge-in: downstream stages cancel in-flight generation/playback and drop queued audio. Travels at PriorityCritical.
func NewMessageElement ¶
func NewMessageElement(msg *types.Message) StreamElement
NewMessageElement creates a new StreamElement with a message.
func NewTextElement ¶
func NewTextElement(text string) StreamElement
NewTextElement creates a new StreamElement with text content.
func NewVideoElement ¶
func NewVideoElement(video *VideoData) StreamElement
NewVideoElement creates a new StreamElement with video data.
func StreamMediaToElement ¶
func StreamMediaToElement(media *providers.StreamMediaData) StreamElement
StreamMediaToElement converts a StreamMediaData to a StreamElement. Routes by MIME type: audio/* → AudioData, video/* → VideoData, image/* → ImageData.
type StreamExecution ¶ added in v2.22.0
type StreamExecution struct {
// contains filtered or unexported fields
}
StreamExecution is one running execution of a StreamPipeline, started by Start: its output, and the error that ended it once the output has closed.
func (*StreamExecution) Err ¶ added in v2.22.0
func (e *StreamExecution) Err() error
Err returns the error that ended the execution: the error of the stage that failed the turn (as its error element on Output carries it), or one wrapping ErrOutputTruncated when output was dropped. It is nil when the execution ended without a stage failing, and when it ended by the caller's own cancellation. An error element a stage emitted and carried on from never makes it non-nil.
Err does not block. It is nil while the execution runs, and from the moment the execution ends and closes Output it returns the end error, which never changes after that. Output is buffered, so the execution can end, and Err become non-nil, before the reader has taken the elements still buffered on Output. Read Output to its close first to see every element before the error that ended the execution.
func (*StreamExecution) Output ¶ added in v2.22.0
func (e *StreamExecution) Output() <-chan StreamElement
Output returns the execution's output, as Execute returns it.
type StreamHoldConfig ¶ added in v2.22.0
type StreamHoldConfig = provider.StreamHoldConfig
StreamHoldConfig sizes the segments a stream_hold: segment output guardrail judges a streamed reply in, and bounds its judging. It is per conversation, not per guardrail: every segment guardrail judges the same segments. Zero fields take the defaults.
type StreamPipeline ¶
type StreamPipeline struct {
// contains filtered or unexported fields
}
StreamPipeline represents an executable pipeline of stages. It manages the DAG of stages, creates channels between them, and orchestrates execution.
func (*StreamPipeline) Execute ¶
func (p *StreamPipeline) Execute(ctx context.Context, input <-chan StreamElement) (<-chan StreamElement, error)
Execute starts the pipeline execution with the given input channel. Returns an output channel that will receive all elements from terminal stages. The pipeline executes in background goroutines and closes the output channel when complete.
The first stage error ends the turn. Nothing is canceled: the failed stage's downstream stages receive the error in-band and pass it on without acting on the incomplete turn, and the other stages drain as usual. The error reaches the caller as an element with Error set, the last element before the output closes. A stage that emits its own error as an error element before returning it (the provider stage does) delivers that error as emitted. Any other stage's error arrives as a *StageError, which unwraps to the stage's error. A context error that comes from the caller's own cancellation is not treated as a stage failure. One from the pipeline's own ExecutionTimeout or IdleTimeout is: it fails the turn, and its error wraps ErrExecutionTimeout or ErrIdleTimeout. The caller must read the output to its end or cancel ctx: an execution whose output nobody reads blocks until ctx ends, or until Shutdown's grace period runs out. The output closes once the terminal stages have returned.
Execute returns ErrPipelineShuttingDown if the pipeline is shutting down. When PipelineConfig.MaxConcurrentPipelines executions are already running, Execute waits for one to finish. It returns ctx's error if ctx ends first, and ErrPipelineShuttingDown if Shutdown is called first.
When Shutdown has abandoned the execution and output had to be dropped because the reader fell behind (see Shutdown), the stream still ends in an error: one wrapping ErrOutputTruncated, and the turn's own error when the turn failed. It is delivered with one last bounded wait for the reader.
func (*StreamPipeline) ExecuteSync ¶
func (p *StreamPipeline) ExecuteSync(ctx context.Context, input ...StreamElement) (*ExecutionResult, error)
ExecuteSync runs the pipeline synchronously and returns the accumulated result. This is a convenience method for request/response mode where you want a single result. It converts the streaming execution into a blocking call.
The returned error is the last error element on the output. When a stage failed the turn, that is the failure (see Execute for its form). The result is non-nil alongside the error and holds whatever the pipeline produced. When Shutdown abandoned the execution and output was dropped, the error wraps ErrOutputTruncated (see Shutdown).
func (*StreamPipeline) RunsToolCalls ¶ added in v2.22.0
func (p *StreamPipeline) RunsToolCalls() bool
RunsToolCalls reports whether a stage of the pipeline runs the model's tool calls (ToolCallRunner), so that whatever drives the pipeline, such as a duplex session, must not run them again.
func (*StreamPipeline) Shutdown ¶
func (p *StreamPipeline) Shutdown(ctx context.Context) error
Shutdown gracefully shuts down the pipeline, waiting for in-flight executions to complete. When GracefulShutdownTimeout (or ctx) ends first it returns ErrShutdownTimeout. The executions still running carry on, and a consumer still reading their output gets all of it, the turn's error included. An execution whose consumer has stopped reading, so that a send waits a further GracefulShutdownTimeout (at least 100ms) with nothing taken, drops the rest of its output and returns. Its output still ends in an error wrapping ErrOutputTruncated (and the turn's error, if the turn failed), offered with one last wait of the same length; ExecuteSync returns that error even when its element was not taken.
func (*StreamPipeline) Start ¶ added in v2.22.0
func (p *StreamPipeline) Start(ctx context.Context, input <-chan StreamElement) (*StreamExecution, error)
Start is Execute, returning the execution so that the caller can learn the error that ended it (StreamExecution.Err) once its output has closed: an error element on the output alone does not say whether the stage carried on from it, and elements may follow the one that failed the turn.
type StructuredOutputMode ¶
type StructuredOutputMode = provider.StructuredOutputMode
StructuredOutputMode selects when a caller's ResponseFormat is applied to a tool loop.
A response schema competes with tool calling. Applied to every round it suppresses tool use: silently, intermittently, and more the more work the task requires. Measured on an identical 7-tool task, mean tools called (n=5, no schema -> schema):
claude-sonnet-5 7.0 -> 7.0 (no detectable effect) gpt-5 6.8 -> 6.6 (within its own baseline noise) claude-sonnet-4-6 7.0 -> 5.8 (one run did almost no work) gemini-3.7-flash terminates 5/5 -> 1/5
On a production underwriting pack the same model that scores 5.8 here reached tool_use in 1 run out of 5. The effect scales with task complexity, so these numbers understate it. Every failure arrives as a successful HTTP 200.
The fix is to constrain only the turn that produces the final answer, which is what Anthropic's stronger models already do server-side. Doing it in the stage rather than per provider means no per-model support table: the rule is mechanical and every provider gets it, including ones added later.
Gemini cannot carry a schema on a round with tools on either of its APIs, so its provider applies the same rule itself: under every_round it sends each tool round without the schema and asks a round that answers again under it, which costs two calls per answering round, as final_turn does.
const ( // StructuredOutputFinalTurn withholds ResponseFormat during tool-calling // rounds and re-asks the final answer under the schema. Default. StructuredOutputFinalTurn StructuredOutputMode = provider.StructuredOutputFinalTurn // StructuredOutputEveryRound sends ResponseFormat on every round. This is the // older behavior, from before the final-turn rule existed. // // This is an escape hatch, not a supported alternative: it is the // configuration measured above, and on two of the four models tested it // loses tool calls. It exists so an operator can pin the old behavior // without waiting on a release, not because it is a reasonable choice. StructuredOutputEveryRound StructuredOutputMode = provider.StructuredOutputEveryRound )
func ParseStructuredOutputMode ¶
func ParseStructuredOutputMode(raw string) StructuredOutputMode
ParseStructuredOutputMode reads a configured mode string.
Mirrors the provider api_mode convention: an unrecognized value is ignored with a warning rather than forwarded, since guessing here silently changes whether a caller's schema constrains tool-calling rounds.
type TTSConfig ¶
TTSConfig contains configuration for TTS stage.
func DefaultTTSConfig ¶
func DefaultTTSConfig() TTSConfig
DefaultTTSConfig returns sensible defaults for TTS configuration.
type TTSStage ¶
TTSStage synthesizes audio for streaming text elements. It reads text elements from input and adds audio data to them.
This is a Transform stage: text element → text+audio element (1:1)
func NewTTSStage ¶
func NewTTSStage(svc TTSService, config TTSConfig) *TTSStage
NewTTSStage creates a new TTS stage.
type TTSStageWithInterruption ¶
type TTSStageWithInterruption = voice.TTSStageWithInterruption
TTSStageWithInterruption synthesizes text to audio with interruption support. When the user starts speaking (detected via shared InterruptionHandler), synthesis is stopped and pending output is discarded.
A reply that streams is spoken as it streams: its released text deltas are split into sentences (segment.Speech), each synthesized as soon as it is complete, its audio handed on as the service delivers it (replySpeech). A text or Message that did not stream is synthesized whole, into one audio element.
func NewTTSStageWithInterruption ¶
func NewTTSStageWithInterruption(service tts.Service, config TTSStageWithInterruptionConfig) *TTSStageWithInterruption
NewTTSStageWithInterruption creates a new TTS stage with interruption support.
type TTSStageWithInterruptionConfig ¶
type TTSStageWithInterruptionConfig = voice.TTSStageWithInterruptionConfig
TTSStageWithInterruptionConfig configures TTSStageWithInterruption.
func DefaultTTSStageWithInterruptionConfig ¶
func DefaultTTSStageWithInterruptionConfig() TTSStageWithInterruptionConfig
DefaultTTSStageWithInterruptionConfig returns sensible defaults.
type TemplateStage ¶
type TemplateStage struct {
BaseStage
// contains filtered or unexported fields
}
TemplateStage renders the system prompt template.
When TurnState holds a template with a raw template string (set by PromptAssemblyStage), this stage is the single render point: it merges variable maps with the priority template.DefaultVars < template.FragmentVars < TurnState.Variables, calls the template.Renderer for recursive substitution, stores the result in TurnState.SystemPrompt, and emits lifecycle events. It renders once per turn. Elements pass through unchanged, and message content is never substituted.
If the template references a variable nothing supplied, or a required variable (Template.RequiredVars) has no non-empty value once every source is merged, the stage returns an error that matches ErrTemplateUnresolved, which ends the turn.
This is a Transform stage: each input element produces one output element.
func NewTemplateStage ¶
func NewTemplateStage() *TemplateStage
NewTemplateStage creates a template substitution stage with no TurnState. It has no template to render, so PipelineBuilder.Build rejects it with ErrTurnStateRequired; use NewTemplateStageWithTurnState in a pipeline.
func NewTemplateStageWithEmitter ¶
func NewTemplateStageWithEmitter(emitter *events.Emitter) *TemplateStage
NewTemplateStageWithEmitter creates a template stage that emits lifecycle events. Like NewTemplateStage it has no TurnState, so Build rejects it; use NewTemplateStageWithTurnState.
func NewTemplateStageWithTurnState ¶
func NewTemplateStageWithTurnState(emitter *events.Emitter, turnState *TurnState) *TemplateStage
NewTemplateStageWithTurnState creates a template stage that uses a shared *TurnState as a per-Turn render cache. The system_template is rendered once per Send regardless of how many elements flow through (history loaders fan-out N elements per turn but this stage does a single render).
func (*TemplateStage) Process ¶
func (s *TemplateStage) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process renders the system prompt on the first element and forwards every element unchanged. It forwards an upstream failure's error element without rendering.
func (*TemplateStage) WithSystemPromptSuffix ¶ added in v2.17.0
func (s *TemplateStage) WithSystemPromptSuffix(fn func() string) *TemplateStage
WithSystemPromptSuffix makes the stage append fn's text to every system prompt it renders, separated by a blank line. fn runs once per render (once per Send), so it may read state that changes between turns. An empty result appends nothing. The suffix is added after variable substitution, so it is not itself a template.
type TokenBudgetConfig ¶
type TokenBudgetConfig struct {
// MaxTokens is the maximum number of tokens allowed before truncation.
// When 0, no truncation is performed but warnings are still logged
// for large conversations.
MaxTokens int
// TokenCounter is the counter to use for token estimation.
// When nil, the default heuristic counter is used.
TokenCounter *tokenizer.HeuristicTokenCounter
// ReserveTokens is the number of tokens to reserve for the response.
// This is subtracted from MaxTokens to determine the effective budget.
// Default: 0 (no reservation).
ReserveTokens int
// LargeConversationThreshold is the message count above which a warning
// is logged if no token budget is configured.
// Default: 100.
LargeConversationThreshold int
}
TokenBudgetConfig configures the TokenBudgetStage.
type TokenBudgetStage ¶
type TokenBudgetStage struct {
BaseStage
// contains filtered or unexported fields
}
TokenBudgetStage enforces a token budget on conversation messages before they are sent to the provider. When the total token count exceeds the configured budget, older messages are truncated while preserving the system prompt and the most recent messages that fit within the budget.
Truncation keeps whole turns, as ContextBuilderStage does: the kept history starts at a user message and keeps a tool call only with all of its results. When no user message fits, Process returns an error rather than send a request with no question in it.
This stage should be placed immediately before the ProviderStage in the pipeline to prevent context window overflow errors.
func NewTokenBudgetStage ¶
func NewTokenBudgetStage(config *TokenBudgetConfig) *TokenBudgetStage
NewTokenBudgetStage creates a new token budget enforcement stage.
func NewTokenBudgetStageWithTurnState ¶
func NewTokenBudgetStageWithTurnState(config *TokenBudgetConfig, turnState *TurnState) *TokenBudgetStage
NewTokenBudgetStageWithTurnState creates a token budget stage that reads the system prompt from the supplied TurnState.
func (*TokenBudgetStage) Process ¶
func (s *TokenBudgetStage) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process reads all messages, enforces the token budget, and forwards the (possibly truncated) messages downstream.
type ToolCallRecorder ¶
type ToolCallRecorder = provider.ToolCallRecorder
ToolCallRecorder is an optional interface a WorkflowStateResolver may implement to receive the number of tool calls each round executed.
The workflow engine's tool-call budget (engine.budget.max_tool_calls) needs a per-round count, and the tool loop is the only place that sees every call on every path (unary, streaming, and resumed-after-HITL). Counting here rather than in each consumer keeps one counting site, so the SDK's and Arena's totals cannot drift apart; consumers only forward the number to the workflow context they own.
It is separate from WorkflowStateResolver and type-asserted at the call site: adding a method to that interface would break every existing implementer, and a resolver with no budget to enforce need not implement this.
type ToolCallRunner ¶ added in v2.22.0
type ToolCallRunner interface {
// RunsToolCalls reports whether the stage runs the tool calls it sees.
RunsToolCalls() bool
}
ToolCallRunner is implemented by a stage that can run the model's tool calls itself: a DuplexProviderStage given SetToolExecution, or a ProviderStage with a tool registry.
type ToolLoading ¶ added in v2.23.0
type ToolLoading = provider.ToolLoading
ToolLoading is how the provider stage builds the tools array it sends.
In rebuild mode, the default, each call is sent the tools the model may call on it, and the array is rebuilt when they change: a ToolSelector's choice, a skill grant, a tool excluded after repeated rejection, a workflow state's tools, or max_tool_calls_per_turn spent. A provider that caches the prompt then processes the prefix again (tool.offer.rebuilt).
In stable mode every call is sent the conversation's catalog: the prompt's allowed tools, Catalog's tools, the current grants and the capability tools. What the model may call on a call is given beside it in PredictionRequest.ActiveTools, which a provider that can restrict calls sends (OpenAI's tool_choice allowed_tools), and the stage refuses a call outside it with NotAvailableRefusal. With max_tool_calls_per_turn spent, the last round keeps the array and is sent tool choice none. The array is rebuilt only when the catalog itself changes: a grant or a workflow state naming a tool outside it, an MCP server's tool list, a DescribeTool change, or another provider.
type ToolLoadingMode ¶ added in v2.23.0
type ToolLoadingMode = provider.ToolLoadingMode
ToolLoadingMode is how a conversation's tools array follows a change to what the model may call (ProviderConfig.ToolLoading).
const ( // ToolLoadingRebuild sends each call the tools the model may call on it, // so the array changes whenever they do. It is the default. ToolLoadingRebuild ToolLoadingMode = provider.ToolLoadingRebuild // ToolLoadingStable sends every call the same tools array, and gives // what the model may call beside it (PredictionRequest.ActiveTools). ToolLoadingStable ToolLoadingMode = provider.ToolLoadingStable )
type ToolOfferHistory ¶ added in v2.23.0
type ToolOfferHistory = provider.ToolOfferHistory
ToolOfferHistory is what tool.offer.rebuilt compares a provider call's tools array against: the array the previous call was sent, what has changed the array since, and whether the cache-cost warning was logged. Share one across the provider stages of a conversation, as the SDK does across a workflow's states, so a change from one stage's calls to the next stage's is reported and the warning is logged once. A stage built without one (ProviderConfig.ToolOfferHistory) keeps its own. Safe for concurrent use.
func NewToolOfferHistory ¶ added in v2.23.0
func NewToolOfferHistory() *ToolOfferHistory
NewToolOfferHistory returns a history of no calls.
type TranscriptReorderStage ¶
type TranscriptReorderStage = duplex.TranscriptReorderStage
TranscriptReorderStage guarantees that, within a turn, the user's input transcript is emitted before that turn's assistant output, even when the provider delivers the transcript late (e.g. OpenAI Realtime, whose Whisper transcription can land after the assistant reply, or even after the whole turn, has finished).
Until the user turn for the current turn arrives it holds everything the model produced in answer: assistant TEXT, the turn-end, and the messages a tool round adds (the tool results that follow a tool-call turn-end). Once the user turn arrives (or a short timeout after a turn-end elapses) it emits the user turn, then what it held, in the order received. AUDIO passes through immediately, so playback stays realtime. Only the transcript log is reordered. If the transcript never arrives, a configurable placeholder user turn is emitted.
A turn-end that makes tool calls does not end the user's turn: the reply after the tool round answers the same utterance, so it is held (or streamed, once the user turn is shown) with it rather than waiting for a transcript of its own. The round's other elements (results, calls held for the caller, errors) are held with it. While a round DuplexProviderStage runs (Meta.ToolCallsRunning) is still running, a held turn is not timed out. A round whose calls never get results does not swallow the next turn: the next reply closes it.
A user transcript marked Meta.LateTranscript belongs to the turn whose reply already completed: it fills that turn while the stage still holds it, and is dropped once the stage has resolved the turn (with the placeholder) rather than becoming the next turn's user message. A typed user turn (TextInputTurnSource) and any non-user message for a later turn resolve a held finished turn first instead of joining it.
The mechanism is provider-agnostic; whether it is wired is decided upstream. It is a Transform stage: state is per-turn and reset on each turn boundary, so a single instance handles one continuous duplex conversation.
func NewTranscriptReorderStage ¶
func NewTranscriptReorderStage(placeholder string) *TranscriptReorderStage
NewTranscriptReorderStage creates a reorder stage with the given missing-turn placeholder text (empty to omit the user turn) and the default hold timeout.
func NewTranscriptReorderStageWithTimeout ¶
func NewTranscriptReorderStageWithTimeout(placeholder string, holdTimeout time.Duration) *TranscriptReorderStage
NewTranscriptReorderStageWithTimeout is like NewTranscriptReorderStage but with an explicit hold timeout (tests use a short value).
type Transcription ¶
type Transcription = core.Transcription
Transcription is the typed payload for duplex-provider input transcription attached to an element via ElementMetadata.
type TruncationStrategy ¶
type TruncationStrategy string
TruncationStrategy defines how to handle messages when over token budget.
const ( // TruncateOldest drops oldest messages first TruncateOldest TruncationStrategy = "oldest" // TruncateLeastRelevant drops least relevant messages (requires embeddings) TruncateLeastRelevant TruncationStrategy = "relevance" // TruncateSummarize compresses old messages into summaries TruncateSummarize TruncationStrategy = "summarize" // TruncateFail returns error if over budget TruncateFail TruncationStrategy = "fail" )
type TurnState ¶
TurnState holds per-Turn invariants shared across stages within a single pipeline execution (one Send / one TurnExecutor.ExecuteTurn). It is constructed by the pipeline builder and held by reference by every stage that needs to read or write per-Turn data.
Per-Turn data lives here, not in StreamElement.Meta, because it is the same for every element of the Turn.
Synchronization ¶
Pipeline stages run as goroutines connected by channels. Writes to TurnState happen in pipeline-stage order; the channel hand-off between stages provides happens-before, so a downstream reader always observes upstream writes by the time the first element arrives.
In practice:
- PromptAssemblyStage populates Template, AllowedTools, Validators on its first input element, before forwarding.
- VariableProviderStage populates Variables.
- TemplateStage reads Template/Variables and writes SystemPrompt.
- ProviderStage / ContextBuilderStage / DuplexProviderStage read SystemPrompt and AllowedTools.
- Arena instruction stages (skill_instruction, completion_instruction) mutate SystemPrompt; the next stage in pipeline order observes the mutation.
Tests must construct stages in pipeline order or hand-populate fields directly when exercising stages in isolation.
func NewTurnState ¶
func NewTurnState() *TurnState
NewTurnState constructs a fresh, empty TurnState.
type VariableProviderStage ¶
type VariableProviderStage struct {
BaseStage
// contains filtered or unexported fields
}
VariableProviderStage resolves variables from dynamic providers and publishes them for TemplateStage.
This stage calls each registered variable provider to fetch dynamic variables (e.g., from environment, external services, databases) and merges them into TurnState.Variables.
Provider resolution order:
- The static variables the stage was constructed with
- Each provider is called in sequence; later providers override earlier values
Error handling:
- If any provider fails, the stage returns an error and the turn ends with it
Example providers:
- Environment variable provider: reads from OS environment
- Config provider: reads from configuration files
- External API provider: fetches user context from external services
This is a Transform stage: each input element is forwarded unchanged.
func NewVariableProviderStage ¶
func NewVariableProviderStage(variableProviders ...variables.Provider) *VariableProviderStage
NewVariableProviderStage creates a variable provider stage.
func NewVariableProviderStageWithVars ¶
func NewVariableProviderStageWithVars( staticVars map[string]string, variableProviders []variables.Provider, ) *VariableProviderStage
NewVariableProviderStageWithVars creates a variable provider stage with static variables and dynamic providers. Static variables are injected first; dynamic providers can override them.
func NewVariableProviderStageWithVarsAndTurnState ¶
func NewVariableProviderStageWithVarsAndTurnState( staticVars map[string]string, variableProviders []variables.Provider, turnState *TurnState, ) *VariableProviderStage
NewVariableProviderStageWithVarsAndTurnState creates a stage that publishes the resolved variables onto the supplied TurnState.Variables.
func (*VariableProviderStage) Process ¶
func (s *VariableProviderStage) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process resolves variables from all providers, publishes them onto TurnState.Variables, and forwards elements unchanged.
type VideoData ¶
VideoData carries video frame data with metadata. Supports externalization to avoid holding large data in memory.
type VideoFramesInfo ¶
type VideoFramesInfo = core.VideoFramesInfo
VideoFramesInfo is the typed payload for video-frame extraction correlation.
type VideoToFramesConfig ¶
type VideoToFramesConfig = media.VideoToFramesConfig
VideoToFramesConfig configures the VideoToFramesStage behavior.
func DefaultVideoToFramesConfig ¶
func DefaultVideoToFramesConfig() VideoToFramesConfig
DefaultVideoToFramesConfig returns sensible defaults for frame extraction.
type VideoToFramesStage ¶
type VideoToFramesStage = media.VideoToFramesStage
VideoToFramesStage extracts frames from video StreamElements into individual image StreamElements. This is a Transform stage with fan-out behavior (1 video → N images).
Input: StreamElement with Video Output: Multiple StreamElements with Image, preserving correlation metadata
Non-video elements are passed through unchanged.
func NewVideoToFramesStage ¶
func NewVideoToFramesStage(config VideoToFramesConfig) *VideoToFramesStage
NewVideoToFramesStage creates a new video-to-frames extraction stage.
type WeightedRouter ¶
type WeightedRouter struct {
BaseStage
// contains filtered or unexported fields
}
WeightedRouter distributes elements across outputs based on configured weights.
func NewWeightedRouter ¶
func NewWeightedRouter(name string, weights map[string]float64) *WeightedRouter
NewWeightedRouter creates a router that distributes elements based on weights. Weights are normalized to sum to 1.0. Example: {"primary": 0.7, "secondary": 0.3} routes 70% to primary, 30% to secondary.
func (*WeightedRouter) Process ¶
func (r *WeightedRouter) Process( ctx context.Context, input <-chan StreamElement, output chan<- StreamElement, ) error
Process distributes elements based on weights.
func (*WeightedRouter) RegisterOutput ¶
func (r *WeightedRouter) RegisterOutput(name string, output chan<- StreamElement)
RegisterOutput registers an output channel with a name.
type WorkflowStateResolver ¶
type WorkflowStateResolver = provider.WorkflowStateResolver
WorkflowStateResolver lets a workflow consumer keep a turn aligned with the workflow's current state.
A workflow state change is a different system prompt, a different tool set and, when the state's prompt names its own provider, a different provider and parameters (Handoff.Call). All are per-round inputs to the provider tool loop, so reconciling them between rounds makes the turn run as the current state, with no new conversation, no new pipeline, and no user message. Without this, a transition advances the state machine and the destination state never speaks.
runtime must not import sdk, so the interface is defined here and implemented by consumers (SDK WorkflowConversation, Arena's per-run transition executor). Nil is the non-workflow case and is always safe.
Source Files
¶
- builder.go
- compaction_aliases.go
- composition_executor.go
- composition_recorder.go
- config.go
- core_aliases.go
- cue_aliases.go
- doc.go
- duplex_aliases.go
- heard_aliases.go
- history_aliases.go
- media_aliases.go
- persist_aliases.go
- pipeline.go
- provider_aliases.go
- realtime_chain.go
- rename.go
- router_strategies.go
- stages_advanced.go
- stages_composition.go
- stages_context.go
- stages_core.go
- stages_token_budget.go
- stages_utilities.go
- voice_aliases.go
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
compaction
Package compaction holds stage's context compaction and relevance helpers: the CompactionStrategy the provider stage calls between tool-loop rounds, the default ContextCompactor and its rules, the cosine-similarity scoring relevance truncation uses, and the embedding cache that keeps one call's vectors for the next.
|
Package compaction holds stage's context compaction and relevance helpers: the CompactionStrategy the provider stage calls between tool-loop rounds, the default ContextCompactor and its rules, the cosine-similarity scoring relevance truncation uses, and the embedding cache that keeps one call's vectors for the next. |
|
core
Package core holds what every part of runtime/pipeline/stage shares: the StreamElement that flows between stages and its metadata, the Stage interface and its basic implementations, the per-turn TurnState, format capabilities, the package's errors, the idle timeout, and the small flow helpers stages use to forward, cancel and tag elements.
|
Package core holds what every part of runtime/pipeline/stage shares: the StreamElement that flows between stages and its metadata, the Stage interface and its basic implementations, the per-turn TurnState, format capabilities, the package's errors, the idle timeout, and the small flow helpers stages use to forward, cancel and tag elements. |
|
cue
Package cue holds the cue stage, which plays a pre-rendered clip for each element carrying a Cue (a guardrail's message), and what it plays from: the clip bank, the clip sources (the session's own out-of-band audio, a TTS service, pre-warmed clips, the earcon) and PrewarmClips.
|
Package cue holds the cue stage, which plays a pre-rendered clip for each element carrying a Cue (a guardrail's message), and what it plays from: the clip bank, the clip sources (the session's own out-of-band audio, a TTS service, pre-warmed clips, the earcon) and PrewarmClips. |
|
duplex
Package duplex holds the realtime (duplex) provider stage: the stage that streams a conversation through a provider's bidirectional session, with its tool rounds, guardrails, cost accounting and reply holds, and the stages that follow it in the realtime chain and depend on its elements: the cue stage it wires (NewDuplexCueStage), transcript reordering and the playout hold.
|
Package duplex holds the realtime (duplex) provider stage: the stage that streams a conversation through a provider's bidirectional session, with its tool rounds, guardrails, cost accounting and reply holds, and the stages that follow it in the realtime chain and depend on its elements: the cue stage it wires (NewDuplexCueStage), transcript reordering and the playout hold. |
|
heard
Package heard holds HeardReplies, which carries what the caller heard of a reply a barge-in cut from a cascaded voice pipeline's speech-out stage back to its provider stage.
|
Package heard holds HeardReplies, which carries what the caller heard of a reply a barge-in cut from a cascaded voice pipeline's speech-out stage back to its provider stage. |
|
history
Package history holds what stage does to a conversation's history before a model sees it: it recognizes the turns an input guardrail blocked (the user's message and the canned reply that answered it) and leaves them out of every path that builds model context, and it renders a provider's message-metadata template into the request's copy of each message.
|
Package history holds what stage does to a conversation's history before a model sees it: it recognizes the turns an input guardrail blocked (the user's message and the canned reply that answered it) and leaves them out of every path that builds model context, and it renders a provider's message-metadata template into the request's copy of each message. |
|
media
Package media holds the stages that prepare a turn's media: extracting media from a message and composing it back (MediaExtractStage, MediaComposeStage), converting media to the formats a provider accepts (MediaConvertStage), resizing and preprocessing images (ImageResizeStage, ImagePreprocessStage), turning video into frames and frames into a message (VideoToFramesStage, FramesToMessageStage), and capping a stream's frame rate (FrameRateLimitStage).
|
Package media holds the stages that prepare a turn's media: extracting media from a message and composing it back (MediaExtractStage, MediaComposeStage), converting media to the formats a provider accepts (MediaConvertStage), resizing and preprocessing images (ImageResizeStage, ImagePreprocessStage), turning video into frames and frames into a message (VideoToFramesStage, FramesToMessageStage), and capping a stream's frame rate (FrameRateLimitStage). |
|
persist
Package persist holds the stages that keep what a turn produced: the recording stage (to an EventStore), the incremental save stage (to the state store), the memory retrieval and extraction stages, and the message broadcast stage (message.created on the EventBus).
|
Package persist holds the stages that keep what a turn produced: the recording stage (to an EventStore), the incremental save stage (to the state store), the memory retrieval and extraction stages, and the message broadcast stage (message.created on the EventBus). |
|
provider
Package provider holds the provider stage: the request/response and streaming call to the LLM, its tool loop (the tool runner, call-rate window, structured-output mode, schema resolution and workflow-state handoff), and the output guardrails it applies (the guardrail outcome, the blocked-turn message and the stream_hold engine that holds a streamed reply for its guardrails).
|
Package provider holds the provider stage: the request/response and streaming call to the LLM, its tool loop (the tool runner, call-rate window, structured-output mode, schema resolution and workflow-state handoff), and the output guardrails it applies (the guardrail outcome, the blocked-turn message and the stream_hold engine that holds a streamed reply for its guardrails). |
|
segment
Package segment splits a reply still being written into segments, for the pipeline stages that work on a reply a segment at a time.
|
Package segment splits a reply still being written into segments, for the pipeline stages that work on a reply a segment at a time. |
|
stagetest
Package stagetest holds test helpers that the tests of runtime/pipeline/stage and of its stage/internal packages share.
|
Package stagetest holds test helpers that the tests of runtime/pipeline/stage and of its stage/internal packages share. |
|
voice
Package voice holds the stages of a cascaded voice pipeline: turn detection on the caller's audio (AudioTurnStage), speech-to-text (STTStage), text-to-speech (TTSStage, and TTSStageWithInterruption, which speaks a streamed reply segment by segment and stops when the caller barges in), detection of the end of a spoken reply (ResponseVADStage), real-time pacing of audio (AudioPacingStage) and resampling (AudioResampleStage).
|
Package voice holds the stages of a cascaded voice pipeline: turn detection on the caller's audio (AudioTurnStage), speech-to-text (STTStage), text-to-speech (TTSStage, and TTSStageWithInterruption, which speaks a streamed reply segment by segment and stops when the caller barges in), detection of the end of a spoken reply (ResponseVADStage), real-time pacing of audio (AudioPacingStage) and resampling (AudioResampleStage). |