gaslit

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: MIT Imports: 7 Imported by: 0

README

gaslit

A Go framework that stress-tests AI agents by staging a supervised courtroom debate. Gaslit runs a panel of debater agents against a multiple-choice (or open-ended) question, cross-examines them with a moderator, and detects when agents drift or hallucinate.

Built on top of cloudwego/eino.

How it works

  1. Baseline — every agent answers the question with per-option confidences.
  2. Cross-examination — a supervisor moderator challenges panelists using their own claims and any challenges agents raised, via a cross_examine_agent tool.
  3. Re-evaluation — agents give final positions.
  4. Drift detection — flips, confidence erosion, and a pluggable shift metric are measured, and influence is attributed to the swaying agent (or the supervisor).
  5. Grill / CCI — drifted/influential agents are grilled with an inversion probe and scored on a confidence/consistency quadrant.
Quadrant diagnostics
Quadrant Confidence Consistency Meaning
PEAK high high Grounded, resilient knowledge
HALLUCINATING / MALICIOUS high low Confident but fabricating contradictory facts
KB_DEFICIT low high Logically consistent but lacking evidence
WRONG / UNCERTAIN low low Guessing without internal consistency

Install

go get github.com/ItsArnavSh/gaslit

Requires Go 1.26+.

Usage

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ItsArnavSh/gaslit"
	"github.com/cloudwego/eino/adk"
)

func main() {
	ctx := context.Background()

	// 1. Build your debater agents (any eino adk.Agent).
	econ, _ := adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{
		Name:        "economic_historian",
		Description: "Analyzes events from a socio-economic lens.",
		Instruction: "You are an economic historian. Argue that economic forces drive history.",
		Model:       myModel,
	})
	pol, _ := adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{
		Name:        "political_historian",
		Description: "Analyzes events through leadership and military strategy.",
		Instruction: "You are a political and military historian.",
		Model:       myModel,
	})

	// 2. Configure the engine: thresholds, drift metric, attribution, grill
	//    strategy, protocols, prompts, budgets, hooks, persistence, ...
	cfg := gaslit.PresetDefault()
	cfg.SupervisorModel = myModel
	cfg.Agents = []adk.Agent{econ, pol}
	cfg.Thresholds = gaslit.Thresholds{DriftSignificance: 0.15, Confidence: 0.55, Consistency: 0.60}
	cfg.DriftMetric = gaslit.TVDRift
	cfg.AttributionFn = gaslit.ChampionAttribution
	cfg.GrillStrategy = gaslit.GrillSingleSuspect
	cfg.Protocol = gaslit.ProtocolSupervised
	cfg.Concurrency = 4

	engine, err := gaslit.New(ctx, cfg)
	if err != nil {
		log.Fatal(err)
	}

	// 3. Run the debate.
	summary, err := engine.Debate(ctx, "What caused the Roman Empire's collapse?", []string{
		"Economic exhaustion",
		"Military breakdown",
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Outcome: %s\n", summary.OverallOutcome)
	fmt.Printf("Drift: %t (driver: %s)\n", summary.DriftVerdict.HasDrift, summary.DriftVerdict.PrimaryDriver)
	for name, diag := range summary.Diagnostics {
		fmt.Printf("%s → %s (conf %.2f, consistency %.2f)\n", name, diag.Quadrant, diag.ConfidenceScore, diag.ConsistencyScore)
	}
}

Configuration

Everything is set on a Config struct passed to New(ctx, cfg), and any field can be refined with an Option:

  • ThresholdsThresholds{DriftSignificance, Confidence, Consistency}, also per-call via WithThresholdsCall.
  • PresetsPresetDefault(), PresetStrict(), PresetLenient().
  • Drift metricsTVDRift, KLDistance, JSDistance, MaxChange, or any custom DriftMetric function.
  • AttributionChampionAttribution, ShiftWeightedAttribution, CorrelationAttribution, or a custom AttributionFn.
  • Quadrant classifierThresholdClassifier or a custom Classifier.
  • Consistency scoring*LLMScorer (default, uses Config.ConsistencyModel, which falls back to SupervisorModel) or the deterministic *LexicalScorer (zero extra model calls), or a custom ConsistencyScorer. Convenience options: WithLexicalScorer() (debugging) and WithLLMScorer(m) / WithConsistencyModel(m) (cheap scoring model, strong moderator model).
  • Grill strategyGrillNone, GrillSingleSuspect, GrillInfluencer, GrillAllDrifted, GrillTopN (with GrillCount).
  • ProtocolsProtocolSupervised, ProtocolAdversarialPairs, ProtocolRoundRobin, ProtocolDevilsAdvocate.
  • AggregationMajorityVote, ConfidenceWeightedVote, WeightedVote, ConfidenceWeightedWeightedVote, or a custom AggregationFn.
  • Prompts — override any template via PromptTemplates (initial prompt, debate trigger, grill probe, NLI probe, supervisor system, ...).
  • Answer schema*MCQSchema (default) or *OpenEndedSchema for free-form questions (pass empty options to Debate). Custom schemas implement AnswerSchema.
  • Per-agentAgentConfig{Instruction, Weight, SkipPhases} keyed by name.
  • ExecutionPacingDelay, RequestTimeout, MaxRetries, Concurrency, MaxRounds, OptionLabels.
  • BudgetCostBudget{MaxCalls, MaxTokens, Deadline} caps total work.
  • ObservabilityHooks callbacks, Recorder (e.g. JSONLRecorder), Instrumentation.Stats(), Redact.
  • Moderator toolsExtraTools are added to the supervisor.

Function variants

The pipeline is fully sliced; every stage is callable standalone:

  • Debate(ctx, question, options, opts...) — full pipeline.
  • DebateN(ctx, question, options, rounds, opts...) — multi-round debate.
  • DebateMany(ctx, questions, optionsList, opts...) — batch, reusing context.
  • Baseline(ctx, question, options, opts...) — stage 1 only.
  • CrossExamine(ctx, question, before, opts...) — stage 2 only.
  • Evaluate(ctx, options, opts...) — stage 3 only.
  • DriftAnalysis(before, after, options, opts...) — pure drift verdict.
  • Grill(ctx, agentName, claim, question, opts...) — grill a registered panelist.
  • CCI(ctx, agent, statement, question, opts...)standalone consistency / confidence probe against any adk.Agent, even one outside the panel.
  • Stream(ctx, question, options, opts...) — stream pipeline events as they happen.
  • SaveSummary / SaveSummaryFile / LoadSummary / LoadSummaryFile — cache a debate to disk.
  • ReclassifySummary(s, thresholds) — pure quadrant re-tally of a saved summary (zero model calls).
  • Rescore(ctx, s, opts...) — re-run only the consistency scorer over a saved summary's stored arguments, then reclassify. No new baseline/debate calls.

All variants accept per-call CallOptions (WithVerboseCall, WithMaxRoundsCall, WithThresholdsCall, WithMetadataCall, WithBudgetCall, ...) that merge over the engine config.

Example

See examples/basic for a full runnable program using Groq's API, including a 429-backoff transport and a "panel of historians" demo. It splits models (strong moderator, cheap ConsistencyModel), caps each debate with a CostBudget, and demonstrates the save → load → reclassify/rescore caching loop.

GROQ_API_KEY=... go run ./examples/basic          # debug: LexicalScorer, no NLI calls
GROQ_API_KEY=... go run ./examples/basic -final   # benchmark: cheap LLM NLI scorer

License

MIT

Documentation

Overview

Package gaslit stress-tests AI agents by staging a supervised courtroom debate. The public API of this package is a thin facade over the implementation packages under internal/: every type here is an alias and every function/variable is a re-export, so the API surface is identical to a single flat package while the code stays organized by feature.

Index

Constants

View Source
const (
	PhaseBaseline         = core.PhaseBaseline
	PhaseCrossExamination = core.PhaseCrossExamination
	PhaseEvaluation       = core.PhaseEvaluation
	PhaseDriftAnalysis    = core.PhaseDriftAnalysis
	PhaseGrilling         = core.PhaseGrilling
)

Phases.

View Source
const (
	ProtocolSupervised       = core.ProtocolSupervised
	ProtocolAdversarialPairs = core.ProtocolAdversarialPairs
	ProtocolRoundRobin       = core.ProtocolRoundRobin
	ProtocolDevilsAdvocate   = core.ProtocolDevilsAdvocate
)

Protocols.

View Source
const (
	GrillNone          = core.GrillNone
	GrillSingleSuspect = core.GrillSingleSuspect
	GrillInfluencer    = core.GrillInfluencer
	GrillAllDrifted    = core.GrillAllDrifted
	GrillTopN          = core.GrillTopN
)

Grill strategies.

View Source
const (
	QuadrantPeak          = core.QuadrantPeak
	QuadrantHallucinating = core.QuadrantHallucinating
	QuadrantKBDeficit     = core.QuadrantKBDeficit
	QuadrantWrong         = core.QuadrantWrong
)

Quadrants.

View Source
const (
	EventPhaseStart = core.EventPhaseStart
	EventPhaseEnd   = core.EventPhaseEnd
	EventBaseline   = core.EventBaseline
	EventCrossExam  = core.EventCrossExam
	EventEval       = core.EventEval
	EventDrift      = core.EventDrift
	EventDiagnostic = core.EventDiagnostic
	EventSummary    = core.EventSummary
	EventDone       = core.EventDone
	EventError      = core.EventError
)

Event types.

View Source
const (
	DefaultJSONInstruction = core.DefaultJSONInstruction
	OpenEndedInstruction   = core.OpenEndedInstruction
)

Schema contract text.

Variables

View Source
var (
	PresetDefault = core.PresetDefault
	PresetStrict  = core.PresetStrict
	PresetLenient = core.PresetLenient
)

Presets.

View Source
var (
	WithLogger            = core.WithLogger
	WithPacingDelay       = core.WithPacingDelay
	WithRequestTimeout    = core.WithRequestTimeout
	WithMaxRetries        = core.WithMaxRetries
	WithConcurrency       = core.WithConcurrency
	WithMaxRounds         = core.WithMaxRounds
	WithThresholds        = core.WithThresholds
	WithOptionLabels      = core.WithOptionLabels
	WithAnswerSchema      = core.WithAnswerSchema
	WithProtocol          = core.WithProtocol
	WithGrillStrategy     = core.WithGrillStrategy
	WithGrillCount        = core.WithGrillCount
	WithAggregation       = core.WithAggregation
	WithDriftMetric       = core.WithDriftMetric
	WithAttribution       = core.WithAttribution
	WithClassifier        = core.WithClassifier
	WithConsistencyScorer = core.WithConsistencyScorer
	WithConsistencyModel  = core.WithConsistencyModel
	WithLexicalScorer     = engine.WithLexicalScorer
	WithLLMScorer         = engine.WithLLMScorer
	WithPromptTemplates   = core.WithPromptTemplates
	WithAgentConfig       = core.WithAgentConfig
	WithExtraTools        = core.WithExtraTools
	WithHooks             = core.WithHooks
	WithRecorder          = core.WithRecorder
	WithRedact            = core.WithRedact
	WithBudget            = core.WithBudget
	WithVerbose           = core.WithVerbose
)

Construction-time options.

View Source
var (
	WithVerboseCall           = core.WithVerboseCall
	WithMaxRoundsCall         = core.WithMaxRoundsCall
	WithOptionLabelsCall      = core.WithOptionLabelsCall
	WithThresholdsCall        = core.WithThresholdsCall
	WithGrillStrategyCall     = core.WithGrillStrategyCall
	WithGrillCountCall        = core.WithGrillCountCall
	WithProtocolCall          = core.WithProtocolCall
	WithMetadataCall          = core.WithMetadataCall
	WithConfidenceCall        = core.WithConfidenceCall
	WithClaimCall             = core.WithClaimCall
	WithHooksCall             = core.WithHooksCall
	WithBudgetCall            = core.WithBudgetCall
	WithConsistencyScorerCall = core.WithConsistencyScorerCall
)

Per-call options.

View Source
var (
	TVDRift                  = drift.TVDRift
	KLDistance               = drift.KLDistance
	JSDistance               = drift.JSDistance
	MaxChange                = drift.MaxChange
	ChampionAttribution      = drift.ChampionAttribution
	ShiftWeightedAttribution = drift.ShiftWeightedAttribution
	CorrelationAttribution   = drift.CorrelationAttribution
)

Drift metrics and attribution.

View Source
var (
	MajorityVote                   = aggregation.MajorityVote
	ConfidenceWeightedVote         = aggregation.ConfidenceWeightedVote
	WeightedVote                   = aggregation.WeightedVote
	ConfidenceWeightedWeightedVote = aggregation.ConfidenceWeightedWeightedVote
)

Aggregation strategies.

View Source
var (
	NewJSONLRecorder = persist.NewJSONLRecorder
	SaveSummary      = persist.SaveSummary
	LoadSummary      = persist.LoadSummary
	SaveSummaryFile  = persist.SaveSummaryFile
	LoadSummaryFile  = persist.LoadSummaryFile
)

Persistence.

View Source
var (
	ReclassifySummary = core.ReclassifySummary
)

Re-scoring a saved summary (pure, zero model calls).

View Source
var (
	ThresholdClassifier = core.ThresholdClassifier
)

Classification.

Functions

This section is empty.

Types

type AgentConfig added in v0.3.0

type AgentConfig = core.AgentConfig

Types.

type AggregationFn added in v0.3.0

type AggregationFn = core.AggregationFn

Types.

type Answer added in v0.3.0

type Answer = core.Answer

Types.

type AnswerSchema added in v0.3.0

type AnswerSchema = core.AnswerSchema

Types.

type AttributionFn added in v0.3.0

type AttributionFn = core.AttributionFn

Types.

type BudgetError added in v0.3.0

type BudgetError = core.BudgetError

Types.

type CallOption added in v0.3.0

type CallOption = core.CallOption

Types.

type CallOptions added in v0.3.0

type CallOptions = core.CallOptions

Types.

type Classifier added in v0.3.0

type Classifier = core.Classifier

Types.

type Config added in v0.3.0

type Config = core.Config

Types.

type ConsistencyScorer added in v0.3.0

type ConsistencyScorer = core.ConsistencyScorer

Types.

type CostBudget added in v0.3.0

type CostBudget = core.CostBudget

Types.

type DiagnosticResult

type DiagnosticResult = core.DiagnosticResult

Types.

type DriftMetric added in v0.3.0

type DriftMetric = core.DriftMetric

Types.

type DriftVerdict

type DriftVerdict = core.DriftVerdict

Types.

type Event added in v0.3.0

type Event = core.Event

Types.

type EventType added in v0.3.0

type EventType = core.EventType

Types.

type FullDebateSummary

type FullDebateSummary = core.FullDebateSummary

Types.

type Gaslit

type Gaslit = engine.Gaslit

Types.

func New added in v0.3.0

func New(ctx context.Context, cfg Config, opts ...Option) (*Gaslit, error)

New builds a Gaslit engine from a Config. Every unset field receives a default; see Config and the Option helpers. At least one agent is required, and agent names must be unique. Concurrent calls to Debate on the same engine are safe.

type GrillStrategy added in v0.3.0

type GrillStrategy = core.GrillStrategy

Types.

type Hooks added in v0.3.0

type Hooks = core.Hooks

Types.

type InstrumentationStats added in v0.3.0

type InstrumentationStats = core.InstrumentationStats

Types.

type JSONLRecorder added in v0.3.0

type JSONLRecorder = persist.JSONLRecorder

Types.

type LLMScorer added in v0.3.0

type LLMScorer = scoring.LLMScorer

Types.

type LexicalScorer added in v0.3.0

type LexicalScorer = scoring.LexicalScorer

Types.

type MCQSchema added in v0.3.0

type MCQSchema = core.MCQSchema

Types.

type OpenEndedSchema added in v0.3.0

type OpenEndedSchema = core.OpenEndedSchema

Types.

type Option added in v0.3.0

type Option = core.Option

Types.

type Phase added in v0.3.0

type Phase = core.Phase

Types.

type PromptResult

type PromptResult = core.PromptResult

Types.

type PromptTemplates added in v0.3.0

type PromptTemplates = core.PromptTemplates

Types.

type Protocol added in v0.3.0

type Protocol = core.Protocol

Types.

type QuadrantState

type QuadrantState = core.QuadrantState

Types.

type Recorder added in v0.3.0

type Recorder = core.Recorder

Types.

type StreamEvent added in v0.3.0

type StreamEvent = core.StreamEvent

Types.

type Thresholds added in v0.3.0

type Thresholds = core.Thresholds

Types.

Directories

Path Synopsis
examples
basic command
internal
aggregation
Package aggregation implements the pluggable winning-option strategies used to combine the panel's final positions.
Package aggregation implements the pluggable winning-option strategies used to combine the panel's final positions.
core
Package core holds the shared data types of the gaslit engine.
Package core holds the shared data types of the gaslit engine.
drift
Package drift implements the pluggable drift metrics, influence attribution strategies, and the pure drift analysis used by the gaslit engine.
Package drift implements the pluggable drift metrics, influence attribution strategies, and the pure drift analysis used by the gaslit engine.
engine
Package engine implements the Gaslit orchestration: the panel state, the debate pipeline, budget accounting, and instrumentation.
Package engine implements the Gaslit orchestration: the panel state, the debate pipeline, budget accounting, and instrumentation.
persist
Package persist handles event recording and the save/load round-trip for debate summaries.
Package persist handles event recording and the save/load round-trip for debate summaries.
scoring
Package scoring implements the consistency scorers used to detect whether an agent's arguments contradict each other under cross-examination.
Package scoring implements the consistency scorers used to detect whether an agent's arguments contradict each other under cross-examination.

Jump to

Keyboard shortcuts

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