Skip to content

Record token usage for every model call. - #115

Open
AlirezaValikhani wants to merge 2 commits into
ClawRunr:mainfrom
AlirezaValikhani:main
Open

AlirezaValikhani wants to merge 2 commits into
ClawRunr:mainfrom
AlirezaValikhani:main

Conversation

@AlirezaValikhani

@AlirezaValikhani AlirezaValikhani commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Persist prompt and completion tokens per streaming and non-streaming round under workspace/usage so cost visibility and budgets can build on it later.

Closese: #105

@arefbehboudi

Copy link
Copy Markdown
Collaborator

Thanks for picking this up! The advisor's placement inside the tool loop is exactly right, and covering subagents is a
nice touch. We compared how OpenClaw and Hermes record usage, and settled on a design. A few changes before we can merge:

1. Store the records in a table, not one file per call. Every tool-loop round writes a YAML file, which grows into
tens of thousands of files, and the next step (a usage page with totals per day, channel and model) would have to read
them all. Both OpenClaw and Hermes keep usage in their SQLite database. Please add one table to the sessions H2 database
(same pool as the session store), one row per model call:

CREATE TABLE IF NOT EXISTS token_usage (
    id                  BIGINT AUTO_INCREMENT PRIMARY KEY,
    recorded_at         TIMESTAMP    NOT NULL,
    session_id          VARCHAR(64),
    conversation        VARCHAR(255),
    channel             VARCHAR(32),
    kind                VARCHAR(16),
    model               VARCHAR(128),
    input_tokens        INT NOT NULL,
    output_tokens       INT NOT NULL,
    cache_read_tokens   INT NOT NULL DEFAULT 0,
    cache_write_tokens  INT NOT NULL DEFAULT 0,
    total_tokens        INT NOT NULL
);
CREATE INDEX IF NOT EXISTS token_usage_recorded_at ON token_usage (recorded_at);

Totals then become one query, and old rows can be removed with one DELETE.

2. Take conversation, channel and kind from the session's metadata, not from the id. UsageSource parses id
prefixes. With #116 (multiple chat sessions, about to be merged) session ids are generated
(20261124_153012_a1b2c3d4), so every record would become UNKNOWN; Teams isn't covered today either. Every session's
metadata already has these three. Please rebase onto main once #116 is merged, then read them from the session.
Calls without a session (e.g. subagents) are stored with those columns empty.

3. Streaming: record only the final usage. Today the first chunk with non-zero usage is recorded, but providers
report usage incrementally (Anthropic sends input tokens at the start and output tokens at the end), so output tokens
end up near zero. Record the last usage the stream reports, when it completes. If a stream ends without one, record
nothing; that's also how OpenClaw handles it.

4. Cache tokens in their own columns. Since Spring AI 2.1, cached tokens are included in the prompt tokens for
Anthropic. Store cache reads and writes separately when the provider reports them, so costs can be computed correctly
later.

5. No blocking I/O on the stream thread. Saving happens inside doOnNext. Please hand it off to another thread
(or a small queue) so a slow write never delays streaming.

Smaller: record the model from the response that actually answered (a subagent may use another provider than the
default). FileSystemUsageRepository, UsageSource and the YAML handling can go once the table is in place.

Happy to help if anything's unclear.

Persist prompt and completion tokens per streaming and non-streaming round under workspace/usage so cost visibility and budgets can build on it later.
@AlirezaValikhani

AlirezaValikhani commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for picking this up! The advisor's placement inside the tool loop is exactly right, and covering subagents is a nice touch. We compared how OpenClaw and Hermes record usage, and settled on a design. A few changes before we can merge:

1. Store the records in a table, not one file per call. Every tool-loop round writes a YAML file, which grows into tens of thousands of files, and the next step (a usage page with totals per day, channel and model) would have to read them all. Both OpenClaw and Hermes keep usage in their SQLite database. Please add one table to the sessions H2 database (same pool as the session store), one row per model call:

CREATE TABLE IF NOT EXISTS token_usage (
    id                  BIGINT AUTO_INCREMENT PRIMARY KEY,
    recorded_at         TIMESTAMP    NOT NULL,
    session_id          VARCHAR(64),
    conversation        VARCHAR(255),
    channel             VARCHAR(32),
    kind                VARCHAR(16),
    model               VARCHAR(128),
    input_tokens        INT NOT NULL,
    output_tokens       INT NOT NULL,
    cache_read_tokens   INT NOT NULL DEFAULT 0,
    cache_write_tokens  INT NOT NULL DEFAULT 0,
    total_tokens        INT NOT NULL
);
CREATE INDEX IF NOT EXISTS token_usage_recorded_at ON token_usage (recorded_at);

Totals then become one query, and old rows can be removed with one DELETE.

2. Take conversation, channel and kind from the session's metadata, not from the id. UsageSource parses id prefixes. With #116 (multiple chat sessions, about to be merged) session ids are generated (20261124_153012_a1b2c3d4), so every record would become UNKNOWN; Teams isn't covered today either. Every session's metadata already has these three. Please rebase onto main once #116 is merged, then read them from the session. Calls without a session (e.g. subagents) are stored with those columns empty.

3. Streaming: record only the final usage. Today the first chunk with non-zero usage is recorded, but providers report usage incrementally (Anthropic sends input tokens at the start and output tokens at the end), so output tokens end up near zero. Record the last usage the stream reports, when it completes. If a stream ends without one, record nothing; that's also how OpenClaw handles it.

4. Cache tokens in their own columns. Since Spring AI 2.1, cached tokens are included in the prompt tokens for Anthropic. Store cache reads and writes separately when the provider reports them, so costs can be computed correctly later.

5. No blocking I/O on the stream thread. Saving happens inside doOnNext. Please hand it off to another thread (or a small queue) so a slow write never delays streaming.

Smaller: record the model from the response that actually answered (a subagent may use another provider than the default). FileSystemUsageRepository, UsageSource and the YAML handling can go once the table is in place.

Happy to help if anything's unclear.

All these changes are done. Please check again, and if there is a problem, leave a comment to me. Thanks, Aref.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants