llms

package
v1.0.178 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package llms provides unified support for interacting with different Language Models (LLMs) from various providers. Designed with an extensible architecture, the package facilitates seamless integration of LLMs with a focus on modularity, encapsulation, and easy configurability.

Each subpackage includes provider-specific LLM implementations and helper files for communication with supported LLM providers. The internal directories within these subpackages contain provider-specific client and API implementations.

The `llms.go` file contains the types and interfaces for interacting with different LLMs.

The `options.go` file provides various options and functions to configure the LLMs.

Index

Constants

View Source
const (
	// InferenceRoleSystem identifies leading system instructions.
	InferenceRoleSystem InferenceRole = "system"
	// InferenceRoleDeveloper identifies leading developer instructions.
	InferenceRoleDeveloper InferenceRole = "developer"
	// InferenceRoleUser identifies user content.
	InferenceRoleUser InferenceRole = "user"
	// InferenceRoleAssistant identifies prior model content.
	InferenceRoleAssistant InferenceRole = "assistant"
	// InferenceRoleTool identifies application-supplied function results.
	InferenceRoleTool InferenceRole = "tool"

	// BlockText is plain text authored by the role.
	BlockText BlockType = "text"
	// BlockFunctionCall is an assistant request to run a function.
	BlockFunctionCall BlockType = "function_call"
	// BlockFunctionOutput is the application's result for one function call.
	BlockFunctionOutput BlockType = "function_call_output"
	// BlockRefusal is an explicit model refusal.
	BlockRefusal BlockType = "refusal"
	// BlockReasoning carries a reasoning summary and opaque provider state.
	BlockReasoning BlockType = "reasoning"

	// FormatText requests unconstrained text.
	FormatText FormatType = "text"
	// FormatJSONObject requests any valid JSON object.
	FormatJSONObject FormatType = "json_object"
	// FormatJSONSchema requests JSON that conforms to a caller schema.
	FormatJSONSchema FormatType = "json_schema"

	// ToolChoiceAuto lets the model decide whether to call tools.
	ToolChoiceAuto ToolChoiceMode = "auto"
	// ToolChoiceNone forbids tool calls.
	ToolChoiceNone ToolChoiceMode = "none"
	// ToolChoiceRequired requires at least one tool call.
	ToolChoiceRequired ToolChoiceMode = "required"
	// ToolChoiceFunction requires a call to the named function.
	ToolChoiceFunction ToolChoiceMode = "function"

	// FinishStop denotes a completed generation.
	FinishStop FinishReason = "stop"
	// FinishLength denotes output truncated by the token limit.
	FinishLength FinishReason = "length"
	// FinishToolCalls denotes pending tool invocations.
	FinishToolCalls FinishReason = "tool_calls"
	// FinishContentFilter denotes content blocked or refused by the provider.
	FinishContentFilter FinishReason = "content_filter"

	// EffortMinimal requests the least reasoning a model allows.
	EffortMinimal Effort = "minimal"
	// EffortLow requests light reasoning.
	EffortLow Effort = "low"
	// EffortMedium requests moderate reasoning.
	EffortMedium Effort = "medium"
	// EffortHigh requests extensive reasoning.
	EffortHigh Effort = "high"

	// InferenceFunction is the tool type accepted by every dialect.
	InferenceFunction = "function"
)

Portable inference vocabulary shared by routers, codecs and provider adapters.

View Source
const ToolTypeFunction = "function"

ToolTypeFunction is the ToolCall.Type of a call to a function tool. Providers set it on every function call they return, so that GetFunctionCallName and GetFunctionCallArguments see the function.

Variables

View Source
var (
	// ErrBatchNotReady is returned by FetchBatchResults when the batch is not
	// yet in a terminal state.
	ErrBatchNotReady = errors.New("batch is not yet terminal")
	// ErrBatchNotSupported is returned when a provider or specific configuration
	// (e.g. an Azure deployment) does not support the Batch API.
	ErrBatchNotSupported = errors.New("provider does not support batching")
	// ErrBatchNotFound is returned by GetBatch / CancelBatch / FetchBatchResults
	// when the batch ID is unknown to the provider.
	ErrBatchNotFound = errors.New("batch not found")
)

Errors returned by Batcher implementations.

View Source
var ErrMissingFunctionCall = errors.New("tool call has no function call")

ErrMissingFunctionCall is returned by ToolCall.RequireFunctionCall for a tool call without a FunctionCall, such as a provider-native web_search call, which a provider cannot send back to the model as a function call.

View Source
var ErrMissingFunctionDefinition = errors.New("tool has no function definition")

ErrMissingFunctionDefinition is returned by Tool.RequireFunction for a tool without a Function definition.

View Source
var ErrModelListNotSupported = errors.New("provider does not list models")

ErrModelListNotSupported is returned by ModelLister.ListModels, and by the NewModelLister constructors, when the client talks to a provider that has no model list: one that does not advertise CapabilityModels. Test for it with errors.Is.

View Source
var ErrUnexpectedRole = errors.New("unexpected role")

ErrUnexpectedRole is returned when a message role is of an unexpected type.

Functions

func CompareVersions added in v1.0.173

func CompareVersions(a, b []int) int

CompareVersions compares two versions component by component, treating a missing component as zero. It returns -1, 0 or 1.

func GenerateFromSinglePrompt

func GenerateFromSinglePrompt(ctx context.Context, llm Model, prompt string, options ...CallOption) (string, error)

GenerateFromSinglePrompt is a convenience function for calling an LLM with a single string prompt, expecting a single string response. It's useful for simple, string-only interactions and provides a slightly more ergonomic API than the more general llms.Model.GenerateContent.

func InferenceFailure added in v0.21.160

func InferenceFailure(err error, status int, operation string) error

InferenceFailure attaches the provider HTTP status to an external failure.

func ReasoningBudget added in v0.21.160

func ReasoningBudget(effort Effort) (int, bool)

ReasoningBudget maps an effort level to a token budget for providers that only expose a numeric budget. Providers with a native effort control use that.

func UnsupportedInference added in v0.21.160

func UnsupportedInference(param string) error

UnsupportedInference reports a control the connector cannot translate.

Types

type BatchHandle added in v0.17.130

type BatchHandle struct {
	// ID is the provider-assigned batch identifier.
	ID string
	// Provider is the LLM provider that owns this batch.
	Provider ProviderType
	// Status is the current lifecycle state.
	Status BatchStatus
	// RequestCounts summarizes per-request progress.
	RequestCounts BatchRequestCounts
	// CreatedAt is when the batch was submitted to the provider. It is nil if
	// the provider did not report a creation time.
	CreatedAt *time.Time
	// CompletedAt is when the batch reached a terminal state. It is nil while
	// the batch is still in a non-terminal state.
	CompletedAt *time.Time
	// ExpiresAt is the deadline by which the batch must complete. It is nil if
	// the provider did not report an expiration time.
	ExpiresAt *time.Time
	// Metadata mirrors any caller-supplied metadata round-tripped through the provider.
	Metadata map[string]string
	// ProviderMeta is the raw provider-specific batch object, kept as an opaque
	// value for callers that need fields this abstraction does not surface
	// (e.g. OpenAI's input_file_id / output_file_id / error_file_id).
	ProviderMeta any
}

BatchHandle is a snapshot of a submitted batch returned by SubmitBatch, GetBatch, and CancelBatch. Callers persist ID across processes to reattach to a long-running batch with GetBatch.

type BatchRequest added in v0.17.130

type BatchRequest struct {
	// CustomID is a caller-supplied identifier used to correlate this request to its
	// result. It must be unique within the batch and is echoed back on each BatchResult.
	CustomID string
	// Messages is the input message sequence, identical to Model.GenerateContent.
	Messages []Message
	// Options are the per-request CallOptions, identical to Model.GenerateContent.
	Options []CallOption
}

BatchRequest is a single request submitted as part of a batch. The Messages and Options fields use the same types as Model.GenerateContent so callers can build batch inputs from the same code paths they use for synchronous calls.

type BatchRequestCounts added in v0.17.130

type BatchRequestCounts struct {
	// Total is the number of requests in the batch.
	Total int
	// Completed is the number of requests that have finished successfully.
	Completed int
	// Failed is the number of requests that returned a per-request error.
	Failed int
}

BatchRequestCounts summarizes per-request progress within a batch.

type BatchRequestError added in v0.17.130

type BatchRequestError struct {
	// Code is the provider's machine-readable error code (e.g. "rate_limit_exceeded").
	Code string
	// Message is a human-readable error description.
	Message string
}

BatchRequestError describes a per-request error returned within a batch's results.

func (*BatchRequestError) Error added in v0.17.130

func (e *BatchRequestError) Error() string

Error implements the error interface so callers can return *BatchRequestError directly.

type BatchResult added in v0.17.130

type BatchResult struct {
	// CustomID matches the CustomID supplied on the original BatchRequest.
	CustomID string
	// Response is the parsed model response. Nil when the per-request call errored.
	Response *ContentResponse
	// Error describes a per-request failure. Nil when the request succeeded.
	Error *BatchRequestError
}

BatchResult is one entry from a completed batch. Exactly one of Response or Error is non-nil for a given result.

type BatchStatus added in v0.17.130

type BatchStatus string

BatchStatus describes the lifecycle state of a batch.

const (
	// BatchStatusValidating indicates the batch input is being validated.
	BatchStatusValidating BatchStatus = "validating"
	// BatchStatusInProgress indicates the batch is being processed.
	BatchStatusInProgress BatchStatus = "in_progress"
	// BatchStatusFinalizing indicates the batch finished processing and results are being prepared.
	BatchStatusFinalizing BatchStatus = "finalizing"
	// BatchStatusCompleted indicates the batch is finished and results are available.
	BatchStatusCompleted BatchStatus = "completed"
	// BatchStatusFailed indicates the batch failed during validation or processing.
	BatchStatusFailed BatchStatus = "failed"
	// BatchStatusExpired indicates the batch was not completed within the provider's
	// completion window and any partial results have been released.
	BatchStatusExpired BatchStatus = "expired"
	// BatchStatusCancelling indicates a cancellation has been requested but not finalized.
	BatchStatusCancelling BatchStatus = "cancelling"
	// BatchStatusCancelled indicates the batch was cancelled by the caller.
	BatchStatusCancelled BatchStatus = "cancelled"
)

func (BatchStatus) IsTerminal added in v0.17.130

func (s BatchStatus) IsTerminal() bool

IsTerminal reports whether the batch has reached a state that will not transition further. Callers polling GetBatch should stop once IsTerminal returns true.

type BatchSubmitOption added in v0.17.130

type BatchSubmitOption func(*BatchSubmitOptions)

BatchSubmitOption configures a single call to Batcher.SubmitBatch.

func WithBatchCompletionWindow added in v0.17.130

func WithBatchCompletionWindow(d time.Duration) BatchSubmitOption

WithBatchCompletionWindow sets the maximum time the provider should hold the batch open. Providers that only support a fixed window ignore conflicting values.

func WithBatchMetadata added in v0.17.130

func WithBatchMetadata(m map[string]string) BatchSubmitOption

WithBatchMetadata attaches caller-supplied metadata to the batch. The provider will round-trip these key/value pairs on the BatchHandle.

type BatchSubmitOptions added in v0.17.130

type BatchSubmitOptions struct {
	// CompletionWindow is the maximum time the provider should hold the batch open.
	// Providers that only support a single window (e.g. OpenAI's "24h") ignore this
	// when it conflicts with their fixed value.
	CompletionWindow time.Duration
	// Metadata is round-tripped through the provider on the batch object.
	Metadata map[string]string
}

BatchSubmitOptions are the options accepted by Batcher.SubmitBatch.

type Batcher added in v0.17.130

type Batcher interface {
	// SubmitBatch enqueues a set of requests for asynchronous processing and
	// returns a handle that callers persist to track the batch across processes.
	SubmitBatch(ctx context.Context, requests []BatchRequest, options ...BatchSubmitOption) (*BatchHandle, error)
	// GetBatch fetches the current state of a submitted batch. Callers poll this
	// until Status.IsTerminal() returns true.
	GetBatch(ctx context.Context, batchID string) (*BatchHandle, error)
	// CancelBatch requests cancellation of an in-flight batch. The returned
	// handle reflects the updated status (typically Cancelling, then Cancelled).
	CancelBatch(ctx context.Context, batchID string) (*BatchHandle, error)
	// FetchBatchResults returns all results for a terminal batch. It returns
	// ErrBatchNotReady if the batch has not yet reached a terminal state.
	// Per-request failures are surfaced on BatchResult.Error rather than as a
	// returned error, so callers can process partial successes.
	FetchBatchResults(ctx context.Context, batchID string) ([]BatchResult, error)
}

Batcher is implemented by LLM providers that support asynchronous batch processing. Callers obtain a Batcher by type-asserting against a concrete provider's *LLM:

if b, ok := llm.(llms.Batcher); ok {
    handle, err := b.SubmitBatch(ctx, requests)
    // ... persist handle.ID, poll GetBatch from a later process, FetchBatchResults when terminal.
}

Implementations accept the same Messages + CallOptions shape as Model.GenerateContent, so building batch inputs reuses existing call sites.

The interface is intentionally async-only: callers own the polling loop. This keeps the contract small and lets callers persist BatchHandle.ID to track a batch across process boundaries.

type BinaryContent

type BinaryContent struct {
	MIMEType string `json:"mime_type"`
	Data     []byte `json:"data"`
}

BinaryContent is content holding some binary data with a MIME type.

func BinaryPart

func BinaryPart(mime string, data []byte) BinaryContent

BinaryPart creates a new BinaryContent from the given MIME type (e.g. "image/png" and binary data).

func (BinaryContent) ContentLength added in v0.17.128

func (bc BinaryContent) ContentLength() int

func (BinaryContent) ContentType added in v0.18.137

func (bc BinaryContent) ContentType() ContentPartType

func (BinaryContent) MarshalJSON

func (bc BinaryContent) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for BinaryContent

func (BinaryContent) String

func (bc BinaryContent) String() string

func (*BinaryContent) UnmarshalJSON

func (bc *BinaryContent) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for BinaryContent

type BinaryContentJSON added in v0.10.55

type BinaryContentJSON struct {
	Type   string     `json:"type"`
	Binary BinaryJSON `json:"binary"`
}

BinaryContentJSON represents the JSON structure for binary content

type BinaryJSON added in v0.10.55

type BinaryJSON struct {
	Data     string `json:"data"`
	MIMEType string `json:"mime_type"`
}

BinaryJSON represents the JSON structure for binary content

type BlockType added in v0.21.160

type BlockType string

BlockType identifies the kind of content in an InferenceBlock.

type CallOption

type CallOption func(*CallOptions)

CallOption is a function that configures a CallOptions.

func WithCandidateCount

func WithCandidateCount(c int) CallOption

WithCandidateCount specifies the number of response candidates to generate.

func WithFrequencyPenalty

func WithFrequencyPenalty(frequencyPenalty float64) CallOption

WithFrequencyPenalty will add an option to set the frequency penalty for sampling.

func WithMaxLength

func WithMaxLength(maxLength int) CallOption

WithMaxLength will add an option to set the maximum length of the generated text.

func WithMaxTokens

func WithMaxTokens(maxTokens int) CallOption

WithMaxTokens specifies the max number of tokens to generate.

func WithMetadata

func WithMetadata(metadata map[string]any) CallOption

WithMetadata will add an option to set metadata to include in the request. The meaning of this field is specific to the backend in use.

func WithMinLength

func WithMinLength(minLength int) CallOption

WithMinLength will add an option to set the minimum length of the generated text.

func WithModel

func WithModel(model string) CallOption

WithModel specifies which model name to use.

func WithN

func WithN(n int) CallOption

WithN will add an option to set how many chat completion choices to generate for each input message.

func WithOptions

func WithOptions(options CallOptions) CallOption

WithOptions specifies options.

func WithPresencePenalty

func WithPresencePenalty(presencePenalty float64) CallOption

WithPresencePenalty will add an option to set the presence penalty for sampling.

func WithPromptCachePolicy added in v0.15.112

func WithPromptCachePolicy(promptCachePolicy *PromptCachePolicy) CallOption

WithPromptCachePolicy allows setting provider-native prompt cache policy.

func WithReasoningEffort added in v0.14.100

func WithReasoningEffort(reasoningEffort ReasoningEffort) CallOption

WithReasoningEffort allows setting the reasoning effort.

func WithRepetitionPenalty

func WithRepetitionPenalty(repetitionPenalty float64) CallOption

WithRepetitionPenalty will add an option to set the repetition penalty for sampling.

func WithResponseFormat added in v0.10.55

func WithResponseFormat(responseFormat *schema.ResponseFormat) CallOption

WithResponseFormat allows setting a custom response format. If it's not set the response MIME type is text/plain. Otherwise, from response format the JSON mode is derived.

func WithSeed

func WithSeed(seed int) CallOption

WithSeed will add an option to use deterministic sampling.

func WithStopWords

func WithStopWords(stopWords []string) CallOption

WithStopWords specifies a list of words to stop generation on.

func WithStreamingFunc

func WithStreamingFunc(streamingFunc func(ctx context.Context, chunk []byte) error) CallOption

WithStreamingFunc specifies the streaming function to use.

func WithStreamingReasoningFunc

func WithStreamingReasoningFunc(streamingReasoningFunc func(ctx context.Context, reasoningChunk, chunk []byte) error) CallOption

WithStreamingReasoningFunc specifies the streaming reasoning function to use.

func WithTemperature

func WithTemperature(temperature float64) CallOption

WithTemperature specifies the model temperature, a hyperparameter that regulates the randomness, or creativity, of the AI's responses.

func WithToolChoice

func WithToolChoice(choice any) CallOption

WithToolChoice will add an option to set the choice of tool to use. It can either be "none", "auto" (the default behavior), or a specific tool as described in the ToolChoice type.

func WithTools

func WithTools(tools []Tool) CallOption

WithTools will add an option to set the tools to use.

func WithTopK

func WithTopK(topK int) CallOption

WithTopK will add an option to use top-k sampling.

func WithTopP

func WithTopP(topP float64) CallOption

WithTopP will add an option to use top-p sampling.

type CallOptions

type CallOptions struct {
	// Model is the model to use.
	Model string
	// CandidateCount is the number of response candidates to generate.
	CandidateCount int
	// MaxTokens is the maximum number of tokens to generate.
	MaxTokens int
	// Temperature is the temperature for sampling, between 0 and 1.
	Temperature float64
	// StopWords is a list of words to stop on.
	StopWords []string
	// StreamingFunc is a function to be called for each chunk of a streaming response.
	// Return an error to stop streaming early.
	StreamingFunc func(ctx context.Context, chunk []byte) error
	// StreamingReasoningFunc is a function to be called for each chunk of a streaming response.
	// Return an error to stop streaming early.
	StreamingReasoningFunc func(ctx context.Context, reasoningChunk, chunk []byte) error
	// TopK is the number of tokens to consider for top-k sampling.
	TopK int
	// TopP is the cumulative probability for top-p sampling.
	TopP float64
	// Seed is a seed for deterministic sampling.
	Seed int
	// MinLength is the minimum length of the generated text.
	MinLength int
	// MaxLength is the maximum length of the generated text.
	MaxLength int
	// N is how many chat completion choices to generate for each input message.
	N int
	// RepetitionPenalty is the repetition penalty for sampling.
	RepetitionPenalty float64
	// FrequencyPenalty is the frequency penalty for sampling.
	FrequencyPenalty float64
	// PresencePenalty is the presence penalty for sampling.
	PresencePenalty float64

	// Tools is a list of tools to use. Each tool can be a specific tool or a function.
	Tools []Tool
	// ToolChoice is the choice of tool to use, it can either be "none", "auto" (the default behavior), or a specific tool as described in the ToolChoice type.
	ToolChoice any

	// Metadata is a map of metadata to include in the request.
	// The meaning of this field is specific to the backend in use.
	Metadata map[string]any

	// ResponseFormat is a custom response format.
	// If it's not set the response MIME type is text/plain.
	// Otherwise, from response format the JSON mode is derived.
	ResponseFormat *schema.ResponseFormat

	ReasoningEffort ReasoningEffort

	// PromptCachePolicy configures provider-native prompt caching.
	PromptCachePolicy *PromptCachePolicy
}

CallOptions is a set of options for calling models. Not all models support all options.

type Capability added in v0.10.54

type Capability uint64

Capability is a bitmask indicating supported features of an LLM provider.

const (
	// Basic text or chat generation
	CapabilityText Capability = 1 << iota

	// Structured response formats
	CapabilityJSONResponse
	CapabilityJSONSchema
	CapabilityJSONSchemaStrict

	// Function/tool calling
	CapabilityFunctionCalling
	CapabilityMultiToolCalling
	CapabilityToolCallStreaming

	// Multimodal (images, audio, etc.)
	CapabilityVision
	CapabilityImageGeneration
	CapabilityAudioTranscription

	// Open weight models / self-hosted
	CapabilitySelfHosted

	// System prompt support
	CapabilitySystemPrompt

	// Web Search tool support, used by models that support web search grounding.
	CapabilityWebSearchTool

	// Prompt Caching
	CapabilityPromptCaching

	// Asynchronous batch processing via the provider's Batch API.
	// Providers that advertise this capability also implement [Batcher].
	CapabilityBatch

	// The provider can list the models an account may call.
	// Providers that advertise this capability also implement [ModelLister].
	CapabilityModels
)

func ProviderCapabilities added in v0.10.54

func ProviderCapabilities(pt ProviderType) Capability

ProviderCapabilities returns the capability mask for a provider type, or zero for an unknown type.

type ContentChoice

type ContentChoice struct {
	// Content is the textual content of a response
	Content string `json:"content"`

	// StopReason is the reason the model stopped generating output.
	StopReason string `json:"stop_reason"`

	// GenerationInfo is arbitrary information the model adds to the response.
	GenerationInfo map[string]any `json:"generation_info"`

	// Usage is the usage of the content choice.
	Usage Usage `json:"usage"`

	// FuncCall is non-nil when the model asks to invoke a function/tool.
	// If a model invokes more than one function/tool, this field will only
	// contain the first one.
	FuncCall *FunctionCall `json:"func_call"`

	// ToolCalls is a list of tool calls the model asks to invoke.
	ToolCalls []ToolCall `json:"tool_calls"`

	// ReasoningContent is the model's reasoning before the final answer, when
	// the provider returns it: deepseek-reasoner's reasoning_content, or
	// Anthropic thinking blocks (empty when the thinking display omits them).
	ReasoningContent string `json:"reasoning_content"`
}

ContentChoice is one of the response choices returned by GenerateContent calls.

func (*ContentChoice) ContentSize added in v0.18.140

func (r *ContentChoice) ContentSize() uint64

ContentSize returns the byte size of the choice's content, reasoning content and tool calls.

type ContentPart

type ContentPart interface {
	String() string
	ContentType() ContentPartType
	ContentLength() int
	// contains filtered or unexported methods
}

ContentPart is an interface all parts of content have to implement.

type ContentPartJSON added in v0.10.55

type ContentPartJSON struct {
	Type         string            `json:"type"`
	Text         string            `json:"text,omitempty"`
	ImageURL     *ImageURLJSON     `json:"image_url,omitempty"`
	Binary       *BinaryJSON       `json:"binary,omitempty"`
	ToolCall     *ToolCallJSON     `json:"tool_call,omitempty"`
	ToolResponse *ToolResponseJSON `json:"tool_response,omitempty"`
}

ContentPartJSON represents the JSON structure for content parts

type ContentPartType added in v0.18.137

type ContentPartType string

ContentPartType identifies the kind of a ContentPart.

const (
	ContentTypeText         ContentPartType = "text"
	ContentTypeImageURL     ContentPartType = "image_url"
	ContentTypeBinary       ContentPartType = "binary"
	ContentTypeToolCall     ContentPartType = "tool_call"
	ContentTypeToolResponse ContentPartType = "tool_response"
)

type ContentResponse

type ContentResponse struct {
	Choices []*ContentChoice
}

ContentResponse is the response returned by a GenerateContent call. It can potentially return multiple content choices.

func (*ContentResponse) ContentSize added in v0.18.140

func (r *ContentResponse) ContentSize() uint64

ContentSize returns the total byte size of all choices.

func (*ContentResponse) String added in v0.17.132

func (r *ContentResponse) String() string

String returns the response content, joining multiple choices with a blank line.

func (*ContentResponse) Usage added in v0.18.140

func (r *ContentResponse) Usage() *Usage

Usage sums the usage across all choices. Never returns nil.

type Effort added in v0.21.160

type Effort string

Effort is a provider-independent request for how much the model should reason before answering. Connectors map it to a native control or a token budget.

func EffortForBudget added in v0.21.160

func EffortForBudget(budget int) Effort

EffortForBudget maps a token budget to the closest effort level for providers that only expose a discrete effort control.

type EffortPolicy added in v1.0.173

type EffortPolicy struct {
	// Default is used when a call does not request a level.
	Default ReasoningEffort
	// Max is the highest level a call may use. ReasoningEffortDefault means
	// there is no ceiling.
	Max ReasoningEffort
	// Supported holds the levels the provider reports for the client's model.
	// When it is not empty, the client uses it in place of its own table for
	// that model. The empty set means the provider reported none.
	Supported EffortSet
	// Implicit is the level the provider reports the client's model applies
	// to a request that names none. ReasoningEffortDefault means the provider
	// did not report it.
	Implicit ReasoningEffort
}

EffortPolicy is the reasoning effort configuration a provider client applies to every call it makes. The zero value changes nothing.

Default and Max come from configuration. Supported and Implicit describe the model the client was built for, as its provider's model list reports it; they are empty unless the list was read.

func (EffortPolicy) IsZero added in v1.0.173

func (p EffortPolicy) IsZero() bool

IsZero reports whether the policy changes nothing: it has no default, no ceiling, and nothing reported by the provider.

func (EffortPolicy) Resolve added in v1.0.173

func (p EffortPolicy) Resolve(requested ReasoningEffort, supported EffortSet, implicit ReasoningEffort) ReasoningEffort

Resolve returns the level to send for one call.

requested is the level the call asked for, supported is the set the model accepts, and implicit is the level the model applies when a request names none (ReasoningEffortDefault when that is unknown or already minimal).

The requested level wins over the policy default. The result is lowered to the ceiling and then snapped to the nearest supported level. When no level is requested and the policy has no default, Resolve returns ReasoningEffortDefault, which tells the provider to send what it sends without an effort setting; the only exception is an implicit level above the ceiling, for which the ceiling is returned when the model accepts a level below the implicit one. A ceiling never raises the level.

type EffortSet added in v1.0.173

type EffortSet uint8

EffortSet is the set of reasoning effort levels a model accepts. The zero value is the empty set: a model without a reasoning control.

func NewEffortSet added in v1.0.173

func NewEffortSet(levels ...ReasoningEffort) EffortSet

NewEffortSet returns the set holding the given levels. ReasoningEffortDefault and values that are not levels are ignored.

func (EffortSet) Empty added in v1.0.173

func (s EffortSet) Empty() bool

Empty reports whether the set holds no level.

func (EffortSet) Has added in v1.0.173

func (s EffortSet) Has(e ReasoningEffort) bool

Has reports whether the set holds the level.

func (EffortSet) Levels added in v1.0.173

func (s EffortSet) Levels() []ReasoningEffort

Levels returns the levels in the set, lowest first.

func (EffortSet) Nearest added in v1.0.173

Nearest returns the level in the set that is closest to e: e itself when the set holds it, otherwise the highest level below e, otherwise the lowest level above e. It returns ReasoningEffortDefault when e is not a level or the set is empty.

func (EffortSet) With added in v1.0.173

func (s EffortSet) With(levels ...ReasoningEffort) EffortSet

With returns the set extended by the given levels.

type Embedder added in v0.10.63

type Embedder interface {
	// CreateEmbedding creates embeddings for the given input texts.
	CreateEmbedding(ctx context.Context, texts []string) ([][]float32, error)
}

Embedder is an interface for models that can create embeddings.

type FinishReason added in v0.21.160

type FinishReason string

FinishReason is the normalized reason a generation ended.

type FormatType added in v0.21.160

type FormatType string

FormatType selects plain text, a JSON object, or a schema-constrained JSON output.

type FunctionCall

type FunctionCall struct {
	// The name of the function to call.
	Name string `json:"name"`
	// The arguments to pass to the function, as a JSON string.
	Arguments string `json:"arguments"`
}

FunctionCall is the name and arguments of a function call.

type FunctionCallBehavior

type FunctionCallBehavior string

FunctionCallBehavior is the behavior to use when calling functions.

const (
	// FunctionCallBehaviorNone will not call any functions.
	FunctionCallBehaviorNone FunctionCallBehavior = "none"
	// FunctionCallBehaviorAuto will call functions automatically.
	FunctionCallBehaviorAuto FunctionCallBehavior = "auto"
)

type FunctionDefinition

type FunctionDefinition struct {
	// Name is the name of the function.
	Name string `json:"name"`
	// Description is a description of the function.
	Description string `json:"description"`
	// Parameters is a list of parameters for the function.
	Parameters *jsonschema.Schema `json:"parameters,omitempty"`
	// Strict is a flag to indicate if the function should be called strictly. Only used for openai llm structured output.
	Strict bool `json:"strict,omitempty"`
}

FunctionDefinition is a definition of a function that can be called by the model.

type FunctionReference

type FunctionReference struct {
	// Name is the name of the function.
	Name string `json:"name"`
}

FunctionReference is a reference to a function.

type ImageURLContent

type ImageURLContent struct {
	URL    string `json:"url"`
	Detail string `json:"detail,omitempty"` // Detail is the detail of the image, e.g. "low", "high".
}

ImageURLContent is content with an URL pointing to an image.

func ImageURLPart

func ImageURLPart(url string) ImageURLContent

ImageURLPart creates a new ImageURLContent from the given URL.

func ImageURLWithDetailPart

func ImageURLWithDetailPart(url string, detail string) ImageURLContent

ImageURLWithDetailPart creates a new ImageURLContent from the given URL and detail.

func (ImageURLContent) ContentLength added in v0.17.128

func (iuc ImageURLContent) ContentLength() int

func (ImageURLContent) ContentType added in v0.18.137

func (iuc ImageURLContent) ContentType() ContentPartType

func (ImageURLContent) MarshalJSON

func (iuc ImageURLContent) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for ImageURLContent

func (ImageURLContent) String

func (iuc ImageURLContent) String() string

func (*ImageURLContent) UnmarshalJSON

func (iuc *ImageURLContent) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for ImageURLContent

type ImageURLContentJSON added in v0.10.55

type ImageURLContentJSON struct {
	Type     string       `json:"type"`
	ImageURL ImageURLJSON `json:"image_url"`
}

ImageURLContentJSON represents the JSON structure for image URL content

type ImageURLJSON added in v0.10.55

type ImageURLJSON struct {
	URL    string `json:"url"`
	Detail string `json:"detail,omitempty"`
}

ImageURLJSON represents the JSON structure for image URL content

type InferenceBlock added in v0.21.160

type InferenceBlock struct {
	Type      BlockType
	Text      string
	ID        string
	Name      string
	Arguments string
	Opaque    json.RawMessage
	Source    string
}

InferenceBlock is one ordered unit of content. Field use by type:

  • text, refusal: Text.
  • function_call: ID, Name, Arguments (raw JSON object bytes, never re-encoded).
  • function_call_output: ID, Text; Name is filled from the matching call.
  • reasoning: Text (summary, may be empty), Opaque (provider state replayed verbatim, may be empty) and Source (router target that produced Opaque).

type InferenceError added in v0.21.160

type InferenceError struct {
	Status int
	Param  string
	Cause  error
}

InferenceError preserves diagnostics while exposing a safe classification. Status is the upstream HTTP status when known, or 400 for an unsupported control. Callers must not expose Cause text to untrusted clients.

func (*InferenceError) Error added in v0.21.160

func (e *InferenceError) Error() string

Error returns internal diagnostics.

func (*InferenceError) Unwrap added in v0.21.160

func (e *InferenceError) Unwrap() error

Unwrap preserves the original provider failure for errors.Is and errors.As.

type InferenceFormat added in v0.21.160

type InferenceFormat struct {
	Type   FormatType
	Name   string
	Schema json.RawMessage
	Strict bool
}

InferenceFormat requests text, a JSON object, or a constrained JSON schema.

type InferenceMessage added in v0.21.160

type InferenceMessage struct {
	Role    InferenceRole
	Content []InferenceBlock
}

InferenceMessage preserves one role and its ordered blocks.

type InferenceModel added in v0.21.160

type InferenceModel interface {
	// ValidateInference rejects controls the connector cannot translate faithfully.
	// It must return UnsupportedInference for each such control.
	ValidateInference(InferenceRequest) error
	// Infer generates one response without executing tools or retrying.
	Infer(context.Context, InferenceRequest) (*InferenceResponse, error)
}

InferenceModel is an optional lossless, single-turn text inference contract implemented by providers next to the legacy Model interface. Implementations must honor option presence, return ordered output blocks, make exactly one upstream attempt, and never execute tools.

type InferenceReasoning added in v0.21.160

type InferenceReasoning struct {
	Effort       Effort
	BudgetTokens *int
}

InferenceReasoning requests reasoning behaviour. Effort is mapped by each connector; BudgetTokens, when set, is passed to providers with a token budget.

func (*InferenceReasoning) EffectiveEffort added in v0.21.160

func (r *InferenceReasoning) EffectiveEffort() (Effort, bool)

EffectiveEffort returns the requested effort, or the effort derived from the budget when only a budget was supplied. ok is false when neither is present.

type InferenceRequest added in v0.21.160

type InferenceRequest struct {
	Model             string
	Messages          []InferenceMessage
	Tools             []InferenceTool
	ToolChoice        *InferenceToolChoice
	ParallelToolCalls *bool
	Temperature       *float64
	TopP              *float64
	MaxTokens         *int
	Stop              []string
	Seed              *int64
	Format            *InferenceFormat
	Reasoning         *InferenceReasoning
}

InferenceRequest preserves caller-supplied generation controls and ordered history. Model is always the exact backend model, never a routing alias. Nil pointers mean "not supplied"; connectors omit the wire field.

func (InferenceRequest) Clone added in v0.21.160

Clone returns a deep copy that shares no slices or pointers with r.

type InferenceResponse added in v0.21.160

type InferenceResponse struct {
	Content      []InferenceBlock
	FinishReason FinishReason
	Usage        Usage
	UsageKnown   bool
	UpstreamID   string
}

InferenceResponse contains one generation with ordered output and usage.

func (InferenceResponse) Clone added in v0.21.160

Clone returns a deep copy of the response.

type InferenceRole added in v0.21.160

type InferenceRole string

InferenceRole identifies who authored a message.

type InferenceTool added in v0.21.160

type InferenceTool struct {
	Name        string
	Description string
	Parameters  json.RawMessage
	Strict      *bool
}

InferenceTool defines a function the application, not the model client, executes.

type InferenceToolChoice added in v0.21.160

type InferenceToolChoice struct {
	Mode ToolChoiceMode
	Name string
}

InferenceToolChoice selects a tool-calling mode; Name is set only for ToolChoiceFunction.

type Message added in v0.11.64

type Message struct {
	Role  Role          `json:"role"`
	Parts []ContentPart `json:"parts"`

	// Source is the source of the message.
	// It's used to identify the source of the message.
	Source *MessageSource `json:"source,omitempty"`
}

Message is the message sent to a LLM. It has a role and a sequence of parts. For example, it can represent one message in a chat session sent by the user, in which case Role will be ChatMessageTypeHuman and Parts will be the sequence of items sent in this specific message.

func MessageFromParts added in v0.11.64

func MessageFromParts(role Role, parts ...ContentPart) Message

MessageFromParts is a helper function to create a Message with a role and a list of parts.

func MessageFromTextParts added in v0.11.64

func MessageFromTextParts(role Role, parts ...string) Message

MessageFromTextParts is a helper function to create a Message with a role and a list of text parts.

func MessageFromToolCalls added in v0.11.64

func MessageFromToolCalls(role Role, toolCalls ...ToolCall) Message

MessageFromToolCalls is a helper function to create a Message with a role and a list of tool calls.

func MessageFromToolResponse added in v0.11.64

func MessageFromToolResponse(role Role, toolResponse ToolCallResponse) Message

MessageFromToolResponse is a helper function to create a Message with a role and a tool response.

func (Message) MarshalJSON added in v0.11.64

func (mc Message) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for MessageContent

func (*Message) Print added in v0.17.128

func (m *Message) Print(w io.Writer)

Print is a debugging helper.

func (*Message) ToMessageContentWithPartsJSON added in v0.11.64

func (mc *Message) ToMessageContentWithPartsJSON() *MessageContentWithPartsJSON

ToMessageContentWithPartsJSON converts MessageContent to MessageContentWithPartsJSON

func (*Message) UnmarshalJSON added in v0.11.64

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

UnmarshalJSON implements json.Unmarshaler for MessageContent

func (Message) WithSource added in v0.17.128

func (m Message) WithSource(src *MessageSource) Message

WithSource returns a copy of the message tagged with src, leaving an existing source untouched so attribution set by a sub-agent survives as messages flow upward.

type MessageContentJSON added in v0.10.55

type MessageContentJSON struct {
	Role   Role           `json:"role"`
	Text   string         `json:"text,omitempty"`
	Source *MessageSource `json:"source,omitempty"`
}

MessageContentJSON represents the JSON structure for MessageContent

type MessageContentWithPartsJSON added in v0.10.55

type MessageContentWithPartsJSON struct {
	Role   Role           `json:"role"`
	Parts  []ContentPart  `json:"parts"`
	Source *MessageSource `json:"source,omitempty"`
}

MessageContentWithPartsJSON represents the JSON structure for MessageContent with parts

type MessageSource added in v0.17.128

type MessageSource struct {
	// Name is the name of the source of the message.
	Name string `json:"name"`
	// RunID is the ID of the run of the message.
	RunID string `json:"run_id,omitempty"`
	// ActionID is the ID of the action of the message.
	ActionID string `json:"action_id,omitempty"`
}

MessageSource records which assistant, run and action produced a message. It is what makes a stored multi-agent transcript attributable.

func (*MessageSource) String added in v0.17.128

func (m *MessageSource) String() string

String renders the source as "runID.name", or "runID.actionID.name" when an action ID is set.

type Messages added in v0.17.128

type Messages = []Message

Messages is an alias for a message slice, used for readability in signatures.

type Model

type Model interface {
	// GetName returns the name of the model.
	GetName() string
	// GetProviderType returns the type of provider.
	GetProviderType() ProviderType
	// GenerateContent asks the model to generate content from a sequence of
	// messages. It's the most general interface for multi-modal LLMs that support
	// chat-like interactions.
	GenerateContent(ctx context.Context, messages []Message, options ...CallOption) (*ContentResponse, error)
}

Model is an interface multi-modal models implement.

type ModelInfo added in v1.0.173

type ModelInfo struct {
	// ID is the identifier to name the model with in a request.
	ID string
	// DisplayName is the human-readable name of the model.
	DisplayName string
	// Family is the model family as the provider names it, such as "opus".
	// It is empty when the provider does not report one; derive it from the
	// ID with [ParseModelName] in that case.
	Family string
	// Created is the release time of the model.
	Created time.Time
	// Lifecycle is the stage of the model in the provider's catalog.
	Lifecycle ModelLifecycle
	// RetiresAt is the announced time at which the model stops answering
	// requests. It is zero when none is announced.
	RetiresAt time.Time
	// Efforts are the reasoning effort levels the provider reports for the
	// model. The set is empty when the provider reports none, which does not
	// mean that the model has no reasoning control.
	Efforts EffortSet
	// DefaultEffort is the level the provider reports the model applies to a
	// request that names none. It is ReasoningEffortDefault when the provider
	// does not report one.
	DefaultEffort ReasoningEffort
}

ModelInfo is one entry of a provider's model list, reduced to what every provider can be asked for. A field the provider does not report is left at its zero value.

type ModelLifecycle added in v1.0.173

type ModelLifecycle string

ModelLifecycle is the stage of a model in its provider's catalog. Providers add stages over time, so a value outside the constants below is possible.

const (
	// ModelLifecycleUnknown means the provider does not report a lifecycle
	// for the model.
	ModelLifecycleUnknown ModelLifecycle = ""
	// ModelLifecycleActive is a model in normal service, with no retirement
	// announced.
	ModelLifecycleActive ModelLifecycle = "active"
	// ModelLifecycleDeprecated is a model that still answers requests but is
	// scheduled for retirement.
	ModelLifecycleDeprecated ModelLifecycle = "deprecated"
	// ModelLifecycleRetired is a model that no longer answers requests.
	ModelLifecycleRetired ModelLifecycle = "retired"
)

type ModelLister added in v1.0.173

type ModelLister interface {
	// ListModels returns every model the provider lists for the account, in
	// the provider's order. The list is not limited to chat models: it can
	// hold embedding, image or audio models as well.
	ListModels(ctx context.Context) ([]ModelInfo, error)
}

ModelLister is implemented by the provider clients that can list the models an account may call. Providers that advertise CapabilityModels implement it; assert it on a Model, or build a lister that needs no model name with the NewModelLister function of the provider package.

type ModelName added in v1.0.173

type ModelName struct {
	// ID is the model ID as given.
	ID string
	// Prefix is the routing or vendor prefix, such as "us.anthropic." in a
	// Bedrock ID or "openai/" in an OpenRouter ID. Empty for first-party IDs.
	Prefix string
	// Family is the name without prefix, version, snapshot and stage, such as
	// "claude-opus", "gpt-mini" or "gemini-flash-lite".
	Family string
	// Version holds the numeric version components, such as [4 8] for
	// claude-opus-4-8 and [5 1] for gpt-5.1. Empty when the ID has none.
	Version []int
	// Snapshot is the dated or numbered build, such as "20250514",
	// "2025-11-13" or "v1:0". Empty for a floating ID.
	Snapshot string
	// Stage is the release stage word, such as "preview". Empty for a
	// generally available model.
	Stage string
	// Variant is the offering a router appends to an ID after a colon, such
	// as "batch" in openai/gpt-5.5:batch or "free". It is the same model
	// served on other terms, so it is not part of the family, but it is part
	// of [ModelName.Key]. Empty for most IDs.
	Variant string
}

ModelName is a model ID split into the parts that tell a model family from its version. It is derived from naming conventions only, so it is a best guess: an ID that follows no convention keeps its whole name as the family and has no version.

func ParseModelName added in v1.0.173

func ParseModelName(id string) ModelName

ParseModelName splits a model ID into family, version, snapshot and stage.

The ID is cut on "-". Number tokens form the version, date and revision tokens the snapshot, stage words the stage, and the remaining tokens the family:

claude-fable-5-1                   family claude-fable   version 5.1
claude-3-5-sonnet-20241022         family claude-sonnet  version 3.5  snapshot 20241022
gpt-5.1-mini                       family gpt-mini       version 5.1
gemini-3-pro-preview               family gemini-pro     version 3    stage preview
us.anthropic.claude-opus-4-20250514-v1:0
                                   prefix us.anthropic.  family claude-opus  version 4
openai/gpt-5.5:batch               prefix openai/        family gpt          version 5.5  variant batch

func (ModelName) HasVersion added in v1.0.173

func (n ModelName) HasVersion() bool

HasVersion reports whether the ID carried a version.

func (ModelName) Key added in v1.0.173

func (n ModelName) Key() string

Key identifies the family across versions, including the prefix and the variant, so that models reached through different routes or served on different terms are not mixed up.

func (ModelName) VersionAtLeast added in v1.0.173

func (n ModelName) VersionAtLeast(parts ...int) bool

VersionAtLeast reports whether the model version is equal to or newer than the given components, for example VersionAtLeast(4, 6). It is false for a model without a version.

func (ModelName) VersionBelow added in v1.0.173

func (n ModelName) VersionBelow(parts ...int) bool

VersionBelow reports whether the model version is older than the given components. It is false for a model without a version.

type PromptCacheBreakpoint added in v0.15.112

type PromptCacheBreakpoint struct {
	// Target identifies the prompt element that should become a cache breakpoint.
	Target PromptCacheTarget
	// TTL overrides the provider cache breakpoint TTL where supported.
	TTL PromptCacheTTL
}

PromptCacheBreakpoint defines a provider-native cache breakpoint.

The term "cache breakpoint" comes from Anthropic prompt caching: https://platform.claude.com/docs/en/build-with-claude/prompt-caching

type PromptCachePolicy added in v0.15.112

type PromptCachePolicy struct {
	// Request configures request-level prompt caching (e.g. OpenAI).
	Request *PromptCacheRequestPolicy
	// Breakpoints configures explicit cache breakpoints (e.g. Anthropic).
	Breakpoints []PromptCacheBreakpoint
}

PromptCachePolicy configures provider-native prompt caching.

It intentionally combines provider-specific terminology:

For OpenAI-like providers, Request controls prompt cache key/retention. For Anthropic, Breakpoints control explicit cache breakpoints on prompt blocks/tools.

type PromptCacheRequestPolicy added in v0.15.112

type PromptCacheRequestPolicy struct {
	// Key identifies a reusable prompt cache entry on providers that support it.
	Key string
	// Retention controls how long the provider should retain the cached prompt.
	Retention PromptCacheRetention
}

PromptCacheRequestPolicy configures provider request-level prompt caching.

Field names such as "Key" and "Retention" align with OpenAI prompt caching request terminology ("prompt_cache_key", "prompt_cache_retention"): https://platform.openai.com/docs/guides/prompt-caching

type PromptCacheRetention added in v0.15.112

type PromptCacheRetention string

PromptCacheRetention specifies provider request-level prompt cache retention.

This terminology ("retention") is provider-specific and follows OpenAI prompt caching terminology: https://platform.openai.com/docs/guides/prompt-caching

const (
	PromptCacheRetentionInMemory PromptCacheRetention = "in-memory"
	PromptCacheRetention24h      PromptCacheRetention = "24h"
)

type PromptCacheTTL added in v0.15.112

type PromptCacheTTL string

PromptCacheTTL specifies Anthropic cache breakpoint TTL.

This terminology ("breakpoint", "TTL") follows Anthropic prompt caching terminology: https://platform.claude.com/docs/en/build-with-claude/prompt-caching

const (
	PromptCacheTTL5m PromptCacheTTL = "5m"
	PromptCacheTTL1h PromptCacheTTL = "1h"
)

type PromptCacheTarget added in v0.15.112

type PromptCacheTarget struct {
	// Kind identifies whether the target is a message part or a tool definition.
	Kind PromptCacheTargetKind
	// MessageIndex selects the original llms.Message index for message_part targets.
	MessageIndex int
	// PartIndex selects the llms.Message.Parts index for message_part targets.
	PartIndex int
	// ToolIndex selects the llms.Tool index for tool targets.
	ToolIndex int
}

PromptCacheTarget identifies a cacheable prompt element.

type PromptCacheTargetKind added in v0.15.112

type PromptCacheTargetKind string

PromptCacheTargetKind identifies the kind of target for a cache breakpoint.

"cache breakpoint" is Anthropic terminology: https://platform.claude.com/docs/en/build-with-claude/prompt-caching

const (
	PromptCacheTargetMessagePart PromptCacheTargetKind = "message_part"
	PromptCacheTargetTool        PromptCacheTargetKind = "tool"
)

type PromptValue

type PromptValue interface {
	String() string
	Messages() []Message
}

PromptValue is the interface that all prompt values must implement.

type ProviderType added in v0.10.54

type ProviderType string

ProviderType is the type of provider.

const (
	// ProviderAnthropic is the type of provider for Anthropic models.
	ProviderAnthropic ProviderType = "ANTHROPIC"
	// ProviderAnthropicBedrock is the type of provider for Anthropic models on Bedrock Mantle.
	ProviderAnthropicBedrock ProviderType = "ANTHROPIC_BEDROCK"
	// ProviderAzure is the type of provider for Azure OpenAI models.
	ProviderAzure ProviderType = "AZURE"
	// ProviderAzureAD is the type of provider for Azure OpenAI models with Azure AD authentication.
	ProviderAzureAD ProviderType = "AZURE_AD"
	// ProviderBedrock is the type of provider for Bedrock Mantle models.
	ProviderBedrock ProviderType = "BEDROCK"
	// ProviderGoogleAI is the type of provider for Google AI models.
	ProviderGoogleAI ProviderType = "GOOGLEAI"
	// ProviderOpenAI is the type of provider for OpenAI models.
	ProviderOpenAI ProviderType = "OPENAI"
	// ProviderOpenAIBedrock is the type of provider for OpenAI models on Bedrock Mantle.
	ProviderOpenAIBedrock ProviderType = "OPENAI_BEDROCK"
	// ProviderOpenRouter is the type of provider for OpenRouter models.
	ProviderOpenRouter ProviderType = "OPENROUTER"
)

func ParseProviderType added in v1.0.173

func ParseProviderType(s string) (ProviderType, error)

ParseProviderType converts a provider type name or one of its common aliases into a ProviderType. Matching ignores case, so callers that must tell a provider prefix from a lower-case vendor prefix in a model ID (for example "openai/gpt-oss-120b") have to check the case themselves before calling it.

func (ProviderType) Supports added in v0.10.54

func (p ProviderType) Supports(cap Capability) bool

Supports reports whether the provider supports ANY of the requested capabilities. Passing an OR of several bits therefore does not mean "all of them": for an all-of check use llmfactory.ModelOptions.RequiredCapabilities, or compare the mask directly:

llms.ProviderCapabilities(pt)&required == required

type ReasoningEffort added in v0.14.100

type ReasoningEffort int

ReasoningEffort is a provider-independent request for how much a model should reason before it answers. Levels are ordered, so they can be compared with < and >. Each provider sends the closest level the selected model accepts; see EffortSet.Nearest.

const (
	// ReasoningEffortDefault means no level was requested. The provider then
	// behaves as it does without any effort setting.
	ReasoningEffortDefault ReasoningEffort = iota
	// ReasoningEffortNone asks for the least reasoning the model allows.
	ReasoningEffortNone
	// ReasoningEffortLow asks for light reasoning.
	ReasoningEffortLow
	// ReasoningEffortMedium asks for moderate reasoning.
	ReasoningEffortMedium
	// ReasoningEffortHigh asks for extensive reasoning.
	ReasoningEffortHigh
	// ReasoningEffortXHigh asks for more reasoning than high, on models that
	// have such a level.
	ReasoningEffortXHigh
	// ReasoningEffortMax asks for the most reasoning the model allows.
	ReasoningEffortMax
)

func ParseReasoningEffort added in v1.0.173

func ParseReasoningEffort(s string) (ReasoningEffort, error)

ParseReasoningEffort converts a configuration name such as "medium" into a level. Matching ignores case and surrounding spaces. ReasoningEffortDefault has no name: leave the effort out instead of naming it.

func (ReasoningEffort) String added in v1.0.173

func (e ReasoningEffort) String() string

String returns the configuration name of the level, or an empty string for ReasoningEffortDefault and for values that are not levels.

type Role added in v0.11.64

type Role string

Role is the type of chat message.

const (
	// RoleAI is a message sent by an AI.
	RoleAI Role = "ai"
	// RoleHuman is a message sent by a human.
	RoleHuman Role = "human"
	// RoleSystem is a message sent by the system.
	RoleSystem Role = "system"
	// RoleGeneric is a message sent by a generic user.
	RoleGeneric Role = "generic"
	// RoleTool is a message sent by a tool.
	RoleTool Role = "tool"
)

type TextContent

type TextContent struct {
	Text string `json:"text"`
}

TextContent is content with some text.

func TextPart

func TextPart(s string) TextContent

TextPart creates TextContent from a given string.

func (TextContent) ContentLength added in v0.17.128

func (tc TextContent) ContentLength() int

func (TextContent) ContentType added in v0.18.137

func (tc TextContent) ContentType() ContentPartType

func (TextContent) MarshalJSON

func (tc TextContent) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for TextContent

func (TextContent) String

func (tc TextContent) String() string

func (*TextContent) UnmarshalJSON

func (tc *TextContent) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for TextContent

type TextContentJSON added in v0.10.55

type TextContentJSON struct {
	Text string `json:"text"`
	Type string `json:"type"`
}

TextContentJSON represents the JSON structure for text content

type Tool

type Tool struct {
	// Type is the type of the tool.
	Type string `json:"type"`
	// Function is the function to call.
	Function *FunctionDefinition `json:"function,omitempty"`
	// WebSearchOptions are the options for the web search tool,
	// For providers and models that support Web Search grounding.
	WebSearchOptions *WebSearchOptions `json:"-"`
}

Tool is a tool that can be used by the model.

func (Tool) RequireFunction added in v1.0.178

func (t Tool) RequireFunction() (*FunctionDefinition, error)

RequireFunction returns the function definition of t, for providers that convert the function tools of a call to their own format. It returns an error wrapping ErrMissingFunctionDefinition when Function is nil. A nil Function.Parameters is valid and means the function takes no arguments.

type ToolCall

type ToolCall struct {
	// ID is the unique identifier of the tool call.
	ID string `json:"id"`
	// Type is the type of the tool call: ToolTypeFunction for function tools,
	// or the tool type for provider-native tools such as web_search.
	Type string `json:"type"`
	// FunctionCall is the function call to be executed.
	FunctionCall *FunctionCall `json:"function,omitempty"`
}

ToolCall is a call to a tool (as requested by the model) that should be executed.

func (ToolCall) ContentLength added in v0.17.128

func (tc ToolCall) ContentLength() int

func (ToolCall) ContentType added in v0.18.137

func (tc ToolCall) ContentType() ContentPartType

func (ToolCall) GetFunctionCallArguments added in v0.14.88

func (tc ToolCall) GetFunctionCallArguments() string

GetFunctionCallArguments returns the raw arguments JSON, or an empty string for provider-native tools.

func (ToolCall) GetFunctionCallName added in v0.14.88

func (tc ToolCall) GetFunctionCallName() string

GetFunctionCallName returns the called function's name, or the tool type for provider-native tools such as web_search.

func (ToolCall) MarshalJSON

func (tc ToolCall) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for ToolCall

func (ToolCall) RequireFunctionCall added in v1.0.178

func (tc ToolCall) RequireFunctionCall() (*FunctionCall, error)

RequireFunctionCall returns the function call of tc, for providers that send the tool calls of the message history back to the model. It does not look at Type, so a call whose Type is empty still has its function call returned. It returns an error wrapping ErrMissingFunctionCall when FunctionCall is nil.

func (ToolCall) String added in v0.11.64

func (tc ToolCall) String() string

String describes the tool call for logs: its ID, the function name (or the tool type of a provider-native call) and its arguments.

func (*ToolCall) UnmarshalJSON

func (tc *ToolCall) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for ToolCall

type ToolCallContentJSON added in v0.10.55

type ToolCallContentJSON struct {
	Type     string       `json:"type"`
	ToolCall ToolCallJSON `json:"tool_call"`
}

ToolCallContentJSON represents the JSON structure for tool call content

type ToolCallJSON added in v0.10.55

type ToolCallJSON struct {
	ID           string        `json:"id"`
	Type         string        `json:"type"`
	FunctionCall *FunctionCall `json:"function"`
}

ToolCallJSON represents the JSON structure for tool call content

type ToolCallJSONOrdered added in v0.10.55

type ToolCallJSONOrdered struct {
	FunctionCall *FunctionCall `json:"function"`
	ID           string        `json:"id"`
	Type         string        `json:"type"`
}

ToolCallJSONOrdered matches the expected field order for marshaling function, id, type This is only for marshaling (UnmarshalJSON still uses ToolCallJSON for flexibility)

type ToolCallResponse

type ToolCallResponse struct {
	// ToolCallID is the ID of the tool call this response is for.
	ToolCallID string `json:"tool_call_id"`
	// Name is the name of the tool that was called.
	Name string `json:"name"`
	// Content is the textual content of the response.
	Content string `json:"content"`
}

ToolCallResponse is the response returned by a tool call.

func (ToolCallResponse) ContentLength added in v0.17.128

func (tc ToolCallResponse) ContentLength() int

func (ToolCallResponse) ContentType added in v0.18.137

func (tc ToolCallResponse) ContentType() ContentPartType

func (ToolCallResponse) MarshalJSON

func (tc ToolCallResponse) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for ToolCallResponse

func (ToolCallResponse) String added in v0.11.64

func (tc ToolCallResponse) String() string

func (*ToolCallResponse) ToToolResponseJSONOrdered added in v0.10.55

func (tc *ToolCallResponse) ToToolResponseJSONOrdered() *ToolResponseJSONOrdered

ToToolResponseJSONOrdered converts ToolCallResponse to ToolResponseJSONOrdered

func (*ToolCallResponse) UnmarshalJSON

func (tc *ToolCallResponse) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for ToolCallResponse

type ToolChoice

type ToolChoice struct {
	// Type is the type of the tool.
	Type string `json:"type"`
	// Function is the function to call (if the tool is a function).
	Function *FunctionReference `json:"function,omitempty"`
}

ToolChoice is a specific tool to use.

type ToolChoiceMode added in v0.21.160

type ToolChoiceMode string

ToolChoiceMode controls whether and which tools the model may call.

type ToolResponseContentJSON added in v0.10.55

type ToolResponseContentJSON struct {
	Type         string           `json:"type"`
	ToolResponse ToolResponseJSON `json:"tool_response"`
}

ToolResponseContentJSON represents the JSON structure for tool response content

type ToolResponseJSON added in v0.10.55

type ToolResponseJSON struct {
	ToolCallID string `json:"tool_call_id"`
	Name       string `json:"name"`
	Content    string `json:"content"`
}

ToolResponseJSON represents the JSON structure for tool response content

type ToolResponseJSONOrdered added in v0.10.55

type ToolResponseJSONOrdered struct {
	ToolCallID string `json:"tool_call_id"`
	Name       string `json:"name"`
	Content    string `json:"content"`
}

ToolResponseJSONOrdered matches the expected field order for marshaling tool_call_id, name, content This is only for marshaling (UnmarshalJSON still uses ToolResponseJSON for flexibility)

type Usage added in v0.18.140

type Usage struct {
	InputTokens      uint64
	OutputTokens     uint64
	CacheWriteTokens uint64
	CacheReadTokens  uint64
	ReasoningTokens  uint64
	TotalTokens      uint64
}

Usage counts the tokens consumed by one or more LLM calls. CacheWriteTokens and CacheReadTokens report prompt-cache effectiveness on providers that support it.

func (*Usage) Add added in v0.18.140

func (r *Usage) Add(other *Usage)

Add accumulates other into r. Both nil receiver and nil argument are no-ops.

type UsageStats added in v0.18.140

type UsageStats struct {
	ModelUsage map[string]*Usage

	// BytesOut is the number of bytes sent to the LLM.
	BytesOut uint64
	// BytesIn is the number of bytes received from the LLM.
	BytesIn uint64
	// LlmCallCount is the number of GenerateContent calls made.
	LlmCallCount uint32
}

UsageStats aggregates token usage per model together with payload sizes and the number of GenerateContent calls made. An assistant's Response.Usage is the total for its whole subtree, including nested assistants.

func (*UsageStats) Add added in v0.18.140

func (r *UsageStats) Add(other *UsageStats)

Add accumulates other into r, merging the per-model usage. Both nil receiver and nil argument are no-ops.

func (*UsageStats) AddModelUsage added in v0.19.142

func (r *UsageStats) AddModelUsage(model string, other *Usage)

AddModelUsage accumulates usage attributed to the named model.

type WebSearchOptions added in v0.14.88

type WebSearchOptions struct {
	// AllowedDomains is a list of domains to search on.
	// Supported by OpenAI, Anthropic, and Azure.
	AllowedDomains []string
	// ExcludedDomains is a list of domains to exclude from search.
	// Supported by Google AI.
	ExcludedDomains []string
	// MaxUses is the maximum number of times the tool can be used.
	// Supported by OpenAI, Anthropic, and Azure.
	MaxUses int
}

Directories

Path Synopsis
Package anthropic implements the Anthropic (Claude) llms.Model with options for API key, model selection, and custom HTTP client or AWS config when used via Bedrock (see NewBedrock in this package).
Package anthropic implements the Anthropic (Claude) llms.Model with options for API key, model selection, and custom HTTP client or AWS config when used via Bedrock (see NewBedrock in this package).
Package bedrock implements an llms.Model backed by AWS Bedrock.
Package bedrock implements an llms.Model backed by AWS Bedrock.
Package googleai implements Google AI (Vertex/Gemini) llms.Model wrappers.
Package googleai implements Google AI (Vertex/Gemini) llms.Model wrappers.
Package openai provides an llms.Model implementation for OpenAI-compatible APIs, including OpenAI and Azure OpenAI endpoints.
Package openai provides an llms.Model implementation for OpenAI-compatible APIs, including OpenAI and Azure OpenAI endpoints.

Jump to

Keyboard shortcuts

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