Class: CountMessageTokensJob
- Inherits:
-
ApplicationJob
- Object
- ActiveJob::Base
- ApplicationJob
- CountMessageTokensJob
- Defined in:
- app/jobs/count_message_tokens_job.rb
Overview
Counts tokens in a message’s payload via the Anthropic API and caches the result on the message record. Enqueued automatically after each LLM message is created.
Instance Method Summary collapse
Instance Method Details
#perform(message_id) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'app/jobs/count_message_tokens_job.rb', line 13 def perform() = Message.find() return if already_counted?() provider = Providers::Anthropic.new = [{role: .api_role, content: .payload["content"].to_s}] token_count = provider.count_tokens( model: Anima::Settings.model, messages: ) # Guard against parallel jobs: reload and re-check before writing. # Uses update! (not update_all) so {Message::Broadcasting} after_update_commit # broadcasts the updated token count to connected clients. .reload return if already_counted?() .update!(token_count: token_count) end |