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 ¶
- Variables
- func ValidRole(role Role) bool
- type Acceptance
- type Agent
- type AgentFunc
- type AssetResolver
- type AudioControls
- type Controls
- type Emit
- type Error
- type Event
- func Activity(name string, data jsontext.Value) Event
- func MediaItem(part Part) Event
- func OutputItem(item Item) Event
- func Reasoning(text string) Event
- func Text(text string) Event
- func TextDelta(text string) Event
- func TextDone(itemID string) Event
- func Tool(callID, name, arguments string) Event
- func ToolDelta(callID, delta string) Event
- func ToolDone(callID string) Event
- func ToolStart(callID, name string) Event
- type EventType
- type FormatKind
- type FunctionTool
- type GenerationControl
- type Info
- type Item
- type ItemType
- type Limits
- type Media
- type Modality
- type Outcome
- type OutputFormat
- type OutputSpec
- type Part
- type PartType
- type ReasoningControl
- type Request
- type Response
- type Role
- type Status
- type StopReason
- type ToolChoice
- type TurnRequest
- type Usage
Constants ¶
This section is empty.
Variables ¶
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 ¶
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.
// 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 AssetResolver ¶
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 ¶
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 ¶
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.
type Error ¶
Error is a sanitized protocol error that an application may return from a resolver or agent.
func NotFound ¶
func NotFound() *Error
NotFound constructs a 404 not_found invalid_request_error for an unknown agent.
func Unsupported ¶
Unsupported constructs a 400 unsupported invalid_request_error for param.
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 OutputItem ¶
OutputItem returns an EventItem carrying an output item.
func TextDone ¶
TextDone marks the end of a text stream for an item. Final text comes from execution's accumulated state, not from this event.
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 ¶
func (c GenerationControl) Has(other GenerationControl) bool
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.
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 ¶
FunctionCallItem returns a completed function call item.
func FunctionCallOutputItem ¶
FunctionCallOutputItem returns a function call output item.
func MessageItem ¶
MessageItem returns a message item with role and content parts.
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.
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 ¶
AssetMedia returns media referenced by an application-owned asset ID.
func InlineMedia ¶
InlineMedia returns media backed by a copied byte slice.
func RemoteMedia ¶
RemoteMedia returns media referenced by an absolute HTTP or HTTPS URL.
type Outcome ¶
type Outcome struct {
Status Status
StopReason StopReason
Usage *Usage
}
Outcome is the final agent result returned from Agent.Run.
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 SummaryPart ¶
SummaryPart returns a reasoning summary text part.
type ReasoningControl ¶
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.
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 ¶
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.
}
TurnRequest is the input to Store.Accept (configured via llmux.WithStore).
Request is the canonical execution request (read-only). Turn is the items submitted in this HTTP request only and is distinguishable from Request.Input (effective history+turn). Retention, continuation, and idempotency are acceptance concerns, not Agent.Run inputs.