llm

package module
v1.6.2 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 18 Imported by: 2 modules, 2 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.

README

go-llm

Go Reference License

go-llm is an application that puts language and speech models from many providers behind one interface, with a web UI, a command-line tool and a Go SDK. Add providers such as Ollama, OpenAI, Anthropic, Google Gemini, Mistral, go-whisper and ElevenLabs. Then ask any of their models to reply, call tools, run agents, embed, read documents, speak, and transcribe or translate speech. Connect remote MCP servers, such as GitHub, Linear or Notion, so your assistant can use their tools too. You can do all of this through the REST API, the web UI, the llm command (which includes a terminal chat), or from Go.

Quick Start

1. Run go-llm, with Docker

The image has the application and its web UI, and keeps its data in the /data volume.

[!WARNING] Don't run go-llm on the internet. It has no authentication yet, so anyone who can reach it can use your API keys, read your chats, memory and files, and run its tools. Publish its port on localhost only, as below, or put it behind a proxy that signs people in, or a VPN.

# A volume for go-llm's data, which is kept when the container is replaced
docker volume create llm

docker run -d --name llm -p 127.0.0.1:8084:8084 -v llm:/data \
  -e OLLAMA_ADDR=http://host.docker.internal:11434 \
  -e OPENAI_API_KEY \
  ghcr.io/mutablelogic/llm

Then open http://localhost:8084/:

  • host.docker.internal is the machine Docker runs on, such as for a local Ollama. Docker Desktop has it; on Linux add --add-host=host.docker.internal:host-gateway.

  • On first start, go-llm adds the Eliza provider (unless NO_ELIZA is set), and a provider for each of these that's set:

    • OLLAMA_ADDR and GOWHISPER_ADDR, as URLs;
    • OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, DEEPSEEK_API_KEY, MISTRAL_API_KEY and ELEVENLABS_API_KEY.

    Keys are read from the environment when they're used, never stored.

  • Connectors: GitHub, Asana, Harvey, HubSpot, PagerDuty and Zoom are offered under Add connector when go-llm starts with your OAuth app's credentials for them, such as GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET. The other well-known connectors need none. See Connectors.

  • UID and GID set the user it runs as, such as the owner of a mounted /data directory.

Or use Docker Compose. The compose file lists every variable the server reads, and its ollama profile adds an Ollama server. Set OLLAMA_ADDR too, so go-llm adds that server as a provider. The port is published on localhost only, unless LLM_BIND says otherwise:

OLLAMA_ADDR=http://ollama:11434 docker compose -f docker/compose.yaml --profile ollama up -d
2. Install the command-line tool

The web UI is all you need to chat. The llm command is for working from the terminal, and for automation:

  • Scripts, cron jobs and CI: ask a model, transcribe a recording, or read a document, then use the output in a pipeline.
  • Files from the shell: attach them with --attach, or pipe text into commands such as llm speak.
  • Setup: add providers, connectors and agents from a script, so an installation can be set up again.
  • Chat in the terminal, which follows other clients of the same conversation.
go install -tags client github.com/mutablelogic/go-llm/cmd/llm@latest

Or run make client in a clone, which builds build/llm. The tool connects to localhost:8084, or the server at --http.addr or LLM_ADDR, such as LLM_ADDR=nas.local:8084.

3. Add providers

Add more providers in the web UI, with Add provider on the Models page, or with the CLI. An API key is given by the name of the server's environment variable, so the key itself is never stored or sent:

llm provider-create-ollama http://host.docker.internal:11434
llm provider-create-openai --api-key-credential OPENAI_API_KEY
llm provider-create-anthropic --api-key-credential ANTHROPIC_API_KEY
llm provider-create-gemini --api-key-credential GEMINI_API_KEY
llm provider-create-mistral --api-key-credential MISTRAL_API_KEY
llm provider-create-gowhisper http://host.docker.internal:8081
llm provider-create-elevenlabs --api-key-credential ELEVENLABS_API_KEY

llm providers
llm models
llm models --capability image_input,tools   # models that see images and call tools
llm models --capability speech_output       # models that speak
4. Ask, and chat

Chat in the web UI, with New chat, or with the CLI. With the CLI, a command's model is remembered until you give another:

llm ask --model gpt-4o-mini "Explain a KV cache in two sentences"

# Files: text is sent as text, images and PDFs as attachments
llm ask --attach main.go "What does this do?"
llm ask --model gpt-4o -a chart.png -a notes.md "Do these agree?"

# Upload a file once, and refer to it by its URI
llm resource-create report.pdf
llm chat -a resource:///<hash> "What does this say?"

llm embed --model mistral-embed "A cat asleep in the sun"
llm ocr --model mistral-ocr-latest report.pdf
llm speak --model ollama:phonon:latest --voice Freya -o hello.wav "Hello, world"
llm transcribe --model voxtral-mini-latest --opt speakers=true --format srt talk.m4a
llm translate --model whisper-1 interview.wav
llm model-load ollama:llama3.2

Or chat in a session, which go-llm keeps, and which the web UI shows too:

llm session-create --model ollama:llama3.2 --system "Be brief" --tools "weatherapi:*"
llm chat                                        # in the terminal
llm chat "Will it rain in Berlin tomorrow?"     # once
llm session-messages
llm sessions
Without Docker
go install github.com/mutablelogic/go-llm/cmd/llm@latest
llm run

The server listens on localhost:8084 and keeps its data in your cache directory. Installed this way it serves the API without the web UI; make in a clone builds both, with npm, into build/llm.

Architecture

flowchart LR
    subgraph Clients
        direction TB
        CLI["`**llm** command
        and interactive chat`"]
        Client["`**registry/httpclient**
        Go client`"]
        UI["`**frontend**
        web UI`"]
    end

    subgraph Server["Server, or your own Go program"]
        direction TB
        API["`**httphandler**
        REST API and events`"]
        Registry["`**registry**
        providers, models, sessions`"]
        Toolkit["`**toolkit**
        tools, in namespaces`"]
        Agents["`**agents**
        prompts which models call as tools`"]
        Memory["`**memory**
        what every session knows`"]
        Heartbeat["`**heartbeat**
        prompts which fire on a schedule`"]
        Events["`**events**
        heartbeats and triggers, with their outcomes`"]
        Resource["`**resource**
        uploaded content, by its hash`"]
        MCP["`**mcp**
        connectors to remote MCP servers`"]
        Stores[("`**stores**
        providers, sessions, agents, memory, heartbeats, events, resources, connectors`")]
    end

    subgraph Providers
        direction TB
        Ollama["`**ollama**`"]
        OpenAI["`**openai**
        OpenAI, Mistral, DeepSeek`"]
        Anthropic["`**anthropic**`"]
        Gemini["`**gemini**`"]
        Whisper["`**gowhisper**`"]
        ElevenLabs["`**elevenlabs**`"]
        Eliza["`**eliza**
        for testing`"]
    end

    subgraph Tools
        direction TB
        HA["Home Assistant"]
        News["NewsAPI"]
        Weather["WeatherAPI"]
        Search["Ollama web search"]
        Remote["Remote MCP servers"]
    end

    CLI --> Client
    Client --> API
    UI --> API
    API --> Registry
    Registry --> Stores
    Registry --> Toolkit
    Toolkit --> Agents
    Toolkit --> Memory
    Agents --> Registry
    API --> Memory
    Memory --> Stores
    Toolkit --> Heartbeat
    API --> Heartbeat
    Heartbeat --> Stores
    Heartbeat --> Events
    API --> Events
    Events --> Agents
    Events --> Stores
    API --> Resource
    Resource --> Stores
    API --> MCP
    MCP --> Toolkit
    MCP --> Stores
    MCP --> Remote
    Toolkit --> HA & News & Weather & Search
    Registry --> Ollama & OpenAI & Anthropic & Gemini & Whisper & ElevenLabs & Eliza

    classDef highlight fill:#e8f0fe,stroke:#1a73e8,stroke-width:2px,color:#111
    class CLI,Client,UI,Registry,Toolkit,Agents,Memory,Heartbeat,Events,Resource,MCP highlight
    class Ollama,OpenAI,Anthropic,Gemini,Whisper,ElevenLabs,Eliza highlight
  • CLI (cmd/llm): runs the application, and is its client, with a command for each operation and a terminal chat that follows other clients of the same session. It uses the Go client in registry/httpclient.
  • Web UI (frontend): chat, browse models and tools, and manage providers, connectors and agents. Built in with make.
  • Registry (registry): finds a model by name, checks what it can do, and asks its provider. It keeps providers, sessions and agents, runs the agent loop, and publishes events. Sessions unchanged for 14 days (--session.retention) are deleted, unless a heartbeat keeps them.
  • Toolkit (toolkit): the tools models can call, in namespaces such as weatherapi, with their logs and progress streamed.
  • Memory (memory): what every session knows about the person and the assistant, such as names, location and time zone, plus memories kept under keys. Each message is sent to the model with its time, in the person's time zone, rather than putting the time in the system prompt, so prompts can be cached.
  • Heartbeats (heartbeat): prompts that fire once or on a schedule, such as reminders or a morning briefing, in the person's time zone.
  • Compaction (registry): keeps a long conversation within its model's context. Earlier messages are summarized by the built-in compact agent, which also updates memories and the title. It happens on request, or automatically above 80% of the context.
  • Events (registry): what happens when a heartbeat fires, or a trigger arrives at POST /llm/event. The event agent decides whether to alert, notify or ignore. Worth-telling outcomes are delivered into the conversation once it's idle, and to its channels.
  • Resources (resource): uploaded content, such as images, documents and audio, kept once by SHA-256 and referred to as resource:///<hash>.
  • Agents: named prompts with a model, tools and input and reply schemas, which models call as tools in the agent namespace. The agents folder has the built-in ones.
  • Connectors (mcp): remote MCP servers whose tools become a namespace of the toolkit. See Connectors.
  • Providers (provider): each wraps a provider's API.

The registry also works on its own, from your own Go program; see examples.

Features

  • Web-based application: chat, with replies streamed and files attached; browse models and tools; and add providers, connectors and agents, all in the browser. Every page follows changes as they happen.
  • Providers: add, change and remove them while go-llm runs. Refer to a model by name, or by provider and name, such as ollama:llama3.2:latest.
  • Ask: a reply to messages, with a system prompt, options, tools, and structured output, optionally streamed.
  • Chat: conversations go-llm keeps, with their model, system prompt, tools and options.
    • The model calls tools until it replies, and long chats are trimmed or compacted to fit.
    • Every client of a session sees new messages, and who's typing.
    • A chat can switch models, such as from Claude to Gemini and back.
    • Attachments a model can't take become notes it can pass to a tool, such as llm:transcribe.
  • Agents: prompts with their own model, tools and schemas, kept as YAML or JSON, that models call as tools, nested as deep as needed.
  • Embed, OCR, speak, illustrate, transcribe and translate: vectors; document text as Markdown; speech in a chosen voice; images from Gemini's Nano Banana models; and transcripts with speakers, or as subtitles.
  • Models: download, delete and unload them where the provider stores them, such as Ollama and go-whisper, and list them by capability.
  • Tools: Home Assistant, NewsAPI, WeatherAPI, Ollama's web search, and any remote MCP server through connectors.
  • Memory: facts about the person and the assistant, and memories with versions, kept as files you can edit.
  • Resources: uploaded or generated files, streamed to and from the store, kept once, and downloadable in ranges.
  • Heartbeats: scheduled prompts with cron expressions, which follow the person's time zone and survive restarts.
  • Messaging: talk to your assistant on Telegram. See Messaging.
  • Events: a stream of changes to providers, models, sessions, memory, heartbeats and connectors.
  • OpenAPI and OpenTelemetry: a described REST API (llm openapi), and traces through the registry, providers and tools.

Providers

Type Provider Generate Embed OCR Transcribe Translate Speak Images Models
ollama Ollama ✅ ✅ ✅ (images) ✅ (phonon) Download, delete, unload
openai OpenAI ✅ ✅ ✅ ✅ (whisper) ✅ (tts)
anthropic Anthropic, with exact token counts ✅
gemini Google Gemini, with exact token counts ✅ ✅ (text, images, audio, PDFs) ✅ ✅ (tts) ✅ (Nano Banana)
openai Mistral, at https://api.mistral.ai/v1 ✅ ✅ ✅ ✅
openai DeepSeek, and other OpenAI-compatible servers ✅
gowhisper go-whisper ✅ ✅ Download, delete
elevenlabs ElevenLabs ✅
eliza A mock of Weizenbaum's 1966 chatbot, for testing ✅

What a model can do depends on the model, as its provider reports it. Requests for something a model is known not to do are rejected before they're sent.

Capabilities

The web UI's Models page shows each model's capabilities as tags, and a model's panel says Yes, No or Unknown for each one. llm models --capability, GET /llm/model?capability= and the llm:models tool list models by capability. A capability the provider doesn't report isn't assumed.

Capability Meaning
chat Replies to messages
tools Calls tools
thinking Reasons before replying
image_input, audio_input, video_input, document_input Takes images, audio, video or documents in a conversation
image_output Makes images
speech_output Speaks text
embedding Embeds text and media
ocr Reads the text in images and documents
transcription, translation Transcribes speech, or translates it into English

CLI Commands

Group Commands
Server run, openapi
Providers providers, provider, provider-create-ollama, provider-create-openai, provider-create-anthropic, provider-create-gemini, provider-create-mistral, provider-create-deepseek, provider-create-gowhisper, provider-create-elevenlabs, provider-create-eliza, provider-update, provider-delete
Models models, model, model-load, model-delete, model-unload
Sessions sessions, session, session-messages, session-create, session-update, session-forget, session-compact, session-delete
Inference ask, chat, embed, ocr, transcribe, translate, speak, illustrate
Tools and agents namespaces, tools, tool, call, agents, agent, agent-create, agent-update, agent-delete
Connectors connectors, connector, connector-create, connector-update, connector-delete
Memory details, detail-set, detail-forget, memories, memory, memory-remember, memory-forget
Heartbeats heartbeats, heartbeat, heartbeat-create, heartbeat-update, heartbeat-delete
Resources resources, resource, resource-create, resource-get, resource-delete
Events events

Run llm <command> --help for its flags. Model options are given with --opt, such as --opt temperature=0.2. These options control the agent loop rather than the model:

Option Default Meaning
max_iterations 10, or 3 for ask How many times the model is asked before it must reply
max_depth 3 How deeply agents can call agents
tool_timeout 30s How long a tool has to return

Connectors

Connectors are remote MCP servers whose tools your assistant can call. Each connector's tools are a namespace of their own, such as linear:list_issues.

  • Adding one: in the web UI, use Add connector on the Tools page. It lists well-known servers such as GitHub, Linear, Notion and Stripe, plus Custom connector for any URL. From the CLI, run llm connector-create <url>.
  • Signing in: if the server needs sign-in, you'll get a Sign in button, or the CLI opens your browser. The server keeps the token and refreshes it.
  • Your own client: some servers, such as GitHub's, don't register clients themselves. For those, set your OAuth app's ID and secret in the server's environment, such as GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET, and register the redirect URL that the connector panel's Advanced section shows with your app.
    • A well-known server's connector, from Add connector, already has the names of those credentials.
    • A custom connector needs them: in the panel's Advanced section, or with llm connector-create --client-id-credential GITHUB_CLIENT_ID --client-secret-credential GITHUB_CLIENT_SECRET <url>.
  • Behind a reverse proxy: run the server with --tls.name=<public host>, so sign-in sends browsers back to the public address.
  • Storage: connectors and their tokens are kept in connectors.json. Only remote servers, over streamable HTTP or SSE, are supported.

The API is documented in mcp/registry/httphandler/README.md.

Tools

Tools are added when their credentials or settings are present:

Namespace Tools Needs
memory Remember details about the person and the assistant; search, keep and forget memories Always added
heartbeat Schedule, list, update and cancel heartbeats Always added
llm models, speak, illustrate, ocr, transcribe and resource: list models by capability, speak, make images, read documents, transcribe, and list or read the chat's files as Markdown Always added
weatherapi Current weather, forecasts and alerts WEATHERAPI_API_KEY, from weatherapi.com
newsapi News articles, headlines and sources NEWSAPI_API_KEY, from newsapi.org
homeassistant Query, search and control smart home devices HOMEASSISTANT_URL, HOMEASSISTANT_API_KEY
ollama Web search and fetch, with Ollama's cloud OLLAMA_API_KEY, from ollama.com
messaging connect, list, send and disconnect chats, such as on Telegram. See Messaging TELEGRAM_BOT_TOKEN, from BotFather
a connector's The tools of a remote MCP server. See Connectors A connector

Give a model tools by name (weatherapi:current), by namespace (weatherapi:*), or all of them (*).

Notes on the llm tools:

  • Preferred models: each tool uses the model the person chose for that capability, which it remembers in the memory as preferred_models, or asks them to choose.
  • Voice notes: speak with format: voice-note makes Ogg Opus voice notes, for Telegram. Models that can't make them need opusenc, from opus-tools, which the Docker image includes.
  • Files they make: speech and images are kept as the chat's files. OCR text is only kept when a name or title is given. A transcript is only kept when a format, name or title is given, or it's longer than 8 KB, when only its start is returned and the rest is read with resource.
  • Reading files: resource reads text, HTML, CSV, PDFs, Word, OpenDocument, EPUB, spreadsheets, emails, calendars, subtitles and more, with go-metadata. It reads a part at a time, carrying on where the last part ended.

Messaging

Connect chats on messaging services to a conversation, so you can talk to your assistant from your phone. Telegram is the first:

  1. Make a bot with BotFather, and set its token as TELEGRAM_BOT_TOKEN.
  2. In a chat whose model has the messaging tools, ask to talk on Telegram. You get a link, valid once for 15 minutes, which the web UI also shows as a QR code.
  3. Open the link, or scan the code, and press Start.
Channels
  • Both ways: what you say on Telegram goes to the conversation. Every reply, and every heartbeat outcome worth telling you, goes to all its channels.
  • More than one: a conversation can have several chats, such as yours and a group's. A chat belongs to one conversation, so connecting it again moves it.
  • Groups: everyone in a connected group can talk to the assistant and see what it remembers about you. Only connect groups whose people you'd tell.
  • Who said it: each message says where it came from and who sent it, so the assistant can tell people apart.
  • Ignored: messages from chats that aren't connected are ignored.
Running the bot
  • No public address needed: the server reads the bot's messages by long polling.
  • One server per bot: don't share a bot's token between servers.
  • Progress: while a reply takes a while, the chat shows what's happening in one message, which is deleted when the reply arrives.
Replies
  • Formatting: Markdown is converted to Telegram's: headings become bold, lists get bullets, and tables are monospaced. Long replies are split between paragraphs.
  • Files: pictures and speech a reply makes are sent with it, with the reply as the caption. Images go as photos, Ogg audio as voice messages, MP3 and M4A as tracks, and anything else as documents, up to 50 MB. Other files, such as transcripts, are only sent with messaging:send.
  • Voice: in a conversation with channels, the assistant is told to speak in voice-note format and to transcribe voice messages it can't hear.
Files you send
  • Kept with the conversation: photos, documents, voice messages, audio and video become the conversation's files, as if dropped into the web UI. A caption becomes the message's text and the files' description.
  • Albums arrive as one message.
  • Compressed photos say so, so the assistant can ask for the original.
  • Over 20 MB: bots can't download files this large, so the assistant is told it didn't get them.
  • Names: files without a name are named by kind and time, such as voice-note-2026-11-08-1035.ogg, and audio and video descriptions include their length.

API

The REST API is under /api, and llm openapi shows it as OpenAPI. Streaming operations, such as ask and transcribe, send server-sent events when text/event-stream is accepted. Each part is documented beside its handlers:

Go

The packages work on their own, without the application:

  • llm: the interfaces of providers and models (Generator, Embedder, Measurer, Recognizer, Transcriber, Speaker, Illustrator, Downloader) and their options.
  • provider/...: a client for each provider.
  • registry: finds models, asks them, and keeps providers, sessions and agents, with HTTP handlers and a client.
  • toolkit: the tools models call.
  • memory, heartbeat, messaging: namespaces of the toolkit, with stores, and HTTP handlers or runners.
  • mcp/...: remote MCP clients, the connector registry, and connectors' tools as namespaces. auth/httpclient discovers how a resource is signed in to.
  • broadcaster: publishes events, and streams them as server-sent events.

The registry is meant to be composed into a larger system. Its options plug in what that system has:

  • WithProviderStore, WithSessionStore, WithAgentStore: keep providers, sessions and agents in a store, such as a database. Each item has a serial, so a stale change is a conflict, and stores can watch for other servers' changes.
  • WithCredentialsProvider: expands an API key's placeholder, such as ${OPENAI_KEY}, from the environment by default, or from a secrets manager.
  • WithToolkit: the tools models can call.
  • WithBroadcaster: shares an event stream with other modules.
  • WithTracer, WithClientOpts: trace and configure requests to providers.

The llm command, in cmd/llm, is one such system. The examples use the packages directly, with Ollama (OLLAMA_ADDR), OpenAI (OPENAI_API_KEY), or Eliza:

Example What it does
ask Ask a question, and stream the reply
tools Your own tool, which the model calls
chat Chat in the terminal
agent Run an agent that replies with JSON
ocr Read an image or PDF as Markdown
transcribe Transcribe or translate speech
go run ./examples/ask "Explain a KV cache in two sentences"

Development

make vet race-test TEST_FLAGS=-short   # as CI runs the tests
make test                              # all tests, with coverage

Tests that call a provider are skipped with -short, or when its key or address isn't set.

Tests with live models

Live tests check that a provider's API accepts what go-llm sends. They're mostly Test_Live… tests in each provider's package, and run when their variable is set and -short isn't:

Variable Package What's tested Billed
OPENAI_API_KEY provider/openai Replies with tools, embeddings, transcription, translation and speakers Yes
MISTRAL_API_KEY provider/openai Replies, embeddings, OCR and transcription Yes
ANTHROPIC_API_KEY provider/anthropic Replies with tools, thinking and structured output, and token counts Yes
GEMINI_API_KEY provider/gemini Model listing and token counts (free), embeddings, and a tool call Yes, apart from listing and counting
ANTHROPIC_API_KEY and GEMINI_API_KEY provider/gemini Test_LiveSwitch: a chat that switches between Claude and Gemini Yes
ELEVENLABS_API_KEY provider/elevenlabs Transcription with speakers Yes
OLLAMA_ADDR provider/ollama Models, embeddings and OCR, with embeddinggemma-2 and deepseek-ocr pulled No
GOWHISPER_ADDR provider/gowhisper Models and transcription, with ggml-medium-q5_0 No

Model names can be changed with variables such as OPENAI_MODEL and OLLAMA_OCR_MODEL. Run one provider's live tests with -count=1 -v:

GEMINI_API_KEY=... go test -count=1 -v -run Live ./provider/gemini/

The billed tests use the cheapest models and cost a fraction of a cent, but make test runs them whenever your shell has the keys. Keep them out with -short, or unset the keys:

make test TEST_FLAGS=-short
env -u OPENAI_API_KEY -u MISTRAL_API_KEY -u ANTHROPIC_API_KEY -u GEMINI_API_KEY -u ELEVENLABS_API_KEY go test ./...

Roadmap

Sessions
  • A model for summaries: a cheaper model writes compaction summaries, rather than the session's own.
Agents and tools
  • Connectors: MCP prompts and resources, as well as tools.
  • Channels, beyond what Telegram does now:
    • locations: shared places told to the model, setting the person's location and time zone, and sending places as map pins;
    • replies: what a message replies to, so "this one" means something;
    • groups: replying only when the assistant is mentioned or replied to;
    • commands: /new, /stop, /forget and /status in Telegram's menu;
    • more of Telegram: recording indicators, editing and deleting the assistant's messages, reactions, and buttons;
    • voice messages transcribed as they arrive, with the chat's default model;
    • channels in the web UI, and Slack.
  • What each model takes, in llm:models: voices, formats, what OCR reads, and image aspect ratios, with errors that say what's accepted.
  • Default models for each chat: a model per capability, set once in a chat, rather than kept in memory.
  • Scheduled runs in the chat: a heartbeat's prompt goes to the chat's own model, with recent runs, rather than only to the event agent.
  • Scheduled agents: agents that run on a schedule.
  • Running Python (experimental): a sandboxed WebAssembly tool that reads and writes the session's files.
Server
  • Authentication and authorization across the API, web UI, CLI, connectors and channels: sign-in with OIDC or API tokens, and roles or scopes for what each person or client can do.
  • A database, and more than one server: shared providers, sessions, agents, memory, heartbeats and resources.
  • External volumes for resources: mount folders, such as from your own filesystem, so their files are resources the assistant can read.
  • Usage: account for each session's use, in tokens, time or cost.
Providers
  • LM Studio, with its own model management API.
  • ElevenLabs' voices for text to speech.
  • OpenAI's images with gpt-image.
  • OpenAI's Responses API, so the newest models can think while calling tools.
  • OpenAI's token limits, which need checking.
Improvements
  • OCR: glm-ocr with Ollama; PDFs with Ollama's image models, page by page; and images inside documents.
  • Speech: speakers with go-whisper's diarizing model; live transcription over a WebSocket; translation with models that hear audio, such as Voxtral Small; and subtitle lengths.
  • Files: UTF-16 text (#192); audio and video metadata; and Markdown parts that end at a heading or paragraph (go-metadata#20).

License

go-llm is licensed under the Apache License, Version 2.0.

Documentation

Index

Constants

View Source
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", "high", "xhigh" or "max"

	// 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"

	// Agents
	MaxIterationsKey = "max_iterations" // uint, most times an agent loop asks the model for its reply
	MaxDepthKey      = "max_depth"      // uint, most agents which run in one another, as an agent calls an agent, as a tool
	ToolTimeoutKey   = "tool_timeout"   // time.Duration, or a string such as "30s", most time a tool an agent loop runs has to return

	// 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

	// Images
	AspectRatioKey = "aspect_ratio" // string, aspect ratio of the images made, such as "16:9"
	ImageSizeKey   = "image_size"   // string, size of the images made, such as "1K", "2K" or "4K"

	// Speech
	VoiceKey        = "voice"        // string, voice the text is spoken in, by its name
	AudioFormatKey  = "audio_format" // string, format of the speech, such as "wav", "mp3" or "pcm"
	SpeedKey        = "speed"        // float64, how fast the text is spoken, where 1 is normal
	InstructionsKey = "instructions" // string, how the text is spoken, such as "calmly
)

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.

View Source
const (
	Ollama     = "ollama"
	Eliza      = "eliza"
	OpenAI     = "openai"
	GoWhisper  = "gowhisper"
	ElevenLabs = "elevenlabs"
	Anthropic  = "anthropic"
	Gemini     = "gemini"
)

Variables

View Source
var Capabilities = []string{"chat", "tools", "thinking", "image_input", "audio_input", "video_input", "document_input", "image_output", "speech_output", "embedding", "ocr", "transcription", "translation"}

Capabilities are the names of what a model can do, in order, which a list of models is filtered by. Temperature is a setting, rather than what a model does, so isn't one.

View Source
var Efforts = []string{"low", "medium", "high", "xhigh", "max"}

Efforts are the reasoning efforts which can be asked of a model, from the least to the most. A model which hasn't the effort makes the nearest it has.

Functions

func ContentLength added in v1.4.2

func ContentLength(r Resource) (int64, bool)

ContentLength returns the length of the resource's content, in bytes, and true, when it's known without reading it, or false

func GetOpt added in v0.5.0

func GetOpt[T any](o *Opts, key string) (T, error)

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

func GetPages(o *Opts) ([]uint, error)

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

func HTTPErr(err error) error

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

func HTTPStatus(err error) (int, bool)

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

func IsToolName(name string) bool

IsToolName returns true if the name is a valid tool name, which is 1 to 64 letters, digits, underscores or hyphens

func MostEffort added in v1.6.0

func MostEffort(effort, most string) string

MostEffort returns the reasoning effort, or the most, when it's more, such as "high" for "max", of a provider whose models have no more than the most, as far as it's known

func NearestEffort added in v1.6.0

func NearestEffort(effort string, levels ...string) string

NearestEffort returns the reasoning effort, when it's one of the levels, or otherwise the level which is nearest it, and the greater, when two are as near, such as "high" for "medium", of "low" and "high". The known efforts are those of Efforts, and "none" and "minimal", which are less than "low", so "none" is "low", of "low" and "high". It's the effort when there are no levels, or it isn't a known effort, such as "huge".

func ReadAll added in v0.5.0

func ReadAll(ctx context.Context, r Resource) ([]byte, error)

ReadAll reads all of a resource's content, for providers which send it whole, such as encoded in a request

func ValidCapabilities added in v1.3.0

func ValidCapabilities(capabilities ...string) error

ValidCapabilities returns ErrBadParameter when any of the names isn't one of Capabilities, so a request for them is refused before models are listed

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

type DownloadProgressFn func(status string, percent float64)

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
	ErrServiceUnavailable
	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) Error

func (e Err) Error() string

func (Err) HTTP added in v0.5.0

func (e Err) HTTP() httpresponse.Err

func (Err) With

func (e Err) With(args ...any) error

func (Err) Withf

func (e Err) Withf(format string, args ...any) error

Withf returns an error wrapping the error code, with a formatted message. As with fmt.Errorf, the format may use %w to wrap errors, so that they can still be matched with errors.Is and errors.As.

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 Illustrator added in v1.4.0

type Illustrator interface {
	// Illustrate returns the images the model makes from the prompt, or,
	// with images, the images it makes by changing, or combining, them, as
	// the prompt says, with their types, such as image/png, and the tokens
	// used. The options can set the aspect ratio of the images
	// (AspectRatioKey), and their size (ImageSizeKey), for a model which
	// takes them. Options which the provider doesn't support are rejected.
	// Returns an error when the model made no image, such as when it
	// refused, with what it said.
	Illustrate(context.Context, Model, string, []Resource, ...Opt) ([]Resource, Usage, error)
}

Illustrator is an interface for providers whose models make images

type Measurer added in v0.6.0

type Measurer interface {
	// Measure returns how many tokens the text is, for the model
	Measure(context.Context, Model, string) (uint, error)
}

Measurer is an interface for providers which count the tokens of text, as a model would, such as to fit what's sent to it into its context

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

func WithCapabilities added in v1.3.0

func WithCapabilities(models []Model, capabilities ...string) ([]Model, error)

WithCapabilities returns the models which are known to have every one of the capabilities, by their names, in their order, or all of them, when there are none. Returns ErrBadParameter when a name isn't one of Capabilities.

type ModelCap added in v0.5.0

type ModelCap struct {
	// Chat, and its features
	Chat     *bool `json:"chat,omitempty" help:"Replies to messages, in a conversation"`
	Tools    *bool `json:"tools,omitempty" help:"Calls tools, as it replies"`
	Thinking *bool `json:"thinking,omitempty" help:"Thinks, or reasons, before it replies"`

	// What a model takes, in a conversation
	ImageInput    *bool `json:"image_input,omitempty" help:"Understands images, in a conversation"`
	AudioInput    *bool `json:"audio_input,omitempty" help:"Hears audio, in a conversation"`
	VideoInput    *bool `json:"video_input,omitempty" help:"Watches video, in a conversation"`
	DocumentInput *bool `` /* 129-byte string literal not displayed */

	// What a model makes, other than text
	ImageOutput  *bool `json:"image_output,omitempty" help:"Makes images"`
	SpeechOutput *bool `json:"speech_output,omitempty" help:"Speaks text, as audio"`

	// What a model converts, with its own operation
	Embedding     *bool `json:"embedding,omitempty" help:"Embeds text, and media, as vectors"`
	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"`

	// Temperature is whether the model takes the sampling options, which are
	// the temperature, top_p and top_k, which the registry leaves out, for a
	// model which doesn't, rather than fail, as a session keeps its options
	// as its model changes. It's a setting, rather than what the model does,
	// so it isn't in String.
	Temperature *bool `json:"temperature,omitempty" help:"Takes a sampling temperature, and the other sampling options"`
}

ModelCap is what a model can do, of what its provider knows. A capability which isn't known is nil.

func (ModelCap) Has added in v1.3.0

func (c ModelCap) Has(name string) (bool, error)

Has returns whether the model is known to have the capability, by its name, such as vision, which isn't so when it isn't known. Returns ErrBadParameter when the name isn't one of Capabilities.

func (ModelCap) Names added in v1.3.0

func (c ModelCap) Names() []string

Names returns the names of the capabilities which the model is known to have, in the order of Capabilities

func (ModelCap) String added in v0.5.0

func (c ModelCap) String() string

String returns the names of the capabilities which the model is known to have, such as "completion, tools, thinking"

type Opt

type Opt func(*Opts) error

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

func WithContextWindow(value uint) Opt

WithContextWindow sets the context window size in tokens, which is one or more

func WithDimensions added in v0.5.0

func WithDimensions(value uint) Opt

WithDimensions sets the number of dimensions of the embedding, which is one or more

func WithFrequencyPenalty added in v0.0.3

func WithFrequencyPenalty(value float64) Opt

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

func WithKeepAlive(value time.Duration) Opt

WithKeepAlive sets how long a model stays loaded after the request, or negative to stay loaded

func WithLanguage added in v0.5.0

func WithLanguage(value string) Opt

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 WithMaxDepth added in v0.6.0

func WithMaxDepth(value uint) Opt

WithMaxDepth sets the most agents which run in one another, as an agent calls an agent, or itself, as a tool, which is one or more

func WithMaxIterations added in v0.6.0

func WithMaxIterations(value uint) Opt

WithMaxIterations sets the most times an agent loop asks the model for its reply, which is one or more

func WithMaxTokens added in v0.0.3

func WithMaxTokens(value uint) Opt

WithMaxTokens sets the maximum tokens to generate, which is one or more

func WithOpt added in v0.5.0

func WithOpt(key string, value any) Opt

WithOpt sets the option with the key to the value, replacing any value already set

func WithPages added in v0.5.0

func WithPages(values ...uint) Opt

WithPages sets the pages of a document to recognize, numbered from zero

func WithPresencePenalty added in v0.0.3

func WithPresencePenalty(value float64) Opt

WithPresencePenalty sets the penalty for tokens already present

func WithRegions added in v0.5.0

func WithRegions(value bool) Opt

WithRegions sets whether the pages of recognized text have their regions, such as paragraphs, titles and tables, with their boxes

func WithSeed added in v0.0.3

func WithSeed(value uint) Opt

WithSeed sets the seed for deterministic generation

func WithSegments added in v0.5.0

func WithSegments(value bool) Opt

WithSegments sets whether a transcript has its segments, with when each was spoken

func WithServiceTier added in v0.5.0

func WithServiceTier(value string) Opt

WithServiceTier sets the provider service tier, for example "auto"

func WithSpeakers added in v0.5.0

func WithSpeakers(value bool) Opt

WithSpeakers sets whether a transcript's segments have who spoke them, which is diarization

func WithStopSequences added in v0.5.0

func WithStopSequences(values ...string) Opt

WithStopSequences sets the sequences which stop generation, replacing any already set

func WithSystemPrompt

func WithSystemPrompt(value string) Opt

WithSystemPrompt sets the system prompt for the model

func WithTableFormat added in v0.5.0

func WithTableFormat(value string) Opt

WithTableFormat sets the format of the tables in recognized text: "markdown" or "html"

func WithTaskType added in v0.5.0

func WithTaskType(value string) Opt

WithTaskType sets the task the embedding is used for

func WithTemperature

func WithTemperature(value float64) Opt

WithTemperature sets the randomness of sampling, which is zero or more

func WithThinking added in v0.5.0

func WithThinking(value bool) Opt

WithThinking enables or disables thinking

func WithThinkingEffort added in v0.5.0

func WithThinkingEffort(value string) Opt

WithThinkingEffort sets the reasoning effort, which is one of Efforts: "low", "medium", "high", "xhigh" or "max". A model which hasn't the effort makes the nearest it has.

func WithTitle added in v0.5.0

func WithTitle(value string) Opt

WithTitle sets the title of the document being embedded

func WithToolChoice added in v0.0.3

func WithToolChoice(value string) Opt

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".

func WithToolTimeout added in v0.6.0

func WithToolTimeout(value time.Duration) Opt

WithToolTimeout sets the most time a tool an agent loop runs has to return, which is more than zero

func WithTopK

func WithTopK(value uint) Opt

WithTopK sets sampling from the K most likely tokens, which is one or more

func WithTopP

func WithTopP(value float64) Opt

WithTopP sets the probability mass for nucleus sampling, between zero and one

func WithUser added in v0.0.6

func WithUser(value string) Opt

WithUser sets the identifier of the end user, for abuse monitoring

type Opts

type Opts struct {
	// contains filtered or unexported fields
}

Opts are the options for an operation, by key

func ApplyOpts

func ApplyOpts(opts ...Opt) (*Opts, error)

ApplyOpts returns the options set by each option in turn, or the first error. Nil options are skipped.

func (*Opts) Delete added in v0.5.0

func (o *Opts) Delete(key string)

Delete removes the option with the key, if it's set

func (*Opts) Get

func (o *Opts) Get(key string) any

Get returns the value of the option with the key, or nil if it isn't set

func (*Opts) Has

func (o *Opts) Has(key string) bool

Has returns true if the option with the key is set

func (*Opts) Keys added in v0.5.0

func (o *Opts) Keys() []string

Keys returns the keys of the options which are set, in sorted order

func (*Opts) Opt added in v0.5.0

func (o *Opts) Opt() Opt

Opt returns an option which sets the values of these options, so options can be applied once, and then passed on without being applied again

type Progress added in v0.6.0

type Progress struct {
	Progress float64 `json:"progress"`
	Total    float64 `json:"total,omitempty"`
	Message  string  `json:"message,omitempty"`
}

Progress is how a tool is getting on, as it runs, as MCP's progress notification is: how far it's got, which increases each time, out of the total, when it's known, or zero, and a message, such as "Agent segment is replying"

func ParseProgress added in v0.6.0

func ParseProgress(text string) Progress

ParseProgress returns the progress which the text of a piece of a stream is, which is a Progress, as JSON, or a message, when it isn't

func (Progress) Percent added in v0.6.0

func (p Progress) Percent() (float64, bool)

Percent returns how far the progress has got, as a percentage, and whether it's known, which it is when there's a total

func (Progress) Text added in v0.6.0

func (p Progress) Text() string

Text returns the progress, as JSON, which is the text of a piece of a stream which is progress

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

type ReadFunc func(context.Context, func(io.Reader) error) error

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.

func ReadBytes added in v0.5.0

func ReadBytes(data []byte) ReadFunc

ReadBytes returns a function which reads the data, for resources whose content is in memory

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 Sized added in v1.4.2

type Sized interface {
	// ContentLength returns the length of the content, in bytes, or -1, when
	// it isn't known
	ContentLength() int64
}

Sized is a resource whose content's length is known, without reading it, such as one which is kept in a store, so a provider can stream it, rather than reading it, to know how large it is

type Speaker added in v1.3.0

type Speaker interface {
	// Speak returns the text, spoken, as audio, whose type is the format it's
	// in, such as audio/wav, and the characters, or tokens, used. The
	// options can set the voice it's spoken in (VoiceKey), the format of the
	// audio (AudioFormatKey), how fast it's spoken (SpeedKey), and how it's
	// spoken (InstructionsKey), for a model which takes them. Options which
	// the provider doesn't support are rejected.
	Speak(context.Context, Model, string, ...Opt) (Resource, Usage, error)
}

Speaker is an interface for providers which speak text, which is text to speech

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"

	// StreamLog is a line logged by a tool as it runs, such as to say what
	// it's doing, which isn't part of the reply
	StreamLog StreamType = "log"

	// StreamProgress is a tool's progress as it runs, such as that an agent
	// it runs is replying, which replaces its progress before, rather than
	// being kept, as a line it logs is, and isn't part of the reply. Its
	// text is a Progress, as JSON, which ParseProgress reads.
	StreamProgress StreamType = "progress"
)

type Tool

type Tool interface {
	// Return the name of the tool
	Name() string

	// Return the title of the tool, for people, such as an agent's, or
	// empty, when it has none, as most tools don't
	Title() 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

	// Return the most time the tool has to return, such as for one which
	// transcribes an hour of audio, or zero for the time a tool has by
	// default, such as the agent loop's tool timeout
	Timeout() time.Duration

	// 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 */

	// Duration is how long it took, which is the time from when it started
	// to when it ended, rather than the sum of what ran at once
	Duration time.Duration `json:"duration,omitempty" help:"How long it took, in nanoseconds" example:"1500000000"`
}

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.

func (Usage) Add added in v0.6.0

func (u Usage) Add(other Usage) Usage

Add returns the tokens, pages, seconds and durations of both usages, as when one follows the other

func (Usage) IsZero added in v0.6.0

func (u Usage) IsZero() bool

IsZero returns true when the usage has no tokens, pages or seconds

type Vector added in v0.5.0

type Vector []float32

Vector is an embedding of a message, whose number of dimensions is the model's, or as set by WithDimensions

Directories

Path Synopsis
Package agents has example agents, as YAML, which the llm server creates when it starts, or which llm agent-create creates, such as:
Package agents has example agents, as YAML, which the llm server creates when it starts, or which llm agent-create creates, such as:
auth
httpclient
Package httpclient is an HTTP client, with go-client, of a resource which may need to be authorized, such as an MCP server's: a request which isn't authorized returns an AuthError, with the server's challenge, and the resource's metadata, and that of its authorization servers, is discovered, which says how a token for it is got.
Package httpclient is an HTTP client, with go-client, of a resource which may need to be authorized, such as an MCP server's: a request which isn't authorized returns an AuthError, with the server's challenge, and the resource's metadata, and that of its authorization servers, is discovered, which says how a token for it is got.
Package broadcaster publishes events, which are changes, such as to a registry's providers, or its sessions, to the channels which watch it, so a server's clients see the changes as they happen
Package broadcaster publishes events, which are changes, such as to a registry's providers, or its sessions, to the channels which watch it, so a server's clients see the changes as they happen
cmd
Package cmd has the broadcaster's commands and flags
Package cmd has the broadcaster's commands and flags
httpclient
Package httpclient is a client of the broadcaster's HTTP API
Package httpclient is a client of the broadcaster's HTTP API
httphandler
Package httphandler has the broadcaster's HTTP API, which streams its events to clients
Package httphandler has the broadcaster's HTTP API, which streams its events to clients
cmd
llm command
examples
agent command
Run an agent, which is the example agent which translates text, with a registry, and a store of agents, without a server:
Run an agent, which is the example agent which translates text, with a registry, and a store of agents, without a server:
ask command
Ask a model a question, and stream its reply, with a registry of providers, without a server:
Ask a model a question, and stream its reply, with a registry of providers, without a server:
chat command
Chat with a model in the terminal, keeping the conversation in memory, without a server, or a store of sessions:
Chat with a model in the terminal, keeping the conversation in memory, without a server, or a store of sessions:
ocr command
Read the text in an image, or a document, such as a PDF, as Markdown, which is optical character recognition (OCR), with a registry of providers, without a server:
Read the text in an image, or a document, such as a PDF, as Markdown, which is optical character recognition (OCR), with a registry of providers, without a server:
tools command
A tool of your own, which a model calls, with a toolkit, and a registry which runs the tools a model calls, until it replies, without a server:
A tool of your own, which a model calls, with a toolkit, and a registry which runs the tools a model calls, until it replies, without a server:
transcribe command
Transcribe the speech in audio, as text, streamed as it's transcribed, or translate it into English, with a registry of providers, without a server:
Transcribe the speech in audio, as text, streamed as it's transcribed, or translate it into English, with a registry of providers, without a server:
frontend
cmd
Package cmd serves the web UI, and its configuration, alongside the API, when the server is built with the "frontend" tag, which embeds the UI, once it's built, with npm, into build/frontend, which make does.
Package cmd serves the web UI, and its configuration, alongside the API, when the server is built with the "frontend" tag, which embeds the UI, once it's built, with npm, into build/frontend, which make does.
Package heartbeat has prompts for sessions, which fire once, at a time, or again and again, on a schedule, such as a briefing every morning, or a reminder.
Package heartbeat has prompts for sessions, which fire once, at a time, or again and again, on a schedule, such as a briefing every morning, or a reminder.
cmd
Package cmd has the heartbeats' commands and flags
Package cmd has the heartbeats' commands and flags
httpclient
Package httpclient is a client of the heartbeats' HTTP API
Package httpclient is a client of the heartbeats' HTTP API
httphandler
Package httphandler has the heartbeats' HTTP API, which lists, creates, gets, changes and deletes them
Package httphandler has the heartbeats' HTTP API, which lists, creates, gets, changes and deletes them
schema
Package schema has the heartbeats' schedules, and what they are: a prompt for a session, at a time, or on a schedule
Package schema has the heartbeats' schedules, and what they are: a prompt for a session, at a time, or on a schedule
internal
deadline
Package deadline has a writer of a stream to a client, such as of server-sent events, which gives each write its own deadline, rather than the server's write timeout, which is for the whole response
Package deadline has a writer of a stream to a client, such as of server-sent events, which gives each write its own deadline, rather than the server's write timeout, which is for the whole response
opusenc
Package opusenc converts audio, such as speech, to voice notes, which are Ogg Opus, with opusenc, of opus-tools, which it runs, such as for the llm tools' voice notes
Package opusenc converts audio, such as speech, to voice notes, which are Ogg Opus, with opusenc, of opus-tools, which it runs, such as for the llm tools' voice notes
reminder
Package reminder has the block of what the system says to a model, in a message, which it reads as information, rather than what the person said, and which is taken out of what the system doesn't say, so it can't be faked, such as by the person, or what a model, or a tool, wrote
Package reminder has the block of what the system says to a model, in a message, which it reads as information, rather than what the person said, and which is taken out of what the system doesn't say, so it can't be faked, such as by the person, or what a model, or a tool, wrote
subtitle
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
taggroup
Package taggroup adds tags to the groups of an OpenAPI specification, which Redoc shows tags in, so modules which register their handlers on their own, in any order, can share a group
Package taggroup adds tags to the groups of an OpenAPI specification, which Redoc shows tags in, so modules which register their handlers on their own, in any order, can share a group
mcp
client
Package client is a client of a remote MCP server, over HTTP, with go-client as its transport, so its options, such as a user agent, headers, a token, and tracing, apply to the requests of the MCP SDK.
Package client is a client of a remote MCP server, over HTTP, with go-client as its transport, so its options, such as a user agent, headers, a token, and tracing, apply to the requests of the MCP SDK.
namespace
Package namespace is the namespace of a connector's tools, in a toolkit: the tools of its MCP server, which are called with its client
Package namespace is the namespace of a connector's tools, in a toolkit: the tools of its MCP server, which are called with its client
registry
Package registry has the connectors, which are remote MCP servers, whose definitions are kept in a store, with a client of each, which Run connects to its server
Package registry has the connectors, which are remote MCP servers, whose definitions are kept in a store, with a client of each, which Run connects to its server
registry/cmd
Package cmd has the commands, and flags, of the MCP connectors: those which call the connectors' API, and the server's
Package cmd has the commands, and flags, of the MCP connectors: those which call the connectors' API, and the server's
registry/httpclient
Package httpclient is a client of the HTTP API of the MCP connectors
Package httpclient is a client of the HTTP API of the MCP connectors
registry/httphandler
Package httphandler has the HTTP API of the MCP connectors, which lists, gets, creates, updates and deletes them
Package httphandler has the HTTP API of the MCP connectors, which lists, gets, creates, updates and deletes them
schema
Package schema has the defaults, and types, of MCP clients, of remote servers
Package schema has the defaults, and types, of MCP clients, of remote servers
test
Package test has a mock MCP server, for tests of the MCP clients, and connectors
Package test has a mock MCP server, for tests of the MCP clients, and connectors
Package memory is what the assistant remembers, which is shared by every session and agent: the details of the person it's talking to, and of itself, such as their names, where the person is, and their time zone and language, which are in the system prompt, each of which is known, not known, or declined, so it isn't.
Package memory is what the assistant remembers, which is shared by every session and agent: the details of the person it's talking to, and of itself, such as their names, where the person is, and their time zone and language, which are in the system prompt, each of which is known, not known, or declined, so it isn't.
cmd
Package cmd has the memory's commands and flags
Package cmd has the memory's commands and flags
httpclient
Package httpclient is a client of the memory's HTTP API
Package httpclient is a client of the memory's HTTP API
httphandler
Package httphandler has the memory's HTTP API, which gets, sets and forgets the details it keeps, and lists, gets, remembers and forgets its memories
Package httphandler has the memory's HTTP API, which gets, sets and forgets the details it keeps, and lists, gets, remembers and forgets its memories
Package messaging connects chats on messaging services, such as Telegram, to sessions, as channels, so the person can talk to their assistant there.
Package messaging connects chats on messaging services, such as Telegram, to sessions, as channels, so the person can talk to their assistant there.
schema
Package schema has the channels of messaging: chats, such as on Telegram, which are attached to sessions, so the person can talk to their assistant there
Package schema has the channels of messaging: chats, such as on Telegram, which are attached to sessions, so the person can talk to their assistant there
telegram
Package telegram is the Telegram messaging provider, a bot, whose chats are channels.
Package telegram is the Telegram messaging provider, a bot, whose chats are channels.
provider
anthropic
anthropic implements an API client for Anthropic's Claude API, which generates replies with the Messages API, and counts tokens.
anthropic implements an API client for Anthropic's Claude API, which generates replies with the Messages API, and counts tokens.
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.
gemini
gemini implements an API client for Google's Gemini API, which lists its models, and counts tokens.
gemini implements an API client for Google's Gemini API, which lists its models, and counts tokens.
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
cmd/tui
Package tui is a terminal interface to chat in a session, which is a throwaway, until there's a better one
Package tui is a terminal interface to chat in a session, which is a throwaway, until there's a better one
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 resource has resources: content, such as images, documents and audio, which is uploaded, or which tools return, which is kept once, by its hash, and referred to as resource:///<hash>.
Package resource has resources: content, such as images, documents and audio, which is uploaded, or which tools return, which is kept once, by its hash, and referred to as resource:///<hash>.
cmd
Package cmd has the resources' commands and flags
Package cmd has the resources' commands and flags
httpclient
Package httpclient is a client of the resources' HTTP API
Package httpclient is a client of the resources' HTTP API
httphandler
Package httphandler has the resources' HTTP API, which uploads, lists, gets, downloads and deletes them
Package httphandler has the resources' HTTP API, which uploads, lists, gets, downloads and deletes them
schema
Package schema has the resources' schema: a resource's content, which is kept once, by its hash, and what it is, such as its name and type, which a session can have, or which is on its own
Package schema has the resources' schema: a resource's content, which is kept once, by its hash, and what it is, such as its name and type, which a session can have, or which is on its own
cmd
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/
llm
Package llm has the llm namespace of tools, which ask the registry's models to do what a model which calls them can't, such as speak text, whose results, such as audio, are resources, which are kept, as resources of the session the tools run in
Package llm has the llm namespace of tools, which ask the registry's models to do what a model which calls them can't, such as speak text, whose results, such as audio, are resources, which are kept, as resources of the session the tools run in
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/

Jump to

Keyboard shortcuts

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