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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272"""Usage summary: what the provider calls used, totalled by day, profile and model.
Catches: a call whose counts never reach the hourly totals, a failed attemptcounted as tokens or not counted at all, a total that shrinks when a session isdeleted (the request rows go with it). None of this is visible from onesession's request records. The backfill of a store from before the totals ischecked on a reference daemon's store inapps/albedo/test/albedo/storage/reference_store_test.gleam.
The query half catches a window or selector the route accepts out of range,and a value that a percent-decoded query turns into a different value (a `+`arriving as a space). What a summary counts from the hourly totals (clientdays, future hours, filters, scopes, the cuts) is compared with a model inapps/albedo/test/albedo/usage/usage_hours_test.gleam."""
import contextlibimport jsonimport sqlite3import timeimport unittestimport urllib.errorimport urllib.parsefrom datetime import datetime
from harness import Albedo, Provider, Reply, exclusive, latest_user, text, wait_until
FIRST = { "input_tokens": 100, "output_tokens": 20, "input_tokens_details": {"cached_tokens": 40}, "output_tokens_details": {"reasoning_tokens": 7},}SECOND = { "input_tokens": 300, "output_tokens": 40, "input_tokens_details": {"cached_tokens": 120}, "output_tokens_details": {"reasoning_tokens": 3},}DAY_MS = 86_400_000
ANTHROPIC = "anthropic:https://api.anthropic.com"OPENAI = "responses:https://api.openai.com/v1"GEMINI = "gemini:https://generativelanguage.googleapis.com"
def encode(parameters): """A query the daemon reads back unchanged: `+` is a space to its query decoder, so a literal plus travels as `%2B`, never as a form-encoded `+`.""" return "?" + urllib.parse.urlencode(parameters, quote_via=urllib.parse.quote)
def reply(request): user = latest_user(request) # A non-retryable error isolates one failed attempt. Upstream now treats # 429 as account rotation/backoff, not an immediate terminal response. if user == "fail this request": return Reply("error", "invalid request", status=400) return text("done", usage=SECOND if user == "second" else FIRST)
def instant(timestamp): return datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
def millis(timestamp): return int(instant(timestamp).timestamp() * 1000)
# exclusive: it reads totals across the whole daemon@exclusiveclass UsageSummaryTests(unittest.TestCase): def setUp(self): self.provider = Provider(reply) self.addCleanup(self.provider.close) self.app = Albedo(self.provider, protocol="responses") self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None)
def usage(self, query=""): with self.app.api(f"/usage{query}") as response: return json.load(response)
def run_prompts(self, *prompts): sessions = [] for prompt in prompts: session = self.app.session(name="usage fixture") self.app.prompt(session, prompt).close() self.app.idle(session) sessions.append(session) return sessions
def delete_session(self, session): resource = f"/sessions/{session}/configuration" with self.app.api(resource) as response: validator = response.getheader("ETag") response.read() with self.app.api( resource.removesuffix("/configuration"), method="DELETE", headers={"If-Match": validator}, ) as response: self.assertEqual(json.load(response)["state"], "complete")
def seed(self, *rows, hour=None): """Writes one hour of call totals, each row being `(provider, account, model, calls, input_tokens, output_tokens)`.
The route reads these totals, never the request rows, and only a provider with an account pool labels a call with an account, which a fixture would need real credentials for. `account` is `""` for a provider without one, which is how the trigger stores it. The hour is the current one unless `hour` says otherwise, so every window covers it. """ if hour is None: hour = int(time.time() * 1000) // 3_600_000 * 3_600_000 with contextlib.closing(sqlite3.connect(self.app.home / "albedo.sqlite")) as db: db.execute("PRAGMA busy_timeout=5000") db.executemany( "INSERT OR REPLACE INTO usage_hours(hour_ms,profile,provider,account," "model,kind,calls,errors,input_tokens,cached_input_tokens," "cache_creation_tokens,output_tokens,reasoning_tokens)" " VALUES(?,'fixture',?,?,?,'turn',?,0,?,0,0,?,0)", [ (hour, provider, account, model, calls, input_tokens, output_tokens) for provider, account, model, calls, input_tokens, output_tokens in rows ], ) db.commit()
def totals(self, summary): (line,) = summary["lines"] return { key: line[key] for key in ( "calls", "errors", "input_tokens", "cached_input_tokens", "cache_creation_tokens", "output_tokens", "reasoning_tokens", ) }
def test_calls_are_totalled_by_day_and_by_model_and_a_failed_attempt_is_an_error( self, ): self.run_prompts("first", "second", "fail this request") summary = self.usage("?days=3") expected = { "calls": 3, "errors": 1, "input_tokens": 400, "cached_input_tokens": 160, "cache_creation_tokens": 0, "output_tokens": 60, "reasoning_tokens": 10, } self.assertEqual(self.totals(summary), expected) (line,) = summary["lines"] self.assertEqual(line["model"], "fixture-model") # Upstream migrates the fixture key into a labelled account. self.assertEqual(line["account"], self.app.profile) self.assertTrue(line["profile"].startswith("fixture")) # Three days, oldest first, the earlier two empty, and the day of use # holds the same totals as the one line. days = summary["days"] self.assertEqual(len(days), 3) for day in days[:2]: self.assertEqual(day["calls"], 0) self.assertEqual({key: days[2][key] for key in expected}, expected) self.assertEqual( [millis(day["start"]) - millis(days[0]["start"]) for day in days], [0, DAY_MS, 2 * DAY_MS], )
def test_title_generation_counts_alongside_the_main_turn(self): self.provider.title_script = lambda request: text( "Generated title", usage=SECOND ) session = self.app.session() self.app.prompt(session, "first").close() self.app.idle(session) wait_until( lambda: self.totals(self.usage())["calls"] == 2, 10, "the title request was not counted", ) self.assertEqual( self.totals(self.usage()), { "calls": 2, "errors": 0, "input_tokens": 400, "cached_input_tokens": 160, "cache_creation_tokens": 0, "output_tokens": 60, "reasoning_tokens": 10, }, )
def test_a_deleted_session_keeps_what_it_used(self): first, second = self.run_prompts("first", "second") before = self.totals(self.usage()) self.assertEqual(before["calls"], 2) self.delete_session(first) # The premise: the session's own request rows went with it. with sqlite3.connect(self.app.home / "albedo.sqlite") as db: self.assertEqual( db.execute( "SELECT COUNT(*) FROM provider_requests WHERE session=?", (first,) ).fetchone()[0], 0, ) self.assertEqual(self.totals(self.usage()), before) self.delete_session(second) self.assertEqual(self.totals(self.usage()), before)
def test_the_window_is_bounded_and_checked(self): self.assertEqual(len(self.usage()["days"]), 7) self.assertEqual(len(self.usage("?days=90")["days"]), 90) for query in ( "?days=0", "?days=91", "?days=x", "?utc_offset_minutes=900", "?utc_offset_minutes=-721", "?hours=1", # An account belongs to a provider, and neither may be empty. "?account=ada%40example.com", "?account=", "?provider=", "?provider=&account=", ): with self.subTest(query=query): with self.assertRaises(urllib.error.HTTPError) as caught: self.usage(query) self.assertEqual(caught.exception.code, 400) caught.exception.close()
def test_scope_values_are_matched_exactly_even_with_an_ampersand_a_quote_or_a_plus( self, ): provider = "custom:https://api.example.com/v1?model='a'&flag=x+y" account = "ada+albedo@example.com" self.seed( (provider, account, "odd", 1, 7, 1), (provider, "ada albedo@example.com", "spaced", 1, 11, 1), (provider, "", "none", 1, 13, 1), ) found = self.usage( encode({"days": 1, "provider": provider, "account": account}) ) self.assertEqual( [(line["model"], line["account"]) for line in found["lines"]], [("odd", account)], ) self.assertEqual(found["days"][0]["input_tokens"], 7)
# A raw `+` in a query arrives as a space, so a client that escaped its # values reaches the plus account and the space account separately. quoted = urllib.parse.quote(provider, safe="") raw = f"?days=1&provider={quoted}&account=ada+albedo%40example.com" self.assertEqual( [line["model"] for line in self.usage(raw)["lines"]], ["spaced"] )
if __name__ == "__main__": unittest.main()