llm

package
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0 modules, 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 llm is the model client: one streaming completion against the configured base URL, with function tools, in one of three wire formats (OpenAI Chat Completions, OpenAI Responses and Anthropic Messages), and one decision from a decision model (OpenAI Decisions, TypeSafe Jev). The API key is a header only. It is never written to a log, and errors that would quote it are scrubbed.

Index

Constants

View Source
const (
	FormatChat      = "chat"
	FormatResponses = "responses"
	FormatAnthropic = "anthropic"
	// FormatTypeSafe is TypeSafe's System One API, which decides and does
	// not chat.
	FormatTypeSafe = "typesafe"
)

The wire formats a Client speaks. An empty format is FormatChat.

View Source
const (
	EffortNone   = "none"
	EffortLow    = "low"
	EffortMedium = "medium"
	EffortHigh   = "high"
	EffortXHigh  = "xhigh"
)

The thinking levels a Request may ask for. An empty Effort leaves the provider's default; EffortNone turns reasoning off where the format can.

View Source
const AnthropicMaxTokens = 32000

AnthropicMaxTokens is the max_tokens an Anthropic request sends when none is configured, as the format requires one.

View Source
const DefaultMaxBytes = 8 << 20

DefaultMaxBytes is the most of one response body a turn will read.

View Source
const MaxModels = 1000

MaxModels is the most model IDs ListModels returns.

Variables

View Source
var (
	ErrProtocol           = errors.New("llm: invalid response protocol")
	ErrIncompleteResponse = errors.New("llm: incomplete response")
	// ErrTokenLimit is an explicit, structurally complete length response with
	// no tool calls. It remains incomplete for normal assistant turns.
	ErrTokenLimit = fmt.Errorf("%w: output token limit reached", ErrIncompleteResponse)
)
View Source
var ErrBaseURL = errors.New("llm: base URL must be http or https with a host")

ErrBaseURL is the error for a base URL this client will not dial.

View Source
var ErrNoChat = errors.New("llm: this provider only makes decisions")

ErrNoChat is the error for a completion asked of a format that cannot chat.

View Source
var ErrTimeout = fmt.Errorf("llm: no response in time: %w", context.DeadlineExceeded)

ErrTimeout is the error when the reply did not start, or stopped coming, within Client.Timeout. It is a context.DeadlineExceeded.

View Source
var ErrTooBig = errors.New("llm: response exceeds the size cap")

ErrTooBig is the error when a response exceeds the size cap.

Formats lists the wire formats in the order the settings show them.

Functions

func IsChatModel

func IsChatModel(id string) bool

IsChatModel reports whether id names a model that can chat, judged by the words providers use in the IDs of the others.

Types

type APIError

type APIError struct {
	Status    int
	Message   string
	Truncated bool
	// contains filtered or unexported fields
}

APIError is a non-2xx response. Error never contains the API key.

func (*APIError) Detail

func (e *APIError) Detail() string

Detail is the provider's message, without the API key, on one line of at most detailMax runes, to show to the user.

func (*APIError) Error

func (e *APIError) Error() string

type Answer

type Answer struct {
	Probability float64
	Choice      string
	Confidence  float64
	Refused     bool
}

Answer is a decision model's answer to one question: the probability of yes, or the choice picked and the model's confidence in it. Refused is set when the model declined the question.

type Choice

type Choice struct {
	Value       string
	Description string
}

Choice is one answer a choice question may pick.

type Client

type Client struct {
	Format      string
	BaseURL     string
	APIKey      string
	Model       string
	Headers     map[string]string
	Temperature *float64
	TopP        *float64
	MaxTokens   int
	// LegacyMaxTokens sends a Chat Completions limit as max_tokens rather
	// than max_completion_tokens, for endpoints that know only the old name.
	LegacyMaxTokens bool
	// MaxBytes caps the response body of one call. Zero means DefaultMaxBytes.
	MaxBytes int
	// HTTP is optional. Its Transport is reused; a redirect is allowed
	// only when its scheme, hostname and port all match BaseURL.
	HTTP *http.Client
	// Timeout is how long a completion waits for the reply to start, and
	// then between two pieces of it, before it fails with ErrTimeout.
	// Zero waits as long as the connection lasts.
	Timeout time.Duration
}

Client talks to one endpoint. A nil Temperature or TopP, or a zero MaxTokens, is omitted so the provider's default applies; an Anthropic request, which needs max_tokens, then sends AnthropicMaxTokens.

func (*Client) Decide

func (c *Client) Decide(ctx context.Context, state string, qs []Question) (map[string]Answer, error)

Decide asks the client's model the questions about state, through OpenAI Decisions or, for FormatTypeSafe, TypeSafe's System One. Every question is answered or refused, or it is an error.

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context) ([]string, error)

ListModels returns the chat models the endpoint offers, sorted and without duplicates: GET {base}/models, following Anthropic's pages.

func (*Client) Stream

func (c *Client) Stream(ctx context.Context, req Request, emit func(Event)) (Message, error)

Stream posts one completion with streaming on and returns the assembled assistant message. emit, when set, receives each text delta. Cancelling ctx stops the read. A redirect is refused unless its scheme, hostname and port all match BaseURL, so the key is not sent in clear or to another service.

func (*Client) Test

func (c *Client) Test(ctx context.Context) error

Test checks the endpoint with a tiny request and no tools. Only the Anthropic format, which requires a limit, sends one.

type Event

type Event struct {
	Content  string
	Thinking string
}

Event is one piece of streamed text. Thinking is set when the model sends a reasoning delta.

type Message

type Message struct {
	Role         string
	Content      string
	Parts        []Part
	ToolCalls    []ToolCall
	ToolCallID   string
	Finish       string
	Opaque       json.RawMessage
	OpaqueFormat string
	OpaqueModel  string
}

Message is one chat message. ToolCalls is set on an assistant message that asked for tools; ToolCallID is set on a tool result. Parts are the files a user message carries besides its text.

Opaque is what the provider needs back with an assistant message, such as reasoning items or signed thinking blocks. It is replayed only to the format and model that produced it (OpaqueFormat, OpaqueModel).

type Part

type Part struct {
	Name string
	MIME string
	Data []byte
}

Part is one file sent with a user message: an image or a PDF.

func (Part) IsImage

func (p Part) IsImage() bool

IsImage reports whether the part is sent as an image.

type Question

type Question struct {
	Name         string
	Instructions string
	Yes, No      string
	Choices      []Choice
}

Question is one question a decision model answers about the state. With Choices it picks one of them; without, it says how likely the answer is yes. Yes and No, when set, say what counts as each.

type Request

type Request struct {
	Messages []Message
	Tools    []Tool
	Model    string
	Effort   string
	// MaxTokens overrides the client's when not zero.
	MaxTokens int
}

Request is one completion. Model and Effort override the client's model and the provider's default thinking when set.

type Tool

type Tool struct {
	Name        string
	Description string
	Parameters  json.RawMessage
}

Tool is a function the model may call. Parameters is a JSON schema.

type ToolCall

type ToolCall struct {
	ID        string
	Name      string
	Arguments string
}

ToolCall is one function call, arguments accumulated from the stream.

Jump to

Keyboard shortcuts

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