From 71d7de5c939fc9bb894ced5740cd0cc6e171cc3a Mon Sep 17 00:00:00 2001 From: merefield Date: Wed, 21 Oct 2026 10:29:53 +0100 Subject: [PATCH 1/3] FEATURE: preserve tool definitions for cache-friendly selection --- README.md | 26 ++- config/locales/server.en.yml | 4 +- config/settings.yml | 10 ++ lib/discourse_chatbot/bot.rb | 48 +++++- lib/discourse_chatbot/llm_client.rb | 4 + plugin.rb | 2 +- spec/lib/bot_tool_selection_spec.rb | 226 +++++++++++++++++++++++++ spec/lib/llm_client_spec.rb | 24 +++ spec/support/tool_selection_helpers.rb | 14 ++ 9 files changed, 347 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 88dfe07..6547dc0 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,7 @@ means no selection call or selection diagnostic; enabled means active filtering. | Setting | Default | Purpose | | --- | --- | --- | | `chatbot_system_one_tool_selection_enabled` | `false` | Enable active selection. | +| `chatbot_system_one_tool_selection_mode` | `remove_definitions` | Omit unselected definitions, or use `restrict_calls` to retain definitions for caching on the official OpenAI Responses API. | | `chatbot_system_one_tool_selection_context` | Empty | Optional administrator guidance, up to 4,000 characters. | | `chatbot_system_one_tool_selection_look_back` | `4` | Include 0–20 preceding messages, independently of the answering model's history window. | | `chatbot_system_one_tool_removal_threshold` | `0.9` | Remove only tools classified irrelevant at or above this probability. | @@ -329,16 +330,33 @@ the eligible set is retained. Existing access rules, credentials and extension a checks run first; selection never enables an otherwise unavailable tool. The selected set stays fixed for the response's tool loop and applies to both Chat Completions -and Responses API requests. It controls tool definitions, execution lookup and tool-dependent -prompts. For user-information collection and staff escalation, the criteria also consider +and Responses API requests. It controls execution lookup and tool-dependent prompts. In the +default `remove_definitions` mode, unselected tool definitions are omitted from the request. +In `restrict_calls` mode, official OpenAI Responses requests retain the full eligible definitions +and their ordering, and use `tool_choice: { type: "allowed_tools", ... }` to restrict callable +tools. An empty selection uses `tool_choice: "none"`. Forced tools and the final iteration's +tool-call limit still apply. Chat Completions, custom endpoints, Azure and other providers use +`remove_definitions` even when `restrict_calls` is selected. + +Stable definitions can improve cache reuse between exchanges with different selections. +They still consume input tokens, and changes to eligible tools, conversation history or other +prompt content can reduce reuse. Compare the existing cached-input and cache-write usage +statistics to assess the cost for your conversations. See OpenAI's +[tool-caching guidance](https://developers.openai.com/api/docs/guides/prompt-caching#manage-tools-with-append-only-updates). + +For user-information collection and staff escalation, the criteria also consider whether the user requests the action or answers a pending collection question. This is a relevance check, not an authorization or proposed-argument check. When Inner Thoughts output is enabled, a selection entry says, for example: “I removed these tools from the available set based on the query: wikipedia, paint_picture.” It includes removed/retained names, per-tool probabilities, protected tools, model and usage. -It also explains keeping all tools or falling back. These diagnostics are not fed back to the -answering model. System One usage is reported separately, like scope-evaluation usage. +In `restrict_calls` mode, the entry instead says tools were disabled while their definitions +were retained for caching, and lists `disabled_tools` separately from `removed_tools`. +Entries report the requested and effective mode, including a mode fallback reason for unsupported +configurations. They also explain keeping all tools or selection failures. These diagnostics +are not fed back to the answering model. System One usage is reported separately, like +scope-evaluation usage. Filtering adds an evaluation call and can change prompt-cache reuse; reduced tool count does not guarantee lower total cost or better answers. Thresholds and guidance should be evaluated against diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml index 879dc0d..2af4d02 100644 --- a/config/locales/server.en.yml +++ b/config/locales/server.en.yml @@ -105,7 +105,8 @@ en: chatbot_open_ai_embeddings_char_limit: "Maximum number of Post characters sent to the selected embeddings provider. Keep this as high as possible without experiencing an error." chatbot_open_ai_embeddings_model_custom_url: "Optional embeddings endpoint override. The endpoint must support the selected provider's OpenAI-compatible embeddings API and receives that provider's shared API key." chatbot_system_one_model: "System One model for semantic judgments. Defaults to TypeSafe AI's jev-latest. The model, URL, and key must all be populated to use System One features." - chatbot_system_one_tool_selection_enabled: "Use System One to remove clearly irrelevant tools for each request. Requires the System One model, URL, and key. Sends the current query, recent conversation context, and eligible tool descriptions to that service. Decisions appear in Inner Thoughts when enabled. Independent of question blocking." + chatbot_system_one_tool_selection_enabled: "Use System One to select tools for each request. Requires the System One model, URL, and key. Sends the current query, recent conversation context, and eligible tool descriptions to that service. Decisions appear in Inner Thoughts when enabled. Independent of question blocking." + chatbot_system_one_tool_selection_mode: "How System One applies tool selection. remove_definitions omits unselected tool descriptions to reduce input tokens. restrict_calls keeps eligible definitions stable for prompt caching and uses allowed_tools to restrict calls on the official OpenAI Responses API; other configurations use remove_definitions. Both modes prevent execution of unselected tools." chatbot_system_one_tool_selection_context: "Optional administrator guidance for tool selection, such as when forum search should remain available. Up to 4,000 characters; longer guidance causes selection to fall back to all eligible tools. Does not grant tool permissions." chatbot_system_one_tool_selection_look_back: "Number of preceding messages sent to System One for tool selection (0–20). Separate from the main model and question-blocking history windows. Each preceding message is limited to 2,000 characters. The current query is always included." chatbot_system_one_tool_removal_threshold: "Minimum irrelevant probability needed to remove a tool. Lower values remove tools more readily. Relevant and unclear tools remain available; configured forced tools are preserved." @@ -360,6 +361,7 @@ en: inner_thoughts: tool_selection: removed: "I removed these tools from the available set based on the query: %{tools}." + restricted: "I disabled these tools based on the query while retaining their definitions for prompt caching: %{tools}." retained: "I kept all available tools after evaluating the query." fallback: "I kept all available tools because System One tool selection could not be completed." forced: "I kept all available tools because the administrator requires a tool call." diff --git a/config/settings.yml b/config/settings.yml index ed07a61..5ae2de7 100644 --- a/config/settings.yml +++ b/config/settings.yml @@ -790,6 +790,16 @@ plugins: chatbot_system_one_tool_selection_enabled: client: false default: false + chatbot_system_one_tool_selection_mode: + client: false + type: enum + default: remove_definitions + choices: + - remove_definitions + - restrict_calls + depends_on: + - chatbot_system_one_tool_selection_enabled + depends_behavior: hidden chatbot_system_one_tool_selection_context: client: false default: '' diff --git a/lib/discourse_chatbot/bot.rb b/lib/discourse_chatbot/bot.rb index 8701a33..4f8297a 100644 --- a/lib/discourse_chatbot/bot.rb +++ b/lib/discourse_chatbot/bot.rb @@ -225,11 +225,31 @@ def select_tools(prompt, opts) ) retained = selection.fetch(:retained_tool_names) @tool_mapping = @tool_mapping.slice(*retained) - @tool_definitions = - @tool_definitions.select { |definition| retained.include?(definition.fetch("name")) } - @tools = @tool_definitions.map { |tool| { type: "function", function: tool } }.presence + requested_mode = SiteSetting.chatbot_system_one_tool_selection_mode + @restrict_tool_calls = + requested_mode == "restrict_calls" && @llm_client.supports_allowed_tools? + if !@restrict_tool_calls + @tool_definitions = + @tool_definitions.select { |definition| retained.include?(definition.fetch("name")) } + @tools = @tool_definitions.map { |tool| { type: "function", function: tool } }.presence + end @tool_selection_applied = true - @initial_inner_thoughts << selection.fetch(:audit) + audit = selection.fetch(:audit) + effective_mode = @restrict_tool_calls ? "restrict_calls" : "remove_definitions" + audit.merge!(requested_mode: requested_mode, effective_mode: effective_mode) + audit[:mode_fallback_reason] = "unsupported_configuration" if requested_mode != effective_mode + if @restrict_tool_calls + disabled = audit.fetch(:removed_tools) + audit.merge!(removed_tools: [], disabled_tools: disabled) + if disabled.present? + audit[:outcome] = "restricted" + audit[:content] = I18n.t( + "chatbot.inner_thoughts.tool_selection.restricted", + tools: disabled.join(", "), + ) + end + end + @initial_inner_thoughts << audit end def has_empty_user_fields?(opts) @@ -465,8 +485,26 @@ def create_chat_completion( if @tools parameters[:tools] = responses_tools - if !use_tools + if !use_tools || (@restrict_tool_calls && @tool_mapping.empty?) parameters[:tool_choice] = "none" + elsif @restrict_tool_calls + forced_choice = SiteSetting.chatbot_tool_choice_first_iteration + if iteration == 1 && forced_choice == FORCE_LOCAL_SEARCH_TOOL + parameters[:tool_choice] = { type: "function", name: "local_forum_search" } + else + parameters[:tool_choice] = { + type: "allowed_tools", + mode: + ( + if iteration == 1 && FORCE_A_TOOL_VALUES.include?(forced_choice) + "required" + else + "auto" + end + ), + tools: @tool_mapping.keys.map { |name| { type: "function", name: name } }, + } + end elsif iteration == 1 if FORCE_A_TOOL_VALUES.include?(SiteSetting.chatbot_tool_choice_first_iteration) parameters[:tool_choice] = "required" diff --git a/lib/discourse_chatbot/llm_client.rb b/lib/discourse_chatbot/llm_client.rb index 3fc3705..8521470 100644 --- a/lib/discourse_chatbot/llm_client.rb +++ b/lib/discourse_chatbot/llm_client.rb @@ -101,6 +101,10 @@ def reasoning_model? REASONING_MODELS.include?(@model_name) end + def supports_allowed_tools? + @official_openai_endpoint && reasoning_model? + end + def responses_parameters(messages, include_reasoning_summary: false) parameters = { model: @model_name, input: responses_input(messages) }.merge( prompt_cache_parameters, diff --git a/plugin.rb b/plugin.rb index ee8cc83..68aa57b 100644 --- a/plugin.rb +++ b/plugin.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true # name: discourse-chatbot # about: a plugin that allows you to have a conversation with a configurable chatbot in Chat, Topics and Private Messages -# version: 3.1.7 +# version: 3.1.8 # authors: merefield # url: https://github.com/merefield/discourse-chatbot diff --git a/spec/lib/bot_tool_selection_spec.rb b/spec/lib/bot_tool_selection_spec.rb index bafe51b..ebc0adb 100644 --- a/spec/lib/bot_tool_selection_spec.rb +++ b/spec/lib/bot_tool_selection_spec.rb @@ -31,6 +31,21 @@ }, } end + let(:responses_final_response) do + { + "status" => "completed", + "output" => [ + { + "type" => "message", + "role" => "assistant", + "content" => [{ "type" => "output_text", "text" => "Four." }], + }, + ], + "usage" => { + "total_tokens" => 10, + }, + } + end before do DiscourseChatbot::Tool.stubs(:descendants).returns([]) @@ -88,8 +103,219 @@ expect(described_class.new({}).get_response(prompt, {})[:reply]).to eq("Four.") end + it "keeps definitions stable across tool-loop calls and exchanges with different selections" do + SiteSetting.chatbot_open_ai_model_low_trust = "gpt-6.1-sol" + SiteSetting.chatbot_system_one_tool_selection_mode = "restrict_calls" + next_selection = selection_response.deep_dup + next_selection[:answers] = { tool_0: judgment("irrelevant"), tool_1: judgment("relevant") } + stub_request(:post, url).to_return( + { body: selection_response.to_json }, + { body: next_selection.to_json }, + ) + tool_response = { + "status" => "completed", + "output" => [ + { + "type" => "function_call", + "call_id" => "call_calculate", + "name" => "calculate", + "arguments" => '{"input":"2 + 2"}', + }, + ], + "usage" => { + "total_tokens" => 10, + }, + } + capture_responses(tool_response, responses_final_response, responses_final_response) + options = { type: DiscourseChatbot::MESSAGE, topic_or_channel_id: 7 } + + first_result = described_class.new(options).get_response(prompt.deep_dup, options) + described_class.new(options).get_response( + [*prompt, { role: "assistant", content: "Four." }, { role: "user", content: "What is pi?" }], + options, + ) + + expect(requests.map { |request| request[:tools] }.uniq.length).to eq(1) + expect(requests.first[:tools].map { |tool| tool[:name] }).to eq(%w[calculate wikipedia]) + expect(requests.map { |request| request.dig(:tool_choice, :tools) }).to eq( + [ + [{ type: "function", name: "calculate" }], + [{ type: "function", name: "calculate" }], + [{ type: "function", name: "wikipedia" }], + ], + ) + expect(requests.map { |request| request[:prompt_cache_key] }.uniq.length).to eq(1) + expect(first_result[:reply]).to eq("Four.") + expect(first_result[:inner_thoughts].first).to include( + outcome: "restricted", + requested_mode: "restrict_calls", + effective_mode: "restrict_calls", + removed_tools: [], + disabled_tools: ["wikipedia"], + retained_tools: ["calculate"], + content: I18n.t("chatbot.inner_thoughts.tool_selection.restricted", tools: "wikipedia"), + ) + expect(JSON.generate(requests.last[:input])).not_to include("disabled_tools", "tool_selection") + expect(WebMock).to have_requested(:post, url).twice + end + + it "disables all calls while keeping definitions when selection excludes every tool" do + SiteSetting.chatbot_open_ai_model_low_trust = "gpt-6-sol" + SiteSetting.chatbot_system_one_tool_selection_mode = "restrict_calls" + selection_response[:answers][:tool_0] = judgment("irrelevant") + stub_request(:post, url).to_return(body: selection_response.to_json) + capture_responses + + result = described_class.new({}).get_response(prompt, {}) + + expect(requests.first[:tools].map { |tool| tool[:name] }).to eq(%w[calculate wikipedia]) + expect(requests.first[:tool_choice]).to eq("none") + expect(result[:inner_thoughts].first).to include(disabled_tools: %w[calculate wikipedia]) + expect(JSON.generate(requests.first[:input])).to include(Date.current.iso8601) + end + + it "retains definitions but disables calls on the last permitted model iteration" do + SiteSetting.chatbot_open_ai_model_low_trust = "gpt-6-sol" + SiteSetting.chatbot_system_one_tool_selection_mode = "restrict_calls" + SiteSetting.chatbot_chain_of_thought_max_iterations = 1 + stub_request(:post, url).to_return(body: selection_response.to_json) + capture_responses + + described_class.new({}).get_response(prompt, {}) + + expect(requests.first[:tools].map { |tool| tool[:name] }).to eq(%w[calculate wikipedia]) + expect(requests.first[:tool_choice]).to eq("none") + end + + it "requires an allowed tool and restores the eligible set when every tool is rejected" do + SiteSetting.chatbot_open_ai_model_low_trust = "gpt-6-sol" + SiteSetting.chatbot_system_one_tool_selection_mode = "restrict_calls" + SiteSetting.chatbot_tool_choice_first_iteration = "force_a_tool" + all_removed = selection_response.deep_dup + all_removed[:answers][:tool_0] = judgment("irrelevant") + stub_request(:post, url).to_return( + { body: selection_response.to_json }, + { body: all_removed.to_json }, + ) + capture_responses(responses_final_response, responses_final_response) + + described_class.new({}).get_response(prompt.deep_dup, {}) + result = described_class.new({}).get_response(prompt.deep_dup, {}) + + expect(requests.first[:tool_choice]).to eq( + type: "allowed_tools", + mode: "required", + tools: [{ type: "function", name: "calculate" }], + ) + expect(requests.last[:tool_choice]).to eq( + type: "allowed_tools", + mode: "required", + tools: %w[calculate wikipedia].map { |name| { type: "function", name: name } }, + ) + expect(result[:inner_thoughts].first).to include( + outcome: "forced", + disabled_tools: [], + protected_tools: %w[calculate wikipedia], + ) + end + + it "keeps a forced local search callable in restrict_calls mode" do + SiteSetting.chatbot_open_ai_model_low_trust = "gpt-6-sol" + SiteSetting.chatbot_system_one_tool_selection_mode = "restrict_calls" + SiteSetting.chatbot_tool_choice_first_iteration = "force_local_forum_search" + SiteSetting.chatbot_embeddings_enabled = true + SiteSetting.chatbot_tools_low_trust = "calculate|wikipedia|local_forum_search" + selection_response[:answers][:tool_2] = judgment("irrelevant") + stub_request(:post, url).to_return(body: selection_response.to_json) + capture_responses + + result = described_class.new({}).get_response(prompt, {}) + + expect(requests.first[:tool_choice]).to eq(type: "function", name: "local_forum_search") + expect(result[:inner_thoughts].first).to include( + disabled_tools: ["wikipedia"], + retained_tools: %w[calculate local_forum_search], + protected_tools: ["local_forum_search"], + ) + end + + it "falls back to definition removal for Chat Completions and reports the effective mode" do + SiteSetting.chatbot_system_one_tool_selection_mode = "restrict_calls" + stub_request(:post, url).to_return(body: selection_response.to_json) + capture_chat + + result = described_class.new({}).get_response(prompt, {}) + + expect(requests.first[:tools].map { |tool| tool[:function]["name"] }).to eq(["calculate"]) + expect(result[:inner_thoughts].first).to include( + outcome: "removed", + requested_mode: "restrict_calls", + effective_mode: "remove_definitions", + mode_fallback_reason: "unsupported_configuration", + removed_tools: ["wikipedia"], + ) + end + + it "keeps all definitions and callable tools when System One fails in restrict_calls mode" do + SiteSetting.chatbot_open_ai_model_low_trust = "gpt-6-sol" + SiteSetting.chatbot_system_one_tool_selection_mode = "restrict_calls" + stub_request(:post, url).to_return(status: 503, body: "unavailable") + capture_responses + + result = described_class.new({}).get_response(prompt, {}) + + expect(requests.first[:tools].map { |tool| tool[:name] }).to eq(%w[calculate wikipedia]) + expect(requests.first[:tool_choice]).to eq( + type: "allowed_tools", + mode: "auto", + tools: %w[calculate wikipedia].map { |name| { type: "function", name: name } }, + ) + expect(result[:inner_thoughts].first).to include(outcome: "fallback", disabled_tools: []) + end + + it "blocks execution of excluded field tools even though their definitions were supplied" do + SiteSetting.chatbot_open_ai_model_low_trust = "gpt-6-sol" + SiteSetting.chatbot_system_one_tool_selection_mode = "restrict_calls" + SiteSetting.chatbot_tools_low_trust = "calculate|user_information" + user = Fabricate(:user) + field = Fabricate(:user_field, name: "Favourite colour", field_type: "text") + excluded_name = DiscourseChatbot::Tools::UserInformation.new(field.name, user.id).name + stub_request(:post, url).to_return(body: selection_response.to_json) + excluded_call = { + "status" => "completed", + "output" => [ + { + "type" => "function_call", + "call_id" => "call_excluded", + "name" => excluded_name, + "arguments" => '{"answer":"blue"}', + }, + ], + "usage" => { + "total_tokens" => 10, + }, + } + capture_responses(excluded_call, responses_final_response) + options = { private: true, user_id: user.id } + + result = described_class.new(options).get_response(prompt, options) + + expect(requests.first[:tools].map { |tool| tool[:name] }).to eq(["calculate", excluded_name]) + expect(requests.first[:tool_choice]).to eq( + type: "allowed_tools", + mode: "auto", + tools: [{ type: "function", name: "calculate" }], + ) + expect(JSON.generate(requests.first[:input])).not_to include(field.name) + expect(UserCustomField.find_by(user_id: user.id, name: "user_field_#{field.id}")).to be_nil + expect(result[:inner_thoughts].find { |entry| entry[:role] == "tool" }[:content]).to eq( + I18n.t("chatbot.prompt.rag.call_function.error"), + ) + end + it "does not evaluate or add diagnostics when the feature is disabled" do SiteSetting.chatbot_system_one_tool_selection_enabled = false + SiteSetting.chatbot_system_one_tool_selection_mode = "restrict_calls" capture_chat result = described_class.new({}).get_response(prompt, {}) diff --git a/spec/lib/llm_client_spec.rb b/spec/lib/llm_client_spec.rb index 8e9b9d0..32d54f5 100644 --- a/spec/lib/llm_client_spec.rb +++ b/spec/lib/llm_client_spec.rb @@ -37,6 +37,30 @@ end end + it "supports allowed_tools only for official OpenAI Responses configurations" do + %w[gpt-5.4-mini gpt-5.6 gpt-6-astra gpt-6.1-sol gpt-6-sol gpt-6-luna].each do |model| + SiteSetting.chatbot_open_ai_model_low_trust = model + expect(described_class.new(trust_level: "low")).to be_supports_allowed_tools + end + + SiteSetting.chatbot_open_ai_model_low_trust = "gpt-4.1-mini" + expect(described_class.new(trust_level: "low")).not_to be_supports_allowed_tools + + SiteSetting.chatbot_open_ai_model_low_trust = "gpt-6-sol" + SiteSetting.chatbot_open_ai_model_custom_url_low_trust = "https://llm.example.com/v1/" + expect(described_class.new(trust_level: "low")).not_to be_supports_allowed_tools + + SiteSetting.chatbot_open_ai_model_custom_url_low_trust = "" + SiteSetting.chatbot_open_ai_model_custom_api_type = "azure" + expect(described_class.new(trust_level: "low")).not_to be_supports_allowed_tools + + SiteSetting.chatbot_open_ai_model_custom_api_type = "open_ai" + %w[anthropic google_gemini x_ai].each do |provider| + SiteSetting.chatbot_llm_provider = provider + expect(described_class.new(trust_level: "low")).not_to be_supports_allowed_tools + end + end + it "uses Anthropic's compatibility endpoint and default model" do SiteSetting.chatbot_llm_provider = "anthropic" diff --git a/spec/support/tool_selection_helpers.rb b/spec/support/tool_selection_helpers.rb index ff63fca..dd5f00e 100644 --- a/spec/support/tool_selection_helpers.rb +++ b/spec/support/tool_selection_helpers.rb @@ -25,5 +25,19 @@ def capture_chat(response = final_response) end .returns(response) end + + def capture_responses(*results) + results = [responses_final_response] if results.empty? + responses = mock + client.stubs(:responses).returns(responses) + responses + .expects(:create) + .times(results.length) + .with do |parameters:| + requests << parameters.deep_dup + true + end + .returns(*results) + end end end From eadfaed934a269ba5092d0e8cb7120895fea8e75 Mon Sep 17 00:00:00 2001 From: merefield Date: Wed, 21 Oct 2026 10:40:05 +0100 Subject: [PATCH 2/3] FEATURE: enable GPT-6 cache breakpoints and gate tool-selection mode choices --- README.md | 7 +++ config/locales/client.en.yml | 3 + config/locales/server.en.yml | 2 +- config/settings.yml | 4 +- lib/discourse_chatbot/llm_client.rb | 2 +- .../tool_selection_mode_site_setting.rb | 25 ++++++++ spec/lib/bot_tool_selection_spec.rb | 6 ++ spec/lib/llm_client_spec.rb | 60 +++++++++++++++++++ .../tool_selection_mode_site_setting_spec.rb | 30 ++++++++++ 9 files changed, 134 insertions(+), 5 deletions(-) create mode 100644 lib/discourse_chatbot/tool_selection_mode_site_setting.rb create mode 100644 spec/lib/tool_selection_mode_site_setting_spec.rb diff --git a/README.md b/README.md index 6547dc0..d1862f3 100644 --- a/README.md +++ b/README.md @@ -338,11 +338,18 @@ tools. An empty selection uses `tool_choice: "none"`. Forced tools and the final tool-call limit still apply. Chat Completions, custom endpoints, Azure and other providers use `remove_definitions` even when `restrict_calls` is selected. +The `restrict_calls` choice is offered when the provider is OpenAI and the API type is not +Azure. Reload the settings page after changing the provider or API type to refresh the choices. +A saved preference is retained when these settings change; runtime compatibility checks still +apply independently to each trust level's model and custom endpoint. + Stable definitions can improve cache reuse between exchanges with different selections. They still consume input tokens, and changes to eligible tools, conversation history or other prompt content can reduce reuse. Compare the existing cached-input and cache-write usage statistics to assess the cost for your conversations. See OpenAI's [tool-caching guidance](https://developers.openai.com/api/docs/guides/prompt-caching#manage-tools-with-append-only-updates). +Official OpenAI GPT-5.6, GPT-6 and GPT-6.1 requests also place an explicit cache breakpoint after +the fixed developer instructions while keeping implicit conversation caching enabled. For user-information collection and staff escalation, the criteria also consider whether the user requests the action or answers a pending collection question. This is a diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml index d3e6628..5ef0c62 100644 --- a/config/locales/client.en.yml +++ b/config/locales/client.en.yml @@ -3,6 +3,9 @@ en: discourse_chatbot: title: "Chatbot" chatbot: + tool_selection_mode: + remove_definitions: "Remove unselected tool definitions" + restrict_calls: "Restrict calls and retain tool definitions for caching" blocked_questions_strategy: system_one: "System One (with example matching fallback)" examples: "Example-based embedding matching" diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml index 2af4d02..087e72c 100644 --- a/config/locales/server.en.yml +++ b/config/locales/server.en.yml @@ -106,7 +106,7 @@ en: chatbot_open_ai_embeddings_model_custom_url: "Optional embeddings endpoint override. The endpoint must support the selected provider's OpenAI-compatible embeddings API and receives that provider's shared API key." chatbot_system_one_model: "System One model for semantic judgments. Defaults to TypeSafe AI's jev-latest. The model, URL, and key must all be populated to use System One features." chatbot_system_one_tool_selection_enabled: "Use System One to select tools for each request. Requires the System One model, URL, and key. Sends the current query, recent conversation context, and eligible tool descriptions to that service. Decisions appear in Inner Thoughts when enabled. Independent of question blocking." - chatbot_system_one_tool_selection_mode: "How System One applies tool selection. remove_definitions omits unselected tool descriptions to reduce input tokens. restrict_calls keeps eligible definitions stable for prompt caching and uses allowed_tools to restrict calls on the official OpenAI Responses API; other configurations use remove_definitions. Both modes prevent execution of unselected tools." + chatbot_system_one_tool_selection_mode: "How System One applies tool selection. remove_definitions omits unselected tool descriptions to reduce input tokens. restrict_calls keeps eligible definitions stable for prompt caching and uses allowed_tools to restrict calls on the official OpenAI Responses API. This choice is offered for OpenAI without Azure; reload the settings page after changing the provider or API type. Unsupported models and custom endpoints use remove_definitions at runtime. Both modes prevent execution of unselected tools." chatbot_system_one_tool_selection_context: "Optional administrator guidance for tool selection, such as when forum search should remain available. Up to 4,000 characters; longer guidance causes selection to fall back to all eligible tools. Does not grant tool permissions." chatbot_system_one_tool_selection_look_back: "Number of preceding messages sent to System One for tool selection (0–20). Separate from the main model and question-blocking history windows. Each preceding message is limited to 2,000 characters. The current query is always included." chatbot_system_one_tool_removal_threshold: "Minimum irrelevant probability needed to remove a tool. Lower values remove tools more readily. Relevant and unclear tools remain available; configured forced tools are preserved." diff --git a/config/settings.yml b/config/settings.yml index 5ae2de7..c18cffe 100644 --- a/config/settings.yml +++ b/config/settings.yml @@ -794,9 +794,7 @@ plugins: client: false type: enum default: remove_definitions - choices: - - remove_definitions - - restrict_calls + enum: "DiscourseChatbot::ToolSelectionModeSiteSetting" depends_on: - chatbot_system_one_tool_selection_enabled depends_behavior: hidden diff --git a/lib/discourse_chatbot/llm_client.rb b/lib/discourse_chatbot/llm_client.rb index 8521470..2afe94e 100644 --- a/lib/discourse_chatbot/llm_client.rb +++ b/lib/discourse_chatbot/llm_client.rb @@ -147,7 +147,7 @@ def chat_completions_generation_parameters end def explicit_prompt_caching? - @official_openai_endpoint && @model_name.match?(/\Agpt-5\.6(?:-|\z)/) + @official_openai_endpoint && @model_name.match?(/\Agpt-(?:5\.6|6|6\.1)(?:-|\z)/) end def chat_completions_messages(messages) diff --git a/lib/discourse_chatbot/tool_selection_mode_site_setting.rb b/lib/discourse_chatbot/tool_selection_mode_site_setting.rb new file mode 100644 index 0000000..d8e85e6 --- /dev/null +++ b/lib/discourse_chatbot/tool_selection_mode_site_setting.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +require "enum_site_setting" + +module DiscourseChatbot + class ToolSelectionModeSiteSetting < ::EnumSiteSetting + def self.values + modes = ["remove_definitions"] + if SiteSetting.chatbot_llm_provider == "open_ai" && + SiteSetting.chatbot_open_ai_model_custom_api_type != "azure" + modes << "restrict_calls" + end + modes.map { |mode| { name: "chatbot.tool_selection_mode.#{mode}", value: mode } } + end + + def self.valid_value?(value) + # Preserve the saved preference when the provider changes; requests apply a compatible mode. + %w[remove_definitions restrict_calls].include?(value) + end + + def self.translate_names? + true + end + end +end diff --git a/spec/lib/bot_tool_selection_spec.rb b/spec/lib/bot_tool_selection_spec.rb index ebc0adb..0dab155 100644 --- a/spec/lib/bot_tool_selection_spec.rb +++ b/spec/lib/bot_tool_selection_spec.rb @@ -137,6 +137,12 @@ expect(requests.map { |request| request[:tools] }.uniq.length).to eq(1) expect(requests.first[:tools].map { |tool| tool[:name] }).to eq(%w[calculate wikipedia]) + expect(requests.map { |request| request[:prompt_cache_options] }.uniq).to eq( + [{ mode: "implicit" }], + ) + expect( + requests.map { |request| request.dig(:input, 0, :content, 0, :prompt_cache_breakpoint) }.uniq, + ).to eq([{ mode: "explicit" }]) expect(requests.map { |request| request.dig(:tool_choice, :tools) }).to eq( [ [{ type: "function", name: "calculate" }], diff --git a/spec/lib/llm_client_spec.rb b/spec/lib/llm_client_spec.rb index 32d54f5..3886ef8 100644 --- a/spec/lib/llm_client_spec.rb +++ b/spec/lib/llm_client_spec.rb @@ -61,6 +61,66 @@ end end + it "adds explicit breakpoints for GPT-5.6 and supported GPT-6 models, preserving implicit caching" do + messages = [ + { role: "developer", content: "Stable instructions", prompt_cache_breakpoint: true }, + ] + %w[gpt-5.6 gpt-5.6-sol gpt-6-astra gpt-6.1-sol gpt-6-sol gpt-6-luna].each do |model| + SiteSetting.chatbot_open_ai_model_low_trust = model + parameters = described_class.new(trust_level: "low").responses_parameters(messages) + + expect(parameters[:prompt_cache_options]).to eq(mode: "implicit") + expect(parameters.dig(:input, 0, :content, 0)).to eq( + type: "input_text", + text: "Stable instructions", + prompt_cache_breakpoint: { + mode: "explicit", + }, + ) + end + + SiteSetting.chatbot_open_ai_model_low_trust = "gpt-5.5" + parameters = described_class.new(trust_level: "low").responses_parameters(messages) + expect(parameters).not_to have_key(:prompt_cache_options) + expect(parameters.dig(:input, 0, :content, 0)).to eq( + type: "input_text", + text: "Stable instructions", + ) + end + + it "omits GPT-6 breakpoints for custom endpoints, Azure and other providers" do + SiteSetting.chatbot_open_ai_model_low_trust = "gpt-6-sol" + messages = [ + { role: "developer", content: "Stable instructions", prompt_cache_breakpoint: true }, + ] + SiteSetting.chatbot_open_ai_model_custom_url_low_trust = "https://llm.example.com/v1/" + parameters = described_class.new(trust_level: "low").responses_parameters(messages) + expect(parameters).not_to have_key(:prompt_cache_options) + expect(parameters.dig(:input, 0, :content, 0)).to eq( + type: "input_text", + text: "Stable instructions", + ) + + SiteSetting.chatbot_open_ai_model_custom_url_low_trust = "" + SiteSetting.chatbot_open_ai_model_custom_api_type = "azure" + parameters = described_class.new(trust_level: "low").responses_parameters(messages) + expect(parameters).not_to have_key(:prompt_cache_options) + expect(parameters.dig(:input, 0, :content, 0)).to eq( + type: "input_text", + text: "Stable instructions", + ) + + SiteSetting.chatbot_open_ai_model_custom_api_type = "" + %w[anthropic google_gemini x_ai].each do |provider| + SiteSetting.chatbot_llm_provider = provider + SiteSetting.chatbot_open_ai_model_custom_low_trust = true + SiteSetting.chatbot_open_ai_model_custom_name_low_trust = "gpt-6-sol" + parameters = described_class.new(trust_level: "low").chat_completions_parameters(messages) + expect(parameters).not_to have_key(:prompt_cache_options) + expect(parameters[:messages].first[:content]).to eq("Stable instructions") + end + end + it "uses Anthropic's compatibility endpoint and default model" do SiteSetting.chatbot_llm_provider = "anthropic" diff --git a/spec/lib/tool_selection_mode_site_setting_spec.rb b/spec/lib/tool_selection_mode_site_setting_spec.rb new file mode 100644 index 0000000..1ec6b00 --- /dev/null +++ b/spec/lib/tool_selection_mode_site_setting_spec.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +require_relative "../plugin_helper" + +RSpec.describe DiscourseChatbot::ToolSelectionModeSiteSetting do + it "offers restrict_calls for OpenAI without Azure and retains saved preferences across providers" do + expect(SiteSetting.chatbot_system_one_tool_selection_mode).to eq("remove_definitions") + expect(described_class.values.pluck(:value)).to eq(%w[remove_definitions restrict_calls]) + SiteSetting.chatbot_system_one_tool_selection_mode = "restrict_calls" + + %w[anthropic google_gemini x_ai].each do |provider| + SiteSetting.chatbot_llm_provider = provider + + expect(described_class.values.pluck(:value)).to eq(["remove_definitions"]) + expect(SiteSetting.chatbot_system_one_tool_selection_mode).to eq("restrict_calls") + SiteSetting.chatbot_system_one_tool_selection_mode = "remove_definitions" + expect(SiteSetting.chatbot_system_one_tool_selection_mode).to eq("remove_definitions") + SiteSetting.chatbot_system_one_tool_selection_mode = "restrict_calls" + end + + SiteSetting.chatbot_llm_provider = "open_ai" + SiteSetting.chatbot_open_ai_model_custom_api_type = "azure" + expect(described_class.values.pluck(:value)).to eq(["remove_definitions"]) + expect(SiteSetting.chatbot_system_one_tool_selection_mode).to eq("restrict_calls") + + SiteSetting.chatbot_open_ai_model_custom_api_type = "" + expect(described_class.values.pluck(:value)).to eq(%w[remove_definitions restrict_calls]) + expect(described_class.valid_value?("unknown")).to eq(false) + end +end From 7dc0f4dee556405887f9c0be8f1a7696466cea63 Mon Sep 17 00:00:00 2001 From: merefield Date: Wed, 21 Oct 2026 10:59:25 +0100 Subject: [PATCH 3/3] FIX: force local search only when eligible and supplied --- README.md | 6 +++-- lib/discourse_chatbot/bot.rb | 12 ++++++--- spec/lib/bot_tool_selection_spec.rb | 41 +++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d1862f3..ed5e5cf 100644 --- a/README.md +++ b/README.md @@ -324,8 +324,10 @@ The current query is not truncated. If the selection state exceeds 40,000 charac administrator guidance exceeds 4,000 characters, all eligible tools remain available. Relevant, unclear, and below-threshold decisions retain the tool. Missing configuration, provider -errors, and invalid responses also retain the eligible set. A forced local search remains -available. If the administrator requires any tool call and selection would remove every tool, +errors, and invalid responses also retain the eligible set. An eligible forced local search +remains available. If local search is unavailable, such as when embeddings are disabled or the +trust-level tool list excludes it, the forced-local-search setting is ignored for that request. +If the administrator requires any tool call and selection would remove every tool, the eligible set is retained. Existing access rules, credentials and extension availability checks run first; selection never enables an otherwise unavailable tool. diff --git a/lib/discourse_chatbot/bot.rb b/lib/discourse_chatbot/bot.rb index 4f8297a..b7cec26 100644 --- a/lib/discourse_chatbot/bot.rb +++ b/lib/discourse_chatbot/bot.rb @@ -476,6 +476,12 @@ def create_chat_completion( +++++++++++++++++++++++++++++++ EOS + force_local_search = + iteration == 1 && + SiteSetting.chatbot_tool_choice_first_iteration == FORCE_LOCAL_SEARCH_TOOL && + @tool_mapping.key?("local_forum_search") && + @tool_definitions.any? { |tool| tool["name"] == "local_forum_search" } + if reasoning_model? parameters = responses_parameters( @@ -489,7 +495,7 @@ def create_chat_completion( parameters[:tool_choice] = "none" elsif @restrict_tool_calls forced_choice = SiteSetting.chatbot_tool_choice_first_iteration - if iteration == 1 && forced_choice == FORCE_LOCAL_SEARCH_TOOL + if force_local_search parameters[:tool_choice] = { type: "function", name: "local_forum_search" } else parameters[:tool_choice] = { @@ -508,7 +514,7 @@ def create_chat_completion( elsif iteration == 1 if FORCE_A_TOOL_VALUES.include?(SiteSetting.chatbot_tool_choice_first_iteration) parameters[:tool_choice] = "required" - elsif SiteSetting.chatbot_tool_choice_first_iteration == FORCE_LOCAL_SEARCH_TOOL + elsif force_local_search parameters[:tool_choice] = { type: "function", name: "local_forum_search" } end end @@ -532,7 +538,7 @@ def create_chat_completion( elsif iteration == 1 if FORCE_A_TOOL_VALUES.include?(SiteSetting.chatbot_tool_choice_first_iteration) parameters.merge!(tool_choice: "required") - elsif SiteSetting.chatbot_tool_choice_first_iteration == FORCE_LOCAL_SEARCH_TOOL + elsif force_local_search parameters.merge!( tool_choice: { type: "function", diff --git a/spec/lib/bot_tool_selection_spec.rb b/spec/lib/bot_tool_selection_spec.rb index 0dab155..27053b5 100644 --- a/spec/lib/bot_tool_selection_spec.rb +++ b/spec/lib/bot_tool_selection_spec.rb @@ -245,6 +245,47 @@ ) end + [ + %w[gpt-4.1-mini remove_definitions], + %w[gpt-6-sol remove_definitions], + %w[gpt-6-sol restrict_calls], + ].each do |model, mode| + it "ignores an ineligible forced local search with #{model} and #{mode}" do + SiteSetting.chatbot_open_ai_model_low_trust = model + SiteSetting.chatbot_system_one_tool_selection_mode = mode + SiteSetting.chatbot_tool_choice_first_iteration = "force_local_forum_search" + stub_request(:post, url).to_return(body: selection_response.to_json) + if model == "gpt-4.1-mini" + client + .expects(:chat) + .twice + .with do |parameters:| + requests << parameters.deep_dup + true + end + .returns(final_response) + else + capture_responses(responses_final_response, responses_final_response) + end + + SiteSetting.chatbot_tools_low_trust = "calculate|wikipedia|local_forum_search" + SiteSetting.chatbot_embeddings_enabled = false + described_class.new({}).get_response(prompt.deep_dup, {}) + + SiteSetting.chatbot_tools_low_trust = "calculate|wikipedia" + SiteSetting.chatbot_embeddings_enabled = true + described_class.new({}).get_response(prompt.deep_dup, {}) + + expected_choice = + if mode == "restrict_calls" + { type: "allowed_tools", mode: "auto", tools: [{ type: "function", name: "calculate" }] } + end + expect(requests.map { |request| request[:tool_choice] }).to eq( + [expected_choice, expected_choice], + ) + end + end + it "falls back to definition removal for Chat Completions and reports the effective mode" do SiteSetting.chatbot_system_one_tool_selection_mode = "restrict_calls" stub_request(:post, url).to_return(body: selection_response.to_json)