Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
8.3 kB · 232 lines
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233//// What the provider calls used, read from the hourly totals that//// `migrations/usage_hours` keeps beside the request ledger. A summary reads//// the totals for a window of days, never the ledger, so it costs the same//// however long the history is. A window can be narrowed to one provider's//// rows, or to one account of it, while the scopes it saw are read before that//// narrowing: a client that narrows still knows what it could choose.
import albedo/daemon/storeimport gleam/dictimport gleam/dynamic/decodeimport gleam/intimport gleam/listimport gleam/option.{type Option, None, Some}import gleam/resultimport sqlight
/// Counts as the providers reported them; one that left a count out adds/// nothing to it. Cached input is part of `input_tokens`, as every provider's/// reducer records it, so it is kept beside the input rather than added to it.pub type Total { Total( calls: Int, errors: Int, input_tokens: Int, cached_input_tokens: Int, cache_creation_tokens: Int, output_tokens: Int, reasoning_tokens: Int, )}
/// One day of the client's, `start_ms` being its midnight as a Unix time.pub type Day { Day(start_ms: Int, total: Total)}
/// What one profile, account and model used over the whole window. An empty/// account is a provider without an account pool.pub type Line { Line( profile: String, provider: String, account: String, model: String, total: Total, )}
/// A provider and account that used the window, spelled as `Line` spells them:/// an empty account is a provider without an account pool.pub type Scope { Scope(provider: String, account: String)}
/// Which rows of the window a summary counts. `scopes` is read before it is/// applied, so it always lists the whole window.pub type Filter { /// Every provider and account. AllScopes /// One provider's rows, and one account of them when `account` is `Some`. /// `Some("")` is that provider's own use, without an account pool. OfProvider(provider: String, account: Option(String))}
pub type Summary { Summary( days: List(Day), lines: List(Line), /// Every provider and account with use in the window, before `filter` /// narrowed the totals. scopes: List(Scope), /// Whether `lines` or `scopes` holds less than the window matched. lines_truncated: Bool, scopes_truncated: Bool, )}
/// A row is one hour (UTC) of one profile, account and model. The account is/// empty, not null, for a provider without an account pool, because a null in a/// primary key never conflicts. Unreported counts are zero here.pub const schema = "CREATE TABLE IF NOT EXISTS usage_hours(hour_ms INTEGER NOT NULL,profile TEXT NOT NULL,provider TEXT NOT NULL,account TEXT NOT NULL,model TEXT NOT NULL,kind TEXT NOT NULL,calls INTEGER NOT NULL,errors INTEGER NOT NULL,input_tokens INTEGER NOT NULL,cached_input_tokens INTEGER NOT NULL,cache_creation_tokens INTEGER NOT NULL,output_tokens INTEGER NOT NULL,reasoning_tokens INTEGER NOT NULL,PRIMARY KEY(hour_ms,profile,provider,account,model,kind)) WITHOUT ROWID;"
const day_ms = 86_400_000
/// The lines kept, most used first.pub const most_lines = 100
/// The scopes kept: enough for a selector to list every provider and account a/// client is ever likely to have.const most_scopes = 200
const sums = "SUM(calls),SUM(errors),SUM(input_tokens),SUM(cached_input_tokens),SUM(cache_creation_tokens),SUM(output_tokens),SUM(reasoning_tokens)"
/// The rows of one window, which every read starts from. The window ends where/// the client's today does: an hour stamped later (a clock set back since) is/// left out of every list alike, rather than counted in lines and scopes that/// the days cannot show.const from_window = " FROM usage_hours WHERE hour_ms>=? AND hour_ms<?"
pub const empty = Total(0, 0, 0, 0, 0, 0, 0)
/// The last `days` days, the one `now_ms` falls in included, for a client whose/// clock is `offset_ms` ahead of UTC. A day without use is an empty total./// Hours are UTC, so a half-hour zone puts the hour that straddles its midnight/// in the earlier day.////// `filter` narrows the days and the lines; `scopes` lists every provider and/// account the window saw, so a client can offer a choice it is not currently/// showing. Each list is read with room for one row more than it keeps, which/// is what says whether it was cut short, and the days come from one aggregate/// over every matching hour, never from the lines: a window with more models/// than lines still totals all of them.pub fn summary( ledger: store.Store, now_ms: Int, days: Int, offset_ms: Int, filter: Filter,) -> Result(Summary, String) { store.snapshot(ledger, fn(db) { let today = { now_ms + offset_ms } / day_ms let first = today - days + 1 let since = first * day_ms - offset_ms let until = { today + 1 } * day_ms - offset_ms let window = [sqlight.int(since), sqlight.int(until)] let #(narrowing, bound) = narrow(filter) use daily <- result.try( store.rows( db, "SELECT (hour_ms+?)/86400000," <> sums <> from_window <> narrowing <> " GROUP BY 1", [sqlight.int(offset_ms), ..list.append(window, bound)], { use day <- decode.field(0, decode.int) use total <- decode.then(total_decoder(1)) decode.success(#(day, total)) }, ), ) use lines <- result.try( store.rows( db, "SELECT profile,provider,account,model," <> sums <> from_window <> narrowing <> " GROUP BY 1,2,3,4 ORDER BY SUM(input_tokens+output_tokens) DESC,1,2,3,4 LIMIT " <> int.to_string(most_lines + 1), list.append(window, bound), { use profile <- decode.field(0, decode.string) use provider <- decode.field(1, decode.string) use account <- decode.field(2, decode.string) use model <- decode.field(3, decode.string) use total <- decode.then(total_decoder(4)) decode.success(Line(profile, provider, account, model, total)) }, ), ) use scopes <- result.try( store.rows( db, "SELECT DISTINCT provider,account" <> from_window <> " ORDER BY 1,2 LIMIT " <> int.to_string(most_scopes + 1), window, { use provider <- decode.field(0, decode.string) use account <- decode.field(1, decode.string) decode.success(Scope(provider, account)) }, ), ) let used = dict.from_list(daily) Ok(Summary( days: list.repeat(Nil, days) |> list.index_map(fn(_, offset) { let day = first + offset Day( start_ms: day * day_ms - offset_ms, total: dict.get(used, day) |> result.unwrap(empty), ) }), lines: list.take(lines, most_lines), scopes: list.take(scopes, most_scopes), lines_truncated: list.length(lines) > most_lines, scopes_truncated: list.length(scopes) > most_scopes, )) })}
/// The condition a filter adds to the window, and the values it binds. An empty/// account is a row without one, which is how an account-less provider's rows/// are spelled.fn narrow(filter: Filter) -> #(String, List(sqlight.Value)) { case filter { AllScopes -> #("", []) OfProvider(provider, account) -> case account { None -> #(" AND provider=?", [sqlight.text(provider)]) Some(account) -> #(" AND provider=? AND account=?", [ sqlight.text(provider), sqlight.text(account), ]) } }}
fn total_decoder(at: Int) -> decode.Decoder(Total) { use calls <- decode.field(at, decode.int) use errors <- decode.field(at + 1, decode.int) use input_tokens <- decode.field(at + 2, decode.int) use cached_input_tokens <- decode.field(at + 3, decode.int) use cache_creation_tokens <- decode.field(at + 4, decode.int) use output_tokens <- decode.field(at + 5, decode.int) use reasoning_tokens <- decode.field(at + 6, decode.int) decode.success(Total( calls, errors, input_tokens, cached_input_tokens, cache_creation_tokens, output_tokens, reasoning_tokens, ))}