Documentation
¶
Overview ¶
Package modelsocket provides a Go client for the ModelSocket protocol.
ModelSocket is a WebSocket-based protocol for efficiently integrating with Large Language Models (LLMs). It provides streaming text generation, tool calling, and sequence forking capabilities.
Thread Safety ¶
Client and Seq are safe for concurrent use by multiple goroutines. However, only one Seq.Generate call can be active per sequence at a time. GenStream should only be consumed by a single goroutine.
Basic Usage ¶
ctx := context.Background()
// Connect to server
client, err := modelsocket.Connect(ctx, "wss://example.com/ws", "api-key")
if err != nil {
log.Fatal(err)
}
defer client.Close(ctx)
// Open a sequence
seq, err := client.Open(ctx, "model-name")
if err != nil {
log.Fatal(err)
}
defer seq.Close(ctx)
// Append user message
err = seq.Append(ctx, "Hello!", modelsocket.AsUser())
if err != nil {
log.Fatal(err)
}
// Generate response using iterator
stream, err := seq.Generate(ctx, modelsocket.GenerateAsAssistant())
if err != nil {
log.Fatal(err)
}
for chunk, err := range stream.Chunks(ctx) {
if err != nil {
log.Fatal(err)
}
fmt.Print(chunk.Text)
}
Observability ¶
Use WithLogger, WithOnSend, and WithOnReceive to add logging and monitoring to the client:
client, err := modelsocket.Connect(ctx, url, apiKey,
modelsocket.WithLogger(slog.Default()),
modelsocket.WithOnSend(func(req *modelsocket.MSRequest) {
metrics.RequestsSent.Inc()
}),
)
Index ¶
- Variables
- type AppendOption
- type Client
- type ClientOption
- type ConnectionError
- type DialOptions
- type FuncTool
- type GenChunk
- type GenOption
- func GenerateAsAssistant() GenOption
- func GenerateAsSystem() GenOption
- func GenerateAsUser() GenOption
- func WithHidden() GenOption
- func WithMaxLength(n int) GenOption
- func WithMaxTokens(n int) GenOption
- func WithRegexMask(pattern string) GenOption
- func WithRepeatPenalty(p float64) GenOption
- func WithSeed(seed int64) GenOption
- func WithStopStrings(stops ...string) GenOption
- func WithTemperature(t float64) GenOption
- func WithTopK(k int) GenOption
- func WithTopP(p float64) GenOption
- type GenStream
- func (g *GenStream) Chunks(ctx context.Context) iter.Seq2[*GenChunk, error]
- func (g *GenStream) InputTokens() int
- func (g *GenStream) Next(ctx context.Context) (*GenChunk, error)
- func (g *GenStream) OutputTokens() int
- func (g *GenStream) Text(ctx context.Context) (string, error)
- func (g *GenStream) TextAndTokens(ctx context.Context) (string, []int, error)
- type MSEvent
- func (e *MSEvent) IsError() bool
- func (e *MSEvent) IsSeqAppendFinish() bool
- func (e *MSEvent) IsSeqClosed() bool
- func (e *MSEvent) IsSeqForkFinish() bool
- func (e *MSEvent) IsSeqGenFinish() bool
- func (e *MSEvent) IsSeqOpened() bool
- func (e *MSEvent) IsSeqState() bool
- func (e *MSEvent) IsSeqText() bool
- func (e *MSEvent) IsSeqToolCall() bool
- func (e *MSEvent) Type() string
- type MSRequest
- func NewAppendRequest(cid, seqID string, data SeqAppendData) *MSRequest
- func NewCloseRequest(cid, seqID string) *MSRequest
- func NewForkRequest(cid, seqID string) *MSRequest
- func NewGenRequest(cid, seqID string, data SeqGenData) *MSRequest
- func NewSeqOpenRequest(cid string, data SeqOpenData) *MSRequest
- func NewToolReturnRequest(cid, seqID string, results []ToolResult, genOpts SeqGenData) *MSRequest
- type OpenOption
- type ProtocolError
- type Role
- type SendError
- type Seq
- func (s *Seq) Append(ctx context.Context, text string, opts ...AppendOption) error
- func (s *Seq) Close(ctx context.Context) error
- func (s *Seq) Fork(ctx context.Context) (*Seq, error)
- func (s *Seq) Generate(ctx context.Context, opts ...GenOption) (*GenStream, error)
- func (s *Seq) ID() string
- func (s *Seq) State() SeqState
- func (s *Seq) ToolReturn(ctx context.Context, results []ToolResult) error
- type SeqAppendData
- type SeqError
- type SeqGenData
- type SeqOpenData
- type SeqState
- type SeqToolCall
- type Tool
- type ToolCall
- type ToolDefinition
- type ToolParameters
- type ToolProperty
- type ToolResult
- type Toolbox
- func (t *Toolbox) Add(tool Tool)
- func (t *Toolbox) Call(ctx context.Context, name string, args string) (string, error)
- func (t *Toolbox) CallTools(ctx context.Context, calls []ToolCall) ([]ToolResult, error)
- func (t *Toolbox) Definitions() []ToolDefinition
- func (t *Toolbox) Get(name string) (Tool, bool)
- func (t *Toolbox) SetToolDefinitionPrompt(prompt string)
- func (t *Toolbox) SetToolInstructions(instructions string)
- func (t *Toolbox) ToolDefinitionPrompt() string
- func (t *Toolbox) ToolInstructions() string
- type Transport
Constants ¶
This section is empty.
Variables ¶
var ( ErrClosed = errors.New("modelsocket: connection closed") ErrSeqClosed = errors.New("modelsocket: sequence closed") ErrTimeout = errors.New("modelsocket: operation timed out") ErrInvalidState = errors.New("modelsocket: invalid sequence state") ErrToolNotFound = errors.New("modelsocket: tool not found") ErrUnexpectedEvent = errors.New("modelsocket: unexpected event") ErrBufferFull = errors.New("modelsocket: buffer full") )
Sentinel errors for common conditions.
Functions ¶
This section is empty.
Types ¶
type AppendOption ¶
type AppendOption func(*appendConfig)
AppendOption configures text appending.
func AsAssistant ¶
func AsAssistant() AppendOption
AsAssistant marks the message as from the assistant.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the main client for connecting to a ModelSocket server. It is safe for concurrent use by multiple goroutines.
func NewWithTransport ¶
func NewWithTransport(ctx context.Context, transport Transport, opts ...ClientOption) *Client
NewWithTransport creates a Client with a custom transport. This is useful for testing or custom transport implementations.
type ClientOption ¶
type ClientOption func(*clientConfig)
ClientOption configures a ModelSocket client.
func WithLogger ¶
func WithLogger(logger *slog.Logger) ClientOption
WithLogger sets a structured logger for the client.
func WithOnReceive ¶
func WithOnReceive(fn func(*MSEvent)) ClientOption
WithOnReceive sets a callback invoked after each event is received.
func WithOnSend ¶
func WithOnSend(fn func(*MSRequest)) ClientOption
WithOnSend sets a callback invoked before each request is sent.
type ConnectionError ¶
ConnectionError represents a connection-level error.
func (*ConnectionError) Error ¶
func (e *ConnectionError) Error() string
func (*ConnectionError) Unwrap ¶
func (e *ConnectionError) Unwrap() error
type DialOptions ¶
type DialOptions struct {
// HTTPHeader specifies additional HTTP headers to send during handshake.
HTTPHeader http.Header
// HTTPClient is the HTTP client used for the handshake.
// If nil, http.DefaultClient is used.
HTTPClient *http.Client
}
DialOptions configures the WebSocket connection.
type FuncTool ¶
type FuncTool struct {
// contains filtered or unexported fields
}
FuncTool wraps a function as a Tool.
func NewFuncTool ¶
func NewFuncTool(def ToolDefinition, fn func(ctx context.Context, args string) (string, error)) *FuncTool
NewFuncTool creates a tool from a function.
func (*FuncTool) Definition ¶
func (f *FuncTool) Definition() ToolDefinition
Definition returns the tool definition.
type GenOption ¶
type GenOption func(*genConfig)
GenOption configures text generation.
func GenerateAsAssistant ¶
func GenerateAsAssistant() GenOption
GenerateAsAssistant generates text as the assistant role.
func GenerateAsSystem ¶
func GenerateAsSystem() GenOption
GenerateAsSystem generates text as the system role.
func GenerateAsUser ¶
func GenerateAsUser() GenOption
GenerateAsUser generates text as the user role.
func WithHidden ¶
func WithHidden() GenOption
WithHidden hides the generated text from the conversation history.
func WithMaxLength ¶
WithMaxLength sets the maximum length in characters.
func WithMaxTokens ¶
WithMaxTokens sets the maximum number of tokens to generate.
func WithRegexMask ¶
WithRegexMask constrains generation to match a regex pattern.
func WithRepeatPenalty ¶
WithRepeatPenalty sets the repetition penalty.
func WithStopStrings ¶
WithStopStrings sets strings that will stop generation.
func WithTemperature ¶
WithTemperature sets the sampling temperature.
type GenStream ¶
type GenStream struct {
// contains filtered or unexported fields
}
GenStream provides streaming access to generated content.
func (*GenStream) InputTokens ¶
InputTokens returns the input token count. Only valid after stream is exhausted.
func (*GenStream) Next ¶
Next returns the next chunk, or nil if done. Returns an error if one occurred during generation. The context can be used to cancel waiting for the next chunk.
func (*GenStream) OutputTokens ¶
OutputTokens returns the output token count. Only valid after stream is exhausted.
type MSEvent ¶
type MSEvent struct {
Event string `json:"event"`
// Common fields
SeqID string `json:"seq_id,omitempty"`
CID string `json:"cid,omitempty"`
// SeqText fields
Text string `json:"text,omitempty"`
Hidden bool `json:"hidden,omitempty"`
NumInputTokens int `json:"num_input_tokens,omitempty"`
NumOutputTokens int `json:"num_output_tokens,omitempty"`
Tokens []int `json:"tokens,omitempty"`
// SeqToolCall fields
ToolCalls []SeqToolCall `json:"tool_calls,omitempty"`
// SeqForkFinish fields
ChildSeqID string `json:"child_seq_id,omitempty"`
// SeqState fields
State SeqState `json:"state,omitempty"`
// SeqClosed fields
InputTokens int `json:"input_tokens,omitempty"`
OutputTokens int `json:"output_tokens,omitempty"`
DurationMs int64 `json:"duration_ms,omitempty"`
ErrorMsg string `json:"error,omitempty"`
// Error fields
Message string `json:"message,omitempty"`
}
MSEvent represents an event received from the server.
func (*MSEvent) IsSeqAppendFinish ¶
IsSeqAppendFinish returns true if this is a seq_append_finish event.
func (*MSEvent) IsSeqClosed ¶
IsSeqClosed returns true if this is a seq_closed event.
func (*MSEvent) IsSeqForkFinish ¶
IsSeqForkFinish returns true if this is a seq_fork_finish event.
func (*MSEvent) IsSeqGenFinish ¶
IsSeqGenFinish returns true if this is a seq_gen_finish event.
func (*MSEvent) IsSeqOpened ¶
IsSeqOpened returns true if this is a seq_opened event.
func (*MSEvent) IsSeqState ¶
IsSeqState returns true if this is a seq_state event.
func (*MSEvent) IsSeqToolCall ¶
IsSeqToolCall returns true if this is a seq_tool_call event.
type MSRequest ¶
type MSRequest struct {
Request string `json:"request"`
CID string `json:"cid"`
SeqID string `json:"seq_id,omitempty"`
Data interface{} `json:"data"`
}
MSRequest represents a request sent to the server.
func NewAppendRequest ¶
func NewAppendRequest(cid, seqID string, data SeqAppendData) *MSRequest
NewAppendRequest creates a new append command request.
func NewCloseRequest ¶
NewCloseRequest creates a new close command request.
func NewForkRequest ¶
NewForkRequest creates a new fork command request.
func NewGenRequest ¶
func NewGenRequest(cid, seqID string, data SeqGenData) *MSRequest
NewGenRequest creates a new gen command request.
func NewSeqOpenRequest ¶
func NewSeqOpenRequest(cid string, data SeqOpenData) *MSRequest
NewSeqOpenRequest creates a new seq_open request.
func NewToolReturnRequest ¶
func NewToolReturnRequest(cid, seqID string, results []ToolResult, genOpts SeqGenData) *MSRequest
NewToolReturnRequest creates a new tool_return command request.
type OpenOption ¶
type OpenOption func(*openConfig)
OpenOption configures sequence opening.
func WithSkipPrelude ¶
func WithSkipPrelude() OpenOption
WithSkipPrelude skips the model's default prelude/system prompt.
func WithToolbox ¶
func WithToolbox(tb *Toolbox) OpenOption
WithToolbox registers a toolbox for tool calling.
type ProtocolError ¶
ProtocolError represents a protocol-level error from the server.
func (*ProtocolError) Error ¶
func (e *ProtocolError) Error() string
type Seq ¶
type Seq struct {
// contains filtered or unexported fields
}
Seq represents an active conversation sequence. It is safe for concurrent use by multiple goroutines. However, only one Generate call can be active at a time.
func (*Seq) ToolReturn ¶
func (s *Seq) ToolReturn(ctx context.Context, results []ToolResult) error
ToolReturn sends tool call results back to the model.
type SeqAppendData ¶
type SeqAppendData struct {
Text string `json:"text"`
Role string `json:"role,omitempty"`
Echo bool `json:"echo,omitempty"`
Hidden bool `json:"hidden,omitempty"`
}
SeqAppendData is the data for an append command.
type SeqGenData ¶
type SeqGenData struct {
Role string `json:"role,omitempty"`
MaxTokens *int `json:"max_tokens,omitempty"`
MaxLength *int `json:"max_length,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
TopK *int `json:"top_k,omitempty"`
RepeatPenalty *float64 `json:"repeat_penalty,omitempty"`
Seed *int64 `json:"seed,omitempty"`
StopStrings []string `json:"stop_strings,omitempty"`
RegexMask *string `json:"regex_mask,omitempty"`
Hidden bool `json:"hidden,omitempty"`
PrefillText *string `json:"prefill_text,omitempty"`
ReturnTokens *bool `json:"return_tokens,omitempty"`
}
SeqGenData is the data for a gen command.
type SeqOpenData ¶
type SeqOpenData struct {
Model string `json:"model"`
ToolsEnabled bool `json:"tools_enabled,omitempty"`
ToolPrompt string `json:"tool_prompt,omitempty"`
SkipPrelude bool `json:"skip_prelude,omitempty"`
}
SeqOpenData is the data for a seq_open request.
type SeqToolCall ¶
SeqToolCall represents a tool call from the model.
type Tool ¶
type Tool interface {
Definition() ToolDefinition
Call(ctx context.Context, args string) (string, error)
}
Tool defines the interface for a callable tool.
type ToolDefinition ¶
type ToolDefinition struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters ToolParameters `json:"parameters"`
}
ToolDefinition describes a tool for the model.
type ToolParameters ¶
type ToolParameters struct {
Type string `json:"type"`
Properties map[string]ToolProperty `json:"properties,omitempty"`
Required []string `json:"required,omitempty"`
}
ToolParameters defines the JSON Schema for tool parameters.
type ToolProperty ¶
type ToolProperty struct {
Type string `json:"type"`
Description string `json:"description,omitempty"`
Enum []string `json:"enum,omitempty"`
}
ToolProperty defines a single parameter property.
type ToolResult ¶
ToolResult represents the result of a tool call.
type Toolbox ¶
type Toolbox struct {
// contains filtered or unexported fields
}
Toolbox manages a collection of tools.
func (*Toolbox) Definitions ¶
func (t *Toolbox) Definitions() []ToolDefinition
Definitions returns all tool definitions.
func (*Toolbox) SetToolDefinitionPrompt ¶
func (*Toolbox) SetToolInstructions ¶
func (*Toolbox) ToolDefinitionPrompt ¶
ToolPrompt returns the tool prompt. If a custom prompt was set via SetToolPrompt, it returns that; otherwise it returns an auto-generated prompt describing all tools.
func (*Toolbox) ToolInstructions ¶
ToolInstructions returns the tool instructions.