discourse/plugins/discourse-ai/app/serializers/ai_tool_serializer.rb
Rafael dos Santos Silva 81350457c0
FEATURE: Show tool token usage warnings in persona editor (#38370)
Non-technical users tend to add all available tools to every persona
without realizing each tool definition is serialized into the LLM
context on every request, consuming tokens and degrading response
quality.

This adds approximate token counts (via cl100k_base tokenizer) to the
tool metadata served by the personas API, then displays a per-tool token
breakdown in the persona editor. A warning appears when 5+ tools are
selected or total tool tokens exceed 2000, educating users to remove
unnecessary tools.

Backend: `token_count` added to `AiToolSerializer` attributes and to
custom tool hashes in the personas index action. Frontend: token list,
total, and conditional warning alert in the tools section of the persona
editor form.



https://github.com/user-attachments/assets/a3a300a4-6701-4569-b454-7ddabbb5df87
2026-03-09 13:57:10 -03:00

40 lines
895 B
Ruby
Vendored

# frozen_string_literal: true
class AiToolSerializer < ApplicationSerializer
attributes :options, :id, :name, :help, :token_count
def include_options?
object.accepted_options.present?
end
def id
object.to_s.split("::").last
end
def name
object.name.humanize.titleize
end
def help
object.help
end
def token_count
DiscourseAi::Tokenizer::OpenAiCl100kTokenizer.size(object.signature.to_json)
end
def options
options = {}
object.accepted_options.each do |option|
processed_option = {
name: option.localized_name,
description: option.localized_description,
type: option.type,
}
processed_option[:values] = option.values if option.values.present?
processed_option[:default] = option.default if option.default.present?
options[option.name] = processed_option
end
options
end
end