Skip to content

Latest commit

 

History

History
466 lines (353 loc) · 11.5 KB

File metadata and controls

466 lines (353 loc) · 11.5 KB
title Types Reference
description Complete type documentation for chit
author zoobzio
published 2025-01-15
updated 2025-01-15
tags
chit
types
reference

Types Reference

Chat

The conversation lifecycle controller.

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

Chat manages conversation state, delegates to a processor for reasoning, and streams output through an emitter. It handles turn-taking via continuations.

Methods:

  • Handle(ctx, input) — process user input
  • ID() — unique identifier
  • Session() — conversation history
  • Config() — configuration
  • HasContinuation() — check if awaiting input

See: API Reference

Config

Configuration for a Chat.

type Config struct {
    SystemPrompt string
    Metadata     map[string]any
}
Field Type Description
SystemPrompt string System message that guides conversation behavior
Metadata map[string]any Optional additional configuration data

Processor

Interface for reasoning and execution logic.

type Processor interface {
    Process(ctx context.Context, input string, session *zyn.Session) (Result, error)
}

Implement this interface to define how your chat handles user input. The processor receives the input and conversation history, and returns a Result.

The context contains the Emitter (retrievable via EmitterFromContext) for pushing resources during processing.

ProcessorFunc

Adapter to use a function as a Processor.

type ProcessorFunc func(ctx context.Context, input string, session *zyn.Session) (Result, error)
processor := chit.ProcessorFunc(func(ctx context.Context, input string, session *zyn.Session) (chit.Result, error) {
    return &chit.Response{Content: "Hello"}, nil
})

Result

Interface for processing outcomes.

type Result interface {
    IsComplete() bool
    IsYielded() bool
}

Two concrete implementations exist: *Response and *Yield.

Method Response Yield
IsComplete() true false
IsYielded() false true

Response

A complete result with content to emit.

type Response struct {
    Content  string
    Metadata map[string]any
}
Field Type Description
Content string Response text to emit to the user
Metadata map[string]any Optional additional information
return &chit.Response{
    Content:  "Here's your answer.",
    Metadata: map[string]any{"tokens": 150},
}, nil

Yield

Indicates processing paused awaiting further input.

type Yield struct {
    Prompt       string
    Continuation Continuation
    Metadata     map[string]any
}
Field Type Description
Prompt string Message to emit while awaiting input
Continuation Continuation Function to call with next input
Metadata map[string]any Optional additional information
return &chit.Yield{
    Prompt: "What's your email?",
    Continuation: func(ctx context.Context, email string) (chit.Result, error) {
        return &chit.Response{Content: "Thanks, " + email}, nil
    },
}, nil

Continuation

Function that resumes processing with new input.

type Continuation func(ctx context.Context, input string) (Result, error)

Continuations can return either *Response (to complete) or *Yield (to chain another continuation).

Emitter

Interface for streaming output to the client.

type Emitter interface {
    Emit(ctx context.Context, msg Message) error
    Push(ctx context.Context, resource Resource) error
    Close() error
}
Method Purpose
Emit Stream conversational text
Push Send structured data synchronously
Close Signal end of output, release resources

Message

A streamed response unit.

type Message struct {
    Role     string
    Content  string
    Metadata map[string]any
}
Field Type Description
Role string Message sender (e.g., "assistant", "system")
Content string Text content of the message
Metadata map[string]any Optional additional information

Resource

Structured data pushed to the client.

type Resource struct {
    Type     string
    URI      string
    Payload  any
    Metadata map[string]any
}
Field Type Description
Type string Kind of resource ("data", "context", "tool_result")
URI string Source URI if retrieved from a data source
Payload any The structured data being delivered
Metadata map[string]any Optional additional information
emitter.Push(ctx, chit.Resource{
    Type:    "data",
    URI:     "db://users/123",
    Payload: map[string]string{"name": "Alice"},
})

Option

Functional option for configuring a Chat.

type Option func(*Chat)

See API Reference for available options.

ChatRequest

The request object that flows through the pipz pipeline.

type ChatRequest struct {
    Input     string
    Session   *zyn.Session
    ChatID    string
    RequestID string
    Result    Result
}
Field Type Description
Input string User input to process
Session *zyn.Session Conversation history
ChatID string ID of the chat instance
RequestID string Unique identifier for this request
Result Result Output (populated by terminal)

Implements pipz.Cloner for concurrent middleware support.

ChatProvider

Interface for types that can provide a pipeline for composition.

type ChatProvider interface {
    GetPipeline() pipz.Chainable[*ChatRequest]
}

Used by WithFallback to compose fallback pipelines. Chat implements this interface.

PipelineOption

Function that wraps a pipeline with additional behavior.

type PipelineOption func(pipz.Chainable[*ChatRequest]) pipz.Chainable[*ChatRequest]

Used internally. See API Reference for the Option-returning wrappers.

Terminal Functions

Internal functions that create the innermost pipeline layer.

NewTerminal

func NewTerminal(processor Processor) pipz.Chainable[*ChatRequest]

Creates the terminal that calls the Processor. Used for fresh input processing.

NewContinuationTerminal

func NewContinuationTerminal(cont Continuation) pipz.Chainable[*ChatRequest]

Creates a terminal that calls the given continuation. Used when resuming yielded processing.

Both terminals:

  • Receive a *ChatRequest with input and session
  • Call their target (processor or continuation) with the input
  • Store the result in req.Result
  • Are wrapped with the same pipeline options for reliability parity

MetricsRecorder

Interface for recording chat metrics.

type MetricsRecorder interface {
    RecordRequest(chatID string, inputLength int)
    RecordLatency(chatID string, duration time.Duration)
}

Used by UseMetrics middleware.

Enricher

Interface for enriching chat requests.

type Enricher interface {
    Enrich(ctx context.Context, req *ChatRequest) error
}

Used by UseEnrich middleware.

Errors

Sentinel errors for chit operations.

var (
    ErrUnknownResultType = errors.New("chit: unknown result type")
    ErrNilProcessor      = errors.New("chit: processor is required")
    ErrNilEmitter        = errors.New("chit: emitter is required")
    ErrEmitterClosed     = errors.New("chit: emitter is closed")
)
Error When
ErrUnknownResultType Processor returned a Result that isn't *Response or *Yield
ErrNilProcessor Attempted to create Chat without a Processor
ErrNilEmitter Attempted to create Chat without an Emitter
ErrEmitterClosed Attempted to emit after Emitter was closed

Signals

Lifecycle signals emitted via capitan.

var (
    ChatCreated         = capitan.NewSignal("chit.chat.created", ...)
    InputReceived       = capitan.NewSignal("chit.input.received", ...)
    ProcessingStarted   = capitan.NewSignal("chit.processing.started", ...)
    ProcessingCompleted = capitan.NewSignal("chit.processing.completed", ...)
    ProcessingFailed    = capitan.NewSignal("chit.processing.failed", ...)
    ResponseEmitted     = capitan.NewSignal("chit.response.emitted", ...)
    ResourcePushed      = capitan.NewSignal("chit.resource.pushed", ...)
    TurnYielded         = capitan.NewSignal("chit.turn.yielded", ...)
    TurnResumed         = capitan.NewSignal("chit.turn.resumed", ...)
)
Signal When Emitted
ChatCreated New Chat instantiated
InputReceived Handle() called with user input
ProcessingStarted Before calling processor/continuation
ProcessingCompleted Processor/continuation returned successfully
ProcessingFailed Processor/continuation returned error
ResponseEmitted Response emitted via Emitter
ResourcePushed Available for processors pushing resources
TurnYielded Continuation stored, awaiting input
TurnResumed Continuation being called

Signal Fields

Field keys for signal event data.

var (
    FieldChatID             = capitan.NewStringKey("chat_id")
    FieldInput              = capitan.NewStringKey("input")
    FieldInputSize          = capitan.NewIntKey("input_size")
    FieldProcessingDuration = capitan.NewDurationKey("processing_duration")
    FieldRole               = capitan.NewStringKey("role")
    FieldContentSize        = capitan.NewIntKey("content_size")
    FieldResourceType       = capitan.NewStringKey("resource_type")
    FieldResourceURI        = capitan.NewStringKey("resource_uri")
    FieldPrompt             = capitan.NewStringKey("prompt")
    FieldError              = capitan.NewErrorKey("error")
)
Field Type Used In
FieldChatID string All signals
FieldInput string InputReceived
FieldInputSize int InputReceived
FieldProcessingDuration time.Duration ProcessingCompleted, ProcessingFailed
FieldRole string ResponseEmitted
FieldContentSize int ResponseEmitted
FieldResourceType string ResourcePushed
FieldResourceURI string ResourcePushed
FieldPrompt string TurnYielded
FieldError error ProcessingFailed

Test Helpers

The github.com/zoobz-io/chit/testing package provides test utilities.

MockProcessor

type MockProcessor struct {
    ProcessFunc func(ctx context.Context, input string, session *zyn.Session) (chit.Result, error)
    Calls       []ProcessCall
}

type ProcessCall struct {
    Input   string
    Session *zyn.Session
}

MockEmitter

type MockEmitter struct {
    EmitFunc  func(ctx context.Context, msg chit.Message) error
    PushFunc  func(ctx context.Context, resource chit.Resource) error
    CloseFunc func() error
    Messages  []chit.Message
    Resources []chit.Resource
    Closed    bool
}

CollectingEmitter

type CollectingEmitter struct {
    Messages  []chit.Message
    Resources []chit.Resource
}

func (e *CollectingEmitter) Content() string

Factory Functions

func EchoProcessor() chit.Processor
func YieldingProcessor(prompt, finalResponse string) chit.Processor

See: Testing Guide

Next Steps