Documentation
¶
Overview ¶
Package meterd implements a reference token-metering price server for aperture's dynamicprice.metered mode. It sells prepaid bundles of LLM tokens over L402: a client pays one Lightning invoice for a bundle of tokens, draws it down across requests, and receives a fresh 402 challenge once the bundle is spent.
Index ¶
- Constants
- func Main()
- func UseLogger(logger btclog.Logger)
- type Bundle
- type Config
- type JSONStore
- func (s *JSONStore) Authorize(tokenID string, estimate int64) (int64, bool, error)
- func (s *JSONStore) Book(tokenID, model string, tokens, priceSats int64) (bool, error)
- func (s *JSONStore) Debit(tokenID string, tokens, releaseEstimate int64) (Bundle, bool, error)
- func (s *JSONStore) ExpireStale(ttl time.Duration) int
- func (s *JSONStore) Flush() error
- func (s *JSONStore) Get(tokenID string) (Bundle, bool)
- type JSONStoreConfig
- type ModelConfig
- type RateSource
- type Server
- func (s *Server) AuthorizeRequest(_ context.Context, req *pricesrpc.AuthorizeRequestRequest) (*pricesrpc.AuthorizeRequestResponse, error)
- func (s *Server) ChallengeMinted(_ context.Context, req *pricesrpc.ChallengeMintedRequest) (*pricesrpc.ChallengeMintedResponse, error)
- func (s *Server) GetPrice(_ context.Context, req *pricesrpc.GetPriceRequest) (*pricesrpc.GetPriceResponse, error)
- func (s *Server) QuoteSession(_ context.Context, req *pricesrpc.QuoteSessionRequest) (*pricesrpc.QuoteSessionResponse, error)
- func (s *Server) ReportUsage(_ context.Context, req *pricesrpc.ReportUsageRequest) (*pricesrpc.ReportUsageResponse, error)
- func (s *Server) SettleSession(_ context.Context, req *pricesrpc.SettleSessionRequest) (*pricesrpc.SettleSessionResponse, error)
- func (s *Server) Start() error
- func (s *Server) Stop()
- type ServerOption
- type Store
Constants ¶
const ( // DefaultListenAddr is the address the daemon serves its gRPC // interface on when no other address is configured. DefaultListenAddr = "127.0.0.1:10010" // DefaultBundleTokens is the number of LLM tokens sold per bundle // when no other bundle size is configured. DefaultBundleTokens = 1_000_000 // DefaultEstimatedTokens is the per-request token estimate reserved on // authorization when the request body carries no max_tokens hint. It // bounds how far concurrent requests on a near-empty bundle can // overdraw. DefaultEstimatedTokens = 4_096 // (un-paid) bundles retained at once, bounding the state an // unauthenticated challenge-mint spammer can accumulate. DefaultMaxUnauthorizedBundles = 10_000 // retained before the janitor reaps it. Un-paid mint spam is reaped far // sooner than a paid, drawn-down bundle. DefaultUnauthorizedBundleTTL = 10 * time.Minute // MaxUsageTailBytes is the upper bound accepted for the configured // usage tail size, guarding against an unbounded per-request capture. MaxUsageTailBytes = 1 << 20 )
const Subsystem = "METR"
Subsystem is the logging tag of the meterd daemon.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Bundle ¶
type Bundle struct {
// Model is the configured model the bundle was booked for.
Model string `json:"model"`
// PriceSats is the price in satoshis the bundle was quoted at.
PriceSats int64 `json:"price_sats"`
// RemainingTokens is the number of unspent LLM tokens.
RemainingTokens int64 `json:"remaining_tokens"`
// CreatedAt is when the bundle was booked.
CreatedAt time.Time `json:"created_at"`
// Authorized is whether the bundle was ever used by an authorized
// request. Bundles that are never authorized are expired by the
// janitor, since their challenge was most likely never paid.
Authorized bool `json:"authorized"`
// Reserved is the number of tokens currently reserved by in-flight
// requests that have been authorized but not yet reported. It is an
// estimate that bounds concurrent overdraw, and is not persisted since
// it only tracks live requests.
Reserved int64 `json:"-"`
}
bundle tracks the prepaid token balance purchased with a single L402 payment.
type Config ¶
type Config struct {
// ConfigFile points to an optional YAML config file.
ConfigFile string `yaml:"-" long:"config" description:"Path to a YAML config file"`
// ListenAddr is the address the gRPC server listens on.
ListenAddr string `yaml:"listenaddr" long:"listenaddr" description:"Address to serve the prices gRPC interface on"`
// BundleTokens is the number of LLM tokens sold per bundle. One L402
// payment purchases one bundle.
BundleTokens int64 `yaml:"bundletokens" long:"bundletokens" description:"Number of LLM tokens sold per bundle"`
// DefaultModel is the model used to price requests whose model is
// missing or not present in the models map. When empty, such requests
// cannot be priced.
DefaultModel string `yaml:"defaultmodel" long:"defaultmodel" description:"Model to price requests with an unknown or missing model as"`
// EstimatedTokens is the per-request token estimate reserved on
// authorization when the request carries no max_tokens hint. It bounds
// concurrent overdraw on a near-empty bundle.
EstimatedTokens int64 `` /* 141-byte string literal not displayed */
// bundles retained at once. When zero, the default is used.
MaxUnauthorizedBundles int `` /* 155-byte string literal not displayed */
// retained before the janitor reaps it. When zero, the default is
// used.
UnauthorizedBundleTTL time.Duration `` /* 138-byte string literal not displayed */
// Models maps a model identifier to its per-token rates.
Models map[string]*ModelConfig `yaml:"models"`
// TLSCertPath is the path to the TLS certificate to serve with. The
// server speaks plaintext when unset, matching aperture's
// dynamicprice.insecure mode.
TLSCertPath string `yaml:"tlscertpath" long:"tlscertpath" description:"Path to the TLS certificate to serve with, plaintext when unset"`
// TLSKeyPath is the path to the TLS key belonging to the certificate.
TLSKeyPath string `yaml:"tlskeypath" long:"tlskeypath" description:"Path to the TLS key to serve with"`
// StatePath is the path to a JSON file the bundle balances are
// persisted to on every change. Persistence is disabled when empty.
StatePath string `` /* 127-byte string literal not displayed */
}
Config holds the daemon configuration. Values are read from an optional YAML config file and can be overridden through command line flags. The models map can only be configured through the YAML file.
func LoadConfig ¶
LoadConfig parses the given command line arguments, merges in the YAML config file when one is provided and validates the result. Command line flags take precedence over values from the config file.
type JSONStore ¶
type JSONStore struct {
// contains filtered or unexported fields
}
store keeps the bundle balances, keyed by the hex-encoded L402 token ID, and optionally persists them to a JSON file. Persistence is coalesced: mutations set a dirty flag that a periodic flush and shutdown drain to disk, rather than rewriting the whole file synchronously on every change.
func NewJSONStore ¶
func NewJSONStore(cfg JSONStoreConfig) (*JSONStore, error)
NewJSONStore creates a store from the given configuration, loading any persisted bundle state.
func (*JSONStore) Authorize ¶
Authorize marks the token's bundle as used and, when the request is going to be allowed, reserves the given estimated per-request cost against its balance to bound concurrent overdraw. It returns the tokens available after existing reservations (remaining minus the total reserved) and whether the token is known. The estimate is not applied to the returned availability, so a single request against a bundle with any positive balance is still authorized.
func (*JSONStore) Book ¶
Book records a fresh bundle for the given token ID. Booking is idempotent: a token that already has a bundle is left untouched. The boolean return value indicates whether a new bundle was created. Booking only marks the store dirty rather than persisting synchronously, so a burst of un-paid challenge mints cannot amplify into a full-file rewrite per request.
func (*JSONStore) Debit ¶
Debit subtracts the actual tokens consumed from the token's balance, clamping at zero, and releases the given reservation estimate taken at authorization time. It returns a copy of the bundle after the debit and whether the token is known. A real debit is flushed to disk immediately, since it moves money.
The proto does not correlate a report with the authorization that preceded it, so the release is approximate: it subtracts the estimate the caller passes, clamped at zero, rather than the exact amount this request reserved.
func (*JSONStore) ExpireStale ¶
ExpireStale removes bundles that were never used by an authorized request within the given TTL and returns the number of removed bundles.
type JSONStoreConfig ¶
type JSONStoreConfig struct {
// StatePath is the path to the JSON file bundle balances are persisted
// to. Persistence is disabled when empty.
StatePath string
// bundles retained at once. When a fresh booking would exceed the cap,
// the oldest un-authorized bundle is evicted. A non-positive value
// disables the bound.
MaxUnauthorized int
// MinEvictionAge is the age below which a never-authorized bundle is
// immune to count-based eviction. Payment happens at the proxy, so a
// just-paid bundle is indistinguishable from mint spam until its
// first authorized request; the age floor keeps a spam burst from
// evicting it in that window. The janitor still reaps bundles older
// than the TTL, so with the floor set to the TTL the worst-case
// retained state under spam is the mint rate times the TTL. A
// non-positive value disables the floor.
MinEvictionAge time.Duration
}
JSONStoreConfig holds the tunables that govern persistence coalescing and the bound on un-paid bundles.
type ModelConfig ¶
type ModelConfig struct {
// InputMsatPerToken is the price in millisatoshi of a single input
// (prompt) token.
InputMsatPerToken int64 `yaml:"inputmsatpertoken" long:"inputmsatpertoken" description:"Price in millisatoshi per input token"`
// OutputMsatPerToken is the price in millisatoshi of a single output
// (completion) token.
OutputMsatPerToken int64 `yaml:"outputmsatpertoken" long:"outputmsatpertoken" description:"Price in millisatoshi per output token"`
}
ModelConfig holds the per-token rates of a single model.
type RateSource ¶
type RateSource interface {
// ResolveModel maps a model identifier to a canonical model name and
// its per-token rates. An empty identifier resolves to the default
// model. A non-empty identifier the source does not know MUST return
// an error rather than fall back: the server's model mismatch guard
// relies on unknown models failing resolution, otherwise a bundle
// bought for a cheap model could be spent on an upstream-hosted model
// the seller never priced.
ResolveModel(model string) (string, *ModelConfig, error)
// BundleTokens returns the number of tokens sold per bundle for the
// given canonical model.
BundleTokens(model string) int64
}
RateSource supplies the model rate table and the bundle sizing policy the server prices with. The default implementation is a static table built from the config's models map. A daemon that builds on meterd as a library can supply a dynamic implementation instead, e.g. one refreshed from an upstream provider's price list with a margin applied.
type Server ¶
type Server struct {
pricesrpc.UnimplementedPricesServer
// contains filtered or unexported fields
}
Server implements the pricesrpc.Prices service with token bundle metering. A client purchases a bundle of Config.BundleTokens LLM tokens with a single L402 payment and draws it down across requests. Once the bundle is spent, AuthorizeRequest denies further requests and quotes the price of the next bundle, prompting aperture to mint a fresh 402 challenge.
func NewServer ¶
func NewServer(cfg *Config, opts ...ServerOption) (*Server, error)
NewServer creates a Server from the given configuration, loading any persisted bundle state. Without options, bundles live in the JSON file store and prices come from the config's static models map.
func (*Server) AuthorizeRequest ¶
func (s *Server) AuthorizeRequest(_ context.Context, req *pricesrpc.AuthorizeRequestRequest) ( *pricesrpc.AuthorizeRequestResponse, error)
AuthorizeRequest allows a request through while the token's bundle still has tokens left. Unknown tokens and exhausted bundles are denied together with a quote for the next bundle, so aperture can mint a fresh challenge without a round trip through GetPrice. A request whose model does not match the bundle's booked model is also denied, so a cheap-model bundle cannot be spent on an expensive model. Business logic denials are never errors; errors are reserved for internal failures.
func (*Server) ChallengeMinted ¶
func (s *Server) ChallengeMinted(_ context.Context, req *pricesrpc.ChallengeMintedRequest) ( *pricesrpc.ChallengeMintedResponse, error)
ChallengeMinted books a fresh token bundle for the minted challenge's token ID, remembering the model and the quoted price. Booking is idempotent per token ID.
func (*Server) GetPrice ¶
func (s *Server) GetPrice(_ context.Context, req *pricesrpc.GetPriceRequest) (*pricesrpc.GetPriceResponse, error)
GetPrice quotes the price of a token bundle for the model named in the JSON body of the serialized HTTP request. Requests naming no model are priced as the default model; requests naming an unknown model are rejected with an InvalidArgument error, since a model the seller never priced must not be quoted (or proxied) at another model's rate.
func (*Server) QuoteSession ¶
func (s *Server) QuoteSession(_ context.Context, req *pricesrpc.QuoteSessionRequest) (*pricesrpc.QuoteSessionResponse, error)
QuoteSession prices one request drawn against a prepaid MPP session balance.
Where GetPrice quotes a whole token bundle, this quotes the single request in hand, at the same blended per-token rate the bundle is priced at. The estimate is the request's max_tokens when it declares one and the configured default otherwise, which is the same estimate the L402 path reserves against a bundle. A session and a bundle therefore charge the same rate for the same work; what differs is only who holds the balance.
Nothing is booked or reserved here. The session's balance lives in aperture, which deducts this estimate itself and refunds whatever is left when the session closes, so a quote the buyer never uses costs the pricer nothing to have given.
func (*Server) ReportUsage ¶
func (s *Server) ReportUsage(_ context.Context, req *pricesrpc.ReportUsageRequest) (*pricesrpc.ReportUsageResponse, error)
ReportUsage extracts the final usage object from the captured response tail and debits the token's bundle by the number of consumed tokens. The informational satoshi amounts of the response are derived from the booked model's rates: the debit is rounded up and the remaining balance is rounded down, so rounding never favors the client.
func (*Server) SettleSession ¶
func (s *Server) SettleSession(_ context.Context, req *pricesrpc.SettleSessionRequest) (*pricesrpc.SettleSessionResponse, error)
SettleSession costs a response that was served against a session balance and returns what the request should actually have cost.
The cost is derived from the same trailing usage object ReportUsage reads, and priced exactly per direction when the prompt and completion split is known: an all-completion workload costs the full output rate rather than the blended one the estimate assumed. Millisatoshis round up to satoshis, so rounding never favours the client.
A response that carries no usage object settles at the estimate rather than at zero. Returning zero would make every unparseable response free, which turns a truncated stream or an unexpected content type into an unmetered request. Leaving the estimate in place charges what the challenge told the buyer a request would cost, which is the honest answer when nothing better is known.
type ServerOption ¶
type ServerOption func(*serverOptions)
ServerOption customizes a Server beyond its config. The options exist so that a daemon building on meterd as a library can swap in its own storage and pricing while reusing the metering logic unchanged.
func WithRateSource ¶
func WithRateSource(rates RateSource) ServerOption
WithRateSource makes the server price with the given rate source instead of the static table built from the config's models map.
func WithStore ¶
func WithStore(store Store) ServerOption
WithStore makes the server track bundles in the given store instead of the default JSON file store.
type Store ¶
type Store interface {
// Book records a fresh bundle for the given token ID. Booking is
// idempotent: a token that already has a bundle is left untouched,
// and the boolean return value reports whether a new bundle was
// created.
Book(tokenID, model string, tokens, priceSats int64) (bool, error)
// Authorize marks the token's bundle as used and, when the request
// is going to be allowed, reserves the given estimated per-request
// cost against its balance to bound concurrent overdraw. It returns
// the tokens available after existing reservations and whether the
// token is known.
Authorize(tokenID string, estimate int64) (int64, bool, error)
// Get returns a copy of the token's bundle.
Get(tokenID string) (Bundle, bool)
// Debit subtracts the actual tokens consumed from the token's
// balance, clamping at zero, and releases the given reservation
// estimate taken at authorization time. It returns a copy of the
// bundle after the debit and whether the token is known.
Debit(tokenID string, tokens, releaseEstimate int64) (Bundle, bool,
error)
// ExpireStale removes bundles that were never used by an authorized
// request within the given TTL and returns the number of removed
// bundles.
ExpireStale(ttl time.Duration) int
// Flush drains any pending state to durable storage. It is safe to
// call on an unchanged store.
Flush() error
}
Store tracks the prepaid token bundles the server meters against, keyed by the hex-encoded L402 token ID. The JSONStore implementation persists the balances to a single JSON file; a daemon embedding meterd can supply a database-backed implementation instead.