{"modulePath":"github.com/MAX-API-Next/MAX-API","version":"v1.0.5","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package billingexpr\n\n## Constants\n\n```go\nconst DefaultExprVersion = 1\n```\nDefaultExprVersion is used when an expression string has no version prefix.\n\n## Functions\n\n```go\nfunc CompileFromCache(exprStr string) (*vm.Program, error)\n```\nCompileFromCache compiles an expression string, using a cached program when available. The cache is keyed by the SHA-256 hex digest of the expression.\n\n```go\nfunc CompileFromCacheByHash(exprStr, hash string) (*vm.Program, error)\n```\nCompileFromCacheByHash is like CompileFromCache but accepts a pre-computed hash, useful when the caller already has the BillingSnapshot.ExprHash.\n\n```go\nfunc ExprHashString(expr string) string\n```\nExprHashString returns the SHA-256 hex digest of an expression string.\n\n```go\nfunc ExprVersion(exprStr string) int\n```\nExprVersion returns the version of a cached expression. Returns DefaultExprVersion if the expression hasn't been compiled yet or is empty.\n\n```go\nfunc InvalidateCache()\n```\nInvalidateCache clears the compiled-expression cache. Called when billing rules are updated.\n\n```go\nfunc ParseExprVersion(exprStr string) (version int, body string)\n```\nParseExprVersion extracts the version tag and body from an expression string. Format: \"v1:tier(...)\" → version=1, body=\"tier(...)\". No prefix defaults to DefaultExprVersion.\n\n```go\nfunc QuotaRound(f float64) int\n```\nQuotaRound converts a float64 quota value to int using half-away-from-zero rounding. Every tiered billing path (pre-consume, settlement, breakdown validation, log fields) MUST use this function to avoid +-1 discrepancies.\n\n```go\nfunc QuotaRoundStrict(f float64) (int, error)\n```\nQuotaRoundStrict rejects an unrepresentable pre-consume estimate.\n\n```go\nfunc UsedVars(exprStr string) map[string]bool\n```\nUsedVars returns the set of identifier names referenced by an expression. The result is cached alongside the compiled program. Returns nil for empty input.\n\n## Types\n\n```go\ntype BillingSnapshot struct {\n\tBillingMode               string  `json:\"billing_mode\"`\n\tModelName                 string  `json:\"model_name\"`\n\tExprString                string  `json:\"expr_string\"`\n\tExprHash                  string  `json:\"expr_hash\"`\n\tGroupRatio                float64 `json:\"group_ratio\"`\n\tEstimatedPromptTokens     int     `json:\"estimated_prompt_tokens\"`\n\tEstimatedCompletionTokens int     `json:\"estimated_completion_tokens\"`\n\tEstimatedQuotaBeforeGroup float64 `json:\"estimated_quota_before_group\"`\n\tEstimatedQuotaAfterGroup  int     `json:\"estimated_quota_after_group\"`\n\tEstimatedTier             string  `json:\"estimated_tier\"`\n\tQuotaPerUnit              float64 `json:\"quota_per_unit\"`\n\tExprVersion               int     `json:\"expr_version\"`\n}\n```\nBillingSnapshot captures the billing rule state frozen at pre-consume time. It is fully serializable and contains no compiled program pointers.\n\n```go\ntype RequestInput struct {\n\tHeaders map[string]string\n\tBody    []byte\n}\n```\n\n```go\ntype TieredResult struct {\n\tActualQuotaBeforeGroup float64 `json:\"actual_quota_before_group\"`\n\tActualQuotaAfterGroup  int     `json:\"actual_quota_after_group\"`\n\tMatchedTier            string  `json:\"matched_tier\"`\n\tCrossedTier            bool    `json:\"crossed_tier\"`\n\t// Clamp records an int32 saturation event during quota conversion so the\n\t// caller can surface it on the consume log for admin auditing.\n\tClamp *common.QuotaClamp `json:\"-\"`\n}\n```\nTieredResult holds everything needed after running tiered settlement.\n\n```go\nfunc ComputeTieredQuota(snap *BillingSnapshot, params TokenParams) (TieredResult, error)\n```\nComputeTieredQuota runs the Expr from a frozen BillingSnapshot against actual token counts and returns the settlement result.\n\n```go\nfunc ComputeTieredQuotaWithRequest(snap *BillingSnapshot, params TokenParams, request RequestInput) (TieredResult, error)\n```\n\n```go\ntype TokenParams struct {\n\tP    float64 // prompt tokens (text) — auto-excludes sub-categories priced separately\n\tC    float64 // completion tokens (text) — auto-excludes sub-categories priced separately\n\tLen  float64 // total input context length for tier conditions (non-Claude: raw prompt_tokens; Claude: text + cache read + cache creation)\n\tCR   float64 // cache read (hit) tokens\n\tCC   float64 // cache creation tokens (5-min TTL for Claude, generic for others)\n\tCC1h float64 // cache creation tokens — 1-hour TTL (Claude only)\n\tImg  float64 // image input tokens\n\tImgO float64 // image output tokens\n\tAI   float64 // audio input tokens\n\tAO   float64 // audio output tokens\n}\n```\nTokenParams holds all token dimensions passed into an Expr evaluation. Fields beyond P and C are optional — when absent they default to 0, which means cache-unaware expressions keep working unchanged.\n\n```go\ntype TraceResult struct {\n\tMatchedTier string  `json:\"matched_tier\"`\n\tCost        float64 `json:\"cost\"`\n}\n```\nTraceResult holds side-channel info captured by the tier() function during Expr execution. This replaces the old Breakdown mechanism — the Expr itself is the single source of truth for billing logic.\n\n```go\nfunc RunExpr(exprStr string, params TokenParams) (float64, TraceResult, error)\n```\nRunExpr compiles (with cache) and executes an expression string. The environment exposes:\n\n  - p, c             — prompt / completion tokens (auto-excluding separately-priced sub-categories)\n  - len              — total input context length for tier conditions (never reduced by sub-category exclusion)\n  - cr, cc, cc1h     — cache read / creation / creation-1h tokens\n  - tier(name, value) — trace callback that records which tier matched\n  - max, min, abs, ceil, floor — standard math helpers\n\nReturns the resulting float64 quota (before group ratio) and a TraceResult with side-channel info captured by tier() during execution.\n\n```go\nfunc RunExprByHash(exprStr, hash string, params TokenParams) (float64, TraceResult, error)\n```\nRunExprByHash is like RunExpr but accepts a pre-computed hash for the cache lookup, avoiding a redundant SHA-256 computation when the caller already holds BillingSnapshot.ExprHash.\n\n```go\nfunc RunExprByHashWithRequest(exprStr, hash string, params TokenParams, request RequestInput) (float64, TraceResult, error)\n```\n\n```go\nfunc RunExprWithRequest(exprStr string, params TokenParams, request RequestInput) (float64, TraceResult, error)\n```\n\n","path":"github.com/MAX-API-Next/MAX-API/pkg/billingexpr","name":"billingexpr","synopsis":"","isRedistributable":true}
