A platform for community discussion. Free, open, simple.
DEV: Extract reusable query generation and extend AI tool discovery (#44295)
Keegan George6aedf51c888d
diff --git a/plugins/discourse-ai/lib/agents/agent.rb b/plugins/discourse-ai/lib/agents/agent.rbindex bfcf7dc9c07..713783942de 100644--- a/plugins/discourse-ai/lib/agents/agent.rb+++ b/plugins/discourse-ai/lib/agents/agent.rb@@ -174,7 +174,7 @@ module DiscourseAitools << Tools::Assign if defined?(::Assigner)tools << Tools::MarkAsSolved if defined?(::DiscourseSolved)- tools+ DiscoursePluginRegistry.apply_modifier(:ai_agent_available_tools, tools).uniqenddef external_agent_id(agent_klass)diff --git a/plugins/discourse-ai/spec/models/reviewable_ai_tool_action_spec.rb b/plugins/discourse-ai/spec/models/reviewable_ai_tool_action_spec.rbindex ed6d356e93c..7a547443168 100644--- a/plugins/discourse-ai/spec/models/reviewable_ai_tool_action_spec.rb+++ b/plugins/discourse-ai/spec/models/reviewable_ai_tool_action_spec.rb@@ -121,6 +121,24 @@ RSpec.describe ReviewableAiToolAction doenddescribe "#perform_approve" do+ it "rebuilds a tool supplied by a plugin for approval" do+ tool_class =+ Class.new(DiscourseAi::Agents::Tools::CloseTopic) do+ def self.name+ "extension_close_topic"+ end+ end+ plugin = Plugin::Instance.new+ modifier = ->(tools) { tools + [tool_class] }+ DiscoursePluginRegistry.register_modifier(plugin, :ai_agent_available_tools, &modifier)+ reviewable = create_reviewable(create_tool_action(tool_name: "extension_close_topic"))++ expect(reviewable.perform(admin, :approve).success?).to eq(true)+ expect(topic.reload.closed).to eq(true)+ ensure+ DiscoursePluginRegistry.unregister_modifier(plugin, :ai_agent_available_tools, &modifier)+ end+it "executes the tool and transitions to approved" dotool_action = create_tool_actionreviewable = create_reviewable(tool_action)diff --git a/plugins/discourse-data-explorer/app/jobs/regular/generate_de_query_with_ai.rb b/plugins/discourse-data-explorer/app/jobs/regular/generate_de_query_with_ai.rbindex bcb33973f19..d01e1f76cec 100644--- a/plugins/discourse-data-explorer/app/jobs/regular/generate_de_query_with_ai.rb+++ b/plugins/discourse-data-explorer/app/jobs/regular/generate_de_query_with_ai.rb@@ -15,41 +15,13 @@ module Jobsuser = User.find_by(id: args[:user_id])return if user.nil?- agent_id =- DiscourseAi::Agents::Agent.external_agent_id(DiscourseDataExplorer::AiQueryGenerator)- agent_record = AiAgent.find_by(id: agent_id)- if agent_record.nil?- return(publish_error(user, I18n.t("discourse_data_explorer.ai.error_agent_not_configured")))- end-- agent_klass = agent_record.class_instance- bot = DiscourseAi::Agents::Bot.as(Discourse.system_user, agent: agent_klass.new)-- user_message = args[:ai_description]- if args[:existing_sql].present?- user_message =- "#{args[:ai_description]}\n\nHere is the current SQL query to refine:\n```sql\n#{args[:existing_sql]}\n```"- end-- context =- DiscourseAi::Agents::BotContext.new(- messages: [{ type: :user, content: user_message }],+ query =+ DiscourseDataExplorer::QueryGeneration.call(user: user,- feature_name: "data_explorer_query_generation",+ ai_description: args[:ai_description],+ existing_sql: args[:existing_sql],)-- bot.reply(context)- parsed = context.feature_context[DiscourseDataExplorer::Tools::SubmitQuery::CONTEXT_KEY] || {}-- if parsed[:sql].blank?- return(publish_error(user, I18n.t("discourse_data_explorer.ai.error_no_sql_returned")))- end-- sql = parsed[:sql].chomp(";").strip- name = parsed[:name].presence || args[:ai_description].to_s.truncate(60, separator: " ")- description = parsed[:description].presence || args[:ai_description]-- publish_complete(user, sql: sql, name: name, description: description)+ publish_complete(user, **query)rescue => epublish_error(user, e.message) if userensurediff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/query_generation.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/query_generation.rbnew file mode 100644index 00000000000..0af52735c1b--- /dev/null+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/query_generation.rb@@ -0,0 +1,46 @@+# frozen_string_literal: true++module DiscourseDataExplorer+ class QueryGeneration+ Error = Class.new(StandardError)++ def self.call(user:, ai_description:, existing_sql: nil)+ raise Discourse::InvalidAccess unless user&.admin?+ unless SiteSetting.data_explorer_enabled && SiteSetting.discourse_ai_enabled &&+ SiteSetting.data_explorer_ai_queries_enabled+ raise Discourse::InvalidAccess+ end+ raise Discourse::InvalidParameters.new(:ai_description) if ai_description.blank?++ agent_id = DiscourseAi::Agents::Agent.external_agent_id(AiQueryGenerator)+ agent_record = AiAgent.find_by(id: agent_id)+ if agent_record.nil?+ raise Error.new(I18n.t("discourse_data_explorer.ai.error_agent_not_configured"))+ end++ bot =+ DiscourseAi::Agents::Bot.as(Discourse.system_user, agent: agent_record.class_instance.new)+ user_message = ai_description+ if existing_sql.present?+ user_message =+ "#{ai_description}\n\nHere is the current SQL query to refine:\n```sql\n#{existing_sql}\n```"+ end+ context =+ DiscourseAi::Agents::BotContext.new(+ messages: [{ type: :user, content: user_message }],+ user: user,+ feature_name: "data_explorer_query_generation",+ )+ bot.reply(context)+ parsed = context.feature_context[Tools::SubmitQuery::CONTEXT_KEY] || {}+ if parsed[:sql].blank?+ raise Error.new(I18n.t("discourse_data_explorer.ai.error_no_sql_returned"))+ end+ {+ sql: parsed[:sql].chomp(";").strip,+ name: parsed[:name].presence || ai_description.to_s.truncate(60, separator: " "),+ description: parsed[:description].presence || ai_description,+ }+ end+ end+enddiff --git a/plugins/discourse-data-explorer/plugin.rb b/plugins/discourse-data-explorer/plugin.rbindex 620a26760ca..4c4c9bae782 100644--- a/plugins/discourse-data-explorer/plugin.rb+++ b/plugins/discourse-data-explorer/plugin.rb@@ -281,6 +281,7 @@ after_initialize dorequire_relative "lib/discourse_data_explorer/tools/run_sql"require_relative "lib/discourse_data_explorer/tools/submit_query"require_relative "lib/discourse_data_explorer/ai_query_generator"+ require_relative "lib/discourse_data_explorer/query_generation"DiscourseAi.register_feature(module_name: :data_explorer,diff --git a/plugins/discourse-data-explorer/spec/jobs/regular/generate_de_query_with_ai_spec.rb b/plugins/discourse-data-explorer/spec/jobs/regular/generate_de_query_with_ai_spec.rbindex 2039ee2b923..5194317aeb6 100644--- a/plugins/discourse-data-explorer/spec/jobs/regular/generate_de_query_with_ai_spec.rb+++ b/plugins/discourse-data-explorer/spec/jobs/regular/generate_de_query_with_ai_spec.rb@@ -4,6 +4,7 @@ describe Jobs::GenerateDeQueryWithAi dofab!(:admin)before do+ SiteSetting.discourse_ai_enabled = trueSiteSetting.data_explorer_enabled = trueSiteSetting.data_explorer_ai_queries_enabled = trueenddiff --git a/plugins/discourse-data-explorer/spec/lib/query_generation_spec.rb b/plugins/discourse-data-explorer/spec/lib/query_generation_spec.rbnew file mode 100644index 00000000000..6c902e22fd2--- /dev/null+++ b/plugins/discourse-data-explorer/spec/lib/query_generation_spec.rb@@ -0,0 +1,61 @@+# frozen_string_literal: true++RSpec.describe DiscourseDataExplorer::QueryGeneration do+ fab!(:admin)+ fab!(:user)++ before do+ SiteSetting.discourse_ai_enabled = true+ SiteSetting.data_explorer_enabled = true+ SiteSetting.data_explorer_ai_queries_enabled = true+ end++ it "rejects non-admin callers" do+ expect { described_class.call(user: user, ai_description: "List users") }.to raise_error(+ Discourse::InvalidAccess,+ )+ end++ it "rejects disabled generation" do+ SiteSetting.data_explorer_ai_queries_enabled = false+ expect { described_class.call(user: admin, ai_description: "List users") }.to raise_error(+ Discourse::InvalidAccess,+ )+ end++ it "rejects a disabled plugin" do+ SiteSetting.data_explorer_enabled = false+ expect { described_class.call(user: admin, ai_description: "List users") }.to raise_error(+ Discourse::InvalidAccess,+ )+ end++ it "rejects an empty request" do+ expect { described_class.call(user: admin, ai_description: "") }.to raise_error(+ Discourse::InvalidParameters,+ )+ end++ it "returns a draft without persisting it and preserves refinement context" do+ record = instance_double(AiAgent, class_instance: DiscourseDataExplorer::AiQueryGenerator)+ agent_id = DiscourseAi::Agents::Agent.external_agent_id(DiscourseDataExplorer::AiQueryGenerator)+ allow(AiAgent).to receive(:find_by).with(id: agent_id).and_return(record)+ bot = instance_double(DiscourseAi::Agents::Bot)+ allow(DiscourseAi::Agents::Bot).to receive(:as).and_return(bot)+ allow(bot).to receive(:reply) do |context|+ expect(context.user).to eq(admin)+ expect(context.feature_name).to eq("data_explorer_query_generation")+ expect(context.messages.first[:content]).to include("SELECT 1", "List users")+ context.feature_context[DiscourseDataExplorer::Tools::SubmitQuery::CONTEXT_KEY] = {+ sql: "SELECT 2",+ }+ end++ result = nil+ expect {+ result =+ described_class.call(user: admin, ai_description: "List users", existing_sql: "SELECT 1")+ }.not_to change { DiscourseDataExplorer::Query.count }+ expect(result).to eq(sql: "SELECT 2", name: "List users", description: "List users")+ end+end