compression

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: Apache-2.0 Imports: 5 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	MinCompressBytes = 2048
	HeadLines        = 20
	TailLines        = 20
)
View Source
const (
	ModeLight        = "light"
	ModeStandard     = "standard"
	ModeAggressive   = "aggressive"
	ModeConservative = "conservative"
	ModeBalanced     = "balanced"
	ModeLite         = "lite"
	ModeFull         = "full"
	ModeAuto         = "auto" // resolved per-request later (see auto.go)
)
View Source
const CavemanDirective = `` /* 1093-byte string literal not displayed */

CavemanDirective is a condensed version of the viral "caveman" system prompt (JuliusBrussee/caveman, adapted by 9Router): reply terse, keep all technical substance, drop only fluff. Measured savings: up to 65% output tokens.

View Source
const CavemanLiteDirective = `` /* 348-byte string literal not displayed */

CavemanLiteDirective keeps every safety clause of the full directive but shortens the style rules: same protections, fewer constraints.

View Source
const DefaultHeadroomKeep = 8

DefaultHeadroomKeep is how many recent messages to keep when pruning.

View Source
const DefaultHeadroomReserve = 120000

DefaultHeadroomReserve is the default max estimated input tokens before pruning (like 9Router ~120k).

Variables

This section is empty.

Functions

func AutoCavemanDirective

func AutoCavemanDirective(body []byte) string

AutoCavemanDirective returns the directive for a request: agentic traffic (tools/tool calls/results anywhere in the body) earns the FULL terse directive — agents save the most and misread least — while plain chat gets the gentler lite variant that distills style, not voice.

func AutoHeadroomProfile

func AutoHeadroomProfile(estTokens, reserve int) (run bool, profile string)

AutoHeadroomProfile maps estimated input tokens against the configured reserve: plenty of room → don't prune at all; approaching the limit → prune conservatively; nearly full → prune aggressively.

func CompressReasoning

func CompressReasoning(body []byte, effort string) ([]byte, int, bool)

CompressReasoning compresses large reasoning_content (CoT) in a DeepSeek chat payload: keeps head+tail lines, preserving the final answer fully. Mimics RTK but for reasoning, per reasoning_effort (low → tight, high/max → looser). Returns (newBody, savedBytes, modified).

func CompressToolResults

func CompressToolResults(body []byte) ([]byte, int, bool)

func CompressToolResultsAuto

func CompressToolResultsAuto(body []byte) ([]byte, int, bool)

CompressToolResultsAuto is rtk_mode=auto: parameters are resolved PER BLOCK from its size, so a given tool_result always gets identical treatment across turns and provider prompt caches stay valid.

func CompressToolResultsWith

func CompressToolResultsWith(body []byte, p RTKParams) ([]byte, int, bool)

CompressToolResultsWith runs one RTK pass with explicit parameters (mode presets map to these in modes.go).

func DecideHeadroom

func DecideHeadroom(global, model, vk *config.Optimization, header string) (bool, string, int, int)

DecideHeadroom resolves headroom pruning: whether it runs, which profile applies and the concrete keep/reserve parameters.

func DirectiveFor

func DirectiveFor(mode string) string

DirectiveFor returns the system directive for a caveman mode preset. Empty/unknown modes map to the legacy full directive.

func EstimateTokens

func EstimateTokens(body []byte) int

EstimateTokens is a public rough estimate (1 token ≈ 4 EN chars) for X-Gateway-Saved-Tokens style headers across providers.

func HasToolTraffic

func HasToolTraffic(body []byte) bool

HasToolTraffic parses only the top-level fields needed to detect agentic traffic. Invalid JSON counts as non-agentic (fail-open).

func InjectCavemanDirective

func InjectCavemanDirective(body []byte) ([]byte, bool, error)

InjectCavemanDirective appends the caveman directive to the request's system prompt (OpenAI chat `messages` or Responses API `instructions`). It returns (body, true, nil) when the body was modified; (body, false, nil) when the payload has no injectable system prompt; and (body, false, err) on invalid JSON so callers can skip without breaking the request.

func InjectCavemanDirectiveWith

func InjectCavemanDirectiveWith(body []byte, directive string) ([]byte, bool, error)

InjectCavemanDirectiveWith injects an explicit directive text (mode presets select between full and lite via DirectiveFor).

func PruneForHeadroom

func PruneForHeadroom(body []byte, reserve int, keep int) ([]byte, int, bool)

PruneForHeadroom prunes old messages when estimated tokens exceed reserve. It keeps all system messages + last keep messages, dropping the middle. Returns (prunedBody, savedTokens, pruned bool).

func ShouldCaveman

func ShouldCaveman(global, model, vk *config.Optimization, header string) bool

ShouldCaveman decides if caveman should run (legacy boolean API).

func ShouldHeadroom

func ShouldHeadroom(global, model, vk *config.Optimization, header string) (bool, int, int)

ShouldHeadroom decides if headroom should run based on global/model/vk/header (legacy API: concrete keep/reserve without the profile layer).

func ShouldRTK

func ShouldRTK(global, model, vk *config.Optimization, header string) bool

ShouldRTK decides if RTK compression should run (legacy boolean API — new callers use DecideRTK, which also resolves the mode preset).

Types

type Decision

type Decision struct {
	Run  bool
	Mode string
}

Decision is the outcome of resolving one optimization for a request. Run=false means skip entirely. Mode is concrete ("light"/"standard"/...) or "auto"; auto is refined against the request body before execution.

func DecideCaveman

func DecideCaveman(global, model, vk *config.Optimization, header string) Decision

DecideCaveman resolves the caveman directive injection.

func DecideRTK

func DecideRTK(global, model, vk *config.Optimization, header string) Decision

DecideRTK resolves RTK compression for a request. The returned mode is concrete unless every configured layer chose "auto".

type OptimizeOptions

type OptimizeOptions struct {
	// Headroom parameters (resolved profile/defaults; 0 = run with defaults).
	Headroom        bool
	HeadroomKeep    int
	HeadroomReserve int

	// RTK parameters. RTKAuto switches to per-block auto parameters
	// (rtk_mode=auto); RTKParams is ignored then.
	RTK       bool
	RTKAuto   bool
	RTKParams RTKParams

	// Caveman directive text (DirectiveFor(mode) resolved by the caller).
	Caveman          bool
	CavemanDirective string
	// CavemanMode is the concrete mode applied (echoed to the client when
	// the directive is injected; empty = no echo).
	CavemanMode string
}

type OptimizeResult

type OptimizeResult struct {
	Changed             bool
	HeadroomPruned      bool
	HeadroomSavedTokens int
	RTKSavedBytes       int
	CavemanInjected     bool
	// CavemanMode echoes the concrete caveman mode on injection.
	CavemanMode string
}

func OptimizeRequest

func OptimizeRequest(body []byte, o OptimizeOptions) ([]byte, OptimizeResult)

OptimizeRequest runs the single-pass pipeline. It returns the original body untouched when nothing applies or the payload is not a chat message body (headroom/RTK need `messages`; caveman alone still handles the Responses `instructions` form).

type ProfileParams

type ProfileParams struct {
	Profile string
	Keep    int
	Reserve int
}

ProfileParams are the concrete headroom parameters a profile maps to.

func HeadroomProfileParams

func HeadroomProfileParams(profile string, reserveOverride, keepOverride int) ProfileParams

HeadroomProfileParams maps a profile name to concrete pruning parameters. Explicit reserve/keep overrides replace the profile defaults when non-zero.

type RTKParams

type RTKParams struct {
	MinBytes     int
	HeadLines    int
	TailLines    int
	CommandAware bool
}

RTKParams controls one RTK compression pass. Presets live in modes.go.

func AutoRTKParamsForBlock

func AutoRTKParamsForBlock(blockLen int) RTKParams

AutoRTKParamsForBlock selects compression parameters for ONE tool_result block by its size: small blocks are handled gently or skipped entirely, huge ones are compressed hard where the tokens are expensive.

func RTKParamsFor

func RTKParamsFor(mode string) RTKParams

RTKParamsFor maps an RTK mode preset to concrete compression parameters (see compression.go for how they are applied). Empty/unknown → standard.

func StandardRTKParams

func StandardRTKParams() RTKParams

Jump to

Keyboard shortcuts

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