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
- Variables
- func GenerateFromSinglePrompt(ctx context.Context, llm Model, prompt string, options ...CallOption) (string, error)
- func InferenceFailure(err error, status int, operation string) error
- func ReasoningBudget(effort Effort) (int, bool)
- func UnsupportedInference(param string) error
- type BatchHandle
- type BatchRequest
- type BatchRequestCounts
- type BatchRequestError
- type BatchResult
- type BatchStatus
- type BatchSubmitOption
- type BatchSubmitOptions
- type Batcher
- type BinaryContent
- type BinaryContentJSON
- type BinaryJSON
- type BlockType
- type CallOption
- func WithCandidateCount(c int) CallOption
- func WithFrequencyPenalty(frequencyPenalty float64) CallOption
- func WithMaxLength(maxLength int) CallOption
- func WithMaxTokens(maxTokens int) CallOption
- func WithMetadata(metadata map[string]any) CallOption
- func WithMinLength(minLength int) CallOption
- func WithModel(model string) CallOption
- func WithN(n int) CallOption
- func WithOptions(options CallOptions) CallOption
- func WithPresencePenalty(presencePenalty float64) CallOption
- func WithPromptCachePolicy(promptCachePolicy *PromptCachePolicy) CallOption
- func WithReasoningEffort(reasoningEffort ReasoningEffort) CallOption
- func WithRepetitionPenalty(repetitionPenalty float64) CallOption
- func WithResponseFormat(responseFormat *schema.ResponseFormat) CallOption
- func WithSeed(seed int) CallOption
- func WithStopWords(stopWords []string) CallOption
- func WithStreamingFunc(streamingFunc func(ctx context.Context, chunk []byte) error) CallOption
- func WithStreamingReasoningFunc(...) CallOption
- func WithTemperature(temperature float64) CallOption
- func WithToolChoice(choice any) CallOption
- func WithTools(tools []Tool) CallOption
- func WithTopK(topK int) CallOption
- func WithTopP(topP float64) CallOption
- type CallOptions
- type Capability
- type ContentChoice
- type ContentPart
- type ContentPartJSON
- type ContentPartType
- type ContentResponse
- type Effort
- type Embedder
- type FinishReason
- type FormatType
- type FunctionCall
- type FunctionCallBehavior
- type FunctionDefinition
- type FunctionReference
- type ImageURLContent
- type ImageURLContentJSON
- type ImageURLJSON
- type InferenceBlock
- type InferenceError
- type InferenceFormat
- type InferenceMessage
- type InferenceModel
- type InferenceReasoning
- type InferenceRequest
- type InferenceResponse
- type InferenceRole
- type InferenceTool
- type InferenceToolChoice
- type Message
- type MessageContentJSON
- type MessageContentWithPartsJSON
- type MessageSource
- type Messages
- type Model
- type PromptCacheBreakpoint
- type PromptCachePolicy
- type PromptCacheRequestPolicy
- type PromptCacheRetention
- type PromptCacheTTL
- type PromptCacheTarget
- type PromptCacheTargetKind
- type PromptValue
- type ProviderType
- type ReasoningEffort
- type Role
- type TextContent
- type TextContentJSON
- type Tool
- type ToolCall
- func (tc ToolCall) ContentLength() int
- func (tc ToolCall) ContentType() ContentPartType
- func (tc ToolCall) GetFunctionCallArguments() string
- func (tc ToolCall) GetFunctionCallName() string
- func (tc ToolCall) MarshalJSON() ([]byte, error)
- func (tc ToolCall) String() string
- func (tc *ToolCall) UnmarshalJSON(data []byte) error
- type ToolCallContentJSON
- type ToolCallJSON
- type ToolCallJSONOrdered
- type ToolCallResponse
- func (tc ToolCallResponse) ContentLength() int
- func (tc ToolCallResponse) ContentType() ContentPartType
- func (tc ToolCallResponse) MarshalJSON() ([]byte, error)
- func (tc ToolCallResponse) String() string
- func (tc *ToolCallResponse) ToToolResponseJSONOrdered() *ToolResponseJSONOrdered
- func (tc *ToolCallResponse) UnmarshalJSON(data []byte) error
- type ToolChoice
- type ToolChoiceMode
- type ToolResponseContentJSON
- type ToolResponseJSON
- type ToolResponseJSONOrdered
- type Usage
- type UsageStats
- type WebSearchOptions
Constants ¶
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.
const ( ReasoningEffortDefault = iota ReasoningEffortNone ReasoningEffortLow ReasoningEffortMedium ReasoningEffortHigh )
Variables ¶
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.
var ErrUnexpectedRole = errors.New("unexpected role")
ErrUnexpectedRole is returned when a message role is of an unexpected type.
Functions ¶
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
InferenceFailure attaches the provider HTTP status to an external failure.
func ReasoningBudget ¶ added in v0.21.160
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
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 ¶
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
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 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 )
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"`
// This field is only used with the deepseek-reasoner model and represents the reasoning contents of the assistant message before the final answer.
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
EffortForBudget maps a token budget to the closest effort level for providers that only expose a discrete effort control.
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
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
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
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
func (r InferenceRequest) Clone() InferenceRequest
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
func (r InferenceResponse) Clone() InferenceResponse
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
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
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
MarshalJSON implements json.Marshaler for MessageContent
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
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 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:
- OpenAI-like providers use request-level cache key/retention terms: https://platform.openai.com/docs/guides/prompt-caching
- Anthropic uses explicit cache breakpoint/TTL terms: https://platform.claude.com/docs/en/build-with-claude/prompt-caching
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 ¶
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. ProviderAnthropic ProviderType = "ANTHROPIC" // ProviderAnthropicBedrock is the type of provider. ProviderAnthropicBedrock ProviderType = "ANTHROPIC_BEDROCK" // ProviderAzure is the type of provider. ProviderAzure ProviderType = "AZURE" // ProviderAzureAD is the type of provider. ProviderAzureAD ProviderType = "AZURE_AD" // ProviderBedrock is the type of provider. ProviderBedrock ProviderType = "BEDROCK" // ProviderCloudflare is the type of provider. ProviderCloudflare ProviderType = "CLOUDFLARE" // ProviderGoogleAI is the type of provider. ProviderGoogleAI ProviderType = "GOOGLEAI" // ProviderOpenAI is the type of provider. ProviderOpenAI ProviderType = "OPENAI" // ProviderOpenAIBedrock is the type of provider. ProviderOpenAIBedrock ProviderType = "OPENAI_BEDROCK" // ProviderOpenRouter is the type of provider. ProviderOpenRouter ProviderType = "OPENROUTER" // ProviderPerplexity is the type of provider. ProviderPerplexity ProviderType = "PERPLEXITY" )
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
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
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.
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. Typically, this would be "function".
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 (ToolCall) ContentType ¶ added in v0.18.137
func (tc ToolCall) ContentType() ContentPartType
func (ToolCall) GetFunctionCallArguments ¶ added in v0.14.88
GetFunctionCallArguments returns the raw arguments JSON, or an empty string for provider-native tools.
func (ToolCall) GetFunctionCallName ¶ added in v0.14.88
GetFunctionCallName returns the called function's name, or the tool type for provider-native tools such as web_search.
func (ToolCall) MarshalJSON ¶
MarshalJSON implements json.Marshaler for ToolCall
func (*ToolCall) UnmarshalJSON ¶
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.
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
}
Source Files
¶
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 cloudflare implements an llms.Model for Cloudflare AI Gateway and compatible APIs.
|
Package cloudflare implements an llms.Model for Cloudflare AI Gateway and compatible APIs. |
|
Package googleai implements Google AI (Vertex/Gemini) llms.Model wrappers.
|
Package googleai implements Google AI (Vertex/Gemini) llms.Model wrappers. |
|
internal/cmd
command
Code generator for vertex.go from googleai.go nolint
|
Code generator for vertex.go from googleai.go nolint |
|
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. |