A platform for community discussion. Free, open, simple.
FIX: Improve AI context and tool error handling (#44742)
Same5e15211979b
diff --git a/plugins/discourse-ai/lib/agents/bot.rb b/plugins/discourse-ai/lib/agents/bot.rbindex 5b6d654f815..40a116396a5 100644--- a/plugins/discourse-ai/lib/agents/bot.rb+++ b/plugins/discourse-ai/lib/agents/bot.rb@@ -260,7 +260,10 @@ module DiscourseAibudget_exhausted = work_budget.remaining <= 0if budget_exhausted && context.subagent_depth.to_i > 0- raise DiscourseAi::Completions::ContextPreparation::Error.new("turn_budget_exhausted")+ raise DiscourseAi::Completions::ContextPreparation::Error.new(+ "turn_budget_exhausted",+ prompt: prompt,+ )endif !final_answer_requested && budget_exhaustedself.class.inject_token_budget_final_answer_hint(prompt)diff --git a/plugins/discourse-ai/lib/agents/tools/custom.rb b/plugins/discourse-ai/lib/agents/tools/custom.rbindex 674085cf6da..4e7246e00c5 100644--- a/plugins/discourse-ai/lib/agents/tools/custom.rb+++ b/plugins/discourse-ai/lib/agents/tools/custom.rb@@ -104,7 +104,15 @@ module DiscourseAiblk.call(raw, true)endend- result = runner.invoke(progress_callback: callback)+ result =+ begin+ runner.invoke(progress_callback: callback)+ rescue MiniRacer::RuntimeError => error+ @chain_next_response = true+ self.custom_raw = nil+ runner.custom_raw = nil+ return { error: error.message }+ end# IMPORTANT: Get custom_raw ONCE - calling it multiple times clears it!custom_raw_value = runner.custom_rawdiff --git a/plugins/discourse-ai/lib/completions/context_preparation.rb b/plugins/discourse-ai/lib/completions/context_preparation.rbindex 19b11f955fe..747a9ef3404 100644--- a/plugins/discourse-ai/lib/completions/context_preparation.rb+++ b/plugins/discourse-ai/lib/completions/context_preparation.rb@@ -16,13 +16,30 @@ module DiscourseAiattr_reader :reasonattr_accessor :raw_context- def initialize(reason)+ def initialize(reason, prompt: nil)@reason = reason- Rails.logger.warn("DiscourseAi: context_preparation reason=#{reason}")+ Rails.logger.warn(+ "DiscourseAi: context_preparation reason=#{reason}#{ContextPreparation.log_context(prompt)}",+ )super(I18n.t("discourse_ai.ai_bot.context_preparation_error", reason: reason))endend+ def self.log_context(prompt)+ return "" if !prompt++ context = { topic_id: prompt.topic_id, post_id: prompt.post_id }+ context[:post_number] = post_number(prompt.post_id) if prompt.post_id+ context.compact.map { |key, value| " #{key}=#{value}" }.join+ end++ def self.post_number(post_id)+ Post.where(id: post_id).pick(:post_number)+ rescue ActiveRecord::ActiveRecordError+ nil+ end+ private_class_method :post_number+INSTRUCTION = <<~TEXT.stripSummarize the conversation evidence supplied as JSON below. This is contextmaintenance, not a request to continue the conversation or execute tools.@@ -59,13 +76,16 @@ module DiscourseAiprompt.skip_trim = truesize, capacity = @llm.prompt_capacity(prompt, **options)if capacity <= 0- raise Error.new(@llm.max_prompt_tokens.to_i <= 0 ? "unknown_capacity" : "hard_overflow")+ raise Error.new(+ @llm.max_prompt_tokens.to_i <= 0 ? "unknown_capacity" : "hard_overflow",+ prompt: prompt,+ )endreturn :not_needed if size < capacity * @threshold / 100.0protected_user_index ||=prompt.messages.rindex { |message| message[:type] == :user && !transient_hint?(message) }- raise Error.new("missing_current_request") if !protected_user_index+ raise Error.new("missing_current_request", prompt: prompt) if !protected_user_index# Prefer complete earlier turns. Never detach provider metadata or a pending# call from its batch. A completed current-turn batch can be summarized only@@ -89,7 +109,7 @@ module DiscourseAiendendif size > capacity && !fits?(prompt, [prompt.messages.first, *tail], **options)- raise Error.new("hard_overflow")+ raise Error.new("hard_overflow", prompt: prompt)endsource = source.reject { |message| transient_hint?(message) }attachments = @llm.context_attachments(source)@@ -118,8 +138,7 @@ module DiscourseAicancel_manager: cancel_manager,feature_context: feature_context,subagent_execution_state: subagent_execution_state,- topic_id: prompt.topic_id,- post_id: prompt.post_id,+ prompt: prompt,)messages = [prompt.messages.first,@@ -129,8 +148,10 @@ module DiscourseAi]candidate = copy_prompt(prompt, messages)candidate_size, candidate_capacity = @llm.prompt_capacity(candidate, **options)- raise Error.new("summary_not_smaller") if candidate_size >= size- raise Error.new("summary_over_capacity") if candidate_size > candidate_capacity+ raise Error.new("summary_not_smaller", prompt: prompt) if candidate_size >= size+ if candidate_size > candidate_capacity+ raise Error.new("summary_over_capacity", prompt: prompt)+ endreturn :cancelled if cancel_manager&.cancelled?@protected_user_index = messages.length - tail.lengthprompt.messages.replace(messages)@@ -141,7 +162,7 @@ module DiscourseAireason = error.is_a?(Error) ? error.reason : "summary_failed"if !error.is_a?(Error)Rails.logger.warn(- "DiscourseAi: context_preparation reason=#{reason} error=#{error.class}: #{error.message}",+ "DiscourseAi: context_preparation reason=#{reason} error=#{error.class}: #{error.message}#{self.class.log_context(prompt)}",)endreturn :cancelled if cancel_manager&.cancelled?@@ -156,7 +177,7 @@ module DiscourseAi# written as a checkpoint so later replies resume after the dropped history.# Priority: recent turns, then the previous summary, then dropped attachments.def drop_oldest_history!(prompt, history, tail, reason, **options)- raise Error.new(reason) if history.empty?+ raise Error.new(reason, prompt: prompt) if history.empty?build =lambda do |notice, start, attachments = []|@@ -181,7 +202,7 @@ module DiscourseAistarts.bsearch do |candidate|fits?(prompt, build.call(HISTORY_DROPPED_NOTICE, candidate), **options)end- raise Error.new(reason) if start.nil?+ raise Error.new(reason, prompt: prompt) if start.nil?notice = HISTORY_DROPPED_NOTICEif checkpoint_index@@ -208,7 +229,7 @@ module DiscourseAiendRails.logger.warn(- "DiscourseAi: context_preparation reason=history_dropped original_reason=#{reason} dropped_history_messages=#{start}",+ "DiscourseAi: context_preparation reason=history_dropped original_reason=#{reason} dropped_history_messages=#{start}#{self.class.log_context(prompt)}",)messages = build.call(notice, start, retained)@protected_user_index = messages.length - tail.length@@ -266,7 +287,7 @@ module DiscourseAiendend- def summarize(source, **options)+ def summarize(source, prompt:, **options)evidence = @llm.context_evidence(source)remaining = evidence.to_jsonoffset = 0@@ -292,8 +313,8 @@ module DiscourseAiPrompt.new(INSTRUCTION,messages: [{ type: :user, content: "#{payload_prefix}#{fragment}" }],- topic_id: options[:topic_id],- post_id: options[:post_id],+ topic_id: prompt.topic_id,+ post_id: prompt.post_id,)probe.skip_trim = trueprobe@@ -309,7 +330,7 @@ module DiscourseAihigh = midpoint - 1endend- raise Error.new("summary_input_overflow") if low.zero?+ raise Error.new("summary_input_overflow", prompt: prompt) if low.zero?# Prefer intact literals and lines. A single oversized token still needs a# bounded fragment; offsets make that exceptional split explicit.if low < remaining.length@@ -320,13 +341,13 @@ module DiscourseAiremaining.slice!(0, low)offset += lowinput_size, input_capacity = @llm.prompt_capacity(compression_prompt)- raise Error.new("summary_input_overflow") if input_size > input_capacity+ raise Error.new("summary_input_overflow", prompt: prompt) if input_size > input_capacityreturn if options[:cancel_manager]&.cancelled?# Maintenance shares the execution completion limit; latency and estimated# token costs must not discard a usable summary or leave evidence uncovered.if options[:subagent_execution_state] &&!options[:subagent_execution_state].reserve_completion- raise Error.new("completion_limit")+ raise Error.new("completion_limit", prompt: prompt)end# Uncapped: thinking tokens count against max_tokens and could leave no summary.summary = +""@@ -338,7 +359,7 @@ module DiscourseAiexecution_context: options[:execution_context],cancel_manager: options[:cancel_manager],) { |partial| summary << partial if partial.is_a?(String) }- raise Error.new("empty_summary") if summary.blank?+ raise Error.new("empty_summary", prompt: prompt) if summary.blank?endsummaryenddiff --git a/plugins/discourse-ai/lib/completions/llm.rb b/plugins/discourse-ai/lib/completions/llm.rbindex 3e8d8b3946c..216bf3bddb1 100644--- a/plugins/discourse-ai/lib/completions/llm.rb+++ b/plugins/discourse-ai/lib/completions/llm.rb@@ -280,13 +280,13 @@ module DiscourseAimaximum: max_tokens || llm_model.max_output_tokens.presence || work.remaining,)if helper_options[:max_tokens] && helper_options[:max_tokens] <= 0- raise ContextPreparation::Error.new("turn_budget_exhausted")+ raise ContextPreparation::Error.new("turn_budget_exhausted", prompt: prompt)end_, _, provider_output = prompt_capacity(prompt, **helper_options)generation_reservation =work.reserve_generation_output(provider_output, max_tokens: helper_options[:max_tokens])if !execution_context.work_execution_state.reserve_completion- raise ContextPreparation::Error.new("completion_limit")+ raise ContextPreparation::Error.new("completion_limit", prompt: prompt)endmodel_params[:max_tokens] = helper_options[:max_tokens] if helper_options[:max_tokens]end@@ -314,9 +314,10 @@ module DiscourseAiif capacity <= 0raise ContextPreparation::Error.new(max_prompt_tokens.to_i <= 0 ? "unknown_capacity" : "hard_overflow",+ prompt: prompt,)end- raise ContextPreparation::Error.new("hard_overflow") if size > capacity+ raise ContextPreparation::Error.new("hard_overflow", prompt: prompt) if size > capacityendcall_context = execution_context&.dup@@ -506,7 +507,10 @@ module DiscourseAi.each do |upload|if upload[:kind] == :document && upload[:text].blank?if dialect.is_a?(Dialects::Converse) || dialect.is_a?(Dialects::Command)- raise ContextPreparation::Error.new("unsupported_document_provider")+ raise ContextPreparation::Error.new(+ "unsupported_document_provider",+ prompt: prompt,+ )endattachment_tokens += document_capacity_tokens(upload)elsif upload[:kind] == :imagediff --git a/plugins/discourse-ai/spec/lib/completions/context_preparation_spec.rb b/plugins/discourse-ai/spec/lib/completions/context_preparation_spec.rbindex cc736ec03e5..dffe5176a74 100644--- a/plugins/discourse-ai/spec/lib/completions/context_preparation_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/context_preparation_spec.rb@@ -133,8 +133,11 @@ RSpec.describe DiscourseAi::Completions::ContextPreparation doendend- it "logs empty_summary when compression produces only whitespace" do+ it "logs the triggering post identifiers when compression produces only whitespace" do+ post = Fabricate(:private_message_post)prompt = history_prompt(repetitions: 600)+ prompt.topic_id = post.topic_id+ prompt.post_id = post.idoriginal = prompt.messages.deep_duplogger =track_log_messages do@@ -145,10 +148,35 @@ RSpec.describe DiscourseAi::Completions::ContextPreparation doendend- expect(logger.warnings).to include("DiscourseAi: context_preparation reason=empty_summary")+ expect(logger.warnings).to include(+ "DiscourseAi: context_preparation reason=empty_summary topic_id=#{post.topic_id} post_id=#{post.id} post_number=#{post.post_number}",+ )expect(prompt.messages).to eq(original)end+ it "keeps the original failure diagnostic when the post lookup is unavailable" do+ post = Fabricate(:private_message_post)+ prompt = history_prompt(repetitions: 600)+ prompt.topic_id = post.topic_id+ prompt.post_id = post.id+ allow(Post).to receive(:where).with(id: post.id).and_raise(+ ActiveRecord::ConnectionNotEstablished,+ )++ logger =+ track_log_messages do+ DiscourseAi::Completions::Llm.with_prepared_responses([""]) do+ expect(described_class.new(model.to_llm, threshold: 20).prepare!(prompt)).to eq(+ :skipped,+ )+ end+ end++ expect(logger.warnings).to include(+ "DiscourseAi: context_preparation reason=empty_summary topic_id=#{post.topic_id} post_id=#{post.id}",+ )+ end+it "logs summary_not_smaller when compression expands the prompt" doprompt = history_prompt(repetitions: 600)original = prompt.messages.deep_dupdiff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rbindex aafb5fdb75f..feebb2b6a4c 100644--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb@@ -481,6 +481,36 @@ RSpec.describe DiscourseAi::AiBot::Playground doexpect(thinking["message"]).to eq("Web search: OpenAI news")end+ [nil, "setCustomRaw", "streamCustomRaw"].each do |custom_output|+ it "returns script errors to the model #{custom_output ? "after #{custom_output}" : "without custom output"}" do+ custom_tool.update!(script: <<~JS)+ function invoke() {+ #{custom_output ? "chain.#{custom_output}('Partial output');" : ""}+ throw new Error("Category not found");+ }+ JS+ source = Fabricate(:private_message_post, user: user, recipient: bot_user)+ answer = "The category lookup failed because the category was not found."+ reply = nil++ DiscourseAi::Completions::Llm.with_prepared_responses(+ [tool_call, answer],+ ) do |_, _, prompts|+ reply = playground.reply_to(source, auto_set_title: false)++ tool_result = prompts.last.messages.find { |message| message[:type] == :tool }+ expect(tool_result).to include(id: tool_call.id, name: tool_call.name)+ expect(JSON.parse(tool_result[:content])).to eq("error" => "Error: Category not found")+ end++ expect(reply.raw).to eq(answer)+ tool_result = reply.post_custom_prompt.custom_prompt.find { |entry| entry[2] == "tool" }+ expect(tool_result.take(4)).to eq(+ ['{"error":"Error: Category not found"}', tool_call.id, "tool", tool_call.name],+ )+ end+ end+it "uses custom tool in conversation" doai_agent.update!(show_thinking: true)agent_klass = AiAgent.all_agents.find { |p| p.name == ai_agent.name }