Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 33 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand All @@ -323,22 +324,48 @@ 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.

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.

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
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
Expand Down
3 changes: 3 additions & 0 deletions config/locales/client.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
4 changes: 3 additions & 1 deletion config/locales/server.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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."
Expand Down Expand Up @@ -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."
Expand Down
8 changes: 8 additions & 0 deletions config/settings.yml
Original file line number Diff line number Diff line change
Expand Up @@ -790,6 +790,14 @@ plugins:
chatbot_system_one_tool_selection_enabled:
client: false
default: false
chatbot_system_one_tool_selection_mode:
client: false
type: enum
default: remove_definitions
enum: "DiscourseChatbot::ToolSelectionModeSiteSetting"
depends_on:
- chatbot_system_one_tool_selection_enabled
depends_behavior: hidden
chatbot_system_one_tool_selection_context:
client: false
default: ''
Expand Down
58 changes: 51 additions & 7 deletions lib/discourse_chatbot/bot.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -456,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(
Expand All @@ -465,12 +491,30 @@ 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 force_local_search
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"
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
Expand All @@ -494,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",
Expand Down
6 changes: 5 additions & 1 deletion lib/discourse_chatbot/llm_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -143,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)
Expand Down
25 changes: 25 additions & 0 deletions lib/discourse_chatbot/tool_selection_mode_site_setting.rb
Original file line number Diff line number Diff line change
@@ -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
2 changes: 1 addition & 1 deletion plugin.rb
Original file line number Diff line number Diff line change
@@ -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

Expand Down
Loading
Loading