A platform for community discussion. Free, open, simple.
FEATURE: add persona support for chat thread title generation (#37557)
Sam7fa0e65f5a39
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_features_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_features_controller.rbindex 320018a8154..c6f75f906b3 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_features_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_features_controller.rb@@ -37,7 +37,8 @@ module DiscourseAidef serialize_feature(feature){name: feature.name,- personas: feature.persona_ids.map { |id| serialize_persona(persona_id_obj_hash[id]) },+ personas:+ feature.persona_ids.map { |id| serialize_persona(persona_id_obj_hash[id]) }.compact,llm_models:feature.llm_models.map do |llm_model|{ id: llm_model.id, name: llm_model.display_name }diff --git a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-feature-setting-groups.js b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-feature-setting-groups.jsindex b6dee15077c..32317019524 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-feature-setting-groups.js+++ b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-feature-setting-groups.js@@ -38,6 +38,7 @@ export const AI_FEATURE_SETTING_GROUPS = {"ai_helper_markdown_tables_persona","ai_helper_custom_prompt_persona","ai_helper_image_caption_persona",+ "ai_helper_chat_thread_title_persona",],},],diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex 5f31d1d17c6..99d02abddc3 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -323,6 +323,7 @@ en:image_caption: "Caption images"translator: "Translator"post_illustrator: "Post illustrator"+ chat_thread_titles: "Chat thread titles"setting_groups:access_permissions: "Access & Permissions"enabled_features: "Enabled Features"diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex c584a8bce0b..c81ea0a969f 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -96,6 +96,7 @@ en:ai_helper_enabled_features: "Select the features to enable in the AI helper."post_ai_helper_allowed_groups: "User groups allowed to access AI Helper features in posts"ai_helper_post_illustrator_persona: "The persona to use for the AI helper's illustrate post feature. Note: you must also create an image generation tool (Admin > Plugins > Discourse AI > Tools) for this feature to work."+ ai_helper_chat_thread_title_persona: "The persona to use for generating chat thread titles."ai_embeddings_selected_model: "Use the selected model for generating embeddings."ai_embeddings_generate_for_pms: "Generate embeddings for personal messages."@@ -439,6 +440,9 @@ en:discover:name: "Discover"description: "Default persona used in the discoveries feature (complimentary search)"+ chat_thread_titler:+ name: "Chat Thread Titler"+ description: "Default persona powering automatic chat thread title generation"topic_not_found: "Summary unavailable, topic not found!"summarizing: "Summarizing topic"diff --git a/plugins/discourse-ai/config/settings.yml b/plugins/discourse-ai/config/settings.ymlindex c1baa99ff73..ab60dcc86a8 100644--- a/plugins/discourse-ai/config/settings.yml+++ b/plugins/discourse-ai/config/settings.yml@@ -163,6 +163,11 @@ discourse_ai:type: enumenum: "DiscourseAi::Configuration::PersonaEnumerator"area: "ai-features/ai_helper"+ ai_helper_chat_thread_title_persona:+ default: "-35"+ type: enum+ enum: "DiscourseAi::Configuration::PersonaEnumerator"+ area: "ai-features/ai_helper"ai_embeddings_enabled:default: falsediff --git a/plugins/discourse-ai/lib/ai_helper/chat_thread_titler.rb b/plugins/discourse-ai/lib/ai_helper/chat_thread_titler.rbindex 73f559da4ae..77cb80e6874 100644--- a/plugins/discourse-ai/lib/ai_helper/chat_thread_titler.rb+++ b/plugins/discourse-ai/lib/ai_helper/chat_thread_titler.rb@@ -3,6 +3,8 @@module DiscourseAimodule AiHelperclass ChatThreadTitler+ FEATURE_NAME = "chat_thread_titles"+def initialize(thread)@thread = threadend@@ -11,47 +13,61 @@ module DiscourseAicontent = thread_content(@thread)return nil if content.blank?- suggested_title = call_llm(content)- return nil if suggested_title.blank?+ result = call_llm(content)+ return nil if result.blank?- cleanup(suggested_title)+ cleanup(result)end+ private+def call_llm(thread_content)- return nil if SiteSetting.ai_default_llm_model.blank?-- chat = "<input>\n#{thread_content}\n</input>"-- prompt =- DiscourseAi::Completions::Prompt.new(- <<~TEXT.strip,- I want you to act as a title generator for chat between users. I will provide you with the chat transcription,- and you will generate a single attention-grabbing title. Please keep the title concise and under 15 words- and ensure that the meaning is maintained. The title will utilize the same language type of the chat.- I want you to only reply the suggested title and nothing else, do not write explanations.- You will find the chat between <input></input> XML tags. Return the suggested title between <title> tags.- TEXT- messages: [{ type: :user, content: chat, id: "User" }],+ ai_persona =+ AiPersona.find_by_id_from_cache(SiteSetting.ai_helper_chat_thread_title_persona)+ return nil if ai_persona.blank?++ persona_klass = ai_persona.class_instance+ llm_model = Assistant.find_ai_helper_model(FEATURE_NAME, persona_klass)+ return nil if llm_model.blank?++ persona = persona_klass.new+ user = Discourse.system_user++ bot = DiscourseAi::Personas::Bot.as(user, persona: persona, model: llm_model)++ context =+ DiscourseAi::Personas::BotContext.new(+ user: user,+ skip_show_thinking: true,+ feature_name: FEATURE_NAME,+ messages: [{ type: :user, content: thread_content }],)- DiscourseAi::Completions::Llm.proxy(SiteSetting.ai_default_llm_model).generate(- prompt,- user: Discourse.system_user,- stop_sequences: ["</input>"],- feature_name: "chat_thread_title",- )+ result = +""+ bot.reply(context) do |partial, _, type|+ if type == :structured_output+ title = partial.read_buffered_property(:title)+ result << title if title.present?+ elsif type.blank?+ result << partial+ end+ end++ result.presenceenddef cleanup(title)- (Nokogiri::HTML5.fragment(title).at("title")&.text || title)+ title+ .to_s+ .strip.split("\n").first- .then { _1.match?(/^("|')(.*)("|')$/) ? _1[1..-2] : _1 }+ .to_s+ .then { _1.match?(/^(["']).*\1$/) ? _1[1..-2] : _1 }.truncate(100, separator: " ")enddef thread_content(thread)- # TODO: Replace me by a proper API callthread.chat_messages.joins(:user)diff --git a/plugins/discourse-ai/lib/configuration/feature.rb b/plugins/discourse-ai/lib/configuration/feature.rbindex 6c12e8d37d2..fed49adf34d 100644--- a/plugins/discourse-ai/lib/configuration/feature.rb+++ b/plugins/discourse-ai/lib/configuration/feature.rb@@ -127,6 +127,13 @@ module DiscourseAiDiscourseAi::Configuration::Module::AI_HELPER_ID,DiscourseAi::Configuration::Module::AI_HELPER,),+ new(+ "chat_thread_titles",+ "ai_helper_chat_thread_title_persona",+ DiscourseAi::Configuration::Module::AI_HELPER_ID,+ DiscourseAi::Configuration::Module::AI_HELPER,+ enabled_by_setting: "ai_helper_automatic_chat_thread_title",+ ),]enddiff --git a/plugins/discourse-ai/lib/personas/chat_thread_titler.rb b/plugins/discourse-ai/lib/personas/chat_thread_titler.rbnew file mode 100644index 00000000000..9117f63dafd--- /dev/null+++ b/plugins/discourse-ai/lib/personas/chat_thread_titler.rb@@ -0,0 +1,38 @@+# frozen_string_literal: true++module DiscourseAi+ module Personas+ class ChatThreadTitler < Persona+ def self.default_enabled+ false+ end++ def system_prompt+ <<~PROMPT.strip+ You are an advanced chat thread title generator. Analyze a given conversation and produce a concise,+ attention-grabbing title that conveys the main topic to someone with no prior context.++ ### Guidelines:++ - Focus on the central theme or topic being discussed+ - Keep the title concise (maximum 15 words)+ - Use the same language as the conversation+ - Maintain an objective and neutral tone+ - Begin directly with the main topic, avoiding introductory phrases+ - Do not use quotation marks around the title+ - Use sentence case (capitalize first word and proper nouns only)++ Format your response as a JSON object with a single key named "title":++ {"title": "Your generated title here"}++ Reply with valid JSON only.+ PROMPT+ end++ def response_format+ [{ "key" => "title", "type" => "string" }]+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/personas/persona.rb b/plugins/discourse-ai/lib/personas/persona.rbindex 129473333a7..af48e6bf6e1 100644--- a/plugins/discourse-ai/lib/personas/persona.rb+++ b/plugins/discourse-ai/lib/personas/persona.rb@@ -71,6 +71,7 @@ module DiscourseAiContentCreator => -32,ReportRunner => -33,Discover => -34,+ ChatThreadTitler => -35,}enddiff --git a/plugins/discourse-ai/spec/lib/modules/ai_helper/chat_thread_titler_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_helper/chat_thread_titler_spec.rbindex 4c39556f6de..e12f3681291 100644--- a/plugins/discourse-ai/spec/lib/modules/ai_helper/chat_thread_titler_spec.rb+++ b/plugins/discourse-ai/spec/lib/modules/ai_helper/chat_thread_titler_spec.rb@@ -6,10 +6,21 @@ RSpec.describe DiscourseAi::AiHelper::ChatThreadTitler dofab!(:thread, :chat_thread)fab!(:chat_message) { Fabricate(:chat_message, thread: thread) }fab!(:user)+ fab!(:llm_model)++ fab!(:chat_thread_titler_persona) do+ Fabricate(+ :ai_persona,+ name: "Chat Thread Titler",+ system_prompt: "Generate a title",+ response_format: [{ "key" => "title", "type" => "string" }],+ )+ endbefore doenable_current_pluginassign_fake_provider_to(:ai_default_llm_model)+ SiteSetting.ai_helper_chat_thread_title_persona = chat_thread_titler_persona.idenddescribe "#suggested_title" do@@ -20,6 +31,25 @@ RSpec.describe DiscourseAi::AiHelper::ChatThreadTitler doexpect(result).to be_nilend++ it "generates a title using the LLM" do+ expected_title = "Discussion about programming"++ result =+ DiscourseAi::Completions::Llm.with_prepared_responses([{ title: expected_title }]) do+ titler.suggested_title+ end++ expect(result).to eq(expected_title)+ end++ it "returns nil when persona is not found" do+ SiteSetting.ai_helper_chat_thread_title_persona = 999_999++ result = titler.suggested_title++ expect(result).to be_nil+ endenddescribe "#cleanup" do@@ -27,7 +57,7 @@ RSpec.describe DiscourseAi::AiHelper::ChatThreadTitler dotitles = "The solitary horse\nThe horse etched in gold"expected_title = "The solitary horse"- result = titler.cleanup(titles)+ result = titler.send(:cleanup, titles)expect(result).to eq(expected_title)end@@ -36,7 +66,7 @@ RSpec.describe DiscourseAi::AiHelper::ChatThreadTitler dotitles = '"The solitary horse"'expected_title = "The solitary horse"- result = titler.cleanup(titles)+ result = titler.send(:cleanup, titles)expect(result).to eq(expected_title)end@@ -45,7 +75,7 @@ RSpec.describe DiscourseAi::AiHelper::ChatThreadTitler dotitles = "'The solitary horse'"expected_title = "The solitary horse"- result = titler.cleanup(titles)+ result = titler.send(:cleanup, titles)expect(result).to eq(expected_title)end@@ -54,24 +84,23 @@ RSpec.describe DiscourseAi::AiHelper::ChatThreadTitler dotitles = "The 'solitary' horse"expected_title = "The 'solitary' horse"- result = titler.cleanup(titles)+ result = titler.send(:cleanup, titles)expect(result).to eq(expected_title)end- it "parses the XML" do- titles = "Here is your title <title>The solitary horse</title> my friend"- expected_title = "The solitary horse"+ it "leaves mismatched quotes intact" do+ titles = %("The solitary horse')- result = titler.cleanup(titles)+ result = titler.send(:cleanup, titles)- expect(result).to eq(expected_title)+ expect(result).to eq(titles)endit "truncates long titles" dotitles = "O cavalo trota pelo campo" + " Pocotó" * 100- result = titler.cleanup(titles)+ result = titler.send(:cleanup, titles)expect(result.size).to be <= 100end@@ -79,8 +108,8 @@ RSpec.describe DiscourseAi::AiHelper::ChatThreadTitler dodescribe "#thread_content" doit "returns the chat message and user" do- expect(titler.thread_content(thread)).to include(chat_message.message)- expect(titler.thread_content(thread)).to include(chat_message.user.username)+ expect(titler.send(:thread_content, thread)).to include(chat_message.message)+ expect(titler.send(:thread_content, thread)).to include(chat_message.user.username)endendend