chat

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Copyright (c) Roman Atachiants and contributors. All rights reserved. Licensed under the MIT license. See LICENSE file in the project root for details. Package chat contains the protocol-neutral agent, request, event, and info types shared by llmux and application-owned agents.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrConcurrentEmit is returned when Emit is invoked concurrently.
	ErrConcurrentEmit = errors.New("llmux: concurrent Emit calls are not supported")
	// ErrEmitClosed is returned when Emit is called after the stream is closed.
	ErrEmitClosed = errors.New("llmux: emission is closed")
	// ErrDelivery is returned when a client write fails. With a positive
	// Acceptance.RunTimeout, the handler stops delivery but does not cancel
	// execution.
	ErrDelivery = errors.New("llmux: client delivery failed")
)

Functions

func ValidRole

func ValidRole(role Role) bool

ValidRole reports whether role is one of the canonical message roles.

Types

type Acceptance

type Acceptance struct {
	Response Response  // Identity for new work; ignored when Replay is set.
	Replay   *Response // When set, skip Agent.Run and encode this result.

	// Agent, when non-nil, is the request-specific executable for this
	// acceptance. It replaces the Catalog agent for Agent.Run only. Catalog.Load
	// still authorizes discovery-independent invocation and supplies Info.
	// When set, llmux does not load or merge continuation history into
	// Request.Input: the Agent owns effective input. Nil keeps the Catalog
	// agent and the ordinary post-Accept history merge for Previous.
	Agent Agent

	// RunTimeout controls execution cancellation:
	//   0  — follow the HTTP request context (cancel on client disconnect)
	//   >0 — detach client cancel, preserve values, bound by this duration;
	//        llmux owns cancel and releases it on every exit. Delivery
	//        failures after disconnect do not cancel execution.
	//   <0 — invalid; the handler rejects and calls Finish when set so
	//        reserved resources cannot leak.
	RunTimeout time.Duration
	Activity   bool // When true, Responses may emit EventActivity.

	// Finish is called exactly once after Agent.Run for a new acceptance.
	// Nil when Replay is set or when no terminal persistence is needed.
	// The Response is read-only and shared with subsequent encoding; Clone
	// before retaining or modifying. err is the operational execution error.
	Finish func(context.Context, *Response, error) error
}

Acceptance is the per-request result of Store.Accept.

For new work, Response carries identity (ID/Created; empty uses library defaults). For replay, Replay holds the complete stored Response and Run is skipped. Finish closes the request-local reservation and should capture any resources that must be released or persisted (idempotency key, turn items).

type Agent

type Agent interface {
	// Run executes once for an accepted HTTP request and streams events through emit.
	// It must stop when emit returns an error.
	Run(context.Context, *Request, Emit) (Outcome, error)
}

Agent is the application-owned execution seam.

type AgentFunc

type AgentFunc func(context.Context, *Request, Emit) (Outcome, error)

AgentFunc adapts a function to Agent.

func (AgentFunc) Run

func (f AgentFunc) Run(ctx context.Context, req *Request, emit Emit) (Outcome, error)

Run calls f, or returns an error if f is nil.

type AssetResolver

type AssetResolver func(context.Context, Media, int64) (Media, error)

AssetResolver is opt-in. It receives the original media descriptor and a hard byte ceiling. It must authorize the reference using the request context and return inline data or another bounded representation. Applications with resolver structs should pass a method value.

type AudioControls

type AudioControls struct {
	Voice  string
	Format string
}

AudioControls configures Chat Completions audio output.

func (AudioControls) Validate

func (a AudioControls) Validate() error

Validate checks Chat Completions audio controls.

type Controls

type Controls struct {
	MaxOutputTokens  *int                      // Maximum tokens to generate.
	Temperature      *float64                  // Sampling temperature.
	TopP             *float64                  // Nucleus sampling threshold.
	Stop             []string                  // Stop sequences.
	Tools            []FunctionTool            // Function tools available to the model.
	ToolChoice       *ToolChoice               // Tool selection policy.
	ParallelToolCall *bool                     // Whether parallel tool calls are allowed.
	Reasoning        *ReasoningControl         // Reasoning effort and summary controls.
	Audio            *AudioControls            // Chat Completions audio output controls.
	ImageGeneration  bool                      // Whether image generation is requested.
	Extensions       map[string]jsontext.Value // Application extension payloads keyed by name.
}

Controls holds generation settings for a request.

type Emit

type Emit func(Event) error

Emit is the serial event function passed to Agent.Run. Emit copies nested item data into execution state before returning, so the agent may retain and mutate the emitted Event afterward. Delivery callbacks receive a borrow of the stored item for EventItem and must not mutate it.

func (Emit) Activity

func (emit Emit) Activity(name string, payload jsontext.Value) error

Activity emits a named JSON activity event.

func (Emit) Delta

func (emit Emit) Delta(text string) error

Delta emits a streamed text fragment.

func (Emit) Text

func (emit Emit) Text(text string) error

Text emits a complete assistant text message.

func (Emit) Tool

func (emit Emit) Tool(callID, name, arguments string) error

Tool emits a completed function call.

type Error

type Error struct {
	Status  int
	Type    string
	Code    string
	Param   string
	Message string
	Err     error
}

Error is a sanitized protocol error that an application may return from a resolver or agent.

func Invalid

func Invalid(param, message string) *Error

Invalid constructs a 400 invalid_request_error for param.

func NotFound

func NotFound() *Error

NotFound constructs a 404 not_found invalid_request_error for an unknown agent.

func Unsupported

func Unsupported(param, message string) *Error

Unsupported constructs a 400 unsupported invalid_request_error for param.

func (*Error) Error

func (e *Error) Error() string

Error returns Message, the wrapped error text, or a default API error string.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error.

type Event

type Event struct {
	Type   EventType
	ItemID string
	CallID string
	Name   string
	Delta  string
	Item   Item
	Data   jsontext.Value
}

Event is the only output path from an Agent.

TextDone and ToolCallDone are closure signals: they carry only the item or call ID. Execution accumulates streamed text and tool arguments and supplies finalized content to protocol encoders through canonical items and its own state. Complete output continues to use EventItem with a fully populated Item.

func Activity

func Activity(name string, data jsontext.Value) Event

Activity builds an EventActivity with a structured JSON payload.

func MediaItem

func MediaItem(part Part) Event

MediaItem returns an EventItem carrying a media output item.

func OutputItem

func OutputItem(item Item) Event

OutputItem returns an EventItem carrying an output item.

func Reasoning

func Reasoning(text string) Event

Reasoning returns an EventItem carrying a reasoning summary item.

func Text

func Text(text string) Event

Text returns an EventItem carrying a complete assistant text message.

func TextDelta

func TextDelta(text string) Event

TextDelta returns an EventTextDelta with a text fragment.

func TextDone

func TextDone(itemID string) Event

TextDone marks the end of a text stream for an item. Final text comes from execution's accumulated state, not from this event.

func Tool

func Tool(callID, name, arguments string) Event

Tool returns an EventItem carrying a completed function call.

func ToolDelta

func ToolDelta(callID, delta string) Event

ToolDelta carries incremental tool call arguments.

func ToolDone

func ToolDone(callID string) Event

ToolDone closes a streaming tool call. Final arguments come from execution's accumulated state, not from this event.

func ToolStart

func ToolStart(callID, name string) Event

ToolStart opens a streaming tool call.

type EventType

type EventType string

EventType tags an event emitted during Agent.Run.

const (
	EventTextDelta     EventType = "text_delta"
	EventTextDone      EventType = "text_done"
	EventToolCallStart EventType = "tool_call_start"
	EventToolCallDelta EventType = "tool_call_delta"
	EventToolCallDone  EventType = "tool_call_done"
	EventItem          EventType = "item"
	EventActivity      EventType = "activity"
)

type FormatKind

type FormatKind string

FormatKind identifies text output formatting for a request.

const (
	FormatText       FormatKind = "text"
	FormatJSONObject FormatKind = "json_object"
	FormatJSONSchema FormatKind = "json_schema"
)

type FunctionTool

type FunctionTool struct {
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	Parameters  jsontext.Value `json:"parameters,omitempty"`
	Strict      *bool          `json:"strict,omitempty"`
}

FunctionTool declares a function tool available to the agent.

func (FunctionTool) Validate

func (t FunctionTool) Validate() error

Validate checks a function tool declaration.

type GenerationControl

type GenerationControl uint16

GenerationControl identifies a generation control understood by an agent.

const (
	ControlMaxOutputTokens GenerationControl = 1 << iota
	ControlTemperature
	ControlTopP
	ControlStop
	ControlParallelToolCalls
	ControlReasoning
	ControlAudio
)

func (GenerationControl) Has

Has reports whether c includes all bits in other.

type Info

type Info struct {
	InputModalities    Modality
	OutputModalities   Modality
	GenerationControls GenerationControl
	Extensions         map[string]bool
	Tools              bool
	ClientTools        bool
	StructuredOutput   bool
	ReasoningSummary   bool
	ImageGeneration    bool
	Continuation       bool

	// Description is a human-readable summary of the agent. Resolver
	// implementations should set it; llmux surfaces it as the MCP tool
	// description when the agent is exposed through /mcp.
	Description string

	// Tool is the stable public MCP tool name for this agent. Empty means
	// the agent is not exposed through MCP; nonempty exposes it, with the
	// name owned by the application (1-128 characters from [A-Za-z0-9._-],
	// unique per catalog). It is never derived from the resolver target.
	Tool string

	// Created is the Unix creation time in seconds shown in the model
	// catalog. Zero is rendered as the zero time value.
	Created int64
	// OwnedBy is the owner label shown in the model catalog.
	OwnedBy string
}

Info describes the selected agent for clients: a human-readable description plus what the agent can actually execute. It is also the unified catalog entry: applications return caller-visible targets mapped to Info, and llmux projects that one catalog into GET /models and MCP.

func (Info) Normalize

func (c Info) Normalize() Info

Normalize fills the defaults implied by a zero Info value.

type Item

type Item struct {
	Type             ItemType       `json:"type"`
	ID               string         `json:"id,omitempty"`
	Status           Status         `json:"status,omitempty"`
	Role             Role           `json:"role,omitempty"`
	Content          []Part         `json:"content,omitempty"`
	CallID           string         `json:"call_id,omitempty"`
	Name             string         `json:"name,omitempty"`
	Arguments        string         `json:"arguments,omitempty"`
	Output           []Part         `json:"output,omitempty"`
	Summary          []Part         `json:"summary,omitempty"`
	EncryptedContent jsontext.Value `json:"encrypted_content,omitempty"`
	Data             jsontext.Value `json:"data,omitempty"`
}

Item is the library-owned tagged union used for both request input and agent output.

func FunctionCallItem

func FunctionCallItem(callID, name, arguments string) Item

FunctionCallItem returns a completed function call item.

func FunctionCallOutputItem

func FunctionCallOutputItem(callID string, output ...Part) Item

FunctionCallOutputItem returns a function call output item.

func MessageItem

func MessageItem(role Role, content ...Part) Item

MessageItem returns a message item with role and content parts.

func (Item) Clone

func (i Item) Clone() Item

Clone returns a deep copy of the item and nested parts or JSON values.

func (Item) Validate

func (i Item) Validate(maxMediaBytes int64, output bool) error

Validate checks the tagged shape of an input or output item.

type ItemType

type ItemType string

ItemType tags the shape of an input or output item.

const (
	ItemMessage            ItemType = "message"
	ItemFunctionCall       ItemType = "function_call"
	ItemFunctionCallOutput ItemType = "function_call_output"
	ItemReasoning          ItemType = "reasoning"
	ItemMedia              ItemType = "media"
	ItemExtension          ItemType = "extension"
)

type Limits

type Limits struct {
	MaxRequestBytes   int64
	MaxMediaBytes     int64
	MaxAssets         int
	MaxOutputBytes    int64
	MaxEventBytes     int64
	MaxMultipartBytes int64
}

Limits bound request, media, event, and accumulated response memory.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the conservative limits used by a Handler when an option leaves a field at zero.

func (Limits) Normalize

func (l Limits) Normalize() Limits

Normalize replaces non-positive fields with their documented defaults.

type Media

type Media struct {
	MIMEType string `json:"mime_type,omitempty"`
	Format   string `json:"format,omitempty"`
	Filename string `json:"filename,omitempty"`
	URL      string `json:"url,omitempty"`
	Ref      string `json:"ref,omitempty"`
	Data     []byte `json:"data,omitempty"`
}

Media identifies bytes, a remote URL, or an application-owned asset.

func AssetMedia

func AssetMedia(mime, ref string) Media

AssetMedia returns media referenced by an application-owned asset ID.

func InlineMedia

func InlineMedia(mime string, data []byte) Media

InlineMedia returns media backed by a copied byte slice.

func RemoteMedia

func RemoteMedia(mime, url string) Media

RemoteMedia returns media referenced by an absolute HTTP or HTTPS URL.

func (Media) Clone

func (m Media) Clone() Media

Clone returns independent byte ownership for media that has inline data.

type Modality

type Modality uint8

Modality is a bit set used for input and output declarations.

const (
	ModalityText Modality = 1 << iota
	ModalityImage
	ModalityAudio
	ModalityFile
)

func (Modality) Has

func (m Modality) Has(other Modality) bool

Has reports whether m includes all bits in other.

type Outcome

type Outcome struct {
	Status     Status
	StopReason StopReason
	Usage      *Usage
}

Outcome is the final agent result returned from Agent.Run.

func (Outcome) Validate

func (o Outcome) Validate() error

Validate checks an agent outcome.

type OutputFormat

type OutputFormat struct {
	Kind        FormatKind
	Name        string
	Description string
	Schema      jsontext.Value
	Strict      bool
}

OutputFormat is text formatting. Zero value = plain text.

func (OutputFormat) IsStructured

func (f OutputFormat) IsStructured() bool

IsStructured reports whether the format requests JSON object output.

func (OutputFormat) Validate

func (f OutputFormat) Validate() error

Validate checks a declared output format.

type OutputSpec

type OutputSpec struct {
	Modalities Modality
	Format     OutputFormat
}

OutputSpec declares expected response modalities and formatting.

type Part

type Part struct {
	Type     PartType       `json:"type"`
	Text     string         `json:"text,omitempty"`
	Media    *Media         `json:"media,omitempty"`
	Data     jsontext.Value `json:"data,omitempty"`
	Detail   string         `json:"detail,omitempty"`
	Filename string         `json:"filename,omitempty"`
}

Part is a typed content part.

func AudioPart

func AudioPart(media Media) Part

AudioPart returns an audio content part backed by media.

func FilePart

func FilePart(media Media) Part

FilePart returns a file content part backed by media.

func ImagePart

func ImagePart(media Media) Part

ImagePart returns an image content part backed by media.

func JSONPart

func JSONPart(data jsontext.Value) Part

JSONPart returns a JSON content part with a copied payload.

func SummaryPart

func SummaryPart(text string) Part

SummaryPart returns a reasoning summary text part.

func TextPart

func TextPart(text string) Part

TextPart returns a text content part.

func (Part) Clone

func (p Part) Clone() Part

Clone returns a deep copy of the part and any nested media or JSON data.

func (Part) Validate

func (p Part) Validate(maxMediaBytes int64) error

Validate checks the tagged shape of a content part and its inline media size.

type PartType

type PartType string

PartType tags a content part within an item.

const (
	PartText             PartType = "text"
	PartImage            PartType = "image"
	PartAudio            PartType = "audio"
	PartFile             PartType = "file"
	PartJSON             PartType = "json"
	PartReasoningSummary PartType = "reasoning_summary"
)

type ReasoningControl

type ReasoningControl struct {
	Effort  string
	Summary bool
}

ReasoningControl configures optional reasoning effort and summary output.

func (ReasoningControl) Validate

func (r ReasoningControl) Validate() error

Validate checks reasoning controls.

type Request

type Request struct {
	Target       string     // Agent target name selected by the resolver.
	Instructions string     // System or developer instructions for the run.
	Input        []Item     // Effective conversation for Agent.Run (history+turn).
	Controls     Controls   // Generation settings.
	Output       OutputSpec // Declared output modalities and format.
}

Request is the protocol-neutral input passed to Agent.Run. It contains only execution fields. Persistence, continuation, and idempotency live on TurnRequest for Lifecycle.Accept.

type Response

type Response struct {
	ID           string            // Response identifier
	Created      int64             // Unix creation time
	CompletedAt  int64             // Unix completion time; zero while in_progress
	Status       Status            // completed, failed, incomplete, cancelled, or in_progress
	Output       []Item            // Output items for this response turn
	Usage        *Usage            // Token usage when known
	Error        *Error            // Sanitized public error when status is failed
	Incomplete   string            // incomplete_details.reason when status is incomplete
	Metadata     map[string]string // Response metadata captured at acceptance
	Store        bool              // Effective content-retention policy
	Target       string            // Model/target echoed for retrieval
	Instructions string            // Instructions echoed for retrieval
	Previous     *string           // Parent response ID for retrieval
}

Response is the complete client-visible response used for creation, finalization, replay, and retrieval. Identity, timestamps, output, and retrieval fields share one value so GET does not need the original execution request or accumulated history.

When passed to Acceptance.Finish, nested data is shared with the response subsequently encoded. Finish callbacks must treat it as read-only and call Clone before retaining or modifying it.

Error is sanitized public error only. Operational Go errors stay on the Finish error argument and are never copied into Error.Message automatically.

func (Response) Clone

func (r Response) Clone() Response

Clone returns a deep copy safe for independent retention.

type Role

type Role string

Role identifies who produced a message item.

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleSystem    Role = "system"
	RoleDeveloper Role = "developer"
	RoleTool      Role = "tool"
)

type Status

type Status string

Status reports lifecycle state for items and outcomes.

const (
	StatusInProgress Status = "in_progress"
	StatusCompleted  Status = "completed"
	StatusIncomplete Status = "incomplete"
	StatusFailed     Status = "failed"
	StatusCancelled  Status = "cancelled"
)

type StopReason

type StopReason string

StopReason explains why generation ended.

const (
	StopNormal    StopReason = "stop"
	StopToolCall  StopReason = "tool_call"
	StopLength    StopReason = "length"
	StopError     StopReason = "error"
	StopCancelled StopReason = "cancelled"
)

type ToolChoice

type ToolChoice struct {
	Mode string
	Name string
}

ToolChoice selects how the model may use declared tools.

func (ToolChoice) Validate

func (t ToolChoice) Validate() error

Validate checks a tool-choice declaration.

type TurnRequest

type TurnRequest struct {
	Request        *Request          // Execution request; treat as read-only.
	Turn           []Item            // Items submitted in this request only.
	Previous       *string           // Prior response ID for continuation.
	Metadata       map[string]string // Application metadata for the response.
	Store          *bool             // Wire store flag; nil when omitted.
	Retain         bool              // Effective retention after StoreDefault.
	IdempotencyKey string            // Idempotency-Key header value, if any.
	Stream         bool              // Whether the client requested streaming.
	CatalogAgent   Agent             // Agent from Catalog.Load for this target.
}

TurnRequest is the input to Store.Accept (configured via llmux.WithStore).

Request is the canonical execution request (read-only at Accept). Turn is the items submitted in this HTTP request only. When Previous is set, Request.Input equals Turn at Accept time: history is not merged yet. Retention, continuation, and idempotency are acceptance concerns, not Agent.Run inputs.

CatalogAgent is the Agent returned by Catalog.Load for Request.Target. Store implementations may type-assert it to reuse load-time binding. Nil when no catalog is configured or Load was not performed for this turn.

type Usage

type Usage struct {
	Input     int
	Output    int
	Total     int
	Cached    int
	Reasoning int
}

Usage reports token accounting for a completed run. Total is supplied independently; callers are not required to set it to Input+Output or any other derived sum.

Jump to

Keyboard shortcuts

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