llm

package
v0.24.0 Latest Latest
Warning

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

Go to latest
Published: Sep 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 llm provides an OpenAI-compatible chat completion client. It is used by the Discord gateway to generate RAG-based answers from retrieved context documents.

Index

Constants

View Source
const (
	// ThinkingDisabled sends "thinking": {"type": "disabled"}.
	ThinkingDisabled = "disabled"
	// ThinkingEnabled omits the "thinking" field entirely, leaving the
	// endpoint's own default in force. The field is omitted rather than sent
	// as {"type":"enabled"} because OpenAI-compatible endpoints that do not
	// implement this vendor parameter reject unknown fields with HTTP 400.
	ThinkingEnabled = "enabled"
)

Thinking modes accepted by Config.Thinking.

Reasoning models (e.g. deepseek-v4-flash) charge reasoning_content against the same max_tokens budget as the visible completion. On inputs whose reasoning runs long the budget is consumed entirely by reasoning and the response comes back with zero-length content and finish_reason="length" — measured on a 2,768-character document: max_tokens=8000 produced 25,388 reasoning characters and 0 content characters. Disabling reasoning on the same document produced a complete answer in 750 completion tokens.

Both users of this client (the summarizer and the extraction worker) do mechanical structured-output work, so ThinkingDisabled is the default.

Variables

View Source
var ErrTruncated = errors.New("llm: response truncated by token budget")

ErrTruncated is the sentinel behind every *TruncatedError, so callers can branch with errors.Is without depending on the struct type.

Functions

This section is empty.

Types

type Client

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

Client is an OpenAI-compatible chat completion client. It communicates with any endpoint that speaks the /v1/chat/completions protocol (OpenAI, Azure OpenAI, local proxies such as cliproxy, etc.).

func New

func New(cfg Config, httpClient *http.Client) *Client

New returns a Client configured with the given Config. httpClient may be nil — an http.Client with cfg.Timeout (default 60 s) is used. When cfg.Timeout is positive it overrides the default. Pass a pre-built httpClient to take full control of transport settings.

func (*Client) Complete

func (c *Client) Complete(ctx context.Context, system, user string) (string, error)

Complete sends a single-turn chat completion request. system is the system prompt; user is the user turn content. 4xx responses are not retried. 5xx and network errors are retried up to 2 times.

func (*Client) CompleteWithMessages

func (c *Client) CompleteWithMessages(ctx context.Context, system string, messages []Message) (string, error)

CompleteWithMessages sends a multi-turn chat completion request. system is the system prompt; messages is the ordered conversation history including the final user turn. The system message is always prepended. 4xx responses are not retried. 5xx and network errors are retried up to 2 times.

Tracing: the entire retry loop is wrapped in a single parent span ("llm.complete") so that retry-induced latency and eventual failure are visible as one logical operation, while each individual HTTP attempt gets its own child span ("llm.complete.attempt", attribute llm.retry.attempt). This mirrors the plan's explicit requirement — a lone "one span per call" design would hide how much of the total latency/failure came from retries.

func (*Client) Enabled

func (c *Client) Enabled() bool

Enabled reports whether the client has the minimum required configuration to make a request (non-empty base URL, model, and a token source configured).

func (*Client) StreamWithMessages added in v0.23.0

func (c *Client) StreamWithMessages(ctx context.Context, system string, messages []Message, onDelta func(string)) (err error)

StreamWithMessages sends a multi-turn chat completion request with stream: true and invokes onDelta once per received content delta.

Unlike CompleteWithMessages, a failed request is never retried: once the HTTP response body starts streaming, retrying risks emitting duplicate tokens to a caller that has already forwarded earlier deltas downstream (e.g. to an SSE client). A 4xx/5xx status returned before any body is read is reported as a plain error with onDelta never called.

Tracing: the whole call is wrapped in a single "llm.stream" span (no retry, so no attempt/parent split is needed — see CompleteWithMessages). err is a named return so the deferred span finalizer can record whatever error value the function ultimately returns, from any of its several return points, without duplicating span.RecordError/SetStatus calls at each one.

type Completer

type Completer interface {
	Enabled() bool
	CompleteWithMessages(ctx context.Context, system string, messages []Message) (string, error)
}

Completer is the minimal interface for LLM chat completion. It is satisfied by *Client and can be used by callers that need to inject a mock or alternative implementation for testing.

type Config

type Config struct {
	BaseURL     string
	Model       string
	APIKey      string // static Bearer token (overrides AuthFile)
	AuthFile    string // path to CliProxyAPI OAuth JSON (e.g. ~/.cli-proxy-api/user.json)
	MaxTokens   int
	Temperature float64
	// Timeout is the per-request HTTP timeout for LLM calls.
	// When zero or negative, the default of 60 s is used.
	// Increase for slow local CPU inference (e.g. gemma3:4b) by setting
	// LLM_TIMEOUT_SECONDS in the environment.
	Timeout time.Duration
	// Thinking controls the vendor "thinking" request parameter:
	// ThinkingDisabled (or "", the zero value) sends
	// "thinking": {"type": "disabled"}; ThinkingEnabled omits the field.
	// Any other value is treated as ThinkingDisabled. Sourced from the
	// LLM_THINKING environment variable via config.Config.LLMThinking.
	Thinking string
}

Config holds the parameters required to construct a Client.

Token resolution order:

  1. APIKey non-empty → static Bearer token
  2. AuthFile non-empty → CliProxyAPI OAuth token (auto-refreshed from disk, 5-min TTL)
  3. both empty → no Authorization header sent

type Message

type Message struct {
	Role    string `json:"role"` // "system", "user", or "assistant"
	Content string `json:"content"`
}

Message is a single chat message in the OpenAI format. It is exported so callers can build multi-turn conversation histories for CompleteWithMessages.

type StreamCompleter added in v0.23.0

type StreamCompleter interface {
	// StreamWithMessages sends a multi-turn chat completion request with
	// stream: true. onDelta is called once per received content delta
	// (never called with an empty string). Returns when the stream ends
	// (a literal "data: [DONE]" line) or ctx is cancelled/times out.
	StreamWithMessages(ctx context.Context, system string, messages []Message, onDelta func(string)) error
}

StreamCompleter is implemented by LLM clients that support token-by-token streaming. It is intentionally NOT merged into Completer — existing fake Completer implementations across internal/curation, internal/collector, internal/search/hyde.go, internal/worker/{summarizer,note_enrichment_worker, entity_extractor}.go would all break if Completer grew a new required method. Callers that need streaming type-assert:

if sc, ok := completer.(llm.StreamCompleter); ok { ... } else { /* fallback */ }

type TruncatedError added in v0.23.0

type TruncatedError struct {
	// FinishReason is the raw finish_reason reported by the provider.
	FinishReason string
	// CompletionTokens is the provider-reported completion token count, or 0
	// when the response carried no usage block (streaming responses usually
	// do not).
	CompletionTokens int
	// ContentLength is the byte length of the content that was produced —
	// a length only, never the content itself.
	ContentLength int
}

TruncatedError reports that generation stopped on the token budget (finish_reason="length") rather than at a natural stop. Both variants are errors:

  • empty content: the whole budget was spent on reasoning_content, and the caller would otherwise see only a confusing "cannot parse empty JSON".
  • non-empty content: a partial completion. Passing it on as success silently loses data (half-parsed entities, half-written summaries).

The response body is deliberately NOT a field of this error and never appears in Error(): completions contain personal data (issue #194).

func (*TruncatedError) Error added in v0.23.0

func (e *TruncatedError) Error() string

func (*TruncatedError) Unwrap added in v0.23.0

func (e *TruncatedError) Unwrap() error

Unwrap makes errors.Is(err, ErrTruncated) hold.

Jump to

Keyboard shortcuts

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