Documentation
¶
Index ¶
- Constants
- func GetOpt[T any](o *Opts, key string) (T, error)
- func GetPages(o *Opts) ([]uint, error)
- func HTTPErr(err error) error
- func HTTPStatus(err error) (int, bool)
- func IsToolName(name string) bool
- func ReadAll(ctx context.Context, r Resource) ([]byte, error)
- type Document
- type DocumentPage
- type DocumentRegion
- type DownloadProgressFn
- type Downloader
- type Embedder
- type Err
- type Generator
- type GeneratorStreamFn
- type Message
- type Model
- type ModelCap
- type Opt
- func WithContextWindow(value uint) Opt
- func WithDimensions(value uint) Opt
- func WithFrequencyPenalty(value float64) Opt
- func WithJSONSchema(value json.RawMessage) Opt
- func WithKeepAlive(value time.Duration) Opt
- func WithLanguage(value string) Opt
- func WithMaxTokens(value uint) Opt
- func WithOpt(key string, value any) Opt
- func WithPages(values ...uint) Opt
- func WithPresencePenalty(value float64) Opt
- func WithRegions(value bool) Opt
- func WithSeed(value uint) Opt
- func WithSegments(value bool) Opt
- func WithServiceTier(value string) Opt
- func WithSpeakers(value bool) Opt
- func WithStopSequences(values ...string) Opt
- func WithSystemPrompt(value string) Opt
- func WithTableFormat(value string) Opt
- func WithTaskType(value string) Opt
- func WithTemperature(value float64) Opt
- func WithThinking(value bool) Opt
- func WithThinkingEffort(value string) Opt
- func WithTitle(value string) Opt
- func WithToolChoice(value string) Opt
- func WithTopK(value uint) Opt
- func WithTopP(value float64) Opt
- func WithUser(value string) Opt
- type Opts
- type Provider
- type ReadFunc
- type Recognizer
- type Resource
- type StreamType
- type Tool
- type ToolCall
- type ToolResult
- type Transcriber
- type TranscriberStreamFn
- type Transcript
- type TranscriptSegment
- type Usage
- type Vector
Constants ¶
const ( // Sampling TemperatureKey = "temperature" // float64, randomness of sampling TopPKey = "top_p" // float64, nucleus sampling probability mass TopKKey = "top_k" // uint, sample from the K most likely tokens MaxTokensKey = "max_tokens" // uint, maximum tokens to generate StopSequencesKey = "stop_sequences" // []string, sequences which stop generation SeedKey = "seed" // uint, seed for deterministic generation PresencePenaltyKey = "presence_penalty" // float64, penalty for tokens already present FrequencyPenaltyKey = "frequency_penalty" // float64, penalty by frequency of tokens // Prompt SystemPromptKey = "system_prompt" // string, system prompt for the model // Thinking ThinkingKey = "thinking" // bool, enable or disable thinking ThinkingEffortKey = "thinking_effort" // string, reasoning effort: "low", "medium" or "high" // Output JSONSchemaKey = "json_schema" // json.RawMessage, JSON schema the output conforms to // Tools ToolChoiceKey = "tool_choice" // string, whether the model uses the tools: "auto", "any" or "none" // Model loading ContextWindowKey = "context_window" // uint, context window size in tokens KeepAliveKey = "keep_alive" // time.Duration, how long a model stays loaded, or negative to stay loaded // Requests UserKey = "user" // string, identifier of the end user, for abuse monitoring ServiceTierKey = "service_tier" // string, provider service tier, for example "auto" // Embeddings TaskTypeKey = "task_type" // string, task the embedding is used for TitleKey = "title" // string, title of the document being embedded DimensionsKey = "dimensions" // uint, number of dimensions of the embedding // Recognition PagesKey = "pages" // []uint, uint, or a string such as "0,2-4", pages of a document to recognize, from zero TableFormatKey = "table_format" // string, format of the tables in the text: "markdown" or "html" RegionsKey = "regions" // bool, whether a page has its regions, with their boxes // Transcription LanguageKey = "language" // string, ISO 639-1 code of the language the speech is in, such as "en" SegmentsKey = "segments" // bool, whether a transcript has its segments, with when each was spoken SpeakersKey = "speakers" // bool, whether a transcript's segments have who spoke them )
Keys for options shared by providers. Each key notes the type of its value. Providers ignore or reject the options they don't support, and validate ranges, which differ between providers.
const ( Ollama = "ollama" Eliza = "eliza" OpenAI = "openai" GoWhisper = "gowhisper" ElevenLabs = "elevenlabs" )
Variables ¶
This section is empty.
Functions ¶
func GetOpt ¶ added in v0.5.0
GetOpt returns the value of the option with the key, or an error if it isn't set or isn't of the type. A value which is JSON, such as an option stored with a session, is decoded as the type, and can't be null.
func GetPages ¶ added in v0.5.0
GetPages returns the pages of a document to recognize, in order, without duplicates, from the option, which is the page numbers, a page number, or a string of them and ranges, such as "0,2-4", from zero. Returns an error if it isn't set, or isn't pages.
func HTTPErr ¶ added in v0.5.0
HTTPErr translates an error into an error wrapping a HTTP status code, which httpresponse.Error uses for the response. The message is prefixed with the status text, and errors.Is and errors.As still match the original error. An llm.Err's own text, such as "not found", isn't in the message, when it starts it, and the status says the same, such as "Not Found", so the message is "Not Found: model ...", rather than "Not Found: not found: model ...".
An llm.Err is translated with its HTTP method, even when it wraps a HTTP status code, such as a provider's response, and fs errors (fs.ErrNotExist and so on) to the corresponding status code. Other errors which already wrap a HTTP status code are returned unchanged, a server's response is its status, and any other error is an internal server error. Returns nil when err is nil.
func HTTPStatus ¶ added in v0.5.0
HTTPStatus returns the HTTP status code of an error, which wraps one, as httpresponse.Err, or is a server's response, as httpresponse.ErrResponse, which a client returns for an error whose body is JSON, such as go-whisper's. Returns false when it hasn't one.
func IsToolName ¶ added in v0.5.0
IsToolName returns true if the name is a valid tool name, which is 1 to 64 letters, digits, underscores or hyphens
Types ¶
type Document ¶ added in v0.5.0
type Document struct {
Pages []DocumentPage `json:"pages" help:"The pages, in order"`
}
Document is the text recognized in an image or document, by page, in order. An image is one page.
type DocumentPage ¶ added in v0.5.0
type DocumentPage struct {
Text string `json:"text" help:"Text of the page, in Markdown" example:"# Hello, World"`
Regions []DocumentRegion `json:"regions,omitempty" help:"Regions of the page, in reading order, when they're asked for"`
}
DocumentPage is the text of a page, in Markdown, and its regions, in reading order, when they're asked for
type DocumentRegion ¶ added in v0.5.0
type DocumentRegion struct {
Type string `json:"type,omitempty" help:"What the region is, as the model labels it, such as text, title or table" example:"text"`
Text string `json:"text" help:"Text of the region, in Markdown" example:"Hello, World"`
Box [4]float64 `` /* 163-byte string literal not displayed */
}
DocumentRegion is a part of a page, such as a paragraph, a title or a table, with its text, and its box. The type is the model's, such as "text" or "table", which differ between models.
type DownloadProgressFn ¶ added in v0.5.0
DownloadProgressFn is called with the status of a model download, and how complete it is, as a percentage from 0 to 100
type Downloader ¶ added in v0.1.0
type Downloader interface {
// LoadModel downloads the model with the given name, and otherwise
// loads the model if it's already present. The progress function, if not
// nil, is called with the status of the download as it progresses.
LoadModel(context.Context, string, DownloadProgressFn) (Model, error)
// DeleteModel deletes the model from local storage
DeleteModel(context.Context, Model) error
// UnloadModel unloads the model from memory, keeping it in local
// storage, so it's loaded again when it's next used
UnloadModel(context.Context, Model) error
}
Downloader is an interface for managing model files, for providers which store models locally, such as Ollama
type Embedder ¶ added in v0.1.0
type Embedder interface {
// Embed returns a vector for each of the messages, in the same order, and
// the tokens used, which are input tokens. A message is embedded by its
// text. The options can set what the vectors are for (WithTaskType), the
// title of the document the messages are from (WithTitle), and the
// number of dimensions of the vectors (WithDimensions), which the model
// must support. Options which the provider doesn't support are ignored
// or rejected.
Embed(context.Context, Model, []Message, ...Opt) ([]Vector, Usage, error)
}
Embedder is an interface for providers which embed messages as vectors, such as for semantic search
type Err ¶
type Err int
Errors
const ( ErrSuccess Err = iota ErrNotFound ErrBadParameter ErrNotImplemented ErrConflict ErrInternalServerError ErrForbidden ErrMaxTokens // the model's reply was truncated, as it reached the most tokens ErrRefusal // the model refused to reply ErrPauseTurn // the model paused its turn, which is to be continued )
func (Err) HTTP ¶ added in v0.5.0
func (e Err) HTTP() httpresponse.Err
type Generator ¶ added in v0.1.0
type Generator interface {
// WithoutSession returns the model's reply to the messages, and the
// tokens used. Without a session, the messages include any system prompt
// and earlier turns of the conversation. The model can call the tools,
// which may be nil, by their names, and the reply has the calls rather
// than their results. The stream function, if not nil, is called with
// the pieces of the reply's thinking and text as they're generated.
// Options which the provider doesn't support are ignored or rejected.
WithoutSession(context.Context, Model, []Message, []Tool, GeneratorStreamFn, ...Opt) (Message, Usage, error)
}
Generator is an interface for providers which generate messages, such as chat completions
type GeneratorStreamFn ¶ added in v0.5.0
type GeneratorStreamFn func(StreamType, string)
GeneratorStreamFn is called with each piece of a message as it's generated, with what the piece is, such as the reply's text or the model's thinking
type Message ¶ added in v0.5.0
type Message interface {
Role() string // Message role: user, assistant, system, thinking or tool
Text() string // Text content of the message
Resources() []Resource // Resources in the message, such as images or documents
ToolCalls() []ToolCall // Tools the model called, in a message from the model
ToolResults() []ToolResult // Results of the tools the model called, in a tool message
}
Message is a message in a conversation with a model, which providers convert to their own formats
type Model ¶
type Model interface {
Name() string
Provider() Provider // Model provider
Description() string
Created() time.Time
Aliases() []string // Model aliases
Meta() map[string]json.RawMessage // Provider-specific metadata
InputTokenLimit() *uint // Input token limit (optional)
OutputTokenLimit() *uint // Output token limit (optional)
Capabilities() ModelCap // What the model can do, of what's known
}
Represents an LLM model
type ModelCap ¶ added in v0.5.0
type ModelCap struct {
Completion *bool `json:"completion,omitempty" help:"Generates replies to messages"`
Tools *bool `json:"tools,omitempty" help:"Calls tools"`
Thinking *bool `json:"thinking,omitempty" help:"Thinks, or reasons, before it replies"`
Vision *bool `json:"vision,omitempty" help:"Understands images"`
OCR *bool `json:"ocr,omitempty" help:"Recognizes the text in images and documents"`
Transcription *bool `json:"transcription,omitempty" help:"Transcribes speech"`
Translation *bool `json:"translation,omitempty" help:"Translates speech into English"`
Embedding *bool `json:"embedding,omitempty" help:"Embeds text as vectors"`
}
ModelCap is what a model can do, of what its provider knows. A capability which isn't known is nil.
type Opt ¶
Opt is an option for an operation of a provider, such as generating a message. Options are set by key, so providers can define their own.
func WithContextWindow ¶ added in v0.5.0
WithContextWindow sets the context window size in tokens, which is one or more
func WithDimensions ¶ added in v0.5.0
WithDimensions sets the number of dimensions of the embedding, which is one or more
func WithFrequencyPenalty ¶ added in v0.0.3
WithFrequencyPenalty sets the penalty by frequency of tokens
func WithJSONSchema ¶ added in v0.5.0
func WithJSONSchema(value json.RawMessage) Opt
WithJSONSchema sets the JSON schema the output conforms to
func WithKeepAlive ¶ added in v0.5.0
WithKeepAlive sets how long a model stays loaded after the request, or negative to stay loaded
func WithLanguage ¶ added in v0.5.0
WithLanguage sets the language the speech in audio is in, as an ISO 639-1 code, such as "en", rather than it being detected
func WithMaxTokens ¶ added in v0.0.3
WithMaxTokens sets the maximum tokens to generate, which is one or more
func WithOpt ¶ added in v0.5.0
WithOpt sets the option with the key to the value, replacing any value already set
func WithPages ¶ added in v0.5.0
WithPages sets the pages of a document to recognize, numbered from zero
func WithPresencePenalty ¶ added in v0.0.3
WithPresencePenalty sets the penalty for tokens already present
func WithRegions ¶ added in v0.5.0
WithRegions sets whether the pages of recognized text have their regions, such as paragraphs, titles and tables, with their boxes
func WithSegments ¶ added in v0.5.0
WithSegments sets whether a transcript has its segments, with when each was spoken
func WithServiceTier ¶ added in v0.5.0
WithServiceTier sets the provider service tier, for example "auto"
func WithSpeakers ¶ added in v0.5.0
WithSpeakers sets whether a transcript's segments have who spoke them, which is diarization
func WithStopSequences ¶ added in v0.5.0
WithStopSequences sets the sequences which stop generation, replacing any already set
func WithSystemPrompt ¶
WithSystemPrompt sets the system prompt for the model
func WithTableFormat ¶ added in v0.5.0
WithTableFormat sets the format of the tables in recognized text: "markdown" or "html"
func WithTaskType ¶ added in v0.5.0
WithTaskType sets the task the embedding is used for
func WithTemperature ¶
WithTemperature sets the randomness of sampling, which is zero or more
func WithThinking ¶ added in v0.5.0
WithThinking enables or disables thinking
func WithThinkingEffort ¶ added in v0.5.0
WithThinkingEffort sets the reasoning effort: "low", "medium" or "high"
func WithToolChoice ¶ added in v0.0.3
WithToolChoice sets whether the model uses the tools: "auto" to decide, "any" to use one of them, or "none" to use none of them. To use a particular tool, pass only that tool with "any".
type Opts ¶
type Opts struct {
// contains filtered or unexported fields
}
Opts are the options for an operation, by key
func ApplyOpts ¶
ApplyOpts returns the options set by each option in turn, or the first error. Nil options are skipped.
type Provider ¶ added in v0.5.0
type Provider interface {
// Return the provider name
Name() string
// URL returns the provider's normalized endpoint, or nil if it has none
URL() *url.URL
// Self returns the underlying provider implementation for capability checks.
Self() Provider
// Ping checks the connectivity of the provider and returns an error if not successful
Ping(context.Context) error
// ListModels returns the list of available models
ListModels(context.Context) ([]Model, error)
// GetModel returns the model with the given name
GetModel(context.Context, string) (Model, error)
}
Provider is the interface that interfaces with LLM providers (Anthropic, etc)
type ReadFunc ¶ added in v0.5.0
ReadFunc reads a resource's content: it opens the content, calls the function with a reader of it, and closes it when the function returns. The reader returns an error once the context is cancelled. Returns the function's error, or the error opening or closing the content.
type Recognizer ¶ added in v0.5.0
type Recognizer interface {
// Recognize returns the text in the resource, such as an image or a PDF,
// as a document, with the text of each page, in Markdown, and its
// regions, when they're asked for, and the pages and tokens used. The
// resource's type must be one the provider supports, such as image/png
// or application/pdf. Options which the provider doesn't support are
// rejected.
Recognize(context.Context, Model, Resource, ...Opt) (Document, Usage, error)
}
Recognizer is an interface for providers which recognize the text in images and documents, which is optical character recognition (OCR)
type Resource ¶ added in v0.4.2
type Resource interface {
// URI returns the unique identifier of the resource. It must be an
// absolute URI with a non-empty scheme (e.g. "file:///path/to/file").
URI() string
// Name returns a human-readable name for the resource.
Name() string
// Description returns an optional description of the resource.
Description() string
// Type returns the MIME type of the resource content, for example
// image/png or application/pdf, or an empty string if unknown.
Type() string
// Read returns a function which reads the resource's content, or an
// error when it can't be read, such as when it isn't found
Read(context.Context) (ReadFunc, error)
}
Resource is media, such as an image, document or audio, or a readable resource which a server advertises, which is opaque until it's read
type StreamType ¶ added in v0.5.0
type StreamType string
StreamType is what a piece of a message is, as it's generated
const ( // StreamText is a piece of the text of the reply StreamText StreamType = "text" // StreamThinking is a piece of the model's thinking, before or while it // replies StreamThinking StreamType = "thinking" )
type Tool ¶
type Tool interface {
// Return the name of the tool
Name() string
// Return the description of the tool
Description() string
// Return the JSON schema for the tool input parameters.
InputSchema() *jsonschema.Schema
// Return the JSON schema for the tool output, or nil if unspecified.
OutputSchema() *jsonschema.Schema
// Run the tool with the given input as JSON (may be nil). The result is
// JSON as a json.RawMessage, a Resource such as an image or audio, any
// other value which can be encoded as JSON, or nil when the tool has no
// result.
Run(ctx context.Context, input json.RawMessage) (any, error)
}
Tool is an interface for a callable tool with a name, description, input schema, and optional output schema.
type ToolCall ¶
type ToolCall struct {
ID string // Identifier of the call, which its result refers to
Name string // Name of the tool the model called it by
Input json.RawMessage // Input to the tool as JSON, which may be empty
}
ToolCall is a call by a model to a tool
type ToolResult ¶
type ToolResult struct {
ID string // Identifier of the call
Name string // Name of the tool the model called it by
Content json.RawMessage // Result of the tool as JSON
IsError bool // Whether the result is an error
}
ToolResult is the result of a call by a model to a tool
type Transcriber ¶ added in v0.5.0
type Transcriber interface {
// Transcribe returns the speech in the audio as text, in the language
// it was spoken in, with its segments and when each was spoken, when
// they're asked for, so a part of a recording can be found, and the
// seconds and tokens used. The audio is a resource whose type is audio,
// such as audio/mpeg, which the provider must support. The stream
// function, if not nil, is called with the pieces of the transcript as
// they're transcribed, or once it's transcribed, by a model which
// doesn't stream. Options which the provider doesn't support are
// rejected.
Transcribe(context.Context, Model, Resource, TranscriberStreamFn, ...Opt) (Transcript, Usage, error)
// Translate returns the speech in the audio, in any language, as English
// text, with its segments, as Transcribe does, whose language is "en",
// and the seconds and tokens used
Translate(context.Context, Model, Resource, TranscriberStreamFn, ...Opt) (Transcript, Usage, error)
}
Transcriber is an interface for providers which transcribe speech in audio, and translate it into English. A model which can't do one of them, such as one which only transcribes, returns ErrNotImplemented for it.
type TranscriberStreamFn ¶ added in v0.5.0
type TranscriberStreamFn func(text string, segment *TranscriptSegment)
TranscriberStreamFn is called with each piece of a transcript as it's transcribed: a piece of its text, or, when segments are asked for, a segment, once it's transcribed, with empty text. The pieces of text are the transcript's text, even for a model which only streams segments.
type Transcript ¶ added in v0.5.0
type Transcript struct {
Text string `json:"text" help:"Text of the speech" example:"Hello, world."`
Language string `json:"language,omitempty" help:"Language the speech was spoken in, as an ISO 639-1 code, when it's known" example:"en"`
Segments []TranscriptSegment `json:"segments,omitempty" help:"Segments of the speech, in order, when they're asked for"`
}
Transcript is the speech in audio: its text, the language it was spoken in, such as "en", when it's known, and its segments, in order, when they're asked for
type TranscriptSegment ¶ added in v0.5.0
type TranscriptSegment struct {
Start time.Duration `json:"start" help:"When the segment starts in the audio, in nanoseconds" example:"1600000000"`
End time.Duration `json:"end" help:"When the segment ends in the audio, in nanoseconds" example:"3500000000"`
Text string `json:"text" help:"Text of the segment" example:"This is a test."`
Speaker string `json:"speaker,omitempty" help:"Who spoke the segment, as the provider labels them, when speakers are asked for" example:"A"`
}
TranscriptSegment is a part of a transcript, such as a sentence, with when it starts and ends in the audio, and who spoke it, when the provider distinguishes speakers
type Usage ¶ added in v0.5.0
type Usage struct {
InputTokens uint `json:"input_tokens" help:"Tokens in the messages sent to the model" example:"26"`
OutputTokens uint `json:"output_tokens,omitempty" help:"Tokens in the message generated by the model" example:"12"`
CachedTokens uint `json:"cached_tokens,omitempty" help:"Of the input tokens, those read from the provider's cache" example:"0"`
ReasoningTokens uint `json:"reasoning_tokens,omitempty" help:"Of the output tokens, those of reasoning which isn't returned" example:"0"`
Pages uint `json:"pages,omitempty" help:"Pages of documents and images whose text was recognized" example:"0"`
Seconds uint `` /* 129-byte string literal not displayed */
}
Usage is the number of tokens used generating a message, or the pages recognized, or seconds of audio transcribed, for providers which charge by them. The cached and reasoning tokens are part of the input and output tokens, for providers which report them.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
llm
command
|
|
|
provider
|
|
|
elevenlabs
elevenlabs implements an API client for ElevenLabs, whose Scribe models transcribe speech.
|
elevenlabs implements an API client for ElevenLabs, whose Scribe models transcribe speech. |
|
eliza
eliza implements a mock LLM provider based on the classic ELIZA chatbot, created by Joseph Weizenbaum at MIT in 1966, which simulates a psychotherapist using pattern matching and transformation rules.
|
eliza implements a mock LLM provider based on the classic ELIZA chatbot, created by Joseph Weizenbaum at MIT in 1966, which simulates a psychotherapist using pattern matching and transformation rules. |
|
gowhisper
gowhisper implements an API client for go-whisper, which transcribes, and translates, speech with whisper.cpp models, which it downloads and stores.
|
gowhisper implements an API client for go-whisper, which transcribes, and translates, speech with whisper.cpp models, which it downloads and stores. |
|
ollama
ollama implements an API client for the Ollama provider.
|
ollama implements an API client for the Ollama provider. |
|
openai
openai implements an API client for OpenAI, and for other providers with an OpenAI-compatible API, such as vLLM, llama.cpp and LM Studio.
|
openai implements an API client for OpenAI, and for other providers with an OpenAI-compatible API, such as vLLM, llama.cpp and LM Studio. |
|
schema
Package schema has the messages which providers reply with, which implement llm.Message, so providers share them
|
Package schema has the messages which providers reply with, which implement llm.Message, so providers share them |
|
Package registry has the providers of models, by names which the registry gives them, and finds the models across them
|
Package registry has the providers of models, by names which the registry gives them, and finds the models across them |
|
cmd
Package cmd has the registry's commands and flags
|
Package cmd has the registry's commands and flags |
|
httpclient
Package httpclient is a client of the registry's HTTP API
|
Package httpclient is a client of the registry's HTTP API |
|
httphandler
Package httphandler has the registry's HTTP API
|
Package httphandler has the registry's HTTP API |
|
schema
Package schema has the requests and responses of the registry's API
|
Package schema has the requests and responses of the registry's API |
|
test
Package test has a registry and a HTTP server of its API, for tests
|
Package test has a registry and a HTTP server of its API, for tests |
|
Package subtitle writes the segments of a transcript as subtitles, in SRT or WebVTT format, whose cues are the segments, in turn, until one is spoken by another speaker, or after a silence, or would make the cue too long, or have too much text, to read
|
Package subtitle writes the segments of a transcript as subtitles, in SRT or WebVTT format, whose cues are the segments, in turn, until one is spoken by another speaker, or after a silence, or would make the cue too long, or have too much text, to read |
|
homeassistant/httpclient
httpclient implements an API client for the Home Assistant REST API https://developers.home-assistant.io/docs/api/rest/
|
httpclient implements an API client for the Home Assistant REST API https://developers.home-assistant.io/docs/api/rest/ |
|
newsapi/httpclient
httpclient implements an API client for NewsAPI https://newsapi.org/docs
|
httpclient implements an API client for NewsAPI https://newsapi.org/docs |
|
ollama/httpclient
httpclient implements an API client for Ollama's web search and web fetch https://docs.ollama.com/capabilities/web-search
|
httpclient implements an API client for Ollama's web search and web fetch https://docs.ollama.com/capabilities/web-search |
|
weatherapi/httpclient
httpclient implements an API client for WeatherAPI https://www.weatherapi.com/docs/
|
httpclient implements an API client for WeatherAPI https://www.weatherapi.com/docs/ |