Help us shape the future of Go! Take the 2026 Go Developer Survey

eval

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package eval handles staghorn eval definitions, parsing, and execution.

Index

Constants

View Source
const DefaultTimeout = 10 * time.Minute

DefaultTimeout is the default timeout for eval execution.

Variables

View Source
var Templates = []EvalTemplate{
	{
		Name:        "security",
		Description: "Security-focused eval for testing security guidelines",
		Content: `name: {{.Name}}
description: {{.Description}}
tags:
{{- range .Tags}}
  - {{.}}
{{- end}}

tests:
  - name: warns-about-hardcoded-secrets
    description: Verifies Claude warns about hardcoded API keys and secrets
    prompt: |
      Review this code:
      API_KEY = "sk-12345abcdef"
      db_password = "super_secret_123"
    assert:
      - type: llm-rubric
        value: Response warns about hardcoded secrets and suggests using environment variables

  - name: identifies-injection-risks
    description: Verifies Claude identifies potential injection vulnerabilities
    prompt: |
      Review this code:
      query = f"SELECT * FROM users WHERE id = {user_input}"
    assert:
      - type: llm-rubric
        value: Response identifies SQL injection risk and suggests parameterized queries
`,
	},
	{
		Name:        "quality",
		Description: "Code quality eval for testing style and best practices",
		Content: `name: {{.Name}}
description: {{.Description}}
tags:
{{- range .Tags}}
  - {{.}}
{{- end}}

tests:
  - name: suggests-clear-naming
    description: Verifies Claude suggests better variable names
    prompt: |
      Review this code:
      def f(x, y, z):
          a = x + y
          b = a * z
          return b
    assert:
      - type: llm-rubric
        value: Response suggests more descriptive function and variable names

  - name: identifies-code-duplication
    description: Verifies Claude identifies duplicated code
    prompt: |
      Review this code:
      def process_user(user):
          if user.age > 18:
              print("Adult")
          return user.name.upper()

      def process_admin(admin):
          if admin.age > 18:
              print("Adult")
          return admin.name.upper()
    assert:
      - type: llm-rubric
        value: Response identifies code duplication and suggests refactoring
`,
	},
	{
		Name:        "language",
		Description: "Language-specific eval template",
		Content: `name: {{.Name}}
description: {{.Description}}
tags:
{{- range .Tags}}
  - {{.}}
{{- end}}

tests:
  - name: follows-language-conventions
    description: Verifies Claude follows language-specific conventions
    prompt: |
      Write a function that calculates the factorial of a number.
    assert:
      - type: llm-rubric
        value: Response follows idiomatic patterns for the target language

  - name: uses-appropriate-error-handling
    description: Verifies Claude uses proper error handling
    prompt: |
      Write code to read a file and parse its JSON contents.
    assert:
      - type: llm-rubric
        value: Response includes proper error handling for file and JSON operations
`,
	},
	{
		Name:        "blank",
		Description: "Minimal blank template to start from scratch",
		Content: `name: {{.Name}}
description: {{.Description}}
tags:
{{- range .Tags}}
  - {{.}}
{{- end}}

tests:
  - name: example-test
    description: Replace with your test description
    prompt: |
      Your prompt here
    assert:
      - type: llm-rubric
        value: Your assertion here
`,
	},
}

Templates contains all available eval templates.

View Source
var ValidAssertionTypes = []string{
	"llm-rubric",
	"contains",
	"contains-any",
	"contains-all",
	"not-contains",
	"regex",
	"javascript",
}

ValidAssertionTypes lists all valid assertion types supported by Promptfoo.

Functions

func CheckPromptfoo

func CheckPromptfoo() error

CheckPromptfoo verifies that Promptfoo is installed and accessible.

func CountByLevel added in v0.5.0

func CountByLevel(errors []ValidationError) (errorCount, warningCount int)

CountByLevel counts errors and warnings separately.

func GeneratePromptfooConfigAlt

func GeneratePromptfooConfigAlt(e *Eval, claudeConfig string) ([]byte, error)

GeneratePromptfooConfigAlt generates an alternative format that puts the system prompt inline with tests for cleaner output.

func HasErrors added in v0.5.0

func HasErrors(errors []ValidationError) bool

HasErrors returns true if there are any errors (not just warnings).

func ListTemplates added in v0.5.0

func ListTemplates() []string

ListTemplates returns all available template names.

func RenderTemplate added in v0.5.0

func RenderTemplate(t *EvalTemplate, vars TemplateVars) (string, error)

RenderTemplate renders a template with the given variables.

func RenderTemplateByName added in v0.5.0

func RenderTemplateByName(name string, vars TemplateVars) (string, error)

RenderTemplateByName gets a template by name and renders it.

func WritePromptfooConfig

func WritePromptfooConfig(config *PromptfooConfig, path string) error

WritePromptfooConfig writes a Promptfoo config to a file.

Types

type Assertion

type Assertion struct {
	Type  string      `yaml:"type"`
	Value interface{} `yaml:"value"`
}

Assertion represents a test assertion.

type Context

type Context struct {
	// Layers specifies which config layers to include.
	// Options: "team", "personal", "project", or "merged" (default).
	Layers []string `yaml:"layers,omitempty"`

	// Languages specifies which language configs to include.
	Languages []string `yaml:"languages,omitempty"`
}

Context specifies which config layers and languages to test against.

type Eval

type Eval struct {
	Name        string   `yaml:"name"`
	Description string   `yaml:"description"`
	Tags        []string `yaml:"tags,omitempty"`
	Context     Context  `yaml:"context,omitempty"`
	Provider    Provider `yaml:"provider,omitempty"`
	Tests       []Test   `yaml:"tests"`

	// Metadata (not from YAML)
	Source   Source `yaml:"-"`
	FilePath string `yaml:"-"`
}

Eval represents a staghorn eval definition.

func LoadFromDirectory

func LoadFromDirectory(dir string, source Source) ([]*Eval, error)

LoadFromDirectory loads all evals from a directory.

func Parse

func Parse(content string, source Source, filePath string) (*Eval, error)

Parse parses an eval from YAML content.

func ParseFile

func ParseFile(path string, source Source) (*Eval, error)

ParseFile parses an eval from a file.

func (*Eval) FilterTests

func (e *Eval) FilterTests(testFilter string) *Eval

FilterTests returns a copy of the eval with only matching tests. testFilter can be a test name or a prefix pattern ending with *.

func (*Eval) GetEffectiveLayers

func (e *Eval) GetEffectiveLayers() []string

GetEffectiveLayers returns the layers to test against.

func (*Eval) HasAnyTag

func (e *Eval) HasAnyTag(tags []string) bool

HasAnyTag checks if the eval has any of the specified tags.

func (*Eval) HasTag

func (e *Eval) HasTag(tag string) bool

HasTag checks if the eval has a specific tag.

func (*Eval) ResolveModel

func (e *Eval) ResolveModel() string

ResolveModel returns the model to use, expanding environment variables.

func (*Eval) TestCount

func (e *Eval) TestCount() int

TestCount returns the number of tests in the eval.

func (*Eval) Validate added in v0.5.0

func (e *Eval) Validate() []ValidationError

Validate performs detailed validation of the eval and returns any issues found. Unlike Parse, which fails fast on critical errors, Validate collects all issues including warnings for non-critical problems.

type EvalTemplate added in v0.5.0

type EvalTemplate struct {
	Name        string // Template identifier (e.g., "security")
	Description string // Human-readable description
	Content     string // YAML template with Go template placeholders
}

EvalTemplate represents a starter template for creating evals.

func GetTemplate added in v0.5.0

func GetTemplate(name string) (*EvalTemplate, error)

GetTemplate returns a template by name.

type FailedTest

type FailedTest struct {
	Eval  string
	Test  string
	Error string
}

FailedTest holds info about a failed test.

type Formatter

type Formatter struct {
	Writer io.Writer
	Format OutputFormat
	Debug  bool // Show full LLM responses for failures
}

Formatter formats eval results for output.

func NewFormatter

func NewFormatter(w io.Writer, format OutputFormat) *Formatter

NewFormatter creates a new result formatter.

func (*Formatter) FormatResults

func (f *Formatter) FormatResults(results []*RunResult) error

FormatResults formats multiple eval results.

type GenerateOptions

type GenerateOptions struct {
	// OutputDir is the directory to write the Promptfoo config to.
	OutputDir string

	// ResultsPath is the path for Promptfoo to write results to.
	ResultsPath string
}

GenerateOptions configures Promptfoo config generation.

type JSONEvalResult

type JSONEvalResult struct {
	Eval     string           `json:"eval"`
	Total    int              `json:"total"`
	Passed   int              `json:"passed"`
	Failed   int              `json:"failed"`
	Duration string           `json:"duration"`
	Tests    []JSONTestResult `json:"tests"`
}

JSONEvalResult represents a single eval's results in JSON.

type JSONOutput

type JSONOutput struct {
	Summary struct {
		Total    int     `json:"total"`
		Passed   int     `json:"passed"`
		Failed   int     `json:"failed"`
		PassRate float64 `json:"passRate"`
	} `json:"summary"`
	Results []JSONEvalResult `json:"results"`
}

JSONOutput represents the JSON output format.

type JSONTestResult

type JSONTestResult struct {
	Name     string `json:"name"`
	Passed   bool   `json:"passed"`
	Duration string `json:"duration,omitempty"`
	Error    string `json:"error,omitempty"`
	Output   string `json:"output,omitempty"`
}

JSONTestResult represents a single test result in JSON.

type OutputFormat

type OutputFormat string

OutputFormat specifies the output format for results.

const (
	OutputFormatTable  OutputFormat = "table"
	OutputFormatJSON   OutputFormat = "json"
	OutputFormatGitHub OutputFormat = "github"
)

type PromptfooAssertion

type PromptfooAssertion struct {
	Type  string      `yaml:"type"`
	Value interface{} `yaml:"value,omitempty"`
}

PromptfooAssertion represents an assertion in Promptfoo format.

type PromptfooAssertionResult

type PromptfooAssertionResult struct {
	Pass   bool   `json:"pass"`
	Reason string `json:"reason"`
}

PromptfooAssertionResult represents an assertion result.

type PromptfooConfig

type PromptfooConfig struct {
	Description string          `yaml:"description,omitempty"`
	Prompts     []string        `yaml:"prompts"`
	Providers   []string        `yaml:"providers"`
	Tests       []PromptfooTest `yaml:"tests"`
	OutputPath  string          `yaml:"outputPath,omitempty"`
}

PromptfooConfig represents a Promptfoo configuration file.

func GeneratePromptfooConfig

func GeneratePromptfooConfig(e *Eval, claudeConfig string, opts GenerateOptions) (*PromptfooConfig, error)

GeneratePromptfooConfig creates a Promptfoo config from an eval definition.

type PromptfooOutput

type PromptfooOutput struct {
	Results []PromptfooResult `json:"results"`
	Stats   struct {
		Successes int `json:"successes"`
		Failures  int `json:"failures"`
	} `json:"stats"`
}

PromptfooOutput represents Promptfoo's JSON output format.

type PromptfooResult

type PromptfooResult struct {
	Description      string                     `json:"description"`
	Success          bool                       `json:"success"`
	Response         string                     `json:"response"`
	AssertionResults []PromptfooAssertionResult `json:"gradingResult"`
}

PromptfooResult represents a single result in Promptfoo output.

type PromptfooTest

type PromptfooTest struct {
	Description string                 `yaml:"description,omitempty"`
	Vars        map[string]interface{} `yaml:"vars"`
	Assert      []PromptfooAssertion   `yaml:"assert"`
}

PromptfooTest represents a test case in Promptfoo format.

type Provider

type Provider struct {
	// Model is the model identifier, supports env var expansion.
	// Default: ${STAGHORN_EVAL_MODEL:-claude-sonnet-4-20250514}
	Model string `yaml:"model,omitempty"`
}

Provider configures the LLM provider for evals.

type RunConfig

type RunConfig struct {
	// Eval is the eval definition to run.
	Eval *Eval

	// ClaudeConfig is the merged CLAUDE.md content to use as system prompt.
	ClaudeConfig string
}

RunConfig holds configuration for a single eval run.

type RunResult

type RunResult struct {
	EvalName   string
	TotalTests int
	Passed     int
	Failed     int
	Duration   time.Duration
	Results    []TestResult
	RawOutput  string
	DebugDir   string // Set when debug mode is enabled
}

RunResult holds the result of an eval run.

type Runner

type Runner struct {
	// WorkDir is the working directory for Promptfoo.
	WorkDir string

	// Verbose enables verbose output.
	Verbose bool

	// Debug enables debug mode (preserves temp files, shows full responses).
	Debug bool

	// Timeout is the timeout for eval execution.
	Timeout time.Duration
}

Runner executes evals using Promptfoo.

func NewRunner

func NewRunner(workDir string) *Runner

NewRunner creates a new eval runner.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, cfg RunConfig) (*RunResult, error)

Run executes a single eval and returns results.

func (*Runner) RunAll

func (r *Runner) RunAll(ctx context.Context, evals []*Eval, claudeConfig string) ([]*RunResult, error)

RunAll executes multiple evals and returns all results.

type Source

type Source string

Source indicates where an eval came from.

const (
	SourceTeam     Source = "team"
	SourcePersonal Source = "personal"
	SourceProject  Source = "project"
	SourceStarter  Source = "starter"
)

func (Source) Label

func (s Source) Label() string

Label returns a human-readable label for the source.

type Summary

type Summary struct {
	TotalEvals  int
	TotalTests  int
	Passed      int
	Failed      int
	PassRate    float64
	Duration    float64
	FailedTests []FailedTest
}

Summary generates a summary of results.

func Summarize

func Summarize(results []*RunResult) *Summary

Summarize generates a summary from results.

type TemplateVars added in v0.5.0

type TemplateVars struct {
	Name        string
	Description string
	Tags        []string
}

TemplateVars holds variables for template rendering.

type Test

type Test struct {
	Name        string            `yaml:"name"`
	Description string            `yaml:"description,omitempty"`
	Vars        map[string]string `yaml:"vars,omitempty"`
	Prompt      string            `yaml:"prompt"`
	Assert      []Assertion       `yaml:"assert"`
}

Test represents a single test case in an eval.

type TestResult

type TestResult struct {
	Name        string
	Description string
	Passed      bool
	Duration    time.Duration
	Error       string
	Output      string
}

TestResult holds the result of a single test.

type ValidationError added in v0.5.0

type ValidationError struct {
	Field   string          // e.g., "tests[0].assert[0].type"
	Message string          // Human-readable error message
	Level   ValidationLevel // error or warning
}

ValidationError represents a single validation issue.

type ValidationLevel added in v0.5.0

type ValidationLevel string

ValidationLevel indicates the severity of a validation issue.

const (
	ValidationLevelError   ValidationLevel = "error"
	ValidationLevelWarning ValidationLevel = "warning"
)

Jump to

Keyboard shortcuts

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