mod_ai_context

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 21 Imported by: ? 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 (
	ModeOff          = "off"
	ModeConservative = "conservative"
	ModeBalanced     = "balanced"
	ModeAggressive   = "aggressive"
)

context compress modes (rule entries, mode is required)

View Source
const (
	ThinkingPolicyTrimAllButLast = "trim-all-but-last"
	ThinkingPolicyKeep           = "keep"
)

thinking block policies (Defaults.thinkingPolicy)

View Source
const (
	RewriteStrengthLite = "lite"
	RewriteStrengthFull = "full"
)

rewrite strengths (Defaults.rewrite.strength)

View Source
const (
	DefaultTriggerRatio          = 0.7
	DefaultKeepLatestImages      = 2
	DefaultToolResultMaxChars    = 2000
	DefaultThinkingPolicy        = ThinkingPolicyTrimAllButLast
	DefaultCharsPerToken         = 4
	DefaultImageTokenEstimate    = 1200
	DefaultRewriteStrength       = RewriteStrengthLite
	DefaultProtectedSurvivalRate = 0.95
)

defaults for the Defaults block of context_rule.data

View Source
const (
	StatusSkipNoRule         = "skip_no_rule"         // no rule matched or mode=off
	StatusSkipProtocol       = "skip_protocol"        // not an OpenAI chat completions request
	StatusSkipBodyIncomplete = "skip_body_incomplete" // request body not fully buffered
	StatusSkipParseErr       = "skip_parse_err"       // messages parsing failed
	StatusSkipUnderThreshold = "skip_under_threshold" // estimate below budget*triggerRatio
	StatusTrim               = "trim"                 // pipeline finished on the lossless trim layers
	StatusRewrite            = "rewrite"              // pipeline finished with the P2 rule rewrite
	StatusRepairRollback     = "repair_rollback"      // repair/serialize failed, original body forwarded
)

context compress status values recorded in AiBasicInfo.ContextCompressStatus and in the access log (ai_context_compress_status). The empty string means the request was not processed by the module; the non-empty value also acts as the per-request idempotency guard for the per-cluster-attempt callback.

View Source
const (
	ModAiContext     = "mod_ai_context"
	ModAiContextDiff = "mod_ai_context_diff"
)
View Source
const (
	DiffCounterInterval = 20 // interval for diff counter (in seconds)
)

Variables

View Source
var CounterKeys = []string{
	"CTX_TOTAL",
	"CTX_SKIP_NO_RULE",
	"CTX_SKIP_PROTOCOL",
	"CTX_SKIP_BODY_INCOMPLETE",
	"CTX_SKIP_PARSE_ERR",
	"CTX_SKIP_UNDER_THRESHOLD",
	"CTX_TRIGGERED",
	"CTX_TRIGGERED_CONSERVATIVE",
	"CTX_TRIGGERED_BALANCED",
	"CTX_TRIGGERED_AGGRESSIVE",
	"CTX_DONE_TRIM",
	"CTX_DONE_REWRITE",
	"CTX_GATE_FALLBACK",
	"CTX_REPAIR_ROLLBACK",
	"CTX_WINDOW_DEFAULTED",
	"CTX_CFG_UNKNOWN_FIELD",
	"CTX_LATENCY_MS",
}

key for counter of mod_ai_context (see design-changes.md 10.2)

Functions

func ConfModAiContextCheck

func ConfModAiContextCheck(cfg *ConfModAiContext, confRoot string) error

Types

type ConfModAiContext

type ConfModAiContext struct {
	Basic struct {
		ProductRulePath string // path for product rule
	}

	Log struct {
		OpenDebug bool // whether open debug
	}
}

The module INI deliberately keeps only bootstrap-style static config (rule file path, log switch). All business tuning lives in the rule.data Defaults block so it can be hot reloaded.

func ConfLoad

func ConfLoad(filePath string, confRoot string) (*ConfModAiContext, error)

load config from config file

func (*ConfModAiContext) Check

func (cfg *ConfModAiContext) Check(confRoot string) error

type ContentPart

type ContentPart struct {
	Type     string    `json:"type"` // text / image_url / thinking / ...
	Text     string    `json:"text,omitempty"`
	Thinking string    `json:"thinking,omitempty"`
	ImageURL *ImageURL `json:"image_url,omitempty"`

	// Extra carries part fields unknown to the pipeline (detail, file data,
	// provider extensions) and round-trips them on marshal.
	Extra map[string]json.RawMessage `json:"-"`
}

ContentPart is one element of a typed-parts message content.

func (ContentPart) MarshalJSON

func (p ContentPart) MarshalJSON() ([]byte, error)

func (*ContentPart) UnmarshalJSON

func (p *ContentPart) UnmarshalJSON(data []byte) error

type ContextDefaults

type ContextDefaults struct {
	TriggerRatio          float64
	KeepLatestImages      int
	ToolResultMaxChars    int
	ThinkingPolicy        string
	CharsPerToken         int
	ImageTokenEstimate    int
	RewriteStrength       string
	ProtectedSurvivalRate float64
}

type ContextParams

type ContextParams struct {
	TriggerRatio          float64 // proactive trigger threshold (ratio of budget)
	KeepLatestImages      int     // keep latest N inline images (0 = no image trim)
	ToolResultMaxChars    int     // max chars of a single tool result (0 = no truncate)
	ThinkingPolicy        string  // trim-all-but-last / keep
	CharsPerToken         int     // bytes per token for heuristic estimation
	ImageTokenEstimate    int     // fixed token estimate per inline base64 image
	RewriteStrength       string  // lite / full
	ProtectedSurvivalRate float64 // fidelity gate threshold for protected tokens

	MaxContextTokens int64 // rule override of the model context window (0 = use window)
	ReserveTokens    int64 // rule override of the output reserve (0 = auto)
}

ContextParams is the per-request parameter set: the Defaults block merged with the rule-level budget overrides. All pipeline tuning flows through it, so a rule reload takes effect on the next request.

type ContextRuleConf

type ContextRuleConf struct {
	Cond      string
	CondBuild condition.Condition

	Mode             string // off / conservative / balanced / aggressive
	MaxContextTokens int64
	ReserveTokens    int64
}

type ContextRuleConfData

type ContextRuleConfData struct {
	Version  *string
	Defaults *ContextDefaults
	Config   *map[string]*ContextRuleConfList

	// UnknownFields counts ignored unknown config fields (rule entries and
	// the Defaults block) for the CTX_CFG_UNKNOWN_FIELD forward-compat alert
	UnknownFields int
}

func ContextRuleConfLoad

func ContextRuleConfLoad(fileName string) (*ContextRuleConfData, error)

type ContextRuleConfDataFile

type ContextRuleConfDataFile struct {
	Version  *string                              `json:"Version"`
	Defaults *DefaultsConfFile                    `json:"Defaults"`
	Config   *map[string]*ContextRuleConfListFile `json:"Config"`
}

type ContextRuleConfFile

type ContextRuleConfFile struct {
	Cond *string `json:"cond"`
	Mode *string `json:"mode"`

	MaxContextTokens *int64 `json:"maxContextTokens"` // 0/absent = use model window
	ReserveTokens    *int64 `json:"reserveTokens"`    // 0/absent = auto clamp(window*15%, 256, 16000)
}

func (*ContextRuleConfFile) Check

func (obj *ContextRuleConfFile) Check() error

func (*ContextRuleConfFile) Convert

func (f *ContextRuleConfFile) Convert() *ContextRuleConf

type ContextRuleConfList

type ContextRuleConfList []*ContextRuleConf

type ContextRuleConfListFile

type ContextRuleConfListFile []*ContextRuleConfFile

func (ContextRuleConfListFile) Check

func (obj ContextRuleConfListFile) Check() error

func (ContextRuleConfListFile) Convert

type DefaultsConfFile

type DefaultsConfFile struct {
	TriggerRatio       *float64         `json:"triggerRatio"`
	KeepLatestImages   *int             `json:"keepLatestImages"`
	ToolResultMaxChars *int             `json:"toolResultMaxChars"`
	ThinkingPolicy     *string          `json:"thinkingPolicy"`
	CharsPerToken      *int             `json:"charsPerToken"`
	ImageTokenEstimate *int             `json:"imageTokenEstimate"`
	Rewrite            *RewriteConfFile `json:"rewrite"`
}

func (*DefaultsConfFile) Check

func (obj *DefaultsConfFile) Check() error

func (*DefaultsConfFile) Convert

func (f *DefaultsConfFile) Convert() *ContextDefaults

type EstimateParams

type EstimateParams struct {
	CharsPerToken      int // bytes per token for text estimation
	ImageTokenEstimate int // fixed token estimate per inline base64 image
}

EstimateParams carries the estimation coefficients. They come from the merged rule parameters and are passed in on every call, so a hot reload of the rule data takes effect immediately; Init does not bake them in.

type FidelityGate

type FidelityGate struct {
	// contains filtered or unexported fields
}

FidelityGate is the P2 quality gate (design 7.4): the rewrite output is accepted only when the token-weighted survival rate of the tombstone protected fragments reaches the configured threshold; otherwise the pipeline falls back to the lossless trim-layer product (GATE_FALLBACK).

func NewFidelityGate

func NewFidelityGate(threshold float64) *FidelityGate

func (*FidelityGate) Pass

func (g *FidelityGate) Pass(survivedTokens, totalTokens int64) bool

Pass reports whether the protected content survived the rewrite well enough. A conversation without protected content always passes.

type HeuristicEstimator

type HeuristicEstimator struct{}

HeuristicEstimator estimates tokens as len(json)/CharsPerToken, aligned with the bfe convention (GetPromptToken, len/4) and OmniRoute's estimateTokens. Inline base64 images are not counted by their raw bytes; each inline image counts ImageTokenEstimate tokens instead.

func NewHeuristicEstimator

func NewHeuristicEstimator() *HeuristicEstimator

func (*HeuristicEstimator) EstimateMessages

func (e *HeuristicEstimator) EstimateMessages(msgs []Message, p EstimateParams) int64

func (*HeuristicEstimator) EstimateText

func (e *HeuristicEstimator) EstimateText(s string, p EstimateParams) int64

type ImageURL

type ImageURL struct {
	URL    string `json:"url"`
	Detail string `json:"detail,omitempty"`
}

type Message

type Message struct {
	Role             string          `json:"role"`
	Content          json.RawMessage `json:"content,omitempty"`
	ReasoningContent string          `json:"reasoning_content,omitempty"`
	Name             string          `json:"name,omitempty"`
	ToolCallID       string          `json:"tool_call_id,omitempty"`
	ToolCalls        []*ToolCall     `json:"tool_calls,omitempty"`

	// Extra carries message fields unknown to the pipeline (e.g. refusal,
	// provider-specific extensions) and round-trips them on marshal.
	Extra map[string]json.RawMessage `json:"-"`
}

Message is the typed model of an OpenAI chat completions message. Content stays a json.RawMessage because it is legal both as a plain string and as an array of typed parts. Fields the pipeline does not know about round-trip through Extra so reserialization preserves the original message shape (precedent: mod_ai_intent/msg_extract.go tolerates string and typed-parts content; the typed model here is what the trim/rewrite stages operate on).

func (Message) MarshalJSON

func (m Message) MarshalJSON() ([]byte, error)

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(data []byte) error

type ModuleAiContext

type ModuleAiContext struct {
	// contains filtered or unexported fields
}

func NewModuleAiContext

func NewModuleAiContext() *ModuleAiContext

func (*ModuleAiContext) Init

module Init

func (*ModuleAiContext) Name

func (m *ModuleAiContext) Name() string

type Pipeline

type Pipeline struct {
	// contains filtered or unexported fields
}

func NewPipeline

func NewPipeline(est TokenEstimator) *Pipeline

func (*Pipeline) Run

func (p *Pipeline) Run(msgs []Message, mode string, params ContextParams, budget int64) PipelineResult

Run degrades the messages until the estimate fits the budget or the mode's capability is exhausted. The input slice is not modified: the pipeline works on a clone, so a rollback is simply not using the result.

type PipelineResult

type PipelineResult struct {
	Messages     []Message // processed messages (repair already applied)
	Stage        string    // StatusTrim or StatusRewrite (pipeline exit stage)
	Estimated    int64     // token estimate of the processed messages
	Legal        bool      // false: repair/validation failed, caller must roll back
	GateFallback bool      // true: fidelity gate failed, P2 product discarded
}

PipelineResult is the outcome of the pipeline for one request.

type RewriteConfFile

type RewriteConfFile struct {
	Strength              *string  `json:"strength"`
	ProtectedSurvivalRate *float64 `json:"protectedSurvivalRate"`
}

func (*RewriteConfFile) Check

func (obj *RewriteConfFile) Check() error

type TokenEstimator

type TokenEstimator interface {
	// EstimateMessages estimates the tokens of the whole messages array
	// (inline base64 images are counted at their fixed placeholder estimate)
	EstimateMessages(msgs []Message, p EstimateParams) int64
	// EstimateText estimates the tokens of a plain text string
	EstimateText(s string, p EstimateParams) int64
}

TokenEstimator abstracts the token estimation of a messages array. The default HeuristicEstimator is used in phase 1; a tiktoken-class implementation can replace it later without changing the interface.

type ToolCall

type ToolCall struct {
	Index    int              `json:"index,omitempty"`
	ID       string           `json:"id"`
	Type     string           `json:"type"`
	Function ToolCallFunction `json:"function"`
}

ToolCall is the OpenAI tool_call object of an assistant message.

type ToolCallFunction

type ToolCallFunction struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

Jump to

Keyboard shortcuts

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