Documentation
¶
Overview ¶
Package gollm provides a high-level interface for interacting with various Language Learning Models (LLMs). This file re-exports configuration types and functions from the config package to provide a clean, centralized API for configuring LLM interactions.
Package gollm provides a high-level interface for interacting with various Language Learning Models (LLMs). It supports multiple providers including OpenAI, Anthropic, Ollama, and others, with features like prompt optimization, caching, and structured output handling.
Package gollm provides a high-level interface for interacting with Language Learning Models (LLMs).
Package gollm provides prompt handling and manipulation functionality for Language Learning Models. This file contains type definitions, re-exports, and utility functions for working with prompts and their associated components like caching, templates, and message handling.
Package gollm provides streaming functionality for Language Learning Models. This file contains type definitions and re-exports for working with streaming responses.
Package gollm provides validation functionality for Language Learning Model interactions. This file contains utilities for validating structured data and generating JSON schemas, which are essential for ensuring proper data formats in LLM communications.
Index ¶
- Constants
- Variables
- func CleanResponse(response string) string
- func DefaultValidate(s interface{}) error
- func GenerateJSONSchema(v interface{}) ([]byte, error)
- func Validate(s interface{}) error
- func ValidateWithCustomValidator(s interface{}, customValidator ValidatorFunc) error
- type CacheType
- type Config
- type ConfigOption
- type ContentPart
- type Function
- type ImageSource
- type ImageURL
- type LLM
- type LogLevel
- type Logger
- type MOA
- type MOAConfig
- type MOALayer
- type MemoryMessage
- type MemoryOption
- type Prompt
- type PromptMessage
- type PromptOption
- type PromptTemplate
- type RetryStrategy
- type SchemaOption
- type StreamConfig
- type StreamOption
- type StreamToken
- type TokenStream
- type Tool
- type ToolCall
- type ToolResult
- type ValidatorFunc
Constants ¶
const ( LogLevelOff = utils.LogLevelOff // Disables all logging LogLevelError = utils.LogLevelError // Logs only errors LogLevelWarn = utils.LogLevelWarn // Logs warnings and errors LogLevelInfo = utils.LogLevelInfo // Logs info, warnings, and errors LogLevelDebug = utils.LogLevelDebug // Logs all messages including debug )
LogLevel constants define available logging verbosity levels
const ( // CacheTypeEphemeral indicates that cached responses should only persist // for the duration of the program's execution. CacheTypeEphemeral = llm.CacheTypeEphemeral )
Cache type constants define the available caching strategies.
Variables ¶
var ( // LoadConfig loads configuration from environment variables and returns a new Config instance. // It automatically detects and loads API keys from environment variables matching the pattern // *_API_KEY (e.g., OPENAI_API_KEY, ANTHROPIC_API_KEY). // // Example usage: // cfg, err := LoadConfig() // if err != nil { // log.Fatal(err) // } LoadConfig = config.LoadConfig // ApplyOptions applies a series of ConfigOption functions to a Config instance. // This enables fluent configuration updates using the builder pattern. // // Example usage: // cfg := NewConfig() // cfg = ApplyOptions(cfg, SetProvider("openai"), SetModel("gpt-3.5-turbo")) ApplyOptions = config.ApplyOptions )
Re-export core configuration functions
var ( // Provider configuration SetProvider = config.SetProvider // Sets the LLM provider (e.g., "openai", "anthropic") SetModel = config.SetModel // Sets the model name for the selected provider SetOllamaEndpoint = config.SetOllamaEndpoint // Sets the endpoint URL for Ollama local deployment SetVLLMEndpoint = config.SetVLLMEndpoint // Sets the endpoint URL for vLLM local deployment SetAPIKey = config.SetAPIKey // Sets the API key for the current provider // Generation parameters SetTemperature = config.SetTemperature // Controls randomness in generation (0.0-1.0) SetMaxTokens = config.SetMaxTokens // Sets maximum tokens to generate SetTopP = config.SetTopP // Controls nucleus sampling SetFrequencyPenalty = config.SetFrequencyPenalty // Penalizes frequent token usage SetPresencePenalty = config.SetPresencePenalty // Penalizes repeated tokens SetSeed = config.SetSeed // Sets random seed for reproducible generation // Advanced generation parameters SetMinP = config.SetMinP // Sets minimum probability threshold SetRepeatPenalty = config.SetRepeatPenalty // Controls repetition penalty SetRepeatLastN = config.SetRepeatLastN // Sets context window for repetition SetMirostat = config.SetMirostat // Enables Mirostat sampling SetMirostatEta = config.SetMirostatEta // Sets Mirostat learning rate SetMirostatTau = config.SetMirostatTau // Sets Mirostat target entropy SetTfsZ = config.SetTfsZ // Sets tail-free sampling parameter // Runtime configuration SetTimeout = config.SetTimeout // Sets request timeout duration SetMaxRetries = config.SetMaxRetries // Sets maximum retry attempts SetRetryDelay = config.SetRetryDelay // Sets delay between retries SetLogLevel = config.SetLogLevel // Sets logging verbosity SetExtraHeaders = config.SetExtraHeaders // Sets additional HTTP headers // Feature toggles SetEnableCaching = config.SetEnableCaching // Enables/disables response caching SetMemory = config.SetMemory // Configures conversation memory // Validation configuration SetCustomValidator = config.SetCustomValidator // Sets a custom validation function to override default validation // Logging SetLogger = config.SetLogger // Sets a custom logger implementation // Configuration creation NewConfig = config.NewConfig // Creates a new Config with default values // Logger utilities NewNopLogger = utils.NewNopLogger // Creates a no-op logger that discards all output )
Re-export ConfigOption functions for configuration modification. Each function returns a ConfigOption that can be used with ApplyOptions to modify configuration settings.
var ( // NewPrompt creates a new prompt instance with the given options. NewPrompt = llm.NewPrompt // CacheOption configures caching behavior for a prompt. CacheOption = llm.CacheOption // WithSystemPrompt adds a system-level prompt message. WithSystemPrompt = llm.WithSystemPrompt // WithMessage adds a single message to the prompt. WithMessage = llm.WithMessage // WithTools configures available tools for the prompt. WithTools = llm.WithTools // WithToolChoice specifies how tools should be selected. WithToolChoice = llm.WithToolChoice // WithMessages adds multiple messages to the prompt. WithMessages = llm.WithMessages // WithDirectives adds special instructions or constraints. WithDirectives = llm.WithDirectives // WithOutput configures the expected output format. WithOutput = llm.WithOutput // WithContext adds contextual information to the prompt. WithContext = llm.WithContext // WithMaxLength sets the maximum length for generated responses. WithMaxLength = llm.WithMaxLength // WithExamples adds example conversations or outputs. WithExamples = llm.WithExamples // WithExpandedStruct enables detailed structure expansion. WithExpandedStruct = llm.WithExpandedStruct // NewPromptTemplate creates a new template for generating prompts. NewPromptTemplate = llm.NewPromptTemplate // WithPromptOptions adds multiple prompt options at once. WithPromptOptions = llm.WithPromptOptions // WithJSONSchemaValidation enables JSON schema validation. WithJSONSchemaValidation = llm.WithJSONSchemaValidation // WithStream enables or disables streaming responses. WithStream = config.WithStream // WithImageURL adds an image by URL to the prompt for vision-capable models. // The detail parameter controls image processing quality: "auto", "low", or "high". WithImageURL = llm.WithImageURL // WithImageBase64 adds a base64-encoded image to the prompt for vision-capable models. // The mediaType should specify the image format (e.g., "image/png", "image/jpeg"). WithImageBase64 = llm.WithImageBase64 // WithImages adds multiple images to the prompt for vision-capable models. WithImages = llm.WithImages )
The following variables are re-exported functions from the llm package. They provide the primary means of constructing and customizing prompts.
Functions ¶
func CleanResponse ¶
CleanResponse processes and cleans up LLM responses by removing markdown formatting and extracting JSON content. It performs the following operations:
- Removes markdown code block delimiters (```json)
- Extracts JSON content between the first '{' and last '}'
- Trims any remaining whitespace
This is particularly useful when working with LLMs that return formatted markdown or when you need to extract clean JSON from a response.
Parameters:
- response: The raw response string from the LLM
Returns:
- A cleaned string containing only the relevant content
func DefaultValidate ¶ added in v0.1.11
func DefaultValidate(s interface{}) error
DefaultValidate performs the standard struct validation using the go-playground/validator. This can be called from custom validators to fall back to default validation behavior.
Example usage in a custom validator:
gollm.SetCustomValidator(func(v interface{}) error {
if config, ok := v.(*gollm.Config); ok && config.Provider == "google" {
return nil // Skip validation for Google
}
return gollm.DefaultValidate(v) // Use default for others
})
func GenerateJSONSchema ¶
GenerateJSONSchema generates a JSON schema for the given struct. The schema is generated based on struct fields and their tags, providing a complete JSON Schema that can be used for validation or documentation.
The function analyzes struct fields and generates a schema that includes:
- Field types and formats
- Required fields
- Validation rules from struct tags
- Nested object structures
- Array specifications
- Custom validation rules
- Format constraints
Example usage:
type Message struct {
Role string `json:"role" validate:"required,oneof=system user assistant"`
Content string `json:"content" validate:"required,min=1"`
Tokens int `json:"tokens,omitempty" validate:"min=0"`
Tags []string `json:"tags,omitempty" validate:"unique"`
}
type Conversation struct {
ID string `json:"id" validate:"required,uuid"`
Messages []Message `json:"messages" validate:"required,min=1"`
Model string `json:"model" validate:"required,model"`
}
schema, err := GenerateJSONSchema(&Conversation{})
Parameters:
- v: The struct to generate schema for. Must be a pointer to a struct.
Returns:
- []byte: The generated JSON schema as a byte slice
- error: Any error encountered during schema generation
func Validate ¶
func Validate(s interface{}) error
Validate checks if the given struct is valid according to its validation rules. It uses struct tags to define validation rules and performs comprehensive validation of the input structure.
The function supports various validation rules through struct tags, including:
- required: Field must be present and non-zero
- min/max: Numeric range validation
- len: Exact length requirement
- email: Email format validation
- url: URL format validation
- regex: Pattern matching
- contains/excludes: String content validation
- unique: Array unique items validation
- minItems/maxItems: Array length validation
- password: Password strength validation
Example usage:
type Config struct {
Model string `validate:"required,model"`
MaxTokens int `validate:"min=1,max=4096"`
Email string `validate:"required,email"`
Password string `validate:"required,password=strong"`
}
config := Config{
Model: "gpt-4",
MaxTokens: 2048,
Email: "user@example.com",
Password: "SecureP@ss123",
}
err := Validate(&config)
Parameters:
- s: The struct to validate. Must be a pointer to a struct.
Returns:
- error: nil if validation passes, otherwise returns detailed validation errors
func ValidateWithCustomValidator ¶ added in v0.1.11
func ValidateWithCustomValidator(s interface{}, customValidator ValidatorFunc) error
ValidateWithCustomValidator checks if the given struct is valid, using a custom validator if provided. This allows for scoped custom validation without affecting other goroutines.
Parameters:
- s: The struct to validate. Must be a pointer to a struct.
- customValidator: Optional ValidatorFunc. If nil, uses default validation.
Returns:
- error: nil if validation passes, otherwise returns validation errors
Example:
err := gollm.ValidateWithCustomValidator(cfg, func(v interface{}) error {
if config, ok := v.(*gollm.Config); ok && config.Provider == "google" {
return nil // Skip validation for Google
}
return gollm.DefaultValidate(v)
})
Types ¶
type CacheType ¶ added in v0.1.0
CacheType defines how prompts should be cached in the system. Different cache types affect the persistence and availability of cached responses.
type Config ¶
Config represents the complete configuration for LLM interactions. It includes settings for model selection, API endpoints, generation parameters, and runtime behavior. See config.Config for detailed field documentation.
Example usage:
cfg := NewConfig()
cfg = ApplyOptions(cfg, SetProvider("openai"), SetModel("gpt-3.5-turbo"))
type ConfigOption ¶
type ConfigOption = config.ConfigOption
ConfigOption is a function type that modifies a Config instance. It enables a builder pattern for configuration, allowing for clean and flexible configuration updates.
Example usage:
cfg := NewConfig() cfg = ApplyOptions(cfg, SetTemperature(0.7), SetMaxTokens(2048))
type ContentPart ¶ added in v0.1.11
type ContentPart = types.ContentPart
ContentPart represents a single part of multimodal content (text or image). Used for vision-capable models that can process both text and images.
type Function ¶ added in v0.1.0
Function defines a callable function that can be used by the LLM. It includes metadata like name, description, and parameter schemas.
type ImageSource ¶ added in v0.1.11
type ImageSource = types.ImageSource
ImageSource represents a base64-encoded image for vision models.
type LLM ¶
type LLM interface {
llm.LLM // Embed the base interface
// GetPromptJSONSchema returns the JSON schema for prompt validation in byte format.
// The schema can be customized using SchemaOption parameters.
GetPromptJSONSchema(opts ...SchemaOption) ([]byte, error)
// GetProvider returns the name of the current LLM provider (e.g., "openai", "anthropic").
GetProvider() string
// GetModel returns the name of the current model being used.
GetModel() string
// UpdateLogLevel changes the logging verbosity for both gollm and internal LLM operations.
UpdateLogLevel(level LogLevel)
// Debug logs a debug message with optional key-value pairs for detailed logging.
Debug(msg string, keysAndValues ...interface{})
// GetLogLevel returns the current logging verbosity level.
GetLogLevel() LogLevel
// SetOllamaEndpoint configures a custom endpoint for Ollama provider.
// Returns an error if the current provider doesn't support endpoint configuration.
SetOllamaEndpoint(endpoint string) error
// SetSystemPrompt updates the system prompt with caching configuration.
// The cacheType parameter determines how the prompt should be cached.
SetSystemPrompt(prompt string, cacheType CacheType)
// HasMemory returns true if this LLM instance has memory enabled.
HasMemory() bool
// ClearMemory removes all messages from the conversation history.
// Does nothing if memory is not enabled.
ClearMemory()
// GetMemory returns the conversation history as a slice of messages.
// Returns nil if memory is not enabled.
GetMemory() []MemoryMessage
// AddToMemory adds a message to the conversation history.
// Does nothing if memory is not enabled.
AddToMemory(role, content string)
// AddStructuredMessage adds a message with cache control to the conversation history.
// The cacheControl parameter specifies caching behavior (e.g., "ephemeral").
// Does nothing if memory is not enabled.
AddStructuredMessage(role, content, cacheControl string)
// SetUseStructuredMessages configures whether to use structured messages.
// When true (default), messages are passed as separate JSON objects to the provider.
// When false, messages are flattened into a single prompt string.
// Does nothing if memory is not enabled.
SetUseStructuredMessages(use bool)
// AddToolResult adds a tool execution result to the conversation history.
// Use this after executing a tool to provide the result back to the LLM.
// Does nothing if memory is not enabled.
AddToolResult(toolCallID, result string)
// AddToolError adds a tool execution error to the conversation history.
// Use this when a tool fails to inform the LLM of the error.
// Does nothing if memory is not enabled.
AddToolError(toolCallID, errorMessage string)
// AddAssistantMessageWithToolCalls adds an assistant message with tool calls.
// This preserves tool calls in the conversation for multi-turn tool usage.
// Does nothing if memory is not enabled.
AddAssistantMessageWithToolCalls(content string, toolCalls []ToolCall)
}
LLM is the interface that wraps the basic LLM operations. It extends the base llm.LLM interface with additional functionality specific to gollm, providing a comprehensive set of methods for LLM interaction, configuration, and management.
func NewLLM ¶
func NewLLM(opts ...ConfigOption) (LLM, error)
NewLLM creates a new LLM instance with the specified configuration options. It supports memory management, caching, and provider-specific optimizations. If memory options are provided, it creates an LLM instance with conversation memory.
The function performs the following setup: 1. Loads and applies configuration from both default and provided options 2. Initializes logging system with appropriate verbosity 3. Sets up provider-specific optimizations (e.g., Anthropic caching headers) 4. Creates and configures the base LLM instance 5. Optionally enables conversation memory if specified in config
Returns an error if: - Configuration loading fails - Provider initialization fails - Memory setup fails (if memory option is enabled)
type LogLevel ¶
LogLevel defines the verbosity of logging output. Available levels are defined as constants: LogLevelOff through LogLevelDebug.
Example usage:
cfg := NewConfig() cfg = ApplyOptions(cfg, SetLogLevel(LogLevelInfo))
type Logger ¶ added in v0.1.10
Logger is the interface for custom loggers. Implement this interface to use your own logging solution.
type MOA ¶ added in v0.0.94
type MOA struct {
// Config holds the MOA system configuration
Config MOAConfig
// Layers contains the processing layers, each with one or more models
Layers []MOALayer
// Aggregator is the LLM instance used to synthesize outputs from multiple models
Aggregator llm.LLM
}
MOA (Mixture of Agents) implements an ensemble learning system that combines multiple language models to produce higher quality outputs. It processes inputs through multiple layers and iterations, then aggregates the results using a designated aggregator model.
func NewMOA ¶ added in v0.0.94
func NewMOA(moaConfig MOAConfig, aggregatorOpts ...ConfigOption) (*MOA, error)
NewMOA creates a new Mixture of Agents instance with the specified configuration and aggregator options.
Parameters:
- moaConfig: Configuration for the MOA system
- aggregatorOpts: Configuration options for the aggregator model
Returns:
- A configured MOA instance
- Any error encountered during initialization
Example:
moa, err := NewMOA(MOAConfig{
Iterations: 3,
Models: []ConfigOption{SetModel("gpt-4"), SetModel("claude-3")},
MaxParallel: 2,
})
func (*MOA) Generate ¶ added in v0.0.94
Generate processes the input through the Mixture of Agents and returns the final output. It runs the input through multiple iterations of processing layers, then aggregates the results using the designated aggregator model.
Parameters:
- ctx: Context for cancellation and timeout control
- input: The text input to process
Returns:
- The final processed output
- Any error encountered during processing
The processing flow is: 1. Input is processed through each layer in sequence 2. Each layer's output becomes the input for the next layer 3. This process repeats for the specified number of iterations 4. Results from all iterations are aggregated into the final output
type MOAConfig ¶ added in v0.0.94
type MOAConfig struct {
// Iterations specifies the number of refinement cycles to perform
Iterations int
// Models defines the set of language models to use in the mixture
// Each model is configured using ConfigOption functions
Models []ConfigOption
// MaxParallel limits the number of concurrent model executions
// If set to 0, all models run concurrently without limitation
MaxParallel int
// AgentTimeout specifies the maximum duration for each agent's execution
// If set to 0, no timeout is applied
AgentTimeout time.Duration
}
MOAConfig represents the configuration for the Mixture of Agents (MOA) system. MOA is an ensemble learning approach that combines multiple language models to produce higher quality outputs through iterative refinement and aggregation.
type MOALayer ¶ added in v0.0.94
type MOALayer struct {
// Models contains the LLM instances that operate within this layer
Models []llm.LLM
}
MOALayer represents a single layer in the Mixture of Agents architecture. Each layer contains one or more language models that process inputs in parallel.
type MemoryMessage ¶ added in v0.1.0
type MemoryMessage = llm.MemoryMessage
MemoryMessage represents a message stored in the LLM's conversation memory. These messages provide context for maintaining coherent conversations.
type MemoryOption ¶ added in v0.0.8
type MemoryOption = config.MemoryOption
MemoryOption configures the memory settings for conversation history. It controls how much context is retained between interactions.
Example usage:
cfg := NewConfig()
cfg = ApplyOptions(cfg, SetMemory(MemoryOption{MaxHistory: 10}))
type Prompt ¶
Prompt represents a complete prompt structure that can be sent to an LLM. It includes system messages, user messages, and optional components like tools and cache settings.
type PromptMessage ¶ added in v0.1.0
type PromptMessage = llm.PromptMessage
PromptMessage represents a single message in a conversation with the LLM. It can be a system message, user message, or assistant message.
type PromptOption ¶
type PromptOption = llm.PromptOption
PromptOption defines a function that can modify a prompt's configuration. These are used to customize prompt behavior in a flexible, chainable way.
type PromptTemplate ¶
type PromptTemplate = llm.PromptTemplate
PromptTemplate defines a reusable template for generating prompts. Templates can include variables that are filled in at runtime.
type RetryStrategy ¶ added in v0.1.4
type RetryStrategy = llm.RetryStrategy
RetryStrategy defines the interface for handling stream interruptions.
type SchemaOption ¶
type SchemaOption = llm.SchemaOption
SchemaOption defines options for JSON schema generation. These control how prompts are validated against schemas.
type StreamConfig ¶ added in v0.1.4
type StreamConfig = llm.StreamConfig
StreamConfig holds configuration options for streaming.
type StreamOption ¶ added in v0.1.4
type StreamOption = llm.StreamOption
StreamOption is a function type that modifies StreamConfig
type StreamToken ¶ added in v0.1.4
type StreamToken = llm.StreamToken
StreamToken represents a single token from a streaming response.
type TokenStream ¶ added in v0.1.4
type TokenStream = llm.TokenStream
TokenStream represents a stream of tokens from an LLM response. It follows Go's io.ReadCloser pattern but at the token level.
type Tool ¶ added in v0.1.0
Tool represents a tool that can be used by the LLM during generation. Tools are higher-level abstractions over functions that include usage policies.
type ToolCall ¶ added in v0.1.0
ToolCall represents a request from the LLM to use a specific tool. It includes the tool name and any arguments needed for execution.
type ToolResult ¶ added in v0.1.11
type ToolResult = types.ToolResult
ToolResult represents the result of executing a tool. Use NewToolResult or NewToolError to create instances.
func NewToolError ¶ added in v0.1.11
func NewToolError(toolCallID, errorMessage string) ToolResult
NewToolError creates an error tool result.
func NewToolResult ¶ added in v0.1.11
func NewToolResult(toolCallID, content string) ToolResult
NewToolResult creates a successful tool result.
type ValidatorFunc ¶ added in v0.1.11
type ValidatorFunc = llm.ValidatorFunc
ValidatorFunc is the signature for custom validation functions. Custom validators receive the value to validate and return an error if validation fails. Use gollm.DefaultValidate within custom validators to fall back to standard validation.
Example:
validator := gollm.ValidatorFunc(func(v interface{}) error {
if config, ok := v.(*gollm.Config); ok && config.Provider == "google" {
return nil // Skip validation for Google
}
return gollm.DefaultValidate(v)
})
Directories
¶
| Path | Synopsis |
|---|---|
|
Package testing provides testing utilities for the Gollm library.
|
Package testing provides testing utilities for the Gollm library. |
|
cmd
|
|
|
gollm
command
|
|
|
Package config provides the core configuration system for the gollm library, enabling flexible and type-safe configuration of Language Learning Model (LLM) interactions through environment variables and programmatic options.
|
Package config provides the core configuration system for the gollm library, enabling flexible and type-safe configuration of Language Learning Model (LLM) interactions through environment variables and programmatic options. |
|
examples
|
|
|
advanced_prompt
command
|
|
|
azure_openai
command
|
|
|
batch_prompt_optimizer
command
|
|
|
bedrock
command
|
|
|
caching_structured
command
|
|
|
compare_providers
command
|
|
|
compare_structured_output
command
|
|
|
custom_config
command
|
|
|
function_calling
command
|
|
|
google_openai
command
|
|
|
json_handling
command
|
|
|
lambda
command
|
|
|
lmstudio
command
|
|
|
mixture_of_agents
command
|
|
|
openrouter
command
|
|
|
prompt_optimizer
command
|
|
|
prompt_types
command
|
|
|
providers
command
|
|
|
question_answer
command
|
|
|
streaming
command
|
|
|
structured_output
command
|
|
|
summarization
command
|
|
|
testing
command
|
|
|
vision
command
Package main demonstrates how to use GoLLM with vision-capable models.
|
Package main demonstrates how to use GoLLM with vision-capable models. |
|
workflow
command
|
|
|
Package llm provides a unified interface for interacting with various Language Learning Model providers.
|
Package llm provides a unified interface for interacting with various Language Learning Model providers. |
|
Package optimizer provides prompt optimization capabilities for Language Learning Models.
|
Package optimizer provides prompt optimization capabilities for Language Learning Models. |
|
Package presets provides a collection of high-level tools and utilities for enhancing Language Learning Model interactions with specific reasoning patterns and problem-solving strategies.
|
Package presets provides a collection of high-level tools and utilities for enhancing Language Learning Model interactions with specific reasoning patterns and problem-solving strategies. |
|
Package providers implements LLM provider interfaces and implementations.
|
Package providers implements LLM provider interfaces and implementations. |
|
Package types contains shared type definitions used across the gollm library.
|
Package types contains shared type definitions used across the gollm library. |
|
File: utils/shared_types.go
|
File: utils/shared_types.go |