llms

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 47 Imported by: 1 module, 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.

README

llms-go

A Go library for building LLM-powered applications with a single, unified API across providers.

Write your code once against one Model interface and run it on Anthropic, OpenAI, Google (Gemini), or OpenRouter. A Manager handles model registration, aliases, and environment-variable overrides so you can swap models without touching application code.

Features

  • Multiple providers — Anthropic, OpenAI, Google Gemini, and OpenRouter behind one interface.
  • Typed structured output — get strongly-typed Go values back via generics; JSON schemas are derived automatically from your types.
  • Streaming — stream text, thinking and reasoning tokens, and incrementally parsed structured output as it arrives.
  • Tool calling and agentic loops — composable toolkits, multi-step execution, per-call timeouts, and built-in web search.
  • Cost and usage tracking — automatic pricing from models.dev data, including long-context price tiers, plus OpenTelemetry GenAI metrics and local stats aggregation.
  • Capability-aware — model metadata gates temperature, reasoning, structured output, and modality behavior so missing features fail gracefully. The metadata can be refreshed without a new release.
  • Retries you can watch — rate limits and overloads are retried with backoff, and a callback reports each wait so you can see the progress.
  • Stalls become errors — a call that goes silent fails, retries, and reports itself instead of hanging until an operator kills the job.
  • Pluggable credentials — environment variables by default, or supply your own source; credentials are resolved per request so they can rotate.

Installation

To install llms-go, run:

go get github.com/aholstenson/llms-go

Import the package in your code:

import llms "github.com/aholstenson/llms-go"

Quick start

Models are resolved through a Manager using fully-qualified provider/model names (for example, anthropic/claude-sonnet-4-5). By default, API keys are read from environment variables: ANTHROPIC_API_KEY, OPENAI_API_KEY, OPENROUTER_API_KEY, or GEMINI_API_KEY (also accepts GOOGLE_API_KEY). See Credentials to supply them yourself.

The following example initializes a manager and generates text:

manager := llms.NewManager()

model, err := manager.GetModel(ctx, "anthropic/claude-sonnet-4-5")
if err != nil {
    log.Fatal(err)
}

result, err := model.GenerateContent(ctx,
    llms.WithMessages(
        llms.NewMessage(llms.RoleUser, llms.NewTextPart("Say hello in one sentence.")),
    ),
)
if err != nil {
    log.Fatal(err)
}

fmt.Println(result.(llms.TextResult).Text)

Aliases

Register friendly names and let environment variables override them at deploy time without code changes:

manager.RegisterAlias("fast", "anthropic/claude-haiku-4-5")
model, _ := manager.GetModel(ctx, "fast") // or set LLM_MODEL_FAST=openai/gpt-4o

Reasoning

Reasoning (thinking) has three modes. Without an option, the provider's default for the model applies:

model.GenerateContent(ctx, llms.WithReasoning(llms.ReasoningOff), ...)  // turn it off
model.GenerateContent(ctx, llms.WithReasoning(llms.ReasoningOn), ...)   // on, default depth
model.GenerateContent(ctx, llms.WithReasoningEffort(llms.EffortHigh), ...) // on, at an effort

Efforts go from EffortMinimal to EffortMax. An effort the model does not accept is moved to the nearest one it does accept. A model that cannot turn reasoning off (for example Claude Opus 5.5) uses its lowest effort when asked to turn it off. Both cases log a warning.

Model data

Pricing, limits and capabilities come from models.dev, embedded in the build. For Anthropic models, the Anthropic Models API is also asked one time for each model, so new Claude models work before the embedded data knows them.

You can use newer data without a new release:

llms.RefreshModelInfo(ctx)             // get models.dev now and cache it for later processes
llms.LoadModelInfo(file)               // use a models.dev api.json that you downloaded
llms.RegisterModelInfo("openai/my-model", llms.ModelInfo{...}) // add or correct one model

Set LLM_MODELS_FILE to the path of a models.dev api.json to use that file in place of the embedded data. Prices can be overridden with a JSON file in LLM_PRICING_FILE (default llms-pricing.json) that maps model names to {"input": ..., "output": ..., "cache_read": ..., "cache_write": ...} in USD per million tokens.

To update the embedded data, run go generate ./....

Attachments

Send images, PDFs and text files as BinaryParts. Give a part a name so the model can refer to the file:

msg := llms.NewMessage(llms.RoleUser,
	llms.NewTextPart("Compare the spec with the report."),
	llms.NewBinaryPart("text/markdown", spec).WithName("spec.md"),
	llms.NewBinaryPart("application/pdf", report).WithName("report.pdf"),
)

Check the input before you start a long run. CheckMessages runs the same check that GenerateContent runs before it sends a request, and it makes no network call:

if err := llms.CheckMessages(model, []*llms.Message{msg}); err != nil {
	var ie *llms.InputError
	if errors.As(err, &ie) {
		// ie.Message and ie.Part tell which part failed.
	}
	if errors.Is(err, llms.ErrUnsupportedModality) { /* the model cannot read this kind of file */ }
	if errors.Is(err, llms.ErrAttachmentTooLarge) { /* send a list of files instead */ }
}

The errors are ErrUnsupportedModality, ErrUnsupportedMediaType, ErrAttachmentTooLarge and ErrInvalidAttachment (for example a text file that is not UTF-8). They are configuration errors, so IsRetryable is false.

ModelInfoOf(model).Limits.Image and .Limits.PDF give the provider limits: the largest image in bytes and pixels, the image formats, the number of images, and the largest PDF in bytes and pages. A zero value means the limit is not known. The check does not count PDF pages, so compare MaxPages with your own page count. Byte limits count the bytes in BinaryPart.Data, before base64 encoding.

Provider Images PDFs Limits
Anthropic image block, name in a label document block, name as the title 7.5 MB, 8000 px, 100 or 600 images and pages
OpenAI input_image, name in a label input_file, name as the file name 1500 images, 50 MB per file
Google inline data, name in a label inline data, name in a label 3600 images, 50 MB and 1000 pages per PDF
OpenRouter image_url, name in a label file part, name as the file name not documented

A label is a text part such as File "chart.png": just before the file.

Text files (text/*, JSON, XML and YAML) are sent as text. Anthropic gets a plain-text document block with the name as its title. The other providers get a text part with the content in a <file> element:

<file name="spec.md" media_type="text/markdown">
...
</file>

Anthropic models with a context window under 1M tokens take 100 images and 100 PDF pages; other Claude models take 600. With more than 20 images, each image must be 2000 px or smaller. Gemini documents its inline request limit as 20 MB on one page and 100 MB on another, so no image byte limit is set for Google. Correct a limit with RegisterModelInfo.

Credentials

A Manager gets its API keys from a CredentialSource. The default is EnvCredentials, which reads the environment variables listed above and memoizes what it finds. Applications that keep keys somewhere else — a secret manager, a config file, a per-tenant lookup — supply their own:

manager, err := llms.NewManager(
    llms.WithManagerCredentials(llms.CredentialFunc(
        func(ctx context.Context, provider string) (llms.Credential, error) {
            token, err := vault.Token(ctx, provider) // your own lookup
            if err != nil {
                return llms.Credential{}, err
            }
            return llms.Credential{APIKey: token}, nil
        },
    )),
)

The source is consulted twice: once when GetModel builds a model, so a missing credential is reported there instead of surfacing as an opaque transport error later, and then once per outbound HTTP request. The per-request call is what makes rotation work — a short-lived token can expire and be replaced without the model being rebuilt or the Manager's model cache being invalidated. It also puts the source in the hot path of every request, so implementations should cache and refresh on expiry rather than doing real work on every call.

Credential.APIKey is placed in whichever authentication header the provider expects. For endpoints that need more than a key — a gateway token, a tenant identifier — Credential.Headers is applied on top, and a credential carrying only headers and no API key is valid.

llms.StaticCredentials("...") covers the single-provider case, and errors.Is(err, llms.ErrNoCredentials) detects a missing credential regardless of which source produced it.

Driving the loop with Session

GenerateContent runs the agentic loop to completion. Session exposes the same loop one step at a time, so you can inspect what the model did, inject operator steering, or gate tool calls between turns:

s, err := llms.NewSession(model,
    llms.WithMessages(llms.NewMessage(llms.RoleUser, llms.NewTextPart("..."))),
    llms.WithTools(llms.NewToolDef(deployTool{})),
    llms.WithMaxSteps(8),
)
if err != nil {
    log.Fatal(err)
}

for {
    info, done, err := s.Step(ctx)
    if err != nil {
        log.Fatal(err)
    }

    for _, tc := range info.Output.ToolCalls {
        fmt.Printf("step %d: model called %q\n", info.Step, tc.Name)
    }

    if done {
        break
    }

    // Steer the next turn based on what just happened.
    s.Inject(llms.NewMessage(llms.RoleUser,
        llms.NewTextPart("Operator: skip deploy, summarize instead.")))
}

res, err := s.Result()

For finer control, StepPlan returns the model's tool calls without executing them and RunTools runs them on demand, useful when tools require approval or run out of process. See examples/agent for the full pattern.

Retries

A request that fails with a temporary error is retried automatically. This includes a rate limit (429), an overload (529), a timeout (408, 504), a server or gateway error (500, 502, 503), and a Cloudflare error between Cloudflare and the provider (520–524, for example 524 when the provider does not answer in time). The library owns the retry loop for all four providers, so the same options apply everywhere:

res, err := model.GenerateContent(ctx,
    llms.WithMessages(llms.NewMessage(llms.RoleUser, llms.NewTextPart("..."))),
    // Up to 10 attempts in total.
    llms.WithMaxRetries(9),
    // Tell the user what is going on between attempts.
    llms.WithRetryNotify(func(_ context.Context, n llms.RetryNotice) {
        log.Printf("Failed attempt %d of %d, waiting %s", n.Attempt, n.MaxAttempts, n.Delay)
    }),
)

Defaults: 2 retries (3 attempts), exponential backoff from 500ms to 8s with 25% jitter, and a server Retry-After hint is used when there is one. WithRetryBackoff replaces the delay policy and WithRetryAfterCap limits how long a server hint can make the library wait.

When the retries run out the error is an *UnavailableError, which carries the status code, the attempts made, and the last Retry-After hint:

var ue *llms.UnavailableError
if errors.As(err, &ue) {
    log.Printf("gave up after %d attempts (status %d)", ue.Attempts, ue.StatusCode)
}

A stream is never retried after its first event reaches your streaming callbacks. Such a failure is reported with the ErrStreamingPartialOutput sentinel instead, so you never replay tokens you have already received. Up to that point the whole model call — opening the request and reading the response — is retried as one attempt. This includes a rate limit or an overload that the provider sends inside a stream that already opened.

Stalls

A model call that goes silent is not a failure any provider reports: there is no error and no token, only a gap. WithStallTimeout turns that gap into a retryable error:

res, err := model.GenerateContent(ctx,
    llms.WithMessages(llms.NewMessage(llms.RoleUser, llms.NewTextPart("..."))),
    // Fail an attempt that has been quiet for 90 seconds.
    llms.WithStallTimeout(90*time.Second),
)

The budget measures bytes from the provider, not the events the library hands you. Keepalives and ping events are bytes, so a model that spends minutes reasoning keeps resetting it; a connection that died does not. The budget applies per attempt and only to the model call, so it never cuts short a slow tool call or a long agentic loop.

A stall is an ordinary transient failure: it is reported through WithRetryNotify, retried while nothing has reached your callbacks, and surfaces as an *UnavailableError wrapping a *StallError when the attempts run out. Detect it with errors.Is(err, llms.ErrStall).

WithRequestTimeout bounds the other half — how long an attempt may wait for the provider to start responding at all. Both default to off.

Streams that end early

A proxy or a load balancer can close a response stream before the provider sends its final event. The connection closes without an error, so the stream looks complete but the response is missing. The library finds this for each provider:

Provider Final event
OpenAI response.completed, response.failed or response.incomplete
Anthropic message_stop
Google A chunk with a finish reason, or a blocked prompt
OpenRouter A chunk with a finish reason

A stream that ends early is a transient failure, like a stall. It is reported through WithRetryNotify, retried while nothing has reached your callbacks, and surfaces as an *UnavailableError when the attempts run out. Detect it with errors.Is(err, llms.ErrStreamEnded). The error message gives the number of events received, the type of the last event and the response ID, if the provider sent one:

stream ended after 214 events without a final response (last event: response.reasoning_summary_text.delta, response ID: resp_123)

Dead HTTP/2 connections are found even without these options. After 15 seconds with no frame, the client sends a ping. If the ping gets no answer in 15 more seconds, the client closes the connection and removes it from the pool. The model does not answer the ping, so a model that reasons for a long time does not cause it to fail. The failed attempt is reported as a *StallError, so it is retried like any other stall, and the next attempt opens a new connection.

Pings are answered by the nearest HTTP/2 server. For most providers this is a CDN or a load balancer, and in some networks it is a proxy. Pings thus find a dead network path, such as a Wi-Fi change, a NAT timeout or a laptop that slept, but not a stuck provider behind a healthy front end. Use WithStallTimeout for that.

Each new model uses a copy of http.DefaultTransport with the pings turned on. To use your own settings, set http.DefaultTransport before you create the model. Changes to the fields of the same value after that are not seen. When http.DefaultTransport is not an *http.Transport, for example a test mock, the library uses it as it is, without pings.

To tell whether the model is thinking or the connection is dead while a turn produces no tokens, register WithLivenessNotify. It fires whenever data arrives after a quiet second, and stops the moment the provider goes silent:

llms.WithLivenessNotify(func(_ context.Context, n llms.LivenessNotice) {
    log.Printf("%s alive, quiet for %s", n.Provider, n.Idle)
})

Recovering a failed turn

A model turn that fails transiently does not end a Session. The turn left no trace — the conversation only grows when a turn succeeds — so the same session can try again, instead of cancelling the run and losing the transcript it has built up. This is what lets a long unattended job survive a stall:

for {
    info, done, err := s.Step(ctx)
    if err != nil {
        if llms.IsRetryable(err) {
            log.Printf("step %d failed, retrying: %v", info.Step, err)
            continue // same session, same transcript, one more model call
        }
        return err
    }
    if done {
        break
    }
}

Step returns done == false alongside such an error, and Session.Retryable reports the same thing. A retried turn does not consume step budget, and emits a fresh StreamingEventMessageStart.

The session also stays usable after a transient failure that comes after some output already reached your streaming callback, for example a stream that was cut after some reasoning deltas. IsRetryable and Session.Retryable are false for it, because another attempt streams the turn again from the start. The error also wraps ErrStreamingPartialOutput. Use IsUnavailable to find all transient failures, with and without partial output:

if llms.IsUnavailable(err) {
    if errors.Is(err, llms.ErrStreamingPartialOutput) {
        ui.DiscardCurrentTurn() // the next attempt streams the turn again
    }
    continue // same session, same transcript, one more model call
}
Content policy blocks

A provider safety system can block a model call. The library reports this as a *ContentPolicyError for every provider:

Provider Blocks
OpenAI Error codes cyber_policy, invalid_prompt, content_policy_violation, content_filter, and a response that is incomplete because of content_filter
Anthropic Stop reason refusal
Google A blocked prompt (promptFeedback.blockReason), and the finish reasons SAFETY, PROHIBITED_CONTENT, BLOCKLIST, SPII, IMAGE_SAFETY, IMAGE_PROHIBITED_CONTENT
OpenRouter Finish reason content_filter, finish reason error with a policy reason from the upstream provider, moderation errors (status 403), and policy errors from the upstream provider

A refusal that the model writes itself, such as an OpenAI refusal content part, is not a block: the turn completes, and Session.Result returns a *RefusalError.

The library does not retry a *ContentPolicyError automatically: the classifier is not deterministic, but it can also block the same transcript each time. The session stays usable (done == false), so you decide what to do:

policyBlocks := 0
for {
    info, done, err := s.Step(ctx)
    if err != nil {
        if llms.IsRetryable(err) {
            continue
        }
        if llms.IsContentPolicy(err) && policyBlocks < 2 {
            policyBlocks++
            log.Printf("step %d blocked by content policy, trying again: %v", info.Step, err)
            continue
        }
        return err
    }
    if done {
        break
    }
}

Session.Retryable is false after a block, because the failure is not transient. The session stays usable also when output already reached your streaming callback. Then the error also wraps ErrStreamingPartialOutput, and another attempt streams the turn again from the start.

A block on a long agentic run is often caused by tool output in the transcript, not by the prompt. Log the latest tool results when you get this error to find the cause.

Usage and cost

A MetricsRecorder collects the token counters of each call. Set one on the Manager to get the total for every call that the Manager's models make:

total := llms.NewMetricsRecorder()
manager, err := llms.NewManager(llms.WithManagerMetricsRecorder(total))

// Later: the cost in USD for each model.
pricing := llms.NewPricingManager(slog.Default())
costs := pricing.CalculateCosts(total.GetStats())

To get the usage of one request, user, or job, put a second recorder in the context of those calls:

scoped := llms.NewMetricsRecorder()
result, err := model.GenerateContent(llms.WithMetrics(ctx, scoped), opts...)

A call with a context recorder goes to the two recorders. The context recorder holds a subset of the Manager recorder, so do not add the two together. The difference between the Manager total and the sum of your context recorders is the usage that no context recorder counted.

Examples

Runnable programs live in examples/:

Example What it shows
examples/basic Minimal text generation
examples/streaming Streaming text and thinking tokens
examples/structured Typed structured output via generics
examples/tools Defining a tool and running an agentic loop
examples/agent Multi-step tool calling with execution control

Each example reads the model name from LLM_EXAMPLE_MODEL (defaulting to anthropic/claude-sonnet-4-5) and the matching provider token from the environment. Run one with:

go run ./examples/basic

License

MIT

Documentation

Index

Constants

View Source
const (
	ModelStatusAlpha      = "alpha"
	ModelStatusBeta       = "beta"
	ModelStatusDeprecated = "deprecated"
)

Model status values used in ModelInfo.Status.

View Source
const DefaultMaxRetries = 2

DefaultMaxRetries is the default number of retries applied to failing requests. Matches the Anthropic and OpenAI SDK defaults so behavior is uniform across providers out of the box.

View Source
const DefaultRetryAfterCap = 60 * time.Second

DefaultRetryAfterCap clamps server-supplied Retry-After hints so a pathological hint cannot stall a request for minutes.

View Source
const DefaultToolCallTimeout = 5 * time.Minute

DefaultToolCallTimeout is the timeout applied to a single tool call when no timeout is configured via WithToolCallTimeout.

View Source
const LivenessQuietThreshold = time.Second

LivenessQuietThreshold is the shortest gap that produces a LivenessNotice. Gaps below it are not reported: while tokens flow the caller already sees the stream, and a notice per token would be pure noise. A model that is thinking sends keepalives instead of tokens, and those land above the threshold — which is what makes "quiet but alive" visible.

View Source
const ModelsFileEnv = "LLM_MODELS_FILE"

ModelsFileEnv names the environment variable that points to a models.dev api.json file (plain or gzip). When it is set, that file is used in place of the embedded data and the refresh cache.

Variables

View Source
var (
	// ErrUnsupportedModality is returned when a part needs an input
	// modality (image, pdf, audio, video) that the model does not accept.
	ErrUnsupportedModality = errors.New("unsupported input modality")
	// ErrUnsupportedMediaType is returned when the model accepts the
	// modality but not the media type, for example image/bmp.
	ErrUnsupportedMediaType = errors.New("unsupported media type")
	// ErrAttachmentTooLarge is returned when a part is larger than a known
	// provider limit (see ImageLimits and PDFLimits).
	ErrAttachmentTooLarge = errors.New("attachment exceeds model input limit")
	// ErrInvalidAttachment is returned when a part is malformed, for
	// example a text file that is not valid UTF-8.
	ErrInvalidAttachment = errors.New("invalid attachment")
)

Sentinel errors for input that a model cannot accept. Each one is wrapped in an *InputError that tells which part failed. They are configuration errors: sending the same input again fails the same way, so do not retry.

View Source
var ErrNoCredentials = errors.New("no credentials available")

ErrNoCredentials sentinels a failure to obtain credentials for a provider. CredentialSource implementations should wrap it so callers can detect a missing-credential condition with errors.Is, regardless of where the credentials were supposed to come from.

View Source
var ErrStall = errors.New("provider stopped sending data")

ErrStall is the sentinel behind every StallError. Use errors.Is to detect a model call that went silent, without caring which provider or phase it was in:

if errors.Is(err, llms.ErrStall) { ... }
View Source
var ErrStreamEnded = errors.New("stream ended without a final response")

ErrStreamEnded is the sentinel for a response stream that ended before the provider sent its final event, for example an OpenAI stream without "response.completed" or an Anthropic stream without "message_stop". The connection closed without an error, so the cause is usually a proxy or a load balancer that cut the stream. Another attempt can succeed.

The retry loop retries this failure while no output has reached the caller. When the attempts run out, or when output already reached the caller, the error is returned in an UnavailableError. Use errors.Is to find it:

if errors.Is(err, llms.ErrStreamEnded) { ... }
View Source
var ErrStreamingPartialOutput = errors.New("streaming output was partially delivered before error")

ErrStreamingPartialOutput sentinels an error returned from a streaming generation where at least one content event had already been dispatched to the caller's StreamingFunc or StructuredStreamingFunc before the underlying stream errored. Callers use errors.Is to detect this case.

The library does not retry such a call by itself, because a new attempt sends the output again from the start. The failed call does not change the conversation, so the caller can still try the turn again. When the error is also an UnavailableError (see IsUnavailable), a Session stays usable: the caller discards the output it received for the failed turn and calls Session.StepPlan (or Step) again.

View Source
var ErrStructuredStreamParse = errors.New("structured stream parse failed")

ErrStructuredStreamParse sentinels an error returned when the jsonstream parser rejects mid-stream content during structured streaming. The parser state is unreliable after such an error, so the generation is aborted. Callers detect this via errors.Is; the underlying parser error is wrapped for diagnostics.

View Source
var ErrToolNotFound = &VisibleToolError{Message: "requested tool not found"}

ErrToolNotFound is set on ToolOutcome.Error when a ToolCall references a tool name not present in the session's tool registry. It is a VisibleToolError, so the model sees the message and can recover by calling a different tool.

Functions

func CheckMessages added in v0.13.0

func CheckMessages(model Model, messages []*Message) error

CheckMessages reports whether model can accept every part of messages. It runs the same input check that GenerateContent and Session run before they send a request, and it makes no network call. Use it to reject a bad input early.

It returns nil or an error that wraps an *InputError. The check uses the model's ModelInfo (see ModelInfoOf). Unknown models, and limits that are not known, are treated permissively. The check does not count PDF pages and does not look at the attachments of tool results.

For a Model that this package did not create, CheckMessages returns nil.

func ConvertToGenaiSchema

func ConvertToGenaiSchema(schema *jsonschema.Schema) *genai.Schema

ConvertToGenaiSchema converts a jsonschema.Schema to Google's genai.Schema.

func ConvertToJsonstreamSchema

func ConvertToJsonstreamSchema(schema *jsonschema.Schema) *jsonstream.Schema

ConvertToJsonstreamSchema converts a jsonschema.Schema to a jsonstream.Schema. This enables incremental JSON parsing for structured streaming output.

func ConvertToJsonstreamSchemaFromType

func ConvertToJsonstreamSchemaFromType[T any](registry map[string]SubParserConfig, opts ...StructuredStreamingOption) *jsonstream.Schema

ConvertToJsonstreamSchemaFromType generates a jsonstream.Schema from a Go type T with streaming enabled for all string fields. It reads jsonstream struct tags and resolves them using the provided registry.

Struct tag format: `jsonstream:"<name>"` where name matches a registered sub-parser.

Example:

type Response struct {
    Topic string `json:"topic"`
    Text  string `json:"text" jsonstream:"markdown"`
}

// The "markdown" tag is resolved via the registry provided by the Manager.
schema := ConvertToJsonstreamSchemaFromType[Response](registry,
    ConfigureSubParser("text", customConfig), // optional programmatic override
)

func IsContentPolicy added in v0.12.0

func IsContentPolicy(err error) bool

IsContentPolicy reports whether err contains a *ContentPolicyError: a provider safety system blocked the model call. See ContentPolicyError for the ways to recover.

func IsRetryable added in v0.9.0

func IsRetryable(err error) bool

IsRetryable reports whether a failed model call can be attempted again against the same conversation without replaying output. It is true for a transient provider failure — a rate limit, an overload, a stream event that could not be decoded, a stream that ended before its final event (see ErrStreamEnded), or a stall (see WithStallTimeout) — that the library's own retries could not clear. It is false once any of the turn's output has reached a streaming callback, because a fresh attempt replays tokens the user has already seen.

A retry is safe because a failed turn leaves the conversation untouched: the provider-native history only grows when a turn succeeds and its tool results are observed. So an unattended job can report the failure, wait, and call Session.StepPlan (or Step) again, instead of cancelling the run and throwing away the transcript it has built up:

info, done, err := session.Step(ctx)
if err != nil && llms.IsRetryable(err) {
	// same session, same transcript, one more model call
	continue
}

A Session tracks this for its own last failure; see Session.Retryable.

A transient failure after partial output is not retryable in this sense, but the Session stays usable after it. The caller discards the partial output and decides whether to try again. See IsUnavailable.

A *ContentPolicyError is not retryable in this sense: the failure is not transient. The Session stays usable after it, but the caller must decide whether to try again. See IsContentPolicy.

func IsUnavailable added in v0.14.0

func IsUnavailable(err error) bool

IsUnavailable reports whether err contains an *UnavailableError: a model call failed with a transient condition, such as a rate limit, an overload, a stall or a stream that ended before its final event. It is true with and without partial output.

A Session stays usable after such an error (Step returns done == false), because a failed turn does not change the conversation. Calling Session.StepPlan (or Step) again tries the turn again against the same transcript:

  • Without partial output, IsRetryable is also true. The caller can try again at once.
  • With partial output (the error also wraps ErrStreamingPartialOutput), IsRetryable is false. Some output of the failed turn already reached the streaming callback. The caller must discard that output before it tries again, because the next attempt streams the turn from the start.

func LoadModelInfo added in v0.9.0

func LoadModelInfo(rd io.Reader) error

LoadModelInfo replaces the models.dev data for this process with a models.dev api.json document (plain or gzip) read from rd. Only the supported providers are used.

func RefreshModelInfo added in v0.9.0

func RefreshModelInfo(ctx context.Context) error

RefreshModelInfo gets the current data from models.dev, uses it for this process, and saves it in the user cache directory. Later processes use the saved copy when it is newer than the data embedded in the build. When LLM_MODELS_FILE is set, later processes use that file instead.

func RegisterModelInfo added in v0.9.0

func RegisterModelInfo(qualifiedName string, info ModelInfo)

RegisterModelInfo adds or replaces the ModelInfo for a fully qualified model name. Use it for models that models.dev does not list or to correct its data. Registered entries win over all models.dev data and over the Anthropic Models API answer, and apply to models that already exist.

The capability flags gate requests: a model registered with Caps.ToolCall=false rejects tools, so set every capability the model has.

func WithMetrics

func WithMetrics(ctx context.Context, recorder MetricsRecorder) context.Context

WithMetrics adds a MetricsRecorder to the context.

func WithStreamScope

func WithStreamScope(ctx context.Context, s StreamScope) context.Context

WithStreamScope attaches a StreamScope to the context.

Types

type BackoffFunc

type BackoffFunc func(attempt int, retryAfter time.Duration, hasRetryAfter bool) time.Duration

BackoffFunc adapts a function value to the BackoffPolicy interface.

func (BackoffFunc) Delay

func (f BackoffFunc) Delay(attempt int, retryAfter time.Duration, hasRetryAfter bool) time.Duration

Delay implements BackoffPolicy.

type BackoffPolicy

type BackoffPolicy interface {
	Delay(attempt int, retryAfter time.Duration, hasRetryAfter bool) time.Duration
}

BackoffPolicy computes the delay before the next retry attempt.

attempt is 0-indexed: 0 is the delay before the first retry (after the original try has just failed). When hasRetryAfter is true the server provided a hint (already clamped to RetryAfterCap by the retry loop) and policies are free to honor or override it; the default policy honors it.

type BinaryPart

type BinaryPart struct {
	MediaType string
	Data      []byte
	Name      string `json:",omitempty"`
}

BinaryPart is inline file content: an image, a PDF, a text file, or other data the provider accepts.

Name is optional. It is the file name (for example "spec.md") that lets the model refer to the file. Providers that have a document title or file name field get it there. For other providers, the part is sent with a short text label that holds the name. See README "Attachments" for the behavior of each provider.

Parts with a text media type (text/*, application/json, application/xml, application/yaml, and +json, +xml or +yaml types) are sent as text. Anthropic gets a plain-text document block with Name as its title. The other providers get a text part with the content in a <file> element that holds the name.

func NewBinaryPart

func NewBinaryPart(mediaType string, data []byte) *BinaryPart

func (*BinaryPart) WithName added in v0.13.0

func (p *BinaryPart) WithName(name string) *BinaryPart

WithName sets the file name of the part and returns the part.

type CallStats

type CallStats struct {
	Success map[string]map[string]int `json:"success"` // service -> counter -> value
	Failure map[string]map[string]int `json:"failure"` // service -> counter -> value
	Costs   map[string]float64        `json:"costs"`   // service -> total cost in USD
}

CallStats represents the aggregated statistics for an entire call.

func (CallStats) Add

func (c CallStats) Add(other CallStats) CallStats

type Capabilities

type Capabilities struct {
	Temperature      bool `json:"temperature"`
	Reasoning        bool `json:"reasoning"`
	ToolCall         bool `json:"tool_call"`
	Attachment       bool `json:"attachment"`
	StructuredOutput bool `json:"structured_output"`
	// ReasoningEfforts lists the effort tiers the model accepts, lowest
	// first. Empty means the model has no effort control or that it is not
	// known. WithReasoningEffort values the model does not accept are moved to
	// the nearest tier in this list.
	ReasoningEfforts []Effort `json:"reasoning_efforts,omitempty"`
	// ReasoningBudget is the thinking-token budget range the model accepts.
	// Nil means the model does not take a thinking-token budget.
	ReasoningBudget *TokenRange `json:"reasoning_budget,omitempty"`
	// AdaptiveThinking marks Anthropic models that accept adaptive thinking,
	// where the model decides how much to think.
	AdaptiveThinking bool `json:"adaptive_thinking,omitempty"`
	// ReasoningMandatory marks models that always reason and reject every
	// form of turning reasoning off.
	ReasoningMandatory bool `json:"reasoning_mandatory,omitempty"`
}

Capabilities describes which behaviors a model supports. These flags gate what providers send to the API.

type Collector

type Collector interface {
	Counter(name string) Counter
	GetCounters() map[string]int
}

Collector accumulates local statistics for a single operation.

func NewCollector

func NewCollector() Collector

NewCollector creates a new local collector for accumulating statistics.

type ConditionalTool

type ConditionalTool interface {
	IsAvailable(ctx context.Context) (bool, error)
}

ConditionalTool is an optional interface that ToolDef values may implement to signal runtime availability. When IsAvailable returns (false, nil) at session creation, the tool is silently excluded from the LLM's tool list and from the session's toolMap. A non-nil error aborts session creation.

type ContentPolicyError added in v0.12.0

type ContentPolicyError struct {
	Provider      string
	Model         string
	StatusCode    int
	Code          string
	Message       string
	PartialOutput bool
	PartialUsage  *TurnUsage
	Cause         error
}

ContentPolicyError is returned when a provider safety system blocks a model call, for example the OpenAI "cyber_policy" error. The provider rejects the call as a whole, so the model produces no turn. This is different from a RefusalError, where the model itself answers with a refusal and the turn completes.

The classifiers that make these decisions are not deterministic. A call that is blocked can pass when it is sent again, but it can also fail the same way each time. Thus the library does not retry it automatically. The caller decides what to do. A Session stays usable after this error (Step returns done == false), so the caller can:

  • call Step again a limited number of times,
  • stop and keep the transcript for analysis,
  • continue the work with a different model.

Use errors.As or IsContentPolicy to find it in a wrapped error chain.

Fields:

  • Provider: the GenAI system (e.g. "openai").
  • Model: the model ID requested.
  • StatusCode: HTTP status when known, 0 when the provider sent the error inside an open stream.
  • Code: the provider's error code, e.g. "cyber_policy".
  • Message: the provider's error message.
  • PartialOutput: true when at least one content event was dispatched to StreamingFunc before the call was blocked. Another attempt sends that output again.
  • PartialUsage: usage reported before the call was blocked, if any.

func (*ContentPolicyError) Error added in v0.12.0

func (e *ContentPolicyError) Error() string

func (*ContentPolicyError) Unwrap added in v0.12.0

func (e *ContentPolicyError) Unwrap() error

type Cost

type Cost struct {
	Input      float64 `json:"input"`
	Output     float64 `json:"output"`
	CacheRead  float64 `json:"cache_read,omitempty"`
	CacheWrite float64 `json:"cache_write,omitempty"`
	// Reasoning is the rate for thinking tokens that a provider reports
	// apart from output tokens. Zero means thinking tokens use the Output
	// rate.
	Reasoning float64 `json:"reasoning,omitempty"`
	// Tiers are higher prices for large requests, ordered by ContextOver.
	Tiers []CostTier `json:"tiers,omitempty"`
}

Cost is the per-model token pricing, in USD per 1 million tokens. A zero value means the dimension is unsupported or free.

func (*Cost) UnmarshalJSON added in v0.9.0

func (c *Cost) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a Cost from the models.dev key names. It also accepts the short keys "i", "o", "r" and "w" that earlier pricing files use.

type CostTier added in v0.9.0

type CostTier struct {
	ContextOver int     `json:"context_over"`
	Input       float64 `json:"input,omitempty"`
	Output      float64 `json:"output,omitempty"`
	CacheRead   float64 `json:"cache_read,omitempty"`
	CacheWrite  float64 `json:"cache_write,omitempty"`
	Reasoning   float64 `json:"reasoning,omitempty"`
}

CostTier is the pricing for requests whose prompt is larger than ContextOver tokens. The prompt size is the input tokens plus the cached (read and written) tokens of one request. A zero rate keeps the base rate.

type Counter

type Counter interface {
	Add(value int)
}

Counter represents a single metric that can be incremented.

type Credential added in v0.6.0

type Credential struct {
	// APIKey is the provider API key. May be empty when Headers carry the
	// authentication instead.
	APIKey string

	// Headers are set on every request after APIKey is applied. Existing
	// values for the same header name are replaced.
	Headers http.Header
}

Credential carries the authentication material for a single provider request.

APIKey is placed in the provider's native authentication header (`Authorization: Bearer` for Anthropic, OpenAI and OpenRouter, `x-goog-api-key` for Google). Headers are applied on top and can carry anything else the endpoint needs, such as a gateway token or a tenant identifier. A Credential with an empty APIKey and non-empty Headers is valid: it means authentication is carried entirely by those headers.

type CredentialFunc added in v0.6.0

type CredentialFunc func(ctx context.Context, provider string) (Credential, error)

CredentialFunc adapts a function value to the CredentialSource interface.

func (CredentialFunc) Credential added in v0.6.0

func (f CredentialFunc) Credential(ctx context.Context, provider string) (Credential, error)

Credential implements CredentialSource.

type CredentialSource added in v0.6.0

type CredentialSource interface {
	Credential(ctx context.Context, provider string) (Credential, error)
}

CredentialSource supplies provider authentication to a Manager. provider is the lowercase provider segment of a resolved model name — "anthropic", "openai", "openrouter" or "google".

A source is consulted twice per model: once when Manager.GetModel builds the model, so a missing credential fails fast rather than surfacing as an opaque transport error later, and then once per outbound HTTP request. The per-request call means rotating or short-lived credentials take effect without rebuilding the model, but it also means implementations sit in the hot path of every request and should keep resolution cheap — cache, and refresh on expiry rather than on every call.

Implementations that cannot resolve a credential outside of a request (for example one that reads a tenant from the context) should return the zero Credential and a nil error for the construction-time call, and do the real work in the per-request call.

Credential must be safe for concurrent use.

func StaticCredentials added in v0.6.0

func StaticCredentials(apiKey string) CredentialSource

StaticCredentials returns a CredentialSource that hands out the same API key for every provider. Useful when the calling application already holds the key and only ever talks to one provider.

type DefaultMetricsRecorder

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

DefaultMetricsRecorder is the default implementation of MetricsRecorder.

func NewMetricsRecorder

func NewMetricsRecorder() *DefaultMetricsRecorder

NewMetricsRecorder creates a new DefaultMetricsRecorder.

func (*DefaultMetricsRecorder) GetStats

func (d *DefaultMetricsRecorder) GetStats() CallStats

GetStats returns a copy of the current aggregated statistics.

func (*DefaultMetricsRecorder) RecordFailure

func (d *DefaultMetricsRecorder) RecordFailure(serviceName string, collector Collector)

RecordFailure records failed operation statistics for a service.

func (*DefaultMetricsRecorder) RecordSuccess

func (d *DefaultMetricsRecorder) RecordSuccess(serviceName string, collector Collector)

RecordSuccess records successful operation statistics for a service.

type Effort added in v0.3.0

type Effort string

Effort is a portable reasoning-effort level: the primary, provider- independent knob for how much a model reasons before answering. It is translated per-provider (OpenAI reasoning effort, Anthropic output-config effort / adaptive thinking, Gemini thinking level, OpenRouter effort) using per-model metadata, and converted to a token budget for budget-style models (older Anthropic models, Gemini 2.5).

Not every model accepts every tier. A tier the model does not accept is moved to the nearest tier it does accept (with a warning), matching how temperature is gated — portability over strictness.

The zero value is the empty string, meaning "no reasoning option given", which leaves reasoning at the provider's default (see ReasoningDefault).

const (
	// EffortNone turns reasoning off, the same as WithReasoning(ReasoningOff).
	EffortNone Effort = "none"
	// EffortMinimal requests the least reasoning a model can do without
	// turning it off.
	EffortMinimal Effort = "minimal"
	// EffortLow requests little reasoning.
	EffortLow Effort = "low"
	// EffortMedium requests a moderate amount of reasoning.
	EffortMedium Effort = "medium"
	// EffortHigh requests extensive reasoning.
	EffortHigh Effort = "high"
	// EffortXHigh requests more reasoning than EffortHigh.
	EffortXHigh Effort = "xhigh"
	// EffortMax requests the most reasoning the model can do.
	EffortMax Effort = "max"
)

type EnvCredentials added in v0.6.0

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

EnvCredentials reads provider API keys from environment variables and is the default CredentialSource used by a Manager:

anthropic   ANTHROPIC_API_KEY
openai      OPENAI_API_KEY
openrouter  OPENROUTER_API_KEY
google      GEMINI_API_KEY, falling back to GOOGLE_API_KEY

Because a source is consulted on every outbound request, resolved keys are memoized per provider — the process environment is read once per provider and every later request is served from the cache. Only successful lookups are cached, so an application that populates the environment after the first (failed) attempt still picks the key up.

The flip side is that a key changed in the environment after it has been read is not observed. That is deliberate: an environment variable is a process-startup input, not a rotation channel. Applications with rotating credentials should supply their own CredentialSource, which is re-consulted per request.

The zero value is ready for use and safe for concurrent use.

func (*EnvCredentials) Credential added in v0.6.0

func (e *EnvCredentials) Credential(_ context.Context, provider string) (Credential, error)

Credential implements CredentialSource.

type ExecutionContext

type ExecutionContext interface {
	// CurrentStep returns the current step number (1-indexed).
	CurrentStep() int

	// MaxSteps returns the maximum number of steps allowed.
	MaxSteps() int

	// RemainingSteps returns how many steps are left.
	RemainingSteps() int

	// ToolCallCount returns the number of times a specific tool has been called.
	ToolCallCount(toolName string) int

	// TotalToolCalls returns the total number of tool calls across all tools.
	TotalToolCalls() int

	// InputTokens returns cumulative uncached input tokens across all steps.
	// Cached prompt tokens are reported separately by CachedTokens and are not
	// included here (the buckets are disjoint; see TurnUsage).
	InputTokens() int64

	// OutputTokens returns cumulative output tokens across all steps.
	OutputTokens() int64

	// CachedTokens returns cumulative cache-read tokens across all steps —
	// prompt tokens served from the cache, disjoint from InputTokens.
	CachedTokens() int64

	// CachedWriteTokens returns cumulative cache-write tokens across all steps —
	// prompt tokens written to the cache when creating a new entry, disjoint
	// from InputTokens. Non-zero only for providers with explicit caching
	// (Anthropic, and Anthropic models via OpenRouter).
	CachedWriteTokens() int64

	// TotalTokens returns all tokens processed across all steps: uncached
	// input + cache-read + cache-write + output.
	TotalTokens() int64
}

ExecutionContext provides read access to the current execution state during an LLM generation loop. Tools can use this to adapt their behavior based on how many times they've been called or how many tokens have been consumed.

func GetExecutionContext

func GetExecutionContext(ctx context.Context) ExecutionContext

GetExecutionContext retrieves the ExecutionContext from the context, or nil if not present.

type ExponentialBackoff

type ExponentialBackoff struct {
	Base   time.Duration // initial delay; default 500ms
	Max    time.Duration // cap; default 8s
	Jitter float64       // 0..1; default 0.25. 0 disables jitter.
}

ExponentialBackoff is the default BackoffPolicy and is also exported as a building block. Delay is Base * 2^attempt, capped at Max, with random jitter in [delay*(1-Jitter), delay). When the server provided a Retry-After hint, that hint is used verbatim instead.

Defaults match the Anthropic and OpenAI SDK backoffs:

&ExponentialBackoff{Base: 500*time.Millisecond, Max: 8*time.Second, Jitter: 0.25}

func (*ExponentialBackoff) Delay

func (e *ExponentialBackoff) Delay(attempt int, retryAfter time.Duration, hasRetryAfter bool) time.Duration

Delay implements BackoffPolicy.

type GenAIErrorType

type GenAIErrorType string

GenAIErrorType represents the type of error that occurred.

const (
	GenAIErrorTypeNoError          GenAIErrorType = ""
	GenAIErrorTypeTimeout          GenAIErrorType = "timeout"
	GenAIErrorTypeInternal         GenAIErrorType = "internal"
	GenAIErrorTypeStreamProcessing GenAIErrorType = "stream_processing"
	GenAIErrorTypeToolCall         GenAIErrorType = "tool_call"
	GenAIErrorTypeEmptyResponse    GenAIErrorType = "empty_response"
	GenAIErrorTypeUnavailable      GenAIErrorType = "unavailable"
	// GenAIErrorTypeContentPolicy is a request or a response that a
	// provider safety system blocked. See ContentPolicyError.
	GenAIErrorTypeContentPolicy GenAIErrorType = "content_policy"
	// GenAIErrorTypeStreamEnded is a response stream that ended before the
	// provider sent its final event. See ErrStreamEnded.
	GenAIErrorTypeStreamEnded GenAIErrorType = "stream_ended"
)

type GenAIModel

type GenAIModel string

GenAIModel represents a specific model identifier.

type GenAIOperation

type GenAIOperation string

GenAIOperation represents the type of operation being performed.

const (
	GenAIOperationChat            GenAIOperation = "chat"
	GenAIOperationGenerateContent GenAIOperation = "generate_content"
)

Common GenAI operations following OpenTelemetry semantic conventions.

type GenAISystem

type GenAISystem string

GenAISystem represents a Generative AI system provider.

const (
	GenAISystemOpenAI    GenAISystem = "openai"
	GenAISystemAnthropic GenAISystem = "anthropic"
	GenAISystemGoogle    GenAISystem = "google"
)

Common GenAI system identifiers following OpenTelemetry semantic conventions.

const GenAISystemOpenRouter GenAISystem = "openrouter"

GenAISystemOpenRouter identifies OpenRouter as the GenAI system for metrics.

type GenerateOption

type GenerateOption func(*generateContentOptions) error

func WithLivenessNotify added in v0.9.0

func WithLivenessNotify(fn LivenessNotifyFunc) GenerateOption

WithLivenessNotify registers a callback that runs when data arrives from the provider after a quiet gap of at least LivenessQuietThreshold. Use it to tell "the model is thinking" apart from "the connection is dead" while a turn produces no tokens:

llms.WithLivenessNotify(func(_ context.Context, n llms.LivenessNotice) {
	log.Printf("%s alive, quiet for %s", n.Provider, n.Idle)
})

Notices stop arriving the moment the provider goes silent, so a watcher can show the growing gap instead of guessing. Gaps shorter than the threshold are not reported: while tokens flow you already have the stream.

The callback runs on the goroutine reading the response, so keep it short. Pass nil to remove a callback.

func WithMaxOutputTokens

func WithMaxOutputTokens(maxOutputTokens int) GenerateOption

WithMaxOutputTokens sets the maximum number of output tokens the model may produce in a single response. This cap covers visible output only; any thinking budget configured via WithMaxThinkingTokens is added on top by providers that count thinking against the output limit.

func WithMaxRetries

func WithMaxRetries(n int) GenerateOption

WithMaxRetries sets the maximum number of retry attempts after the initial request. The total number of attempts is n+1. Default is DefaultMaxRetries (2). Passing 0 disables retries; n < 0 returns an error.

The retry loop is owned by llms-go for every provider, so WithMaxRetries, WithRetryBackoff and WithRetryNotify behave the same everywhere.

A streaming request is retried as a whole while no event has reached a streaming callback. This includes a rate limit or an overload that the provider sends inside a stream that opened with status 200. After an event reached a callback, the stream is never retried: a failure surfaces to the caller with ErrStreamingPartialOutput. A non-streaming request is retried as a whole. Anthropic and OpenAI stream every generation; Google and OpenRouter stream only when a streaming callback is set.

func WithMaxSteps

func WithMaxSteps(maxSteps int) GenerateOption

WithMaxSteps sets the maximum number of steps, such as tool calls, to make.

func WithMaxThinkingTokens deprecated

func WithMaxThinkingTokens(maxThinkingTokens int) GenerateOption

WithMaxThinkingTokens sets the maximum number of tokens to use for thinking.

Deprecated: prefer WithReasoningEffort, the portable reasoning knob. This option remains as an advanced escape hatch for budget-style models (older Anthropic models, Gemini 2.5) and OpenRouter, where it turns reasoning on and takes precedence over WithReasoningEffort. On effort-only models (OpenAI, newer Anthropic and Gemini) it does not control reasoning and is ignored except for reserving output headroom; use WithReasoningEffort there instead.

func WithMessages

func WithMessages(messages ...*Message) GenerateOption

WithMessages sets the messages that the LLM will use to generate content.

func WithParentExecution

func WithParentExecution(parent ExecutionContext) GenerateOption

WithParentExecution rolls this generation's token and tool-call totals up to a parent ExecutionContext. Use it for the lightweight sub-agent pattern: a tool's Execute calls another model's GenerateContent with WithParentExecution(GetExecutionContext(ctx)) so child spend accrues to the parent tracker.

Step budgets are NOT rolled up: the child runs its own independent WithMaxSteps budget and does not consume the parent's remaining steps. Only token and tool-call accounting accrues to the parent.

func WithReasoning added in v0.9.0

func WithReasoning(mode ReasoningMode) GenerateOption

WithReasoning sets whether the model reasons. ReasoningOff and ReasoningDefault clear an effort set with WithReasoningEffort; ReasoningOn keeps it.

func WithReasoningEffort added in v0.3.0

func WithReasoningEffort(e Effort) GenerateOption

WithReasoningEffort turns reasoning on at the given effort. This is the recommended way to control reasoning/thinking across providers: the effort is mapped to each provider's native control, or to a token budget for budget-style models. EffortNone turns reasoning off.

Without a reasoning option the provider's default applies; see ReasoningDefault. An effort given after WithReasoning(ReasoningOff) turns reasoning back on: the last reasoning option wins.

func WithRequestTimeout added in v0.9.0

func WithRequestTimeout(d time.Duration) GenerateOption

WithRequestTimeout bounds how long one attempt may wait for the provider to start responding. Pass 0 (the default) to disable it.

What that covers depends on the provider. Anthropic and OpenAI stream, so it is the time to open the stream and the rest is governed by WithStallTimeout. Google and OpenRouter make non-streaming requests when no streaming callback is set, and those send nothing until the answer is complete — so for them this is effectively a deadline on the whole generation. Size it accordingly, or leave it off and rely on WithStallTimeout for the streaming paths.

The budget applies per attempt, so exceeding it is a retryable *StallError rather than the end of the run.

func WithResponseSchema

func WithResponseSchema[T any]() GenerateOption

WithResponseSchema enables structured output with a JSON schema derived from type T. The schema name is auto-derived from the type name (e.g., "TopicSummary" -> "topic_summary").

func WithRetryAfterCap

func WithRetryAfterCap(d time.Duration) GenerateOption

WithRetryAfterCap clamps server-supplied Retry-After hints to the given upper bound. Default is DefaultRetryAfterCap (60s). Pass 0 to disable the cap entirely. The cap is applied to both the internal sleep duration and to the value surfaced on UnavailableError.RetryAfter.

func WithRetryBackoff

func WithRetryBackoff(p BackoffPolicy) GenerateOption

WithRetryBackoff overrides the BackoffPolicy that decides how long to wait between attempts. It applies to every provider. The default is an ExponentialBackoff with 500ms base, an 8s cap and 25% jitter, which honors a server Retry-After hint when there is one.

func WithRetryNotify added in v0.8.0

func WithRetryNotify(fn RetryNotifyFunc) GenerateOption

WithRetryNotify registers a callback that runs after a failed attempt, just before the library waits to make the next attempt. Use it to show retry progress to the user:

llms.WithRetryNotify(func(_ context.Context, n llms.RetryNotice) {
	log.Printf("Failed attempt %d of %d, waiting %s", n.Attempt, n.MaxAttempts, n.Delay)
})

The callback runs on the goroutine that made the request, so keep it short. It is not called for an error that is not retryable, and not called for the last attempt, because no wait follows it — use the returned UnavailableError to report the final failure. Pass nil to remove a callback.

func WithSnapshot added in v0.5.0

func WithSnapshot(snap *SessionSnapshot) GenerateOption

WithSnapshot restores a Session from a SessionSnapshot captured earlier with Session.Snapshot, reconstructing the transcript, the consumed step budget, the plan/observe phase, and cumulative token usage. Use it with NewSession, re-supplying tools and other options (notably the same WithMaxSteps) as for the original session:

s, err := llms.NewSession(ctx, model,
	llms.WithSnapshot(&snap),
	llms.WithTools(tools...),
	llms.WithMaxSteps(8),
)

When the snapshot's phase is SessionPhaseAwaitingTools the restored session is primed for StepObserve with the outcomes of snap.PendingCalls (no model call); otherwise the next call is StepPlan/Step. WithSnapshot is mutually exclusive with WithMessages — it supplies the transcript itself.

func WithStallTimeout added in v0.9.0

func WithStallTimeout(d time.Duration) GenerateOption

WithStallTimeout fails a model call that has already started responding and then goes quiet for longer than d. Pass 0 (the default) to disable it.

The budget measures bytes from the provider, not the events the library hands you. Keepalives and provider ping events are bytes, so a model that spends minutes reasoning keeps resetting the budget; a connection that died mid-response does not. This is the setting that turns a silent hang into a visible failure.

A stall is retryable. It is reported through WithRetryNotify like a rate limit, retried while nothing has reached your streaming callbacks, and surfaces as an UnavailableError wrapping a *StallError when the attempts run out. Because the budget applies per attempt, and only to the model call, it does not cut short a slow tool call (see WithToolCallTimeout) or a long agentic loop.

Pick a value well above the provider's keepalive interval — a minute or two is generous for every supported provider:

llms.WithStallTimeout(90 * time.Second)

func WithStreamingFunc

func WithStreamingFunc(streaming StreamingFunc) GenerateOption

WithStreamingFunc enables streaming of the LLM's response. The given function will be called with each chunk of the response.

func WithStructuredStreaming

func WithStructuredStreaming[T any](handler StructuredStreamingFunc, streamOpts ...StructuredStreamingOption) GenerateOption

WithStructuredStreaming enables structured streaming output with auto-generated jsonstream schema. Events are emitted as the JSON is parsed incrementally.

All string fields automatically have streaming enabled. Use struct tags or options to configure sub-parsers for specific fields. Tag values are resolved via the Manager's sub-parser registry.

Struct tag example:

type Response struct {
    Topic string `json:"topic"`
    Text  string `json:"text" jsonstream:"markdown"`  // Resolved via Manager.RegisterSubParser("markdown", ...)
}

Programmatic example (overrides tags):

llms.WithStructuredStreaming[Response](handler,
    llms.ConfigureSubParser("text", mySubParserConfig),
)

func WithStructuredStreamingCustom

func WithStructuredStreamingCustom[T any](jsSchema *jsonstream.Schema, handler StructuredStreamingFunc) GenerateOption

WithStructuredStreamingCustom enables structured streaming with a custom jsonstream schema. Use this for advanced control over which fields emit streaming events.

func WithSystemPrompt

func WithSystemPrompt(systemPrompt string) GenerateOption

WithSystemPrompt sets the system prompt for the LLM.

func WithTemperature

func WithTemperature(temperature float64) GenerateOption

WithTemperature sets the temperature of the LLM. A higher temperature will result in more creative and varied responses. Anthropic models and models that use fixed sampling values (for example Gemini 3.6 and later) do not get the temperature, and a warning is logged.

func WithToolCallTimeout

func WithToolCallTimeout(timeout time.Duration) GenerateOption

WithToolCallTimeout sets the maximum duration a single tool call may run before its context is cancelled. Pass 0 to disable the timeout. If the option is not set at all, DefaultToolCallTimeout (5 minutes) applies.

func WithToolkits

func WithToolkits(toolkits ...Toolkit) GenerateOption

WithToolkits sets tools from one or more toolkits.

func WithTools

func WithTools(tools ...ToolDef) GenerateOption

WithTools sets the tools that the LLM can use.

func WithWebSearch

func WithWebSearch(webSearch bool) GenerateOption

WithWebSearch enables web search tool calls.

type ImageLimits added in v0.13.0

type ImageLimits struct {
	// MediaTypes lists the image media types the provider accepts, for
	// example "image/png". Empty means not known.
	MediaTypes []string `json:"media_types,omitempty"`
	// MaxBytes is the largest image, in bytes of BinaryPart.Data (before
	// base64 encoding).
	MaxBytes int64 `json:"max_bytes,omitempty"`
	// MaxWidth and MaxHeight are the largest image size in pixels that the
	// provider accepts. Larger images are rejected, not scaled down.
	MaxWidth  int `json:"max_width,omitempty"`
	MaxHeight int `json:"max_height,omitempty"`
	// MaxCount is the largest number of images in one request.
	MaxCount int `json:"max_count,omitempty"`
	// ManyImages is the number of images in one request above which the
	// lower ManyMaxWidth and ManyMaxHeight apply. Zero means no such rule.
	ManyImages   int `json:"many_images,omitempty"`
	ManyMaxWidth int `json:"many_max_width,omitempty"`
	// ManyMaxHeight is the pixel height limit when ManyImages applies.
	ManyMaxHeight int `json:"many_max_height,omitempty"`
}

ImageLimits are the documented provider limits for image input. They are not in models.dev data; this package sets them for each provider (see README "Attachments"). A zero field means no limit is known. CheckMessages and GenerateContent reject an image that goes above a limit with ErrAttachmentTooLarge or ErrUnsupportedMediaType.

type ImagePart

type ImagePart struct {
	URL string
}

func NewImagePart

func NewImagePart(url string) *ImagePart

type InputError added in v0.13.0

type InputError struct {
	// Model is the qualified model name, for example "anthropic/claude-opus-4-5".
	Model string
	// Message is the index of the message in the list that was checked.
	Message int
	// Part is the index of the part in Message.Parts.
	Part int
	// Name is BinaryPart.Name, or "" when the part has no name.
	Name string
	// MediaType is the media type of the part, or "" for an *ImagePart.
	MediaType string
	// Modality is the input modality of the part: "image", "pdf", "audio",
	// "video", "text", or "" when it is not known.
	Modality string
	// Detail is a human-readable description of the problem.
	Detail string
	// Err is the sentinel error for the problem.
	Err error
}

InputError tells which message part a model cannot accept. Err is one of ErrUnsupportedModality, ErrUnsupportedMediaType, ErrAttachmentTooLarge or ErrInvalidAttachment, so errors.Is works on the wrapped chain:

if errors.Is(err, llms.ErrUnsupportedModality) { ... }

Use errors.As to get the location of the part.

func (*InputError) Error added in v0.13.0

func (e *InputError) Error() string

func (*InputError) Unwrap added in v0.13.0

func (e *InputError) Unwrap() error

type Limits

type Limits struct {
	Context int `json:"context,omitempty"`
	// Input is the maximum prompt size when it is lower than Context.
	Input  int `json:"input,omitempty"`
	Output int `json:"output,omitempty"`
	// Image is the provider's limits for image input.
	Image ImageLimits `json:"image,omitzero"`
	// PDF is the provider's limits for PDF input.
	PDF PDFLimits `json:"pdf,omitzero"`
}

Limits describes the token and attachment limits for a model.

type LivenessNotice added in v0.9.0

type LivenessNotice struct {
	// Provider is the GenAI system that sent data, e.g. "anthropic".
	Provider string
	// Model is the model ID that was requested.
	Model string
	// Idle is how long the call was quiet before this data arrived. Only
	// gaps of at least LivenessQuietThreshold are reported.
	Idle time.Duration
	// StallTimeout is the gap that would have failed the call, or 0 when
	// stall detection is off for this phase.
	StallTimeout time.Duration
	// Phase says whether the call was waiting for the response to start or
	// reading a response that had already started.
	Phase StallPhase
}

LivenessNotice reports that data arrived from the provider after a quiet gap. It is given to the callback registered with WithLivenessNotify.

type LivenessNotifyFunc added in v0.9.0

type LivenessNotifyFunc func(ctx context.Context, n LivenessNotice)

LivenessNotifyFunc is called when data arrives after a quiet gap.

type LoopResult

type LoopResult struct {
	StopReason StopReason
	Steps      int
	FinalText  string
	Messages   []*Message
	Usage      TurnUsage
}

LoopResult is the trajectory recovered from a step-limited run via MaxStepsError.

type Manager

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

Manager is used to get access to different LLM models, with support for dynamic selection based on environment variables.

func NewManager

func NewManager(opts ...ManagerOption) (*Manager, error)

func (*Manager) GetModel

func (m *Manager) GetModel(ctx context.Context, name string) (Model, error)

func (*Manager) RegisterAlias

func (m *Manager) RegisterAlias(alias, target string)

func (*Manager) RegisterOverride

func (m *Manager) RegisterOverride(alias, target string)

RegisterOverride sets a model override that takes priority over both environment variables and registered aliases. Use this for explicit user-provided flags (e.g. CLI --interactive-model).

func (*Manager) RegisterSubParser

func (m *Manager) RegisterSubParser(name string, config SubParserConfig)

RegisterSubParser registers a sub-parser config by name. Struct fields tagged with `jsonstream:"<name>"` will use this config when building streaming schemas for models created by this Manager.

func (*Manager) ResolveModelName

func (m *Manager) ResolveModelName(name string) (string, error)

ResolveModelName resolves an alias to the actual provider/model name.

type ManagerOption

type ManagerOption func(*Manager) error

ManagerOption configures a Manager during construction.

func WithManagerCredentials added in v0.6.0

func WithManagerCredentials(credentials CredentialSource) ManagerOption

WithManagerCredentials sets the CredentialSource used to authenticate requests for the models this Manager creates. Defaults to EnvCredentials, which reads the conventional per-provider environment variables.

The source is consulted once per model at construction and then once per outbound HTTP request, so credentials can rotate without the models being rebuilt. See CredentialSource for the full contract.

func WithManagerLogger

func WithManagerLogger(logger *slog.Logger) ManagerOption

WithManagerLogger sets the logger used by the Manager and the models it creates. Defaults to slog.Default() if not provided.

func WithManagerMetrics

func WithManagerMetrics(metrics *Metrics) ManagerOption

WithManagerMetrics sets the metrics used by the Manager and the models it creates. Defaults to NewNoopMetrics() if not provided.

func WithManagerMetricsRecorder added in v0.15.0

func WithManagerMetricsRecorder(recorder MetricsRecorder) ManagerOption

WithManagerMetricsRecorder sets a MetricsRecorder that receives the statistics of every call made through the models this Manager creates. Use it to keep a total, for example of token usage and cost, that does not depend on the context of each call.

A recorder set with WithMetrics on a context also receives the calls made with that context. The statistics of such a call go to the two recorders, so the context recorder holds a subset of the Manager recorder. Do not add the two together. If the same recorder instance is set in the two places, it receives each call one time.

The recorder is called from many goroutines and must be safe for concurrent use. No recorder is set by default.

type MaxStepsError

type MaxStepsError struct {
	Result *LoopResult
}

MaxStepsError is returned by GenerateContent / Session.Result when the loop hits its step budget. Callers can errors.As it to recover the trajectory accumulated before the budget ran out.

func (*MaxStepsError) Error

func (e *MaxStepsError) Error() string

type MaxTokensError

type MaxTokensError struct {
	Result *LoopResult
}

MaxTokensError is returned by GenerateContent / Session.Result when the final turn stopped because the model hit the output-token cap mid-generation. Callers can errors.As it to recover the partial text and usage that was produced before truncation.

func (*MaxTokensError) Error

func (e *MaxTokensError) Error() string

type Message

type Message struct {
	Role  Role
	Parts []MessagePart
	Cache bool
}

func NewMessage

func NewMessage(role Role, parts ...MessagePart) *Message

func (*Message) MarshalJSON

func (m *Message) MarshalJSON() ([]byte, error)

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(data []byte) error

func (*Message) WithCache

func (m *Message) WithCache(cache bool) *Message

type MessagePart

type MessagePart interface {
	// contains filtered or unexported methods
}

type Metrics

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

Metrics provides standardized GenAI metrics for the LLM implementations.

Conventions and attribute names taken from the the specification at: https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-metrics/

func NewMetrics

func NewMetrics(meter metric.Meter) (*Metrics, error)

NewMetrics creates a new Metrics instance with all the standardized GenAI metrics.

func NewNoopMetrics

func NewNoopMetrics() *Metrics

NewNoopMetrics creates a Metrics instance with no-op implementations.

func (*Metrics) RecordCall

func (m *Metrics) RecordCall(
	ctx context.Context,
	system GenAISystem,
	operation GenAIOperation,
	model GenAIModel,
	inputTokens int64,
	outputTokens int64,
	cachedReadTokens int64,
	cachedWriteTokens int64,
)

RecordCall records token usage for a single API call to a GenAI system.

func (*Metrics) RecordCallDuration

func (m *Metrics) RecordCallDuration(ctx context.Context, system GenAISystem, operation GenAIOperation, model GenAIModel, duration time.Duration, errorType GenAIErrorType)

RecordCallDuration records the duration of a request to GenAI systems.

func (*Metrics) RecordGenerateRequest

func (m *Metrics) RecordGenerateRequest(ctx context.Context, system GenAISystem, operation GenAIOperation, model GenAIModel)

RecordGenerateRequest records a new request to generate content with LLMs.

func (*Metrics) RecordTimeToFirstToken

func (m *Metrics) RecordTimeToFirstToken(ctx context.Context, system GenAISystem, operation GenAIOperation, model GenAIModel, duration time.Duration)

RecordTimeToFirstToken records the time to generate the first token for a GenAI response.

type MetricsRecorder

type MetricsRecorder interface {
	RecordSuccess(serviceName string, collector Collector)
	RecordFailure(serviceName string, collector Collector)
}

MetricsRecorder aggregates statistics from multiple service calls.

func GetMetrics

func GetMetrics(ctx context.Context) MetricsRecorder

GetMetrics retrieves the MetricsRecorder from the context, or nil if not present.

type Model

type Model interface {
	GenerateContent(ctx context.Context, opts ...GenerateOption) (Result, error)
}

Model represents an LLM API that can be used to generate content.

type ModelInfo

type ModelInfo struct {
	Cost       Cost         `json:"cost"`
	Limits     Limits       `json:"limits"`
	Caps       Capabilities `json:"capabilities"`
	Modalities []string     `json:"modalities,omitempty"` // input modalities: text/image/audio/pdf/video
	Family     string       `json:"family,omitempty"`
	Knowledge  string       `json:"knowledge,omitempty"` // training cutoff
	Released   string       `json:"released,omitempty"`  // release date
	// Status is empty for generally available models, otherwise one of
	// ModelStatusAlpha, ModelStatusBeta or ModelStatusDeprecated.
	Status string `json:"status,omitempty"`
}

ModelInfo holds the metadata for a model: pricing, token limits, and the capabilities that gate what providers send to the API.

It is built from models.dev data (embedded at build time, or loaded with LoadModelInfo, LLM_MODELS_FILE or RefreshModelInfo), from RegisterModelInfo, and for Anthropic models also from the Anthropic Models API at runtime.

func LookupModelInfo

func LookupModelInfo(qualifiedName string) (ModelInfo, bool)

LookupModelInfo returns the ModelInfo for a fully qualified model name (e.g. "anthropic/claude-haiku-4-5" or "openrouter/google/gemini-2.5-flash-lite"). Entries from RegisterModelInfo win over models.dev data. The boolean is false when the model is not known, in which case the zero ModelInfo is returned and callers should treat the model permissively.

func ModelInfoOf added in v0.13.0

func ModelInfoOf(model Model) (ModelInfo, bool)

ModelInfoOf returns the ModelInfo that model uses to gate requests, without a network call. For Anthropic models it includes the Models API data when an earlier request got it. The boolean is false when the model is not known or when this package did not create the Model.

type PDFLimits added in v0.13.0

type PDFLimits struct {
	// MaxBytes is the largest PDF, in bytes of BinaryPart.Data (before
	// base64 encoding).
	MaxBytes int64 `json:"max_bytes,omitempty"`
	// MaxPages is the largest number of pages in one request.
	MaxPages int `json:"max_pages,omitempty"`
}

PDFLimits are the documented provider limits for PDF input. A zero field means no limit is known. CheckMessages and GenerateContent reject a PDF above MaxBytes with ErrAttachmentTooLarge. They do not count pages, so check MaxPages yourself when you know the page count.

type PlanInfo

type PlanInfo struct {
	// Step is the 1-indexed model turn this info describes.
	Step int
	// Output is what the model produced this turn.
	Output TurnOutput
	// ToolCalls == Output.ToolCalls, surfaced for convenience.
	ToolCalls []ToolCall
	// NeedsTools is true when the caller must run tools then StepObserve.
	NeedsTools bool
	// Exec is the live execution tracker.
	Exec ExecutionContext
}

PlanInfo is the result of the model-call phase of a step.

type PricingManager

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

PricingManager resolves model pricing.

Pricing comes from the model info (see LookupModelInfo). A user-supplied override file (LLM_PRICING_FILE) takes precedence, which is how manual pricing corrections are handled. The override file is a JSON object mapping the fully qualified model name to a Cost value, with the models.dev key names ("input", "output", "cache_read", "cache_write", "reasoning"). Tier breakdown counters are recorded from the model info, so tiers in the override file only change the price of tiers the model info also has.

func NewPricingManager

func NewPricingManager(logger *slog.Logger) *PricingManager

NewPricingManager creates a new PricingManager. It loads pricing overrides from the file specified in LLM_PRICING_FILE, or defaults to llms-pricing.json in the current directory. When the file is absent or fails to load, pricing falls back to the model info.

func (*PricingManager) CalculateCosts

func (pm *PricingManager) CalculateCosts(stats CallStats) map[string]float64

CalculateCosts calculates the total cost for each service based on token usage. Returns a map of service name to total cost in USD.

Requests larger than a cost tier are billed at the tier price; see CostTier.

func (*PricingManager) GetModelPricing

func (pm *PricingManager) GetModelPricing(serviceName string) *Cost

GetModelPricing returns the pricing for a specific model.

Resolution order: (1) override file entry, (2) model info, (3) nil when nothing is known.

type ReasoningMode added in v0.9.0

type ReasoningMode int

ReasoningMode selects whether a model reasons (thinks) before answering.

const (
	// ReasoningDefault sends no reasoning setting, so the provider's default
	// for the model applies. Some models reason by default (for example
	// Claude Opus 5 and later, Gemini 2.5 and 3, most OpenAI reasoning
	// models) and some do not.
	ReasoningDefault ReasoningMode = iota
	// ReasoningOff turns reasoning off. Models that cannot turn reasoning
	// off use their lowest effort tier instead, with a warning.
	ReasoningOff
	// ReasoningOn turns reasoning on. Without WithReasoningEffort the
	// provider's default depth applies, except for OpenAI and OpenRouter,
	// which use EffortMedium.
	ReasoningOn
)

type RefusalError

type RefusalError struct {
	Result *LoopResult
}

RefusalError is returned by GenerateContent / Session.Result when the model itself wrote a refusal (see StopReasonRefusal). errors.As recovers any partial trajectory the model emitted before refusing. A provider safety system that blocks the call gives a *ContentPolicyError instead.

func (*RefusalError) Error

func (e *RefusalError) Error() string

type ResponseSchema

type ResponseSchema struct {
	Name      string
	Schema    any                       // *jsonschema.Schema
	ParseInto func([]byte) (any, error) // For parsing into typed result
}

ResponseSchema contains the JSON schema for structured output.

type Result

type Result interface {
	// contains filtered or unexported methods
}

Result is returned by GenerateContent.

type RetryNotice added in v0.8.0

type RetryNotice struct {
	// Provider is the GenAI system that failed, e.g. "anthropic".
	Provider string
	// Model is the model ID that was requested.
	Model string
	// Attempt is the 1-based number of the attempt that just failed.
	Attempt int
	// MaxAttempts is the total number of attempts allowed, which is
	// MaxRetries+1.
	MaxAttempts int
	// Delay is how long the library waits before the next attempt.
	Delay time.Duration
	// StatusCode is the HTTP status of the failed attempt, or 0 when the
	// provider did not report one.
	StatusCode int
	// RetryAfter is the server hint, after RetryAfterCap is applied. It is 0
	// when the server gave no hint. The backoff policy decides whether to
	// use it, so Delay can differ.
	RetryAfter time.Duration
	// HasRetryAfter is true when the server gave a hint.
	HasRetryAfter bool
	// Err is the error that caused the retry.
	Err error
}

RetryNotice describes an attempt that failed and the pause that comes before the next attempt. It is given to the callback registered with WithRetryNotify.

type RetryNotifyFunc added in v0.8.0

type RetryNotifyFunc func(ctx context.Context, notice RetryNotice)

RetryNotifyFunc is called after a failed attempt, just before the library waits to try again.

type Role

type Role string
const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
)

type SearchToolArgs

type SearchToolArgs interface {
	Query() string
}

type SearchToolResult

type SearchToolResult interface {
	Count() int
	Items() []SearchToolResultItem
}

type SearchToolResultItem

type SearchToolResultItem interface {
	Title() string
	URL() string
}

type Session

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

Session is a driveable agentic loop. Each call to Step advances exactly one model turn; the caller drives the loop and may interpose between turns (inspect/approve tool calls, inject a message, fork a sub-agent). GenerateContent is a Session run to completion internally.

A Session is not safe for concurrent use. All methods must be called from a single goroutine. To inject messages from another goroutine (e.g. an operator-steering UI), send them over a channel and have the driving goroutine call Inject between Steps.

func NewSession

func NewSession(ctx context.Context, m Model, options ...GenerateOption) (*Session, error)

NewSession creates a driveable Session for the given model. The model must be one of the built-in providers (Anthropic, OpenAI/OpenRouter, Google). The ctx is used for session-creation work such as ConditionalTool availability checks; it is not retained for later turns.

func (*Session) Inject

func (s *Session) Inject(msgs ...*Message)

Inject appends caller messages as a user turn before the next Step.

func (*Session) Messages

func (s *Session) Messages() []*Message

Messages returns the neutral accumulated transcript.

func (*Session) Result

func (s *Session) Result() (Result, error)

Result returns the terminal Result for the session. It returns a *MaxStepsError when the run was step-limited, a *MaxTokensError when the final turn was truncated by the output-token cap, a *RefusalError when the model declined to produce content, or the underlying error if the run failed.

func (*Session) ResumeForToolResults

func (s *Session) ResumeForToolResults(calls []ToolCall) error

ResumeForToolResults puts a Session reconstructed from a persisted transcript (replayed via WithMessages) into the awaiting-observe state for the assistant turn's tool calls, so StepObserve can feed outcomes back without a model call in this process. It does not consume step budget and must be called on a ready, non-done session.

func (*Session) Retryable added in v0.9.0

func (s *Session) Retryable() bool

Retryable reports whether the session's last failure can be retried without replaying output: the model turn failed transiently before any of its output reached the caller, so calling StepPlan (or Step) again retries that turn against the same transcript. It is false on a clean session and after a failure that ended the run.

A retried turn starts a fresh model call, so a caller watching the stream sees another StreamingEventMessageStart for it.

The session also stays usable after two failures for which Retryable is false. Step returns done == false for them:

  • A transient failure after some output of the turn already reached the streaming callback (IsUnavailable is true and the error wraps ErrStreamingPartialOutput). The caller discards that output and calls StepPlan (or Step) again to try the turn from the start.
  • A content policy block. See IsContentPolicy.

func (*Session) RunTools

func (s *Session) RunTools(ctx context.Context, calls []ToolCall) ([]ToolOutcome, error)

RunTools executes the given tool calls in parallel using the session's tool registry, preserving call order in the returned slice. Cancellation mid-fan-in surfaces ctx.Err(). The session's ExecutionContext is attached to ctx so tools (and any sub-agents they spawn) can see it.

RunTools is the standard tool-execution path used by Step. Call it directly when you want to interpose between StepPlan and StepObserve — for example, to gate or audit calls before they run — while still using the session's tool dispatch and parallelism.

func (*Session) Snapshot added in v0.5.0

func (s *Session) Snapshot() SessionSnapshot

Snapshot captures the session's durable state for persistence and later restore via WithSnapshot. It is safe to call between turns (phaseReady) or after a StepPlan that yielded tool calls but before StepObserve (awaiting-tools). Snapshotting a done or failed session is allowed but not meaningfully resumable. ThinkingTokens is not tracked cumulatively and is reported as zero, matching loopResult.

func (*Session) Step

func (s *Session) Step(ctx context.Context) (StepInfo, bool, error)

Step advances one model turn: Turn.Next -> (if tool calls) parallel doToolCall fan-out -> Turn.Observe. It returns done=true when the model ends its turn with no tool calls, the step budget is exhausted, or ctx is cancelled. A non-nil error is returned for genuine failures (provider error, context cancellation); step-limit termination is reported via done=true with Result() returning a *MaxStepsError.

An error with done=false is a model failure the session survived: the turn can be attempted again by calling Step once more. This is a transient failure (see IsUnavailable, IsRetryable and Session.Retryable) or a content policy block (see IsContentPolicy). When the error wraps ErrStreamingPartialOutput, some output of the failed turn already reached the streaming callback; the caller discards it before it tries again.

func (*Session) StepObserve

func (s *Session) StepObserve(ctx context.Context, outcomes []ToolOutcome) (StepInfo, bool, error)

StepObserve completes a step: it appends the tool-outcome message to the neutral transcript and folds the outcomes into the provider-native history (Turn.Observe for a live plan, Turn.ObserveToolResults for a Session reconstructed via ResumeForToolResults). Call exactly once after a StepPlan / ResumeForToolResults that yielded tool calls. It emits no streaming events. StepObserve is not a model call and does not consume step budget.

func (*Session) StepPlan

func (s *Session) StepPlan(ctx context.Context) (PlanInfo, bool, error)

StepPlan runs exactly one model turn (Turn.Next) WITHOUT executing tools. NeedsTools == len(ToolCalls)>0 && !done. When NeedsTools is false the session is done (terminal/budget/ctx) and StepObserve MUST NOT be called. Conversely, when NeedsTools is true the caller MUST run the tools and then call StepObserve exactly once.

func (*Session) StopReason

func (s *Session) StopReason() StopReason

StopReason returns the most recent stop reason observed by the session.

type SessionPhase added in v0.5.0

type SessionPhase string

SessionPhase is the serializable phase of a Session at snapshot time. It is the stable, public counterpart of the internal stepPhase.

const (
	// SessionPhaseReady means the session is between turns: the next call on a
	// restored session is StepPlan (or Step).
	SessionPhaseReady SessionPhase = "ready"
	// SessionPhaseAwaitingTools means the model requested tool calls that have
	// not yet been observed: the next call on a restored session is StepObserve
	// with the outcomes of SessionSnapshot.PendingCalls (no model call).
	SessionPhaseAwaitingTools SessionPhase = "awaiting_tools"
)

type SessionSnapshot added in v0.5.0

type SessionSnapshot struct {
	// Transcript is the neutral accumulated message history (Session.Messages).
	Transcript []*Message `json:"transcript"`
	// Step is the number of model turns already consumed, so a restored
	// session continues against the same WithMaxSteps budget instead of
	// resetting to zero.
	Step int `json:"step"`
	// Phase is the session phase at snapshot time.
	Phase SessionPhase `json:"phase"`
	// PendingCalls carries the tool calls awaiting outcomes; set only when
	// Phase is SessionPhaseAwaitingTools.
	PendingCalls []ToolCall `json:"pendingCalls,omitempty"`
	// Usage is the cumulative token usage so cost tracking survives the
	// round-trip.
	Usage TurnUsage `json:"usage"`
}

SessionSnapshot is the durable, JSON-serializable state of a Session. It captures everything needed to reconstruct an in-flight session in another process (or after a restart): the neutral transcript, the consumed step budget, the plan/observe phase plus any pending tool calls, and cumulative token usage. Restore it with WithSnapshot.

Snapshot a session at a phaseReady boundary (between turns) or at an awaiting-tools boundary (after StepPlan yielded tool calls, before StepObserve). A done or failed session's snapshot is not meaningfully resumable.

type StallError added in v0.9.0

type StallError struct {
	// Provider is the GenAI system that went silent, e.g. "anthropic".
	Provider string
	// Model is the model ID that was requested, or "" when not known.
	Model string
	// Phase says whether the call was waiting for the response to start or
	// reading a response that had already started.
	Phase StallPhase
	// Timeout is the budget that was exceeded.
	Timeout time.Duration
}

StallError reports a model call that stopped producing data for longer than the configured budget. It is what turns a silent hang into a failed attempt: the retry loop treats it as retryable, so it is reported through WithRetryNotify and, when the attempts run out, surfaces wrapped in an UnavailableError like any other transient provider failure.

The budgets come from WithStallTimeout (quiet time inside a response) and WithRequestTimeout (time to the first byte of a response). Both are off unless set.

A StallError is also reported, without any option set, when an HTTP/2 connection to the provider stops answering health check pings. The connection is then closed after about 30 seconds of silence, and Timeout is that health check window. Pings are answered by the nearest HTTP/2 server, which is often a CDN or a proxy, so they find a dead network path but not a stuck provider behind a healthy front end. WithStallTimeout finds both.

func (*StallError) Error added in v0.9.0

func (e *StallError) Error() string

func (*StallError) Unwrap added in v0.9.0

func (e *StallError) Unwrap() error

type StallPhase added in v0.9.0

type StallPhase string

StallPhase says where a model call went silent.

const (
	// StallPhaseResponse means the request was sent but the provider never
	// returned response headers. For a streaming provider this is the wait
	// for the stream to open; for a non-streaming one it covers the whole
	// generation, because nothing arrives until the answer is complete.
	StallPhaseResponse StallPhase = "response"
	// StallPhaseStream means the response had started and then went quiet.
	// Keepalives count as data, so a model that is merely thinking does not
	// reach this state — a dead connection or a wedged generation does.
	StallPhaseStream StallPhase = "stream"
)

type StepInfo

type StepInfo struct {
	// Step is the 1-indexed model turn this info describes.
	Step int
	// Output is what the model produced this turn.
	Output TurnOutput
	// Outcomes are the results of this turn's tool calls (nil if none).
	Outcomes []ToolOutcome
	// Exec is the live execution tracker.
	Exec ExecutionContext
}

StepInfo describes the result of a single Session.Step.

type StopReason

type StopReason string

StopReason describes why a model turn (or the loop) stopped.

const (
	StopReasonEndTurn   StopReason = "end_turn"
	StopReasonToolUse   StopReason = "tool_use"
	StopReasonMaxTokens StopReason = "max_tokens"
	// StopReasonRefusal means that the model itself wrote a refusal, for
	// example an OpenAI refusal content part. A provider safety system that
	// blocks the call does not give this stop reason: the turn fails with a
	// *ContentPolicyError.
	StopReasonRefusal StopReason = "refusal"
	// StopReasonMaxSteps is loop-level: it is set by Session when the
	// configured step budget is exhausted, never by a Turn.
	StopReasonMaxSteps StopReason = "max_steps"
)

type StreamSchemaOptions

type StreamSchemaOptions struct {
	// SubParsers maps field paths to their sub-parser configurations.
	// Field paths use dot notation for nested fields (e.g., "response.content").
	// Programmatic configuration overrides struct tag configuration.
	SubParsers map[string]SubParserConfig
	// contains filtered or unexported fields
}

StreamSchemaOptions holds configuration options for structured streaming schema generation.

type StreamScope

type StreamScope struct {
	AgentID string
	RunID   string
}

StreamScope identifies which agent/run a stream of events belongs to. It is carried out-of-band on the context so sub-agents can be distinguished without changing the StreamingEvent types.

func GetStreamScope

func GetStreamScope(ctx context.Context) (StreamScope, bool)

GetStreamScope retrieves the StreamScope from the context, if present.

type StreamingEvent

type StreamingEvent interface {
	// contains filtered or unexported methods
}

type StreamingEventCitation

type StreamingEventCitation struct {
	Title string
	URL   string
}

type StreamingEventMessageEnd

type StreamingEventMessageEnd struct {
	Final bool
}

StreamingEventMessageEnd signals the end of an LLM response message. Final is true when this is the last message in an agentic loop (no more tool calls will follow). Intermediate replies have Final set to false.

type StreamingEventMessageStart

type StreamingEventMessageStart struct{}

StreamingEventMessageStart signals the beginning of a new LLM response message.

type StreamingEventTextChunk

type StreamingEventTextChunk struct {
	Text string
}

type StreamingEventThinking

type StreamingEventThinking struct {
	Text string
}

StreamingEventThinking streams thinking/reasoning token chunks.

type StreamingEventToolError added in v0.2.0

type StreamingEventToolError struct {
	ID     string
	ToolID string
	Error  error
}

StreamingEventToolError is the terminal event for a tool call that failed, emitted in place of StreamingEventToolResult. It always follows the matching StreamingEventToolUse (paired by ID), so consumers tracking the tool-call lifecycle can move the call out of a running state on failure. Error carries the failure (including tool panics, surfaced as a VisibleToolError).

Because Go type switches are not exhaustiveness-checked, a consumer that does not handle this event will leave a failed call pinned to its running state; handle it alongside StreamingEventToolResult.

type StreamingEventToolResult

type StreamingEventToolResult struct {
	ID     string
	ToolID string
	Result any
}

type StreamingEventToolUse

type StreamingEventToolUse struct {
	ID        string
	ToolID    string
	Arguments any
}

type StreamingFunc

type StreamingFunc func(ctx context.Context, event StreamingEvent) error

StreamingFunc is a function that will be called when the LLM is streaming content.

type StructuredResult

type StructuredResult[T any] struct {
	Data T
	Raw  string // Original JSON for debugging
}

StructuredResult contains parsed JSON response.

type StructuredStreamingFunc

type StructuredStreamingFunc func(ctx context.Context, event jsonstream.Event) error

StructuredStreamingFunc is called with jsonstream events during structured streaming.

type StructuredStreamingOption

type StructuredStreamingOption func(*StreamSchemaOptions)

StructuredStreamingOption configures options for structured streaming.

func ConfigureSubParser

func ConfigureSubParser(fieldPath string, config SubParserConfig) StructuredStreamingOption

ConfigureSubParser sets a sub-parser config for a specific field. This overrides any struct tag configuration for that field. Field paths use dot notation for nested fields (e.g., "response.content").

type SubParserConfig

type SubParserConfig interface {
	CreateSubParser() jsonstream.SubParser
}

SubParserConfig configures a sub-parser for a streaming field.

type TextPart

type TextPart struct {
	Text string
}

func NewTextPart

func NewTextPart(text string) *TextPart

type TextResult

type TextResult struct {
	Text string
}

TextResult contains plain text response.

type ThinkingBlock

type ThinkingBlock struct {
	Text      string
	Signature string
	Data      string
	Redacted  bool
}

ThinkingBlock is one neutral extended-thinking/reasoning block produced by the model. Signature is the provider-opaque cryptographic signature (Anthropic) that must be replayed verbatim; Data carries the encrypted payload of a redacted thinking block when Redacted is true.

type ThinkingPart

type ThinkingPart struct {
	Text      string
	Signature string
	Redacted  bool
	Data      string
}

ThinkingPart carries a model extended-thinking/reasoning block in neutral form. Signature is the provider-opaque cryptographic signature (Anthropic) that must be replayed verbatim alongside tool use; Redacted/Data cover an encrypted redacted_thinking block. It appears in an assistant message, before any text or tool-call parts.

func NewThinkingPart

func NewThinkingPart(text, signature string) *ThinkingPart

type TokenRange added in v0.9.0

type TokenRange struct {
	Min int `json:"min,omitempty"`
	Max int `json:"max,omitempty"`
}

TokenRange is an inclusive token count range. A zero Max means no upper limit is known.

type Tool

type Tool[I any, O any] interface {
	// Name is the unique name of the tool.
	Name() string

	// Description is a short description of the tool. Used by the LLM to
	// determine if the tool is relevant to the current task.
	Description() string

	// Schema is the schema of the tool's input. Should be a pointer to a struct.
	Schema() I

	// Execute is the function that will be called when the tool is invoked.
	Execute(ctx context.Context, input I) (O, error)

	// Render turns a successful Execute output into the result delivered to
	// the model. Use TextResult for the common text-only case, or set
	// Attachments to deliver images/binary content.
	Render(O) ToolResult
}

Tool is used to describe a tool that can be used by the LLM.

type ToolCall

type ToolCall struct {
	ID        string
	Name      string
	Arguments string
}

ToolCall is a single tool invocation requested by the model. Arguments is the raw JSON arguments string as produced by the provider.

type ToolCallPart

type ToolCallPart struct {
	ID        string
	Name      string
	Arguments string
}

ToolCallPart is a tool invocation requested by the model. It appears in an assistant message and is paired with a ToolResultPart by ID. Arguments is the raw JSON arguments string as produced by the provider.

func NewToolCallPart

func NewToolCallPart(id, name, arguments string) *ToolCallPart

type ToolDef

type ToolDef interface {
	Name() string
	Description() string
	Schema() any
	Execute(ctx context.Context, in any) (any, error)
	Render(any) ToolResult
}

func NewToolDef

func NewToolDef[I any, O any](tool Tool[I, O]) ToolDef

type ToolOutcome

type ToolOutcome struct {
	ID    string
	Name  string
	Text  string
	Error error
	// Attachments are optional rich-content parts (*ImagePart / *BinaryPart)
	// produced by the tool's Render, delivered to the model alongside Text.
	// Only meaningful on the success path (Error == nil).
	Attachments []MessagePart
}

ToolOutcome is the result of executing a ToolCall. Exactly one of Text or Error is meaningful: Error is non-nil when the call failed, otherwise Text holds the rendered tool result.

The full error is preserved in Error for callers and logs. The message sent to the model is produced by ModelError, which redacts internal detail unless the error chain contains a VisibleToolError.

func (ToolOutcome) ModelError

func (o ToolOutcome) ModelError() string

ModelError returns the message that should be sent to the model for this outcome. It returns "" when the call succeeded. When Error is non-nil but the chain contains no VisibleToolError, a generic placeholder is returned so internal details (paths, secrets, stack traces) are not leaked.

type ToolResult added in v0.5.0

type ToolResult struct {
	// Text is what the model reads as the tool result.
	Text string
	// Attachments are optional rich-content parts (*ImagePart / *BinaryPart)
	// delivered to the model alongside the textual result.
	Attachments []MessagePart
}

ToolResult is what a tool renders from a successful Execute. Text is what the model reads as the result; Attachments optionally carry rich content (*ImagePart / *BinaryPart) that is delivered to the model either natively (Anthropic tool-result blocks) or as a trailing synthetic user message (OpenAI / Google / OpenRouter).

Render only concerns the success path: errors continue to flow through ToolOutcome.Error / ModelError / VisibleToolError.

func TextToolResult added in v0.5.0

func TextToolResult(text string) ToolResult

TextToolResult is a convenience constructor for the common text-only tool result. (Named to avoid colliding with the TextResult Result type.)

func (ToolResult) WithBinary added in v0.5.0

func (r ToolResult) WithBinary(mediaType string, data []byte) ToolResult

WithBinary returns a copy of the result with a binary attachment appended, e.g. TextToolResult("rendered chart").WithBinary("image/png", png).

func (ToolResult) WithImage added in v0.5.0

func (r ToolResult) WithImage(url string) ToolResult

WithImage returns a copy of the result with an image attachment appended. It chains off TextToolResult (or a bare ToolResult{}) for the rich-content case, e.g. TextToolResult("done").WithImage("https://...").

type ToolResultPart

type ToolResultPart struct {
	ID    string
	Name  string
	Text  string
	Error string
	// Attachments are optional rich-content parts (*ImagePart / *BinaryPart)
	// produced by a tool alongside its textual result. They are delivered to
	// the model either natively (Anthropic) or via a trailing synthetic user
	// message (OpenAI / Google / OpenRouter).
	Attachments []MessagePart
}

ToolResultPart is the result of a tool invocation. It appears in a user message and is paired with its ToolCallPart by ID. Exactly one of Text or Error is meaningful: Error is non-empty when the call failed, otherwise Text holds the rendered tool result.

func NewToolResultPart

func NewToolResultPart(id, name, text, errText string) *ToolResultPart

func (*ToolResultPart) MarshalJSON added in v0.5.0

func (p *ToolResultPart) MarshalJSON() ([]byte, error)

func (*ToolResultPart) UnmarshalJSON added in v0.5.0

func (p *ToolResultPart) UnmarshalJSON(data []byte) error

type Toolkit

type Toolkit interface {
	Tools() []ToolDef
}

Toolkit is a composable collection of tools.

type Turn

type Turn interface {
	// Next performs exactly one model API call, emitting streaming events
	// (chunk/thinking/tooluse) internally, and returns the neutral output.
	Next(ctx context.Context) (TurnOutput, error)

	// Observe appends the assistant message and the tool results from this
	// turn to the provider-native history, ready for the next Next.
	Observe(ctx context.Context, out TurnOutput, outcomes []ToolOutcome) error

	// ObserveToolResults folds outcomes into native history WITHOUT appending
	// an assistant message — used when the assistant turn is already in native
	// history (a Session reconstructed via WithMessages where Next never ran
	// this process). calls carries the originating tool calls so providers
	// that pair results to calls can do so when no stashed response exists.
	ObserveToolResults(ctx context.Context, calls []ToolCall, outcomes []ToolOutcome) error

	// Inject queues caller-supplied messages to be appended before the next
	// Next call.
	Inject(msgs ...*Message)

	// FinalText returns the assistant text for the terminal turn, or the
	// accumulated jsonstream buffer when structured streaming is active.
	FinalText() string
}

Turn is the provider-specific seam: exactly one model API call. It is stateful and owns its provider-native message history, so provider bookkeeping (Anthropic cache-control, Google Part ordering, thinking signatures) never round-trips through neutral types.

type TurnOutput

type TurnOutput struct {
	Text       string
	Thinking   []ThinkingBlock
	ToolCalls  []ToolCall
	StopReason StopReason
	Usage      TurnUsage
}

TurnOutput is the neutral result of exactly one model API call.

type TurnUsage

type TurnUsage struct {
	// InputTokens is the count of fresh (uncached) prompt tokens — prompt
	// tokens that were neither read from nor written to the cache.
	InputTokens int64
	// OutputTokens is the count of generated output tokens.
	OutputTokens int64
	// CachedReadTokens is the count of prompt tokens served from the cache,
	// billed at the cache-read rate. Disjoint from InputTokens.
	CachedReadTokens int64
	// CachedWriteTokens is the count of prompt tokens written to the cache when
	// creating a new entry, billed at the cache-write rate. Reported only by
	// providers with explicit caching (Anthropic); zero for providers whose
	// caching is implicit. Disjoint from InputTokens.
	CachedWriteTokens int64
	// ThinkingTokens is the count of reasoning/thinking tokens when the provider
	// reports them separately.
	ThinkingTokens int64
}

TurnUsage carries per-turn token accounting in neutral form.

The prompt-token buckets are disjoint: every prompt token is counted in exactly one of InputTokens, CachedReadTokens, or CachedWriteTokens. So the total number of prompt tokens processed for a turn is:

InputTokens + CachedReadTokens + CachedWriteTokens

This mirrors Anthropic's native usage accounting. Providers whose APIs instead report a single prompt total with the cached tokens nested inside it (Google, OpenAI, OpenRouter) are normalized to this disjoint form before TurnUsage is populated, so InputTokens is always *uncached* input regardless of provider. Keeping the buckets disjoint is what makes cost correct: cached tokens are billed once at the (cheaper) cache rate, never double-counted at the full input rate as well.

type UnavailableError

type UnavailableError struct {
	Provider      string
	Model         string
	StatusCode    int
	RetryAfter    time.Duration
	HasRetryAfter bool
	Attempts      int
	PartialOutput bool
	PartialUsage  *TurnUsage
	Cause         error
}

UnavailableError is the structured error returned by providers when a generation fails with a transient unavailability condition (rate limit, overload, server error). Callers use errors.As to recover it from a wrapped error chain.

Fields:

  • Provider: the GenAI system (e.g. "openai", "anthropic"), or "" if not stamped.
  • Model: the model ID requested, or "" if not stamped.
  • StatusCode: HTTP status when known, 0 otherwise (e.g. an overload or rate limit that Anthropic or OpenAI sent inside an open stream).
  • RetryAfter: the server's Retry-After hint (after RetryAfterCap is applied), or 0 if no hint was provided. This is the raw hint, not what the SDK actually slept (jitter/cap may differ); outer-loop schedulers want the raw hint.
  • HasRetryAfter: true when the server provided a hint.
  • Attempts: number of attempts actually made (>=1). llms-go owns the retry loop for every provider, so this count is exact.
  • PartialOutput: true when at least one content event was dispatched to StreamingFunc before the stream errored.
  • PartialUsage: usage accumulated up to the point of a mid-stream failure, if the provider reported any. Nil when no usage was seen before the stream errored. Surface this to cost accounting so the tokens already generated (and billed) are not silently dropped.

func (*UnavailableError) Error

func (e *UnavailableError) Error() string

func (*UnavailableError) Unwrap

func (e *UnavailableError) Unwrap() error

type VisibleToolError

type VisibleToolError struct {
	Message string
}

VisibleToolError marks an error as safe to surface to the model in the tool-result block. Tools that want the model to read a specific message (for self-correction, etc.) should return a VisibleToolError directly or wrap one in a chain via fmt.Errorf("...: %w", ...).

Any error that does not contain a VisibleToolError in its chain is reduced to a generic placeholder when rendered for the model; the full error remains in ToolOutcome.Error for callers and logs.

func NewVisibleToolError

func NewVisibleToolError(format string, args ...any) *VisibleToolError

NewVisibleToolError returns a VisibleToolError with a formatted message.

func (*VisibleToolError) Error

func (e *VisibleToolError) Error() string

Directories

Path Synopsis
cmd
genmodelinfo command
Command genmodelinfo regenerates modelinfo_data.json.gz from models.dev.
Command genmodelinfo regenerates modelinfo_data.json.gz from models.dev.
examples
agent command
Command agent demonstrates the driveable Session API: the caller advances the agentic loop one model turn at a time, inspects what the model did, can Inject operator steering between turns, and uses the lightweight sub-agent pattern (a tool whose Execute calls another model with WithParentExecution so its token/step spend rolls up to the parent).
Command agent demonstrates the driveable Session API: the caller advances the agentic loop one model turn at a time, inspects what the model did, can Inject operator steering between turns, and uses the lightweight sub-agent pattern (a tool whose Execute calls another model with WithParentExecution so its token/step spend rolls up to the parent).
basic command
Command basic demonstrates the simplest possible text generation with llms-go: resolve a model through a Manager and ask it a question.
Command basic demonstrates the simplest possible text generation with llms-go: resolve a model through a Manager and ask it a question.
streaming command
Command streaming demonstrates streaming a response token-by-token, including reasoning/thinking tokens when the model supports them.
Command streaming demonstrates streaming a response token-by-token, including reasoning/thinking tokens when the model supports them.
structured command
Command structured demonstrates typed structured output.
Command structured demonstrates typed structured output.
tools command
Command tools demonstrates defining a tool and letting the model call it in an agentic loop.
Command tools demonstrates defining a tool and letting the model call it in an agentic loop.
internal
modelsdev
Package modelsdev models the models.dev api.json format and reduces it to the providers the llms package supports.
Package modelsdev models the models.dev api.json format and reduces it to the providers the llms package supports.

Jump to

Keyboard shortcuts

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