Documentation
¶
Index ¶
- Variables
- func AnalyzeComparisonResults[T any](results []ComparisonResult[T]) string
- func ChainOfThought(ctx context.Context, l LLM, question string, opts ...PromptOption) (string, error)
- func CleanResponse(response string) string
- func ExtractStructuredData[T any](ctx context.Context, l LLM, text string, opts ...PromptOption) (*T, error)
- func GenerateJSONSchema(v interface{}) ([]byte, error)
- func OptimizePrompt(ctx context.Context, llm LLM, config OptimizationConfig) (optimizedPrompt string, response string, err error)
- func QuestionAnswer(ctx context.Context, l LLM, question string, opts ...PromptOption) (string, error)
- func Summarize(ctx context.Context, l LLM, text string, opts ...PromptOption) (string, error)
- func Validate(s interface{}) error
- type BatchPromptOptimizer
- type ComparisonResult
- type Config
- type ConfigOption
- func SetAPIKey(apiKey string) ConfigOption
- func SetDebugLevel(level LogLevel) ConfigOption
- func SetFrequencyPenalty(penalty float64) ConfigOption
- func SetMaxRetries(maxRetries int) ConfigOption
- func SetMaxTokens(maxTokens int) ConfigOption
- func SetMemory(maxTokens int) ConfigOption
- func SetMinP(minP float64) ConfigOption
- func SetMirostat(mode int) ConfigOption
- func SetMirostatEta(eta float64) ConfigOption
- func SetMirostatTau(tau float64) ConfigOption
- func SetModel(model string) ConfigOption
- func SetOllamaEndpoint(endpoint string) ConfigOption
- func SetPresencePenalty(penalty float64) ConfigOption
- func SetProvider(provider string) ConfigOption
- func SetRepeatLastN(n int) ConfigOption
- func SetRepeatPenalty(penalty float64) ConfigOption
- func SetRetryDelay(retryDelay time.Duration) ConfigOption
- func SetSeed(seed int) ConfigOption
- func SetTemperature(temperature float64) ConfigOption
- func SetTfsZ(z float64) ConfigOption
- func SetTimeout(timeout time.Duration) ConfigOption
- func SetTopP(topP float64) ConfigOption
- type Example
- type GenerateOption
- type IterationCallback
- type LLM
- type LogLevel
- type MOA
- type MOAConfig
- type MOALayer
- type MemoryOption
- type Metric
- type OptimizationConfig
- type OptimizationEntry
- type OptimizationResult
- type OptimizerOption
- func WithCustomMetrics(metrics ...Metric) OptimizerOption
- func WithIterationCallback(callback IterationCallback) OptimizerOption
- func WithIterations(iterations int) OptimizerOption
- func WithMaxRetries(maxRetries int) OptimizerOption
- func WithMemorySize(size int) OptimizerOption
- func WithOptimizationGoal(goal string) OptimizerOption
- func WithRatingSystem(system string) OptimizerOption
- func WithRetryDelay(delay time.Duration) OptimizerOption
- func WithThreshold(threshold float64) OptimizerOption
- func WithVerbose() OptimizerOption
- type Prompt
- type PromptExample
- type PromptOptimizer
- type PromptOption
- type PromptTemplate
- type PromptTemplateOption
- type SchemaOption
- type ValidateFunc
Constants ¶
This section is empty.
Variables ¶
var QuestionAnswerTemplate = NewPromptTemplate( "QuestionAnswer", "Answer the given question", "Answer the following question:\n\n{{.Question}}", WithPromptOptions( WithDirectives("Provide a clear and concise answer"), WithOutput("Answer:"), ), )
Functions ¶
func AnalyzeComparisonResults ¶
func AnalyzeComparisonResults[T any](results []ComparisonResult[T]) string
func ChainOfThought ¶
func ChainOfThought(ctx context.Context, l LLM, question string, opts ...PromptOption) (string, error)
ChainOfThought performs a chain of thought reasoning
func CleanResponse ¶
CleanResponse removes markdown code block syntax and trims the JSON response
func ExtractStructuredData ¶
func ExtractStructuredData[T any](ctx context.Context, l LLM, text string, opts ...PromptOption) (*T, error)
ExtractStructuredData extracts structured data from text based on a given struct type
func GenerateJSONSchema ¶
GenerateJSONSchema generates a JSON schema for the given struct
func OptimizePrompt ¶ added in v0.0.93
func OptimizePrompt(ctx context.Context, llm LLM, config OptimizationConfig) (optimizedPrompt string, response string, err error)
OptimizePrompt optimizes the given prompt and generates a response
func QuestionAnswer ¶
func QuestionAnswer(ctx context.Context, l LLM, question string, opts ...PromptOption) (string, error)
QuestionAnswer performs question answering
Types ¶
type BatchPromptOptimizer ¶ added in v0.0.93
BatchPromptOptimizer handles batch optimization of prompts
func NewBatchPromptOptimizer ¶ added in v0.0.93
func NewBatchPromptOptimizer(llm LLM) *BatchPromptOptimizer
NewBatchPromptOptimizer creates a new BatchPromptOptimizer
func (*BatchPromptOptimizer) OptimizePrompts ¶ added in v0.0.93
func (bpo *BatchPromptOptimizer) OptimizePrompts(ctx context.Context, examples []PromptExample) []OptimizationResult
OptimizePrompts optimizes a batch of prompts concurrently
type ComparisonResult ¶
type ComparisonResult[T any] struct { Provider string Model string Response string Data T Error error Attempts int }
func CompareModels ¶
func CompareModels[T any](ctx context.Context, prompt string, validateFunc ValidateFunc[T], configs ...*Config) ([]ComparisonResult[T], error)
CompareModels now uses a generic type T and accepts a validation function
type Config ¶
type Config struct {
Provider string
Model string
OllamaEndpoint string
Temperature float64
MaxTokens int
TopP float64
FrequencyPenalty float64
PresencePenalty float64
Timeout time.Duration
MaxRetries int
RetryDelay time.Duration
APIKey string
DebugLevel LogLevel
MemoryOption *MemoryOption
Seed *int
MinP *float64
RepeatPenalty *float64
RepeatLastN *int
Mirostat *int
MirostatEta *float64
MirostatTau *float64
TfsZ *float64
}
Config holds the configuration for the LLM
func LoadConfig ¶
LoadConfig loads the configuration from environment variables
type ConfigOption ¶
type ConfigOption func(*Config)
ConfigOption is a function type for modifying Config
func SetAPIKey ¶
func SetAPIKey(apiKey string) ConfigOption
SetAPIKey sets the API key for the current provider in the Config
func SetDebugLevel ¶
func SetDebugLevel(level LogLevel) ConfigOption
SetDebugLevel sets the debug level in the Config
func SetFrequencyPenalty ¶ added in v0.0.95
func SetFrequencyPenalty(penalty float64) ConfigOption
SetFrequencyPenalty sets the frequency penalty. It penalizes new tokens based on their frequency in the text so far. Higher values decrease the model's likelihood to repeat the same line verbatim.
func SetMaxRetries ¶
func SetMaxRetries(maxRetries int) ConfigOption
SetMaxRetries sets the maximum number of retries in the Config
func SetMaxTokens ¶
func SetMaxTokens(maxTokens int) ConfigOption
SetMaxTokens sets the max tokens in the Config
func SetMemory ¶ added in v0.0.8
func SetMemory(maxTokens int) ConfigOption
SetMemory sets the memory option for the LLM
func SetMinP ¶ added in v0.0.95
func SetMinP(minP float64) ConfigOption
SetMinP sets the minimum probability for a token to be considered, relative to the probability of the most likely token. It aims to ensure a balance of quality and variety. (Default: 0.05)
func SetMirostat ¶ added in v0.0.95
func SetMirostat(mode int) ConfigOption
SetMirostat enables Mirostat sampling for controlling perplexity. (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)
func SetMirostatEta ¶ added in v0.0.95
func SetMirostatEta(eta float64) ConfigOption
SetMirostatEta influences how quickly the algorithm responds to feedback from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. (Default: 0.1)
func SetMirostatTau ¶ added in v0.0.95
func SetMirostatTau(tau float64) ConfigOption
SetMirostatTau controls the balance between coherence and diversity of the output. A lower value will result in more focused and coherent text. (Default: 5.0)
func SetOllamaEndpoint ¶
func SetOllamaEndpoint(endpoint string) ConfigOption
SetOllamaEndpoint sets the Ollama endpoint in the Config
func SetPresencePenalty ¶ added in v0.0.95
func SetPresencePenalty(penalty float64) ConfigOption
SetPresencePenalty sets the presence penalty. It penalizes new tokens based on whether they appear in the text so far. Higher values increase the model's likelihood to talk about new topics.
func SetProvider ¶
func SetProvider(provider string) ConfigOption
SetProvider sets the provider in the Config
func SetRepeatLastN ¶ added in v0.0.95
func SetRepeatLastN(n int) ConfigOption
SetRepeatLastN sets how far back the model should look to prevent repetition. (Default: 64, 0 = disabled, -1 = num_ctx)
func SetRepeatPenalty ¶ added in v0.0.95
func SetRepeatPenalty(penalty float64) ConfigOption
SetRepeatPenalty sets how strongly to penalize repetitions. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. (Default: 1.1)
func SetRetryDelay ¶
func SetRetryDelay(retryDelay time.Duration) ConfigOption
SetRetryDelay sets the delay between retries in the Config
func SetSeed ¶ added in v0.0.95
func SetSeed(seed int) ConfigOption
SetSeed sets the random number seed for generation. Setting this to a specific number will make the model generate the same text for the same prompt. (Default: 0)
func SetTemperature ¶
func SetTemperature(temperature float64) ConfigOption
SetTemperature sets the temperature in the Config
func SetTfsZ ¶ added in v0.0.95
func SetTfsZ(z float64) ConfigOption
SetTfsZ sets the value for tail free sampling, which is used to reduce the impact of less probable tokens. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting. (Default: 1)
func SetTimeout ¶
func SetTimeout(timeout time.Duration) ConfigOption
SetTimeout sets the timeout in the Config
func SetTopP ¶ added in v0.0.95
func SetTopP(topP float64) ConfigOption
SetTopP sets the top-p value. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. (Default: 0.9)
type GenerateOption ¶
type GenerateOption func(*generateConfig)
GenerateOption is a function type for configuring generate options
func WithJSONSchemaValidation ¶
func WithJSONSchemaValidation() GenerateOption
WithJSONSchemaValidation returns a GenerateOption that enables JSON schema validation
type IterationCallback ¶ added in v0.0.9
type IterationCallback func(iteration int, entry OptimizationEntry)
IterationCallback is a function type for the iteration callback
type LLM ¶
type LLM interface {
// Generate produces a response given a context, prompt, and optional generate options
Generate(ctx context.Context, prompt *Prompt, opts ...GenerateOption) (string, error)
// SetOption sets an option for the LLM
SetOption(key string, value interface{})
// GetPromptJSONSchema returns the JSON schema for the prompt
GetPromptJSONSchema(opts ...SchemaOption) ([]byte, error)
// GetProvider returns the provider of the LLM
GetProvider() string
// GetModel returns the model of the LLM
GetModel() string
// UpdateDebugLevel updates the debug level of the LLM
UpdateDebugLevel(level LogLevel)
// Debug logs a debug message with optional key-value pairs
Debug(msg string, keysAndValues ...interface{})
// GetDebugLevel returns the current debug level of the LLM
GetDebugLevel() LogLevel
SetOllamaEndpoint(endpoint string) error
}
LLM is the interface that wraps the basic LLM operations
func NewLLM ¶
func NewLLM(opts ...ConfigOption) (LLM, error)
NewLLM creates a new LLM instance, potentially with memory if the option is set
type MOA ¶ added in v0.0.94
MOA represents the Mixture of Agents
type MOAConfig ¶ added in v0.0.94
type MOAConfig struct {
Iterations int
Models [][]ConfigOption // Each inner slice represents a model's configuration
MaxParallel int // Maximum number of parallel requests per layer (0 for sequential processing)
AgentTimeout time.Duration // Timeout for each agent's request (0 for no timeout)
}
MOAConfig represents the configuration for the Mixture of Agents
type MOALayer ¶ added in v0.0.94
type MOALayer struct {
Models []LLM
}
MOALayer represents a single layer in the Mixture of Agents
type MemoryOption ¶ added in v0.0.8
type MemoryOption struct {
MaxTokens int
}
type OptimizationConfig ¶ added in v0.0.93
type OptimizationConfig struct {
Prompt string
Description string
Metrics []Metric
RatingSystem string
Threshold float64
MaxRetries int
RetryDelay time.Duration
}
OptimizationConfig holds the configuration for prompt optimization
func DefaultOptimizationConfig ¶ added in v0.0.93
func DefaultOptimizationConfig() OptimizationConfig
DefaultOptimizationConfig returns a default configuration for prompt optimization
type OptimizationEntry ¶ added in v0.0.9
type OptimizationEntry = llm.OptimizationEntry
type OptimizationResult ¶ added in v0.0.93
type OptimizationResult struct {
Name string
OriginalPrompt string
OptimizedPrompt string
GeneratedContent string
Error error
}
OptimizationResult represents the result of a single prompt optimization
type OptimizerOption ¶ added in v0.0.9
type OptimizerOption func(*PromptOptimizer)
OptimizerOption is a function type for configuring the PromptOptimizer
func WithCustomMetrics ¶ added in v0.0.9
func WithCustomMetrics(metrics ...Metric) OptimizerOption
WithCustomMetrics adds custom metrics to the PromptOptimizer
func WithIterationCallback ¶ added in v0.0.9
func WithIterationCallback(callback IterationCallback) OptimizerOption
Modify the existing WithIterationCallback function
func WithIterations ¶ added in v0.0.91
func WithIterations(iterations int) OptimizerOption
func WithMaxRetries ¶ added in v0.0.9
func WithMaxRetries(maxRetries int) OptimizerOption
WithMaxRetries sets the maximum number of retries for the PromptOptimizer
func WithMemorySize ¶ added in v0.0.91
func WithMemorySize(size int) OptimizerOption
WithMemorySize sets the memory size for the PromptOptimizer
func WithOptimizationGoal ¶ added in v0.0.9
func WithOptimizationGoal(goal string) OptimizerOption
WithOptimizationGoal sets the optimization goal for the PromptOptimizer
func WithRatingSystem ¶ added in v0.0.9
func WithRatingSystem(system string) OptimizerOption
WithRatingSystem sets the rating system for the PromptOptimizer
func WithRetryDelay ¶ added in v0.0.9
func WithRetryDelay(delay time.Duration) OptimizerOption
WithRetryDelay sets the delay between retries for the PromptOptimizer
func WithThreshold ¶ added in v0.0.9
func WithThreshold(threshold float64) OptimizerOption
WithThreshold sets the threshold for the PromptOptimizer
func WithVerbose ¶ added in v0.0.92
func WithVerbose() OptimizerOption
type Prompt ¶
type Prompt struct {
Input string `json:"input" jsonschema:"required,description=The main input text for the LLM" validate:"required"`
Output string `json:"output,omitempty" jsonschema:"description=Specification for the expected output format"`
Directives []string `json:"directives,omitempty" jsonschema:"description=List of directives to guide the LLM"`
Context string `json:"context,omitempty" jsonschema:"description=Additional context for the LLM"`
MaxLength int `` /* 128-byte string literal not displayed */
Examples []string `json:"examples,omitempty" jsonschema:"description=List of examples to guide the LLM"`
}
Prompt represents a structured prompt for an LLM
func NewPrompt ¶
func NewPrompt(input string, opts ...PromptOption) *Prompt
NewPrompt creates a new Prompt with the given input and applies any provided options
func (*Prompt) Apply ¶
func (p *Prompt) Apply(opts ...PromptOption)
Apply applies the given options to the Prompt
func (*Prompt) GenerateJSONSchema ¶
func (p *Prompt) GenerateJSONSchema(opts ...SchemaOption) ([]byte, error)
GenerateJSONSchema returns the JSON Schema for the Prompt struct
type PromptExample ¶ added in v0.0.93
type PromptExample struct {
Name string
Prompt string
Description string
Metrics []Metric
Threshold float64
}
PromptExample represents a single prompt to be optimized
type PromptOptimizer ¶ added in v0.0.9
type PromptOptimizer struct {
// contains filtered or unexported fields
}
PromptOptimizer is the public interface for the prompt optimization system
func NewPromptOptimizer ¶ added in v0.0.9
func NewPromptOptimizer(l LLM, initialPrompt string, taskDesc string, opts ...OptimizerOption) *PromptOptimizer
NewPromptOptimizer creates a new PromptOptimizer
func (*PromptOptimizer) GetOptimizationHistory ¶ added in v0.0.9
func (po *PromptOptimizer) GetOptimizationHistory() []OptimizationEntry
GetOptimizationHistory returns the history of optimization attempts
func (*PromptOptimizer) OptimizePrompt ¶ added in v0.0.9
func (po *PromptOptimizer) OptimizePrompt(ctx context.Context) (string, error)
OptimizePrompt runs the optimization process
type PromptOption ¶
type PromptOption func(*Prompt)
PromptOption is a function type that modifies a Prompt
func WithContext ¶
func WithContext(context string) PromptOption
WithContext adds context to the Prompt
func WithDirectives ¶
func WithDirectives(directives ...string) PromptOption
WithDirectives adds directives to the Prompt
func WithExamples ¶
func WithExamples(examples ...string) PromptOption
WithExamples adds examples to the Prompt
func WithMaxLength ¶
func WithMaxLength(length int) PromptOption
WithMaxLength sets the maximum length for the output
func WithOutput ¶
func WithOutput(output string) PromptOption
WithOutput adds an output specification to the Prompt
type PromptTemplate ¶
type PromptTemplate struct {
Name string
Description string
Template string
Options []PromptOption
}
PromptTemplate represents a template for generating prompts
func NewPromptTemplate ¶
func NewPromptTemplate(name, description, template string, opts ...PromptTemplateOption) *PromptTemplate
NewPromptTemplate creates a new PromptTemplate with the given name, description, and template
type PromptTemplateOption ¶
type PromptTemplateOption func(*PromptTemplate)
PromptTemplateOption is a function type that modifies a PromptTemplate
func WithPromptOptions ¶
func WithPromptOptions(options ...PromptOption) PromptTemplateOption
WithPromptOptions adds PromptOptions to the PromptTemplate
type SchemaOption ¶
type SchemaOption func(*jsonschema.Reflector)
SchemaOption is a function type for schema generation options
func WithExpandedStruct ¶
func WithExpandedStruct(expanded bool) SchemaOption
WithExpandedStruct sets the ExpandedStruct option for schema generation
type ValidateFunc ¶
ValidateFunc is a function type for custom validation logic