provider

package
v0.7.37 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package provider asks model provider APIs (Anthropic, and any OpenAI-compatible server) with a key the player saved, and runs the tool loop in process. It uses only the standard library for HTTP and SSE.

Index

Constants

View Source
const (
	ClientAPI = "api"
	ClientCLI = "cli"
)

Client kinds in the ordered client list.

View Source
const (
	DefaultMaxTurns  = 10
	DefaultTimeout   = 2 * time.Minute
	DefaultMaxResult = 16 << 10
)

Defaults.

View Source
const (
	KindAnthropic = "anthropic"
	KindOpenAI    = "openai" // OpenAI-compatible Chat Completions
)

Kinds of adapter.

View Source
const ErrNoTools = "This model can't use tools; pick another."

ErrNoTools is the plain message shown when a model can't call tools.

Variables

View Source
var ErrNoKey = errors.New("no key saved")

ErrNoKey says no key is saved for the provider.

View Source
var Presets = []Preset{
	{ID: "anthropic", Name: "Anthropic (Claude)", Kind: KindAnthropic, BaseURL: "https://api.anthropic.com/v1", NeedKey: true,
		Models: map[string]string{"efficient": "claude-haiku-5-5", "balanced": "claude-sonnet-5-5", "best": "claude-opus-5-5"},
		Doc:    "https://platform.claude.com/docs/en/models/overview"},
	{ID: "openai", Name: "OpenAI", Kind: KindOpenAI, BaseURL: "https://api.openai.com/v1", NeedKey: true,
		Models: map[string]string{"efficient": "gpt-6-luna", "balanced": "gpt-6.2-sol", "best": "gpt-6.2-astra"},
		Doc:    "https://developers.openai.com/api/docs/models", Extra: map[string]any{"reasoning_effort": "none"}},
	{ID: "openrouter", Name: "OpenRouter", Kind: KindOpenAI, BaseURL: "https://openrouter.ai/api/v1", NeedKey: true,
		Models: map[string]string{"efficient": "anthropic/claude-haiku-5.5", "balanced": "anthropic/claude-sonnet-5.5", "best": "anthropic/claude-opus-5.5"},
		Doc:    "https://openrouter.ai/api/v1/models", Note: "Pick a free model from the list to pay nothing."},
	{ID: "ollama", Name: "Ollama (on this PC)", Kind: KindOpenAI, BaseURL: "http://localhost:11434/v1", Local: true,
		Doc: "https://docs.ollama.com/api/openai-compatibility", Note: "Pick a model that supports tools."},
	{ID: "lmstudio", Name: "LM Studio (on this PC)", Kind: KindOpenAI, BaseURL: "http://localhost:1234/v1", Local: true,
		Doc: "https://lmstudio.ai/docs/developer/openai-compat", Note: "Pick a model that supports tools."},
	{ID: "custom", Name: "Other OpenAI-compatible server", Kind: KindOpenAI, Local: false,
		Doc: "", Note: "Enter the server's base URL (ending in /v1) and a model."},
}

Presets lists the providers. Model ids were read from each provider's own docs on 2026-11-24:

Functions

func CleanKey

func CleanKey(key string) (string, error)

CleanKey trims a pasted key; it must be one line of printable characters.

func DataDir

func DataDir() string

DataDir is the advisor's data folder: <user config dir>/wowc-advisor.

func IsStart

func IsStart(err error) bool

IsStart reports whether err is a StartError.

func KeyTarget

func KeyTarget(provider string) string

KeyTarget is the credential's name in the key store: wowc-advisor:<provider>.

func Save

func Save(path string, s Settings) error

Save writes the settings (no keys are ever part of them).

func SettingsPath

func SettingsPath() string

SettingsPath is providers.json in the data folder.

Types

type Adapter

type Adapter interface {
	Chat(ctx context.Context, req Request, onText func(string)) (Reply, error)
}

Adapter makes one model call; onText (may be nil) is told text as it streams.

func NewAdapter

func NewAdapter(p Preset, baseURL, key string) Adapter

NewAdapter builds the adapter for a preset (or a custom base URL) with key.

type Anthropic

type Anthropic struct{ Endpoint }

Anthropic talks to the Messages API (https://platform.claude.com/docs/en/api/messages). The system prompt and the tool list carry cache-control breakpoints, so repeat asks read them from the cache.

func (Anthropic) Chat

func (a Anthropic) Chat(ctx context.Context, req Request, onText func(string)) (Reply, error)

Chat makes one Messages call.

func (Anthropic) Models

func (a Anthropic) Models(ctx context.Context) ([]string, error)

Models lists the models the key can use.

type Call

type Call struct {
	ID, Name string
	Args     json.RawMessage
}

Call is a tool call the model asked for.

type ClientRef

type ClientRef struct {
	Kind     string `json:"kind"`               // "api" or "cli"
	Provider string `json:"provider,omitempty"` // a preset id, for an API client
	BaseURL  string `json:"base_url,omitempty"` // overrides the preset's (required for "custom")
	Model    string `json:"model,omitempty"`    // a model id; empty: the tier's default
	Tier     string `json:"tier,omitempty"`     // efficient, balanced or best; empty: the overlay's model setting
	Agent    string `json:"agent,omitempty"`    // for a CLI client: a preset name or a command
}

ClientRef is one configured AI client. It holds no key: only whether one is saved is ever shown.

func (ClientRef) Validate

func (c ClientRef) Validate() (ClientRef, error)

Validate checks one client and fills its defaults.

type Endpoint

type Endpoint struct {
	BaseURL string
	Key     string
	HTTP    *http.Client // nil: http.DefaultClient (the caller's context sets the timeout)
	// Extra fields merged into every request body (for example reasoning_effort).
	Extra map[string]any
}

Endpoint is where an adapter sends its calls. Key may be empty for a local server.

func (Endpoint) ModelList

func (e Endpoint) ModelList(ctx context.Context, headers map[string]string) ([]string, error)

ModelList asks an OpenAI-style /models endpoint (also Anthropic's, which uses the same shape) for model ids.

type FileKeyStore

type FileKeyStore struct{ Dir string }

FileKeyStore keeps each key in its own file in Dir, readable only by the user (mode 0600, in a 0700 folder). It is the store wherever the platform has no small pure-Go keychain binding.

func (FileKeyStore) Delete

func (f FileKeyStore) Delete(provider string) error

Delete removes the key.

func (FileKeyStore) Get

func (f FileKeyStore) Get(provider string) (string, error)

Get reads the key.

func (FileKeyStore) Set

func (f FileKeyStore) Set(provider, key string) error

Set writes the key, replacing any earlier one.

type KeyStore

type KeyStore interface {
	// Get returns the saved key, or ErrNoKey.
	Get(provider string) (string, error)
	Set(provider, key string) error
	// Delete removes the key; deleting a key that is not there is not an error.
	Delete(provider string) error
}

KeyStore keeps the player's API keys, one per provider. Keys never go in the config file or a log.

func DefaultKeyStore

func DefaultKeyStore() KeyStore

DefaultKeyStore is a private file in the data folder: macOS and Linux have no small pure-Go keychain binding (the macOS one shells out to `security`, which would put the key in a process argument list), so the key sits in <data folder>/keys/<provider>.key, mode 0600 in a 0700 folder.

type Lister

type Lister interface {
	Models(ctx context.Context) ([]string, error)
}

Lister is an adapter that can list models.

type Loop

type Loop struct {
	Adapter   Adapter
	Model     string
	System    string
	Prompt    string
	Tools     Tools
	MaxTurns  int           // at most this many model calls (default 10)
	Timeout   time.Duration // for the whole loop (default 2 minutes)
	MaxResult int           // bytes kept of one tool result (default 16 KiB)
	Stream    bool
	OnText    func(string)
}

Loop limits and inputs.

func (Loop) Run

func (l Loop) Run(ctx context.Context) (string, Usage, error)

Run asks the model, runs the tools it calls and feeds the results back until it answers. It returns the final text and the usage summed over every call.

type Message

type Message struct {
	Role    string // "user" or "assistant"
	Text    string
	Calls   []Call
	Results []Result
}

Message is one turn of the conversation. An assistant message carries text and tool calls; a user message carries text, or the results of the assistant's calls.

type NoToolsError

type NoToolsError struct{}

NoToolsError is returned when the provider says the model does not support tools.

func (NoToolsError) Error

func (NoToolsError) Error() string

type OpenAI

type OpenAI struct{ Endpoint }

OpenAI talks to an OpenAI-compatible Chat Completions endpoint (BaseURL ends in /v1): OpenAI, OpenRouter, Ollama, LM Studio and the like. Key may be empty.

func (OpenAI) Chat

func (o OpenAI) Chat(ctx context.Context, req Request, onText func(string)) (Reply, error)

Chat makes one Chat Completions call.

func (OpenAI) Models

func (o OpenAI) Models(ctx context.Context) ([]string, error)

Models lists the server's models.

type Preset

type Preset struct {
	ID      string            `json:"id"`
	Name    string            `json:"name"`
	Kind    string            `json:"kind"`
	BaseURL string            `json:"base_url"`
	NeedKey bool              `json:"needs_key"`
	Local   bool              `json:"local"`  // a server on the player's PC: list its installed models
	Models  map[string]string `json:"models"` // default model id per tier (efficient, balanced, best)
	Doc     string            `json:"doc"`    // where the model ids were read
	Note    string            `json:"note,omitempty"`
	Extra   map[string]any    `json:"-"` // fields added to every request
}

Preset is a provider the player can pick.

func PresetByID

func PresetByID(id string) (Preset, bool)

PresetByID finds a preset.

func (Preset) ModelFor

func (p Preset) ModelFor(tier, custom string) string

ModelFor picks the model id: the custom one when the tier is custom, else the preset's default for the tier (balanced and best fall back to efficient's, which may be empty for local servers).

type Reply

type Reply struct {
	Text  string
	Calls []Call
	Usage Usage
}

Reply is what one model call returned.

type Request

type Request struct {
	Model    string
	System   string
	Messages []Message
	Tools    []ToolDef
	Stream   bool
}

Request is one model call.

type Result

type Result struct {
	CallID, Name, Text string
	IsError            bool
}

Result is the answer to a Call.

type Settings

type Settings struct {
	Clients []ClientRef `json:"clients"`
}

Settings is the saved client list: tried in order, the first is the active one. Empty means the CLI-only setup the advisor always had (the agent from ask.json or detection).

func Load

func Load(path string) (Settings, error)

Load reads the settings; a missing file is empty settings.

type StartError

type StartError struct{ Msg string }

Error kinds. StartError means the provider could not be used at all (no key, not reachable, key refused), so the next client in a fallback list may be tried. NoToolsError means the model cannot use tools.

func (*StartError) Error

func (e *StartError) Error() string

type ToolDef

type ToolDef struct {
	Name, Description string
	Schema            json.RawMessage // JSON Schema of the arguments
}

ToolDef is a tool offered to the model.

type Tools

type Tools interface {
	List(ctx context.Context) ([]ToolDef, error)
	// Call runs one tool; isErr marks a tool-level failure whose text is shown to the model.
	Call(ctx context.Context, name string, args json.RawMessage) (text string, isErr bool, err error)
}

Tools is the set of tools the model may call.

type Usage

type Usage struct{ In, Out, Cached int }

Usage counts tokens: In is fresh input (including tokens written to a cache), Cached the input read from a cache, Out the output.

func (Usage) Add

func (u Usage) Add(o Usage) Usage

Add sums two usages.

Jump to

Keyboard shortcuts

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