session

package
v2.22.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 18 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package session provides session abstractions for managing conversations. Sessions wrap pipelines and provide convenient APIs for text and duplex streaming interactions.

Package session provides session abstractions for managing conversations.

Index

Constants

View Source
const DefaultDrainTimeout = 30 * time.Second

DefaultDrainTimeout is the maximum time to wait for pipeline completion during Drain.

Variables

View Source
var ErrSessionClosed = errors.New("session is closed")

ErrSessionClosed is returned by a duplex session's input methods once the session has ended without an error of its own: Close was called, or the provider closed the session.

Functions

This section is empty.

Types

type AsyncToolCheckResult

type AsyncToolCheckResult struct {
	// ShouldWait is true if the tool requires human approval before execution.
	ShouldWait bool
	// PendingInfo provides context when ShouldWait is true.
	PendingInfo *tools.PendingToolInfo
	// Handled is true when the checker executed the handler directly
	// (i.e., the tool was an async tool but the check passed, so it ran immediately).
	Handled bool
	// HandlerResult contains the JSON-encoded result when Handled is true.
	HandlerResult json.RawMessage
	// HandlerError is set when Handled is true but execution failed.
	HandlerError error
}

AsyncToolCheckResult describes the outcome of an HITL check on a tool call.

type AsyncToolChecker

type AsyncToolChecker func(ctx context.Context, callID, name string, args map[string]any) *AsyncToolCheckResult

AsyncToolChecker is called before a duplex session executes a tool call, to determine if it requires human approval. Returns nil if the tool is not an async tool (falls through to normal registry execution). The context is the tool-execution context so a checker persisting the held call honors cancellation and deadlines. It is consulted only when the session runs tool calls itself (not when the pipeline runs them).

type BaseSession

type BaseSession interface {
	// Identity
	ID() string

	// Variable management for template substitution
	Variables() map[string]string
	SetVar(name, value string)
	GetVar(name string) (string, bool)

	// State management - encapsulates StateStore access
	Messages(ctx context.Context) ([]types.Message, error)
	Clear(ctx context.Context) error
}

BaseSession represents core session capabilities shared by all session types.

type DuplexSession

type DuplexSession interface {
	BaseSession

	// SendChunk sends a chunk to the session (populate MediaData for media, Content for text).
	// This method is thread-safe and can be called from multiple goroutines.
	// Once the session has ended it returns at once, and so do the other
	// input methods: with the error that ended it (see Error), else with a
	// ErrSessionClosed.
	SendChunk(ctx context.Context, chunk *providers.StreamChunk) error

	// SendText is a convenience method for sending text directly.
	SendText(ctx context.Context, text string) error

	// SendFrame sends an image frame to the session for realtime video scenarios.
	// This is a convenience method that wraps SendChunk with proper image formatting.
	SendFrame(ctx context.Context, frame *ImageFrame) error

	// SendVideoChunk sends a video chunk to the session for encoded video streaming.
	// This is a convenience method that wraps SendChunk with proper video formatting.
	SendVideoChunk(ctx context.Context, chunk *VideoChunk) error

	// Response returns a receive-only channel for streaming responses.
	// The channel emits StreamChunks containing LLM responses (text, media, tool calls, etc).
	Response() <-chan providers.StreamChunk

	// Close ends the streaming session and releases resources.
	Close() error

	// Drain gracefully stops the session: sends EndOfStream to the pipeline,
	// waits for the provider to finish processing (up to the given timeout),
	// then closes. Returns nil if the pipeline completes within the timeout.
	Drain(ctx context.Context) error

	// Done returns a channel that's closed when the session ends.
	Done() <-chan struct{}

	// Error returns the error that ended the session: nil while it runs, and
	// nil when it ended without one.
	Error() error

	// SubmitToolResults sends resolved/rejected tool results back into the
	// duplex pipeline so they flow to the provider via ToolResponseSupport.
	// Used after HITL approval or client tool fulfillment.
	SubmitToolResults(ctx context.Context, responses []providers.ToolResponse) error

	// ForkSession creates a new session that is a fork of this one.
	// The new session will have an independent copy of the conversation state.
	ForkSession(
		ctx context.Context,
		forkID string,
		pipelineBuilder PipelineBuilder,
	) (DuplexSession, error)
}

DuplexSession manages bidirectional streaming conversations. Uses providers.StreamChunk for BOTH input and output for API symmetry.

func NewDuplexSession

func NewDuplexSession(ctx context.Context, cfg *DuplexSessionConfig) (DuplexSession, error)

NewDuplexSession creates a bidirectional session from a config. PipelineBuilder and Provider are required.

If Config is provided (ASM mode):

  • Passes streaming provider + base config to PipelineBuilder
  • DuplexProviderStage creates the session lazily using TurnState.SystemPrompt
  • Single long-running pipeline execution

If Config is nil (VAD mode):

  • No streaming provider or config
  • Calls PipelineBuilder with nil streaming provider
  • VAD middleware triggers multiple pipeline executions

type DuplexSessionConfig

type DuplexSessionConfig struct {
	ConversationID  string
	UserID          string
	StateStore      statestore.Store                // StateStore for conversation history
	PipelineBuilder PipelineBuilder                 // Function to build pipeline (required, typically a closure from SDK)
	Provider        providers.Provider              // Provider for LLM calls (required)
	Config          *providers.StreamingInputConfig // For ASM mode: base streaming config. For VAD mode: nil
	// ToolRegistry runs the session's tool calls when no stage of the
	// pipeline does (stage.StreamPipeline.RunsToolCalls): a pipeline that
	// runs them is never doubled by the session. With no registry and no
	// such stage nothing runs them, and an assistant turn
	// that made tool calls is forwarded for the caller to answer with
	// SubmitToolResults.
	ToolRegistry *tools.Registry
	// AsyncToolChecker gates the calls the session runs itself; it is not
	// consulted when the pipeline runs them (the stage's ApprovalGate holds
	// calls there).
	AsyncToolChecker AsyncToolChecker
	// Caller is who the conversation acts for (sdk.WithCaller). Every tool call
	// the session runs carries it; when the pipeline runs them it is given
	// it (stage.DuplexToolConfig.Caller). The zero value means none was set.
	Caller    types.Caller
	Metadata  map[string]interface{}
	Variables map[string]string // Initial variables for template substitution
}

DuplexSessionConfig configures a DuplexSession.

PipelineBuilder and Provider are required. PipelineBuilder is typically a closure created in SDK that captures configuration.

Two modes based on Config field:

ASM Mode (Config provided):

  • Pipeline is the single source of truth
  • DuplexProviderStage creates the session lazily using TurnState.SystemPrompt
  • PipelineBuilder receives streaming provider + base config (NOT a pre-created session)
  • Single long-running pipeline execution for continuous streaming

VAD Mode (Config nil):

  • No provider session created
  • Calls PipelineBuilder with nil streaming provider
  • Builder creates pipeline with VAD middleware and provider middleware for one-shot calls
  • Multiple pipeline executions, one per detected turn

StateStore should match what's configured in the Pipeline middleware.

type ImageFrame

type ImageFrame struct {
	// Data is the raw image data (JPEG, PNG, etc.)
	Data []byte

	// MIMEType is the MIME type of the image (e.g., "image/jpeg")
	MIMEType string

	// Width is the image width in pixels (optional, for metadata)
	Width int

	// Height is the image height in pixels (optional, for metadata)
	Height int

	// FrameNum is the sequence number for ordering frames
	FrameNum int64

	// Timestamp is when the frame was captured
	Timestamp time.Time
}

ImageFrame represents an image frame for streaming. Use this with DuplexSession.SendFrame() for realtime video scenarios.

type PipelineBuilder

type PipelineBuilder func(
	ctx context.Context,
	provider providers.Provider,
	streamProvider providers.StreamInputSupport,
	streamConfig *providers.StreamingInputConfig,
	conversationID string,
	store statestore.Store,
) (*stage.StreamPipeline, error)

PipelineBuilder creates a StreamPipeline for a DuplexSession. This is typically a closure created in SDK that captures configuration.

For ASM mode: streamProvider will be non-nil, builder passes it to DuplexProviderStage, which creates the session lazily using TurnState.SystemPrompt (published by PromptAssemblyStage).

For VAD mode: streamProvider will be nil, builder creates pipeline with VAD/TTS stages.

type UnarySession

type UnarySession interface {
	BaseSession

	// Execution methods
	Execute(ctx context.Context, role, content string) (*pipeline.ExecutionResult, error)
	ExecuteWithMessage(ctx context.Context, message types.Message) (*pipeline.ExecutionResult, error)
	ExecuteStream(ctx context.Context, role, content string) (<-chan providers.StreamChunk, error)
	ExecuteStreamWithMessage(ctx context.Context, message types.Message) (<-chan providers.StreamChunk, error)

	// ResumeWithToolResults injects tool result messages into the session
	// history and re-executes the pipeline so the LLM can continue.
	ResumeWithToolResults(ctx context.Context, toolResults []types.Message) (*pipeline.ExecutionResult, error)

	// ResumeStreamWithToolResults is the streaming equivalent of ResumeWithToolResults.
	// It injects tool result messages and returns a streaming channel.
	ResumeStreamWithToolResults(ctx context.Context, toolResults []types.Message) (<-chan providers.StreamChunk, error)

	// ForkSession creates a new session that is a fork of this one.
	// The new session will have an independent copy of the conversation state.
	ForkSession(ctx context.Context, forkID string, pipeline *stage.StreamPipeline) (UnarySession, error)
}

UnarySession manages unary (request/response) conversations with multimodal support.

func NewUnarySession

func NewUnarySession(cfg UnarySessionConfig) (UnarySession, error)

NewUnarySession creates a new unary session.

type UnarySessionConfig

type UnarySessionConfig struct {
	ConversationID string
	UserID         string
	StateStore     statestore.Store // Must match Pipeline's StateStore stages
	Pipeline       *stage.StreamPipeline
	Metadata       map[string]interface{}
	Variables      map[string]string // Initial variables for template substitution
	// StreamReasoning makes the streaming methods (ExecuteStream,
	// ExecuteStreamWithMessage, ResumeStreamWithToolResults) send the model's
	// reasoning text as it arrives, as chunks carrying only
	// providers.StreamChunk.Reasoning. Off by default: the reasoning is on the
	// turn's messages either way.
	StreamReasoning bool
}

UnarySessionConfig configures a TextSession. StateStore should match what's configured in the Pipeline stages.

type VideoChunk

type VideoChunk struct {
	// Data is the encoded video data (H.264, VP8, etc.)
	Data []byte

	// MIMEType is the MIME type of the video (e.g., "video/h264")
	MIMEType string

	// Width is the video width in pixels (optional, for metadata)
	Width int

	// Height is the video height in pixels (optional, for metadata)
	Height int

	// ChunkIndex is the sequence number for ordering chunks
	ChunkIndex int

	// IsKeyFrame indicates if this chunk contains a keyframe
	IsKeyFrame bool

	// Timestamp is when the chunk was created/captured
	Timestamp time.Time

	// Duration is the duration of this video chunk
	Duration time.Duration
}

VideoChunk represents a video chunk for streaming. Use this with DuplexSession.SendVideoChunk() for encoded video segments.

Jump to

Keyboard shortcuts

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