Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: add conditional param visibility and new reasoning options (#38106)

Sam4f49efbdb0c1
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-llm-editor-form.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-llm-editor-form.gjs
index ab3fe9d3c5f..65953f18eac 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-llm-editor-form.gjs
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-llm-editor-form.gjs
@@ -15,9 +15,13 @@ import {
addUniqueValueToArray,
removeValueFromArray,
} from "discourse/lib/array-tools";
-import { eq, gt } from "discourse/truth-helpers";
+import { eq, gt, not } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
import AiLlmAttachmentTypes from "discourse/plugins/discourse-ai/discourse/components/ai-llm-attachment-types";
+import {
+ isProviderParamHidden,
+ normalizeProviderParams,
+} from "discourse/plugins/discourse-ai/discourse/lib/llm-provider-param-helpers";
import DurationSelector from "./ai-quota-duration-selector";
import AiSecretSelector from "./ai-secret-selector";
import AiLlmQuotaModal from "./modal/ai-llm-quota-modal";
@@ -184,26 +188,7 @@ export default class AiLlmEditorForm extends Component {
@action
metaProviderParams(provider) {
const params = this.args.llms.resultSetMeta.provider_params[provider] || {};
-
- return Object.entries(params).reduce((acc, [field, value]) => {
- if (typeof value === "string") {
- acc[field] = { type: value };
- } else if (typeof value === "object") {
- if (value.values) {
- value = { ...value };
- value.values = value.values.map((v) => ({ id: v, name: v }));
- }
-
- acc[field] = {
- type: value.type || "text",
- values: value.values || [],
- default: value.default ?? undefined,
- };
- } else {
- acc[field] = { type: "text" }; // fallback
- }
- return acc;
- }, {});
+ return normalizeProviderParams(params);
}
@action
@@ -296,6 +281,11 @@ export default class AiLlmEditorForm extends Component {
});
}
+ @action
+ isProviderParamHidden(params, providerParamsData) {
+ return isProviderParamHidden(params, providerParamsData);
+ }
+
@action
providerParamsKeys(providerParams) {
return providerParams ? Object.keys(providerParams) : [];
@@ -389,36 +379,40 @@ export default class AiLlmEditorForm extends Component {
(get (this.metaProviderParams data.provider) name)
as |params|
}}
- <object.Field
- @name={{name}}
- @title={{i18n
- (concat "discourse_ai.llms.provider_fields." name)
- }}
- @format="large"
- as |field|
- >
- {{#if (eq params.type "enum")}}
- <field.Select @includeNone={{false}} as |select|>
- {{#each params.values as |option|}}
- <select.Option
- @value={{option.id}}
- >{{option.name}}</select.Option>
- {{/each}}
- </field.Select>
- {{else if (eq params.type "checkbox")}}
- <field.Checkbox />
- {{else if (eq params.type "secret")}}
- <field.Custom>
- <AiSecretSelector
- @value={{field.value}}
- @secrets={{this.availableSecrets}}
- @onChange={{field.set}}
- />
- </field.Custom>
- {{else}}
- <field.Input @type={{params.type}} />
- {{/if}}
- </object.Field>
+ {{#if
+ (not (this.isProviderParamHidden params providerParamsData))
+ }}
+ <object.Field
+ @name={{name}}
+ @title={{i18n
+ (concat "discourse_ai.llms.provider_fields." name)
+ }}
+ @format="large"
+ as |field|
+ >
+ {{#if (eq params.type "enum")}}
+ <field.Select @includeNone={{false}} as |select|>
+ {{#each params.values as |option|}}
+ <select.Option
+ @value={{option.id}}
+ >{{option.name}}</select.Option>
+ {{/each}}
+ </field.Select>
+ {{else if (eq params.type "checkbox")}}
+ <field.Checkbox />
+ {{else if (eq params.type "secret")}}
+ <field.Custom>
+ <AiSecretSelector
+ @value={{field.value}}
+ @secrets={{this.availableSecrets}}
+ @onChange={{field.set}}
+ />
+ </field.Custom>
+ {{else}}
+ <field.Input @type={{params.type}} />
+ {{/if}}
+ </object.Field>
+ {{/if}}
{{/let}}
{{/each}}
</form.Object>
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb
index 5193d4297c4..64926e7cfe2 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb
@@ -220,6 +220,7 @@ module DiscourseAi
:vision_enabled,
:input_cost,
:cached_input_cost,
+ :cache_write_cost,
:output_cost,
allowed_attachment_types: [],
)
@@ -237,11 +238,16 @@ module DiscourseAi
if received_prov_params.present?
received_prov_params.each do |pname, value|
- if extra_field_names[pname.to_sym] == :checkbox
+ field_def = extra_field_names[pname.to_sym]
+ is_checkbox =
+ field_def == :checkbox || (field_def.is_a?(Hash) && field_def[:type] == :checkbox)
+ if is_checkbox
received_prov_params[pname] = ActiveModel::Type::Boolean.new.cast(value)
end
end
+ sanitize_dependent_params!(received_prov_params, extra_field_names)
+
permitted[:provider_params] = received_prov_params.permit!
end
end
@@ -249,6 +255,26 @@ module DiscourseAi
permitted
end
+ def sanitize_dependent_params!(prov_params, field_definitions)
+ prov_params.each do |pname, _value|
+ field_def = field_definitions[pname.to_sym]
+ next unless field_def.is_a?(Hash) && field_def[:depends_on]
+
+ deps = Array(field_def[:depends_on])
+ parent_inactive =
+ deps.any? do |dep|
+ parent_val = prov_params[dep.to_s]
+ parent_val.nil? || parent_val == false || parent_val == "false" ||
+ parent_val == "default" || parent_val == ""
+ end
+
+ if parent_inactive
+ default = field_def[:default]
+ prov_params[pname] = default || nil
+ end
+ end
+ end
+
def ai_llm_logger_fields
{
display_name: {
diff --git a/plugins/discourse-ai/app/models/llm_model.rb b/plugins/discourse-ai/app/models/llm_model.rb
index b2555994e58..68f45c48423 100644
--- a/plugins/discourse-ai/app/models/llm_model.rb
+++ b/plugins/discourse-ai/app/models/llm_model.rb
@@ -58,63 +58,103 @@ class LlmModel < ActiveRecord::Base
access_key_id: :secret,
role_arn: :text,
region: :text,
+ enable_reasoning: :checkbox,
+ adaptive_thinking: {
+ type: :checkbox,
+ depends_on: :enable_reasoning,
+ },
+ reasoning_tokens: {
+ type: :number,
+ depends_on: :enable_reasoning,
+ hidden_if: :adaptive_thinking,
+ },
+ effort: {
+ type: :enum,
+ values: %w[default low medium high max],
+ default: "default",
+ },
disable_native_tools: :checkbox,
disable_native_structured_output: :checkbox,
- disable_temperature: :checkbox,
- disable_top_p: :checkbox,
- enable_reasoning: :checkbox,
- reasoning_tokens: :number,
+ disable_temperature: {
+ type: :checkbox,
+ hidden_if: %i[enable_reasoning adaptive_thinking],
+ },
+ disable_top_p: {
+ type: :checkbox,
+ hidden_if: %i[enable_reasoning adaptive_thinking],
+ },
prompt_caching: {
type: :enum,
values: %w[never tool_results always],
default: "never",
},
+ },
+ anthropic: {
+ enable_reasoning: :checkbox,
+ adaptive_thinking: {
+ type: :checkbox,
+ depends_on: :enable_reasoning,
+ },
+ reasoning_tokens: {
+ type: :number,
+ depends_on: :enable_reasoning,
+ hidden_if: :adaptive_thinking,
+ },
effort: {
type: :enum,
- values: %w[default low medium high],
+ values: %w[default low medium high max],
default: "default",
},
- },
- anthropic: {
disable_native_tools: :checkbox,
disable_native_structured_output: :checkbox,
- disable_temperature: :checkbox,
- disable_top_p: :checkbox,
- enable_reasoning: :checkbox,
- reasoning_tokens: :number,
+ disable_temperature: {
+ type: :checkbox,
+ hidden_if: %i[enable_reasoning adaptive_thinking],
+ },
+ disable_top_p: {
+ type: :checkbox,
+ hidden_if: %i[enable_reasoning adaptive_thinking],
+ },
prompt_caching: {
type: :enum,
values: %w[never tool_results always],
default: "never",
},
- effort: {
- type: :enum,
- values: %w[default low medium high],
- default: "default",
- },
},
open_ai: {
organization: :text,
disable_native_tools: :checkbox,
- disable_temperature: :checkbox,
- disable_top_p: :checkbox,
- disable_streaming: :checkbox,
reasoning_effort: {
type: :enum,
- values: %w[default minimal low medium high],
+ values: %w[default none minimal low medium high xhigh],
default: "default",
},
+ disable_temperature: {
+ type: :checkbox,
+ hidden_if: :reasoning_effort,
+ },
+ disable_top_p: {
+ type: :checkbox,
+ hidden_if: :reasoning_effort,
+ },
+ disable_streaming: :checkbox,
},
groq: {
disable_native_tools: :checkbox,
- disable_temperature: :checkbox,
- disable_top_p: :checkbox,
- disable_streaming: :checkbox,
reasoning_effort: {
type: :enum,
- values: %w[default minimal low medium high],
+ values: %w[default none minimal low medium high xhigh],
default: "default",
},
+ disable_temperature: {
+ type: :checkbox,
+ hidden_if: :reasoning_effort,
+ },
+ disable_top_p: {
+ type: :checkbox,
+ hidden_if: :reasoning_effort,
+ },
+ disable_streaming: :checkbox,
},
mistral: {
disable_native_tools: :checkbox,
@@ -122,19 +162,38 @@ class LlmModel < ActiveRecord::Base
google: {
disable_native_tools: :checkbox,
enable_thinking: :checkbox,
- disable_temperature: :checkbox,
+ thinking_level: {
+ type: :enum,
+ values: %w[default minimal low medium high],
+ default: "default",
+ depends_on: :enable_thinking,
+ },
+ thinking_tokens: {
+ type: :number,
+ depends_on: :enable_thinking,
+ hidden_if: :thinking_level,
+ },
+ disable_temperature: {
+ type: :checkbox,
+ hidden_if: :enable_thinking,
+ },
disable_top_p: :checkbox,
- thinking_tokens: :number,
},
azure: {
disable_native_tools: :checkbox,
reasoning_effort: {
type: :enum,
- values: %w[default minimal low medium high xhigh],
+ values: %w[default none minimal low medium high xhigh],
default: "default",
},
- disable_temperature: :checkbox,
- disable_top_p: :checkbox,
+ disable_temperature: {
+ type: :checkbox,
+ hidden_if: :reasoning_effort,
+ },
+ disable_top_p: {
+ type: :checkbox,
+ hidden_if: :reasoning_effort,
+ },
disable_streaming: :checkbox,
},
hugging_face: {
@@ -144,6 +203,21 @@ class LlmModel < ActiveRecord::Base
vllm: {
disable_system_prompt: :checkbox,
disable_native_tools: :checkbox,
+ enable_thinking: :checkbox,
+ reasoning_effort: {
+ type: :enum,
+ values: %w[default none minimal low medium high xhigh],
+ default: "default",
+ },
+ disable_temperature: {
+ type: :checkbox,
+ hidden_if: :reasoning_effort,
+ },
+ disable_top_p: {
+ type: :checkbox,
+ hidden_if: :reasoning_effort,
+ },
+ disable_streaming: :checkbox,
},
ollama: {
disable_system_prompt: :checkbox,
@@ -241,9 +315,17 @@ class LlmModel < ActiveRecord::Base
return value if value.nil?
param_def = self.class.provider_params.dig(provider&.to_sym, key.to_sym)
- if param_def == :secret && value.to_s =~ /\A\d+\z/
- resolved = AiSecret.find_by(id: value.to_i)
- return resolved&.secret if resolved
+
+ if param_def.is_a?(Hash) && param_def[:depends_on]
+ deps = Array(param_def[:depends_on])
+ return nil if deps.any? { |dep| !param_active?(dep) }
+ end
+
+ if param_def == :secret || (param_def.is_a?(Hash) && param_def[:type] == :secret)
+ if value.to_s =~ /\A\d+\z/
+ resolved = AiSecret.find_by(id: value.to_i)
+ return resolved&.secret if resolved
+ end
end
value
@@ -295,6 +377,12 @@ class LlmModel < ActiveRecord::Base
private
+ def param_active?(key)
+ val = provider_params&.dig(key.to_s)
+ return false if val.nil? || val == false || val == "false" || val == "default" || val == ""
+ true
+ end
+
def api_key_or_secret_present
return if seeded?
if ai_secret_id.present?
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/lib/llm-provider-param-helpers.js b/plugins/discourse-ai/assets/javascripts/discourse/lib/llm-provider-param-helpers.js
new file mode 100644
index 00000000000..e069527f692
--- /dev/null
+++ b/plugins/discourse-ai/assets/javascripts/discourse/lib/llm-provider-param-helpers.js
@@ -0,0 +1,65 @@
+// Returns whether a provider param value is "active" (non-default, truthy).
+// Treats null, undefined, false, "false", "default", and "" as inactive.
+export function isParamActive(val) {
+ if (val === null || val === undefined || val === false) {
+ return false;
+ }
+ if (val === "false" || val === "default" || val === "") {
+ return false;
+ }
+ return true;
+}
+
+// Determines if a provider param field should be hidden based on
+// depends_on / hidden_if metadata and current param values.
+export function isProviderParamHidden(paramMeta, providerParamsData) {
+ if (paramMeta.depends_on) {
+ const deps = Array.isArray(paramMeta.depends_on)
+ ? paramMeta.depends_on
+ : [paramMeta.depends_on];
+ if (deps.some((field) => !isParamActive(providerParamsData[field]))) {
+ return true;
+ }
+ }
+
+ if (paramMeta.hidden_if) {
+ const conditions = Array.isArray(paramMeta.hidden_if)
+ ? paramMeta.hidden_if
+ : [paramMeta.hidden_if];
+ if (conditions.some((field) => isParamActive(providerParamsData[field]))) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+// Normalizes raw provider_params metadata (from the server) into a
+// consistent shape for the editor form.
+export function normalizeProviderParams(rawParams) {
+ if (!rawParams) {
+ return {};
+ }
+
+ return Object.entries(rawParams).reduce((acc, [field, value]) => {
+ if (typeof value === "string") {
+ acc[field] = { type: value };
+ } else if (typeof value === "object") {
+ if (value.values) {
+ value = { ...value };
+ value.values = value.values.map((v) => ({ id: v, name: v }));
+ }
+
+ acc[field] = {
+ type: value.type || "text",
+ values: value.values || [],
+ default: value.default ?? undefined,
+ hidden_if: value.hidden_if ?? undefined,
+ depends_on: value.depends_on ?? undefined,
+ };
+ } else {
+ acc[field] = { type: "text" };
+ }
+ return acc;
+ }, {});
+}
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index 1fa6521260b..c2437c8c051 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -851,7 +851,9 @@ en:
disable_streaming: "Disable streaming completions (convert streaming to non streaming requests)"
reasoning_effort: "Reasoning effort (only applicable to reasoning models)"
enable_reasoning: "Enable reasoning (only applicable to reasoning models)"
- enable_thinking: "Enable thinking (only on applicable models eg: flash 2.5)"
+ adaptive_thinking: "Enable adaptive thinking (recommended for Claude 4.6 models)"
+ enable_thinking: "Enable thinking (Gemini 2.5 models - uses token budget)"
+ thinking_level: "Thinking level (Gemini 3 models - controls reasoning depth)"
thinking_tokens: "Number of tokens used for thinking"
reasoning_tokens: "Number of tokens used for reasoning"
disable_temperature: "Disable temperature (some thinking models don't support temperature)"
diff --git a/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb b/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb
index 19e173e82be..4b9188d3ead 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb
@@ -43,8 +43,10 @@ module DiscourseAi
options = { model: mapped_model, max_tokens: max_tokens }
- # reasoning has even higher token limits
- if llm_model.lookup_custom_param("enable_reasoning")
+ if llm_model.lookup_custom_param("adaptive_thinking")
+ options[:thinking] = { type: "adaptive" }
+ options[:max_tokens] = 32_000
+ elsif llm_model.lookup_custom_param("enable_reasoning")
reasoning_tokens =
llm_model.lookup_custom_param("reasoning_tokens").to_i.clamp(1024, 32_768)
@@ -58,7 +60,7 @@ module DiscourseAi
# effort parameter
effort = llm_model.lookup_custom_param("effort")
- options[:output_config] = { effort: effort } if %w[low medium high].include?(effort)
+ options[:output_config] = { effort: effort } if %w[low medium high max].include?(effort)
options
end
diff --git a/plugins/discourse-ai/lib/completions/endpoints/anthropic_shared.rb b/plugins/discourse-ai/lib/completions/endpoints/anthropic_shared.rb
index 2bda2a4fb7b..d85c965a59e 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/anthropic_shared.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/anthropic_shared.rb
@@ -6,8 +6,21 @@ module DiscourseAi
module AnthropicShared
def normalize_model_params(model_params)
model_params = model_params.dup
- model_params.delete(:top_p) if llm_model.lookup_custom_param("disable_top_p")
- model_params.delete(:temperature) if llm_model.lookup_custom_param("disable_temperature")
+
+ thinking_enabled =
+ llm_model.lookup_custom_param("adaptive_thinking") ||
+ llm_model.lookup_custom_param("enable_reasoning")
+
+ if thinking_enabled
+ model_params.delete(:temperature)
+ model_params.delete(:top_p)
+ else
+ model_params.delete(:top_p) if llm_model.lookup_custom_param("disable_top_p")
+ if llm_model.lookup_custom_param("disable_temperature")
+ model_params.delete(:temperature)
+ end
+ end
+
model_params
end
@@ -77,10 +90,6 @@ module DiscourseAi
payload[:system] = prompt.system_prompt if prompt.system_prompt.present? &&
!payload[:system]
- if dialect.tool_choice == :none && prompt.has_tools?
- apply_tool_choice_none(payload, dialect)
- end
-
if model_params[:response_format].present?
response_format = model_params[:response_format].deep_symbolize_keys
if supports_native_structured_output?
@@ -102,14 +111,32 @@ module DiscourseAi
return if dialect.tool_choice.blank?
if dialect.tool_choice == :none
payload[:tool_choice] = { type: "none" }
+ elsif thinking_enabled?(payload)
+ inject_force_tool_guidance(payload, prompt.tool_choice)
else
payload[:tool_choice] = { type: "tool", name: prompt.tool_choice }
end
end
- def apply_tool_choice_none(payload, dialect)
- # No-op for Anthropic API (uses native tool_choice: {type: "none"})
- # Bedrock overrides this to inject a user message workaround
+ def thinking_enabled?(payload)
+ thinking = payload[:thinking]
+ thinking.present? && %w[enabled adaptive].include?(thinking[:type].to_s)
+ end
+
+ def inject_force_tool_guidance(payload, tool_name)
+ guidance =
+ "Important: You must respond by calling the '#{tool_name}' tool immediately. " \
+ "Do not respond with text."
+ last_msg = payload[:messages]&.last
+ if last_msg && last_msg[:role] == "user"
+ if last_msg[:content].is_a?(String)
+ last_msg[:content] = last_msg[:content] + "\n\n#{guidance}"
+ elsif last_msg[:content].is_a?(Array)
+ last_msg[:content] << { type: "text", text: guidance }
+ end
+ else
+ payload[:messages] << { role: "user", content: guidance }
+ end
end
end
end
diff --git a/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rb b/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rb
index 7a33ea33be7..0416895d9ed 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rb
@@ -21,7 +21,10 @@ module DiscourseAi
max_tokens = 8192 if bedrock_model_id.match?(/3.[57]/)
result = { anthropic_version: "bedrock-2023-05-31" }
- if llm_model.lookup_custom_param("enable_reasoning")
+ if llm_model.lookup_custom_param("adaptive_thinking")
+ max_tokens = 32_000
+ result[:thinking] = { type: "adaptive" }
+ elsif llm_model.lookup_custom_param("enable_reasoning")
# we require special headers to go over 64k output tokens, lets
# wait for feature requests before enabling this
reasoning_tokens =
@@ -35,7 +38,9 @@ module DiscourseAi
# effort parameter
effort = llm_model.lookup_custom_param("effort")
- result[:output_config] = { effort: effort } if %w[low medium high].include?(effort)
+ result[:output_config] = { effort: effort } if %w[low medium high max].include?(
+ effort,
+ )
result
else
@@ -115,19 +120,6 @@ module DiscourseAi
end
end
- def apply_tool_choice(payload, dialect, prompt)
- return if dialect.tool_choice.blank?
- if dialect.tool_choice != :none
- payload[:tool_choice] = { type: "tool", name: prompt.tool_choice }
- end
- # tool_choice: {type: "none"} not supported on Bedrock — handled by apply_tool_choice_none
- end
-
- def apply_tool_choice_none(payload, dialect)
- no_tool_text = dialect.no_more_tool_calls_text_user
- payload[:messages] << { role: "user", content: no_tool_text } if no_tool_text.present?
- end
-
def prepare_request(payload)
headers = { "content-type" => "application/json", "Accept" => "*/*" }
region = llm_model.lookup_custom_param("region")
diff --git a/plugins/discourse-ai/lib/completions/endpoints/gemini.rb b/plugins/discourse-ai/lib/completions/endpoints/gemini.rb
index 05b988ab8c5..6f568f3c400 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/gemini.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/gemini.rb
@@ -33,7 +33,16 @@ module DiscourseAi
model_params[:topP] = model_params.delete(:top_p) if model_params[:top_p]
- model_params.delete(:temperature) if llm_model.lookup_custom_param("disable_temperature")
+ thinking_enabled =
+ %w[minimal low medium high].include?(llm_model.lookup_custom_param("thinking_level")) ||
+ llm_model.lookup_custom_param("enable_thinking")
+
+ if thinking_enabled
+ model_params.delete(:temperature)
+ elsif llm_model.lookup_custom_param("disable_temperature")
+ model_params.delete(:temperature)
+ end
+
model_params.delete(:topP) if llm_model.lookup_custom_param("disable_top_p")
model_params
@@ -101,7 +110,10 @@ module DiscourseAi
end
end
- if llm_model.lookup_custom_param("enable_thinking")
+ thinking_level = llm_model.lookup_custom_param("thinking_level")
+ if %w[minimal low medium high].include?(thinking_level)
+ payload[:generationConfig][:thinkingConfig] = { thinkingLevel: thinking_level }
+ elsif llm_model.lookup_custom_param("enable_thinking")
thinking_tokens = llm_model.lookup_custom_param("thinking_tokens").to_i
thinking_tokens = thinking_tokens.clamp(0, 24_576)
payload[:generationConfig][:thinkingConfig] = { thinkingBudget: thinking_tokens }
diff --git a/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb b/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb
index db062bb3487..175cfd076b8 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb
@@ -25,8 +25,15 @@ module DiscourseAi
model_params[:stop] = model_params.delete(:stop_sequences)
end
- model_params.delete(:top_p) if llm_model.lookup_custom_param("disable_top_p")
- model_params.delete(:temperature) if llm_model.lookup_custom_param("disable_temperature")
+ if reasoning_effort
+ model_params.delete(:temperature)
+ model_params.delete(:top_p)
+ else
+ model_params.delete(:top_p) if llm_model.lookup_custom_param("disable_top_p")
+ if llm_model.lookup_custom_param("disable_temperature")
+ model_params.delete(:temperature)
+ end
+ end
model_params
end
@@ -63,7 +70,9 @@ module DiscourseAi
def reasoning_effort
return @reasoning_effort if defined?(@reasoning_effort)
@reasoning_effort = llm_model.lookup_custom_param("reasoning_effort")
- @reasoning_effort = nil if !%w[minimal low medium high].include?(@reasoning_effort)
+ @reasoning_effort = nil if !%w[none minimal low medium high xhigh].include?(
+ @reasoning_effort,
+ )
@reasoning_effort
end
diff --git a/plugins/discourse-ai/lib/completions/endpoints/open_ai_responses.rb b/plugins/discourse-ai/lib/completions/endpoints/open_ai_responses.rb
index cfed7749f4e..cb3c3dc47f6 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/open_ai_responses.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/open_ai_responses.rb
@@ -16,8 +16,15 @@ module DiscourseAi
model_params[:stop] = model_params.delete(:stop_sequences)
end
- model_params.delete(:top_p) if llm_model.lookup_custom_param("disable_top_p")
- model_params.delete(:temperature) if llm_model.lookup_custom_param("disable_temperature")
+ if reasoning_effort
+ model_params.delete(:temperature)
+ model_params.delete(:top_p)
+ else
+ model_params.delete(:top_p) if llm_model.lookup_custom_param("disable_top_p")
+ if llm_model.lookup_custom_param("disable_temperature")
+ model_params.delete(:temperature)
+ end
+ end
model_params
end
@@ -54,7 +61,9 @@ module DiscourseAi
def reasoning_effort
return @reasoning_effort if defined?(@reasoning_effort)
@reasoning_effort = llm_model.lookup_custom_param("reasoning_effort")
- @reasoning_effort = nil if !%w[minimal low medium high].include?(@reasoning_effort)
+ @reasoning_effort = nil if !%w[none minimal low medium high xhigh].include?(
+ @reasoning_effort,
+ )
@reasoning_effort
end
diff --git a/plugins/discourse-ai/lib/completions/endpoints/vllm.rb b/plugins/discourse-ai/lib/completions/endpoints/vllm.rb
index 2c6221e6ec6..40e8680bdd5 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/vllm.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/vllm.rb
@@ -3,50 +3,81 @@
module DiscourseAi
module Completions
module Endpoints
- class Vllm < Base
+ class Vllm < OpenAi
def self.can_contact?(llm_model)
llm_model.provider == "vllm"
end
- def normalize_model_params(model_params)
- model_params = model_params.dup
+ def provider_id
+ AiApiAuditLog::Provider::Vllm
+ end
+
+ def decode(response_raw)
+ parsed = JSON.parse(response_raw, symbolize_names: true)
+ result = processor.process_message(parsed)
- # max_tokens, temperature are already supported
- if model_params[:stop_sequences]
- model_params[:stop] = model_params.delete(:stop_sequences)
+ if output_thinking
+ reasoning = parsed.dig(:choices, 0, :message, :reasoning_content)
+ result.unshift(Thinking.new(message: reasoning)) if reasoning.present?
end
- model_params
+ result
end
- def default_options
- { max_tokens: 2000, model: llm_model.name }
- end
+ def decode_chunk(chunk)
+ @decoder ||= JsonStreamDecoder.new
+
+ elements = []
+ (@decoder << chunk).each do |parsed_json|
+ if output_thinking
+ reasoning = parsed_json.dig(:choices, 0, :delta, :reasoning_content)
+ if reasoning.present?
+ if @thinking.nil?
+ @thinking = Thinking.new(message: reasoning.dup, partial: true)
+ else
+ @thinking.message << reasoning
+ end
+ elements << Thinking.new(message: reasoning, partial: true)
+ elsif @thinking
+ @thinking.partial = false
+ elements << @thinking
+ @thinking = nil
+ end
+ end
- def provider_id
- AiApiAuditLog::Provider::Vllm
- end
+ result = processor.process_streamed_message(parsed_json)
+ elements << result if result
+ end
- private
+ elements = elements.flatten.compact
- def model_uri
- if llm_model.url.to_s.starts_with?("srv://")
- service = DiscourseAi::Utils::DnsSrv.lookup(llm_model.url.sub("srv://", ""))
- api_endpoint = "https://#{service.target}:#{service.port}/v1/chat/completions"
- else
- api_endpoint = llm_model.url
- end
+ seen_tools = Set.new
+ elements.select { |item| !item.is_a?(ToolCall) || seen_tools.add?(item) }
+ end
- @uri ||= URI(api_endpoint)
+ def decode_chunk_finish
+ result = []
+ if @thinking
+ @thinking.partial = false
+ result << @thinking
+ @thinking = nil
+ end
+ result.concat(processor.finish)
end
+ private
+
def prepare_payload(prompt, model_params, dialect)
- payload = default_options.merge(model_params).merge(messages: prompt)
- if @streaming_mode
- payload[:stream] = true if @streaming_mode
+ payload = super
+
+ if @streaming_mode && !payload.key?(:stream_options)
payload[:stream_options] = { include_usage: true }
end
+ if llm_model.lookup_custom_param("enable_thinking")
+ payload[:chat_template_kwargs] = { enable_thinking: true }
+ end
+
payload
end
@@ -58,44 +89,6 @@ module DiscourseAi
Net::HTTP::Post.new(model_uri, headers).tap { |r| r.body = payload }
end
-
- def xml_tools_enabled?
- true
- end
-
- def final_log_update(log)
- log.request_tokens = @prompt_tokens if @prompt_tokens
- log.response_tokens = @completion_tokens if @completion_tokens
- end
-
- def decode(response_raw)
- json = JSON.parse(response_raw, symbolize_names: true)
- @prompt_tokens = json.dig(:usage, :prompt_tokens)
- @completion_tokens = json.dig(:usage, :completion_tokens)
- [json.dig(:choices, 0, :message, :content)]
- end
-
- def decode_chunk(chunk)
- @json_decoder ||= JsonStreamDecoder.new
- (@json_decoder << chunk)
- .map do |parsed|
- # vLLM keeps sending usage over and over again
- prompt_tokens = parsed.dig(:usage, :prompt_tokens)
- completion_tokens = parsed.dig(:usage, :completion_tokens)
-
- @prompt_tokens = prompt_tokens if prompt_tokens
-
- @completion_tokens = completion_tokens if completion_tokens
-
- text = parsed.dig(:choices, 0, :delta, :content)
- if text.to_s.empty?
- nil
- else
- text
- end
- end
- .compact
- end
end
end
end
diff --git a/plugins/discourse-ai/lib/completions/open_ai_message_processor.rb b/plugins/discourse-ai/lib/completions/open_ai_message_processor.rb
index bd733246129..15a9e5ac8f8 100644
--- a/plugins/discourse-ai/lib/completions/open_ai_message_processor.rb
+++ b/plugins/discourse-ai/lib/completions/open_ai_message_processor.rb
@@ -130,9 +130,9 @@ module DiscourseAi::Completions
prompt_tokens = usage[:prompt_tokens].to_i
completion_tokens = usage[:completion_tokens].to_i
- @prompt_tokens ||= prompt_tokens - cached_tokens
- @completion_tokens ||= completion_tokens if completion_tokens.positive?
- @cache_read_tokens ||= cached_tokens
+ @prompt_tokens = prompt_tokens - cached_tokens
+ @completion_tokens = completion_tokens if completion_tokens.positive?
+ @cache_read_tokens = cached_tokens
end
end
end
diff --git a/plugins/discourse-ai/lib/configuration/llm_validator.rb b/plugins/discourse-ai/lib/configuration/llm_validator.rb
index daa8c138bbb..34db3a94b0b 100644
--- a/plugins/discourse-ai/lib/configuration/llm_validator.rb
+++ b/plugins/discourse-ai/lib/configuration/llm_validator.rb
@@ -37,6 +37,8 @@ module DiscourseAi
"How much is 1 + 1?",
user: @opts[:user] || Discourse.system_user,
feature_name: "llm_validator",
+ temperature: 0.7,
+ top_p: 0.9,
)
.present?
end
diff --git a/plugins/discourse-ai/lib/personas/tools/github_file_content.rb b/plugins/discourse-ai/lib/personas/tools/github_file_content.rb
index 3360e597b6a..8a35da827ee 100644
--- a/plugins/discourse-ai/lib/personas/tools/github_file_content.rb
+++ b/plugins/discourse-ai/lib/personas/tools/github_file_content.rb
@@ -90,7 +90,7 @@ module DiscourseAi
if response_code == "200"
file_data = JSON.parse(body)
- content = Base64.decode64(file_data["content"])
+ content = ensure_utf8(Base64.decode64(file_data["content"].to_s))
snippet =
extract_requested_content(
content,
@@ -121,6 +121,7 @@ module DiscourseAi
"#{label}:\n#{entry[:content]}"
end
.join("\n")
+ blob = ensure_utf8(blob)
truncated_blob = truncate(blob, max_length: 20_000, percent_length: 0.3, llm: llm)
result[:file_contents] = truncated_blob
end
@@ -195,6 +196,16 @@ module DiscourseAi
"#{start_line}-#{end_line}"
end
+
+ def ensure_utf8(text)
+ return "" if text.nil?
+
+ result = text.dup
+ result.force_encoding(Encoding::UTF_8)
+ return result if result.valid_encoding?
+
+ result.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "")
+ end
end
end
end
diff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb
index 1681f114f0e..0789d6ed6e2 100644
--- a/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb
@@ -503,6 +503,68 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic do
expect(log.response_tokens).to eq(25)
end
+ it "strips temperature and top_p when reasoning is enabled" do
+ model.update!(provider_params: { enable_reasoning: true, reasoning_tokens: 2048 })
+
+ parsed_body = nil
+ stub_request(:post, url).with(
+ body:
+ proc do |req_body|
+ parsed_body = JSON.parse(req_body, symbolize_names: true)
+ true
+ end,
+ ).to_return(
+ status: 200,
+ body: {
+ id: "msg_123",
+ type: "message",
+ role: "assistant",
+ content: [{ type: "text", text: "response" }],
+ model: "claude-3-opus-20240229",
+ usage: {
+ input_tokens: 10,
+ output_tokens: 5,
+ },
+ }.to_json,
+ )
+
+ llm.generate(prompt, user: Discourse.system_user, temperature: 0.7, top_p: 0.9)
+
+ expect(parsed_body).not_to have_key(:temperature)
+ expect(parsed_body).not_to have_key(:top_p)
+ end
+
+ it "strips temperature and top_p when adaptive thinking is enabled" do
+ model.update!(provider_params: { enable_reasoning: true, adaptive_thinking: true })
+
+ parsed_body = nil
+ stub_request(:post, url).with(
+ body:
+ proc do |req_body|
+ parsed_body = JSON.parse(req_body, symbolize_names: true)
+ true
+ end,
+ ).to_return(
+ status: 200,
+ body: {
+ id: "msg_123",
+ type: "message",
+ role: "assistant",
+ content: [{ type: "text", text: "response" }],
+ model: "claude-3-opus-20240229",
+ usage: {
+ input_tokens: 10,
+ output_tokens: 5,
+ },
+ }.to_json,
+ )
+
+ llm.generate(prompt, user: Discourse.system_user, temperature: 0.7, top_p: 0.9)
+
+ expect(parsed_body).not_to have_key(:temperature)
+ expect(parsed_body).not_to have_key(:top_p)
+ end
+
it "can operate in regular mode" do
body = <<~STRING
{
@@ -1247,6 +1309,121 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic do
# Verify that tool_choice: "echo" is present
expect(parsed_body.dig(:tool_choice, :name)).to eq("echo")
end
+
+ it "skips tool_choice and injects guidance when thinking is enabled" do
+ model.update!(provider_params: { enable_reasoning: true, adaptive_thinking: true })
+
+ prompt =
+ DiscourseAi::Completions::Prompt.new(
+ "You are a bot",
+ messages: [type: :user, id: "user1", content: "echo hello"],
+ tools: [echo_tool],
+ tool_choice: "echo",
+ )
+
+ response_body = {
+ id: "msg_01RdJkxCbsEj9VFyFYAkfy2S",
+ type: "message",
+ role: "assistant",
+ model: "claude-3-haiku-20240307",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_bdrk_014CMjxtGmKUtGoEFPgc7PF7",
+ name: "echo",
+ input: {
+ text: "hello",
+ },
+ },
+ ],
+ stop_reason: "end_turn",
+ stop_sequence: nil,
+ usage: {
+ input_tokens: 345,
+ output_tokens: 65,
+ },
+ }.to_json
+
+ parsed_body = nil
+ stub_request(:post, url).with(
+ body:
+ proc do |req_body|
+ parsed_body = JSON.parse(req_body, symbolize_names: true)
+ true
+ end,
+ ).to_return(status: 200, body: response_body)
+
+ llm.generate(prompt, user: Discourse.system_user)
+
+ expect(parsed_body).not_to have_key(:tool_choice)
+ last_message = parsed_body[:messages].last
+ expect(last_message[:role]).to eq("user")
+ expect(last_message[:content]).to include("'echo' tool")
+ end
+
+ it "appends guidance as a text block when last user message has array content" do
+ model.update!(provider_params: { enable_reasoning: true, adaptive_thinking: true })
+
+ prompt =
+ DiscourseAi::Completions::Prompt.new(
+ "You are a bot",
+ messages: [
+ { type: :user, id: "user1", content: "echo hello" },
+ {
+ type: :tool_call,
+ id: "call_1",
+ name: "echo",
+ content: { arguments: { text: "hello" } }.to_json,
+ },
+ { type: :tool, id: "call_1", name: "echo", content: "hello" },
+ ],
+ tools: [echo_tool],
+ tool_choice: "echo",
+ )
+
+ response_body = {
+ id: "msg_01RdJkxCbsEj9VFyFYAkfy2S",
+ type: "message",
+ role: "assistant",
+ model: "claude-3-haiku-20240307",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_014CMjxtGmKUtGoEFPgc7PF7",
+ name: "echo",
+ input: {
+ text: "hello again",
+ },
+ },
+ ],
+ stop_reason: "end_turn",
+ stop_sequence: nil,
+ usage: {
+ input_tokens: 345,
+ output_tokens: 65,
+ },
+ }.to_json
+
+ parsed_body = nil
+ stub_request(:post, url).with(
+ body:
+ proc do |req_body|
+ parsed_body = JSON.parse(req_body, symbolize_names: true)
+ true
+ end,
+ ).to_return(status: 200, body: response_body)
+
+ llm.generate(prompt, user: Discourse.system_user)
+
+ expect(parsed_body).not_to have_key(:tool_choice)
+ last_message = parsed_body[:messages].last
+ expect(last_message[:role]).to eq("user")
+ expect(last_message[:content]).to be_an(Array)
+ expect(last_message[:content].first[:type]).to eq("tool_result")
+ guidance_block = last_message[:content].last
+ expect(guidance_block[:type]).to eq("text")
+ expect(guidance_block[:text]).to include("'echo' tool")
+ end
end
describe "structured output via output_config" do
@@ -1433,7 +1610,114 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic do
end
end
+ describe "adaptive thinking" do
+ it "sends adaptive thinking config when enabled" do
+ model.update!(provider_params: { enable_reasoning: true, adaptive_thinking: true })
+
+ parsed_body = nil
+ stub_request(:post, url).with(
+ body:
+ proc do |req_body|
+ parsed_body = JSON.parse(req_body, symbolize_names: true)
+ true
+ end,
+ headers: {
+ "Content-Type" => "application/json",
+ "X-Api-Key" => "123",
+ "Anthropic-Version" => "2023-06-01",
+ },
+ ).to_return(
+ status: 200,
+ body: {
+ id: "msg_123",
+ type: "message",
+ role: "assistant",
+ content: [{ type: "text", text: "test response" }],
+ model: "claude-3-opus-20240229",
+ usage: {
+ input_tokens: 10,
+ output_tokens: 5,
+ },
+ }.to_json,
+ )
+
+ llm.generate(prompt, user: Discourse.system_user)
+ expect(parsed_body[:thinking]).to eq({ type: "adaptive" })
+ expect(parsed_body[:max_tokens]).to eq(32_000)
+ end
+
+ it "adaptive_thinking takes priority over enable_reasoning" do
+ model.update!(
+ provider_params: {
+ adaptive_thinking: true,
+ enable_reasoning: true,
+ reasoning_tokens: 10_000,
+ },
+ )
+
+ parsed_body = nil
+ stub_request(:post, url).with(
+ body:
+ proc do |req_body|
+ parsed_body = JSON.parse(req_body, symbolize_names: true)
+ true
+ end,
+ ).to_return(
+ status: 200,
+ body: {
+ id: "msg_123",
+ type: "message",
+ role: "assistant",
+ content: [{ type: "text", text: "test response" }],
+ model: "claude-3-opus-20240229",
+ usage: {
+ input_tokens: 10,
+ output_tokens: 5,
+ },
+ }.to_json,
+ )
+
+ llm.generate(prompt, user: Discourse.system_user)
+ expect(parsed_body[:thinking]).to eq({ type: "adaptive" })
+ expect(parsed_body[:max_tokens]).to eq(32_000)
+ end
+ end
+
describe "effort parameter" do
+ it "includes effort in output_config when set to max" do
+ model.update!(provider_params: { effort: "max" })
+
+ parsed_body = nil
+ stub_request(:post, url).with(
+ body:
+ proc do |req_body|
+ parsed_body = JSON.parse(req_body, symbolize_names: true)
+ true
+ end,
+ headers: {
+ "Content-Type" => "application/json",
+ "X-Api-Key" => "123",
+ "Anthropic-Version" => "2023-06-01",
+ },
+ ).to_return(
+ status: 200,
+ body: {
+ id: "msg_123",
+ type: "message",
+ role: "assistant",
+ content: [{ type: "text", text: "test response" }],
+ model: "claude-3-opus-20240229",
+ usage: {
+ input_tokens: 10,
+ output_tokens: 5,
+ },
+ }.to_json,
+ )
+
+ llm.generate(prompt, user: Discourse.system_user)
+ expect(parsed_body.dig(:output_config, :effort)).to eq("max")
+ end
+
it "includes effort in output_config when set to low, medium, or high" do
model.update!(provider_params: { effort: "high" })
diff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/aws_bedrock_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/aws_bedrock_spec.rb
index ae675c0ebff..0e51937e449 100644
--- a/plugins/discourse-ai/spec/lib/completions/endpoints/aws_bedrock_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/aws_bedrock_spec.rb
@@ -389,6 +389,44 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
expect(log.response_tokens).to eq(20)
end
+ it "strips temperature and top_p when reasoning is enabled" do
+ model.update!(
+ provider_params: {
+ access_key_id: "123",
+ region: "us-east-1",
+ enable_reasoning: true,
+ reasoning_tokens: 2048,
+ },
+ )
+
+ proxy = DiscourseAi::Completions::Llm.proxy(model)
+ request = nil
+
+ content = {
+ content: [text: "response"],
+ usage: {
+ input_tokens: 10,
+ output_tokens: 5,
+ },
+ }.to_json
+
+ stub_request(
+ :post,
+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-sonnet-20240229-v1:0/invoke",
+ )
+ .with do |inner_request|
+ request = inner_request
+ true
+ end
+ .to_return(status: 200, body: content)
+
+ proxy.generate("test prompt", user: user, temperature: 0.7, top_p: 0.9)
+
+ request_body = JSON.parse(request.body)
+ expect(request_body).not_to have_key("temperature")
+ expect(request_body).not_to have_key("top_p")
+ end
+
it "supports claude 3 streaming" do
proxy = DiscourseAi::Completions::Llm.proxy(model)
@@ -489,7 +527,7 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
end
describe "disabled tool use" do
- it "handles tool_choice: :none by adding a user message instead of using tool_choice param" do
+ it "sets tool_choice to none natively" do
proxy = DiscourseAi::Completions::Llm.proxy(model)
request = nil
@@ -527,26 +565,21 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
end
.to_return(status: 200, body: content)
- proxy.generate(prompt, user: user)
+ result = proxy.generate(prompt, user: user)
request_body = JSON.parse(request.body)
- expect(request_body).not_to have_key("tool_choice")
+ expect(request_body.dig("tool_choice", "type")).to eq("none")
messages = request_body["messages"]
- expect(messages.length).to eq(2)
-
- last_message = messages.last
- expect(last_message["role"]).to eq("user")
+ expect(messages.length).to eq(1)
- expect(last_message["content"]).to eq(
- DiscourseAi::Completions::Dialects::Dialect.no_more_tool_calls_text_user,
- )
+ expect(result).to eq("I won't use any tools. Here's a direct response instead.")
end
end
describe "tool_choice :none with response_format" do
- it "injects user message workaround and assistant prefill when structured output is disabled" do
+ it "sets tool_choice none and appends assistant prefill when structured output is disabled" do
model.update!(
provider_params: model.provider_params.merge("disable_native_structured_output" => true),
)
@@ -610,26 +643,19 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
request_body = JSON.parse(request.body)
- expect(request_body).not_to have_key("tool_choice")
+ expect(request_body.dig("tool_choice", "type")).to eq("none")
expect(request_body).not_to have_key("output_config")
messages = request_body["messages"]
- expect(messages.length).to eq(3)
+ expect(messages.length).to eq(2)
expect(messages[0]["role"]).to eq("user")
- expect(messages[1]["role"]).to eq("user")
- expect(messages[1]["content"]).to eq(
- DiscourseAi::Completions::Dialects::Dialect.no_more_tool_calls_text_user,
- )
- expect(messages[2]).to eq({ "role" => "assistant", "content" => "{" })
+ expect(messages[1]).to eq({ "role" => "assistant", "content" => "{" })
end
end
describe "forced tool use" do
- it "can properly force tool use" do
- proxy = DiscourseAi::Completions::Llm.proxy(model)
- request = nil
-
- tools = [
+ let(:tools) do
+ [
{
name: "echo",
description: "echo something",
@@ -638,17 +664,10 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
],
},
]
+ end
- prompt =
- DiscourseAi::Completions::Prompt.new(
- "You are a bot",
- messages: [type: :user, id: "user1", content: "echo hello"],
- tools: tools,
- tool_choice: "echo",
- )
-
- # Mock response from Bedrock
- content = {
+ let(:tool_response_body) do
+ {
content: [
{
type: "tool_use",
@@ -664,6 +683,19 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
output_tokens: 15,
},
}.to_json
+ end
+
+ it "can properly force tool use" do
+ proxy = DiscourseAi::Completions::Llm.proxy(model)
+ request = nil
+
+ prompt =
+ DiscourseAi::Completions::Prompt.new(
+ "You are a bot",
+ messages: [type: :user, id: "user1", content: "echo hello"],
+ tools: tools,
+ tool_choice: "echo",
+ )
stub_request(
:post,
@@ -673,16 +705,51 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
request = inner_request
true
end
- .to_return(status: 200, body: content)
+ .to_return(status: 200, body: tool_response_body)
proxy.generate(prompt, user: user)
- # Parse the request body
request_body = JSON.parse(request.body)
- # Verify that tool_choice: "echo" is present
expect(request_body.dig("tool_choice", "name")).to eq("echo")
end
+
+ it "skips tool_choice and injects guidance when thinking is enabled" do
+ model.update!(
+ provider_params:
+ model.provider_params.merge("enable_reasoning" => true, "adaptive_thinking" => true),
+ )
+
+ proxy = DiscourseAi::Completions::Llm.proxy(model)
+ request = nil
+
+ prompt =
+ DiscourseAi::Completions::Prompt.new(
+ "You are a bot",
+ messages: [type: :user, id: "user1", content: "echo hello"],
+ tools: tools,
+ tool_choice: "echo",
+ )
+
+ stub_request(
+ :post,
+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-sonnet-20240229-v1:0/invoke",
+ )
+ .with do |inner_request|
+ request = inner_request
+ true
+ end
+ .to_return(status: 200, body: tool_response_body)
+
+ proxy.generate(prompt, user: user)
+
+ request_body = JSON.parse(request.body)
+
+ expect(request_body).not_to have_key("tool_choice")
+ last_message = request_body["messages"].last
+ expect(last_message["role"]).to eq("user")
+ expect(last_message["content"]).to include("'echo' tool")
+ end
end
describe "role-based authentication" do
@@ -1265,7 +1332,116 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
end
end
+ describe "adaptive thinking" do
+ it "sends adaptive thinking config when enabled" do
+ model.update!(
+ provider_params: {
+ access_key_id: "123",
+ region: "us-east-1",
+ enable_reasoning: true,
+ adaptive_thinking: true,
+ },
+ )
+
+ proxy = DiscourseAi::Completions::Llm.proxy(model)
+ request = nil
+
+ content = {
+ content: [text: "test response"],
+ usage: {
+ input_tokens: 10,
+ output_tokens: 5,
+ },
+ }.to_json
+
+ stub_request(
+ :post,
+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-sonnet-20240229-v1:0/invoke",
+ )
+ .with do |inner_request|
+ request = inner_request
+ true
+ end
+ .to_return(status: 200, body: content)
+
+ proxy.generate("test prompt", user: user)
+
+ request_body = JSON.parse(request.body)
+ expect(request_body["thinking"]).to eq({ "type" => "adaptive" })
+ expect(request_body["max_tokens"]).to eq(32_000)
+ end
+
+ it "adaptive_thinking takes priority over enable_reasoning" do
+ model.update!(
+ provider_params: {
+ access_key_id: "123",
+ region: "us-east-1",
+ enable_reasoning: true,
+ adaptive_thinking: true,
+ reasoning_tokens: 10_000,
+ },
+ )
+
+ proxy = DiscourseAi::Completions::Llm.proxy(model)
+ request = nil
+
+ content = {
+ content: [text: "test response"],
+ usage: {
+ input_tokens: 10,
+ output_tokens: 5,
+ },
+ }.to_json
+
+ stub_request(
+ :post,
+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-sonnet-20240229-v1:0/invoke",
+ )
+ .with do |inner_request|
+ request = inner_request
+ true
+ end
+ .to_return(status: 200, body: content)
+
+ proxy.generate("test prompt", user: user)
+
+ request_body = JSON.parse(request.body)
+ expect(request_body["thinking"]).to eq({ "type" => "adaptive" })
+ expect(request_body["max_tokens"]).to eq(32_000)
+ end
+ end
+
describe "effort parameter" do
+ it "includes effort in output_config when set to max" do
+ model.update!(provider_params: { access_key_id: "123", region: "us-east-1", effort: "max" })
+
+ proxy = DiscourseAi::Completions::Llm.proxy(model)
+ request = nil
+
+ content = {
+ content: [text: "test response"],
+ usage: {
+ input_tokens: 10,
+ output_tokens: 5,
+ },
+ }.to_json
+
+ stub_request(
+ :post,
+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-sonnet-20240229-v1:0/invoke",
+ )
+ .with do |inner_request|
+ request = inner_request
+ true
+ end
+ .to_return(status: 200, body: content)
+
+ proxy.generate("test prompt", user: user)
+
+ request_body = JSON.parse(request.body)
+ expect(request_body.dig("output_config", "effort")).to eq("max")
+ end
+
it "includes effort in output_config when set to low, medium, or high" do
model.update!(
provider_params: {
diff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/gemini_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/gemini_spec.rb
index b66132caa54..4720b7f5c8f 100644
--- a/plugins/discourse-ai/spec/lib/completions/endpoints/gemini_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/gemini_spec.rb
@@ -302,6 +302,127 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Gemini do
expect(parsed.dig(:generationConfig, :thinkingConfig)).to be_nil
end
+ it "correctly configures thinking level when set" do
+ model.update!(provider_params: { enable_thinking: true, thinking_level: "high" })
+
+ response = gemini_mock.response("Using thinking level").to_json
+ req_body = nil
+
+ llm = DiscourseAi::Completions::Llm.proxy(model)
+ url = "#{model.url}:generateContent?key=123"
+
+ stub_request(:post, url).with(
+ body:
+ proc do |_req_body|
+ req_body = _req_body
+ true
+ end,
+ ).to_return(status: 200, body: response)
+
+ response = llm.generate("Hello", user: user)
+ parsed = JSON.parse(req_body, symbolize_names: true)
+
+ expect(parsed.dig(:generationConfig, :thinkingConfig)).to eq({ thinkingLevel: "high" })
+ end
+
+ it "thinking_level takes priority over enable_thinking" do
+ model.update!(
+ provider_params: {
+ enable_thinking: true,
+ thinking_level: "medium",
+ thinking_tokens: "10000",
+ },
+ )
+
+ response = gemini_mock.response("Thinking level priority").to_json
+ req_body = nil
+
+ llm = DiscourseAi::Completions::Llm.proxy(model)
+ url = "#{model.url}:generateContent?key=123"
+
+ stub_request(:post, url).with(
+ body:
+ proc do |_req_body|
+ req_body = _req_body
+ true
+ end,
+ ).to_return(status: 200, body: response)
+
+ response = llm.generate("Hello", user: user)
+ parsed = JSON.parse(req_body, symbolize_names: true)
+
+ expect(parsed.dig(:generationConfig, :thinkingConfig)).to eq({ thinkingLevel: "medium" })
+ end
+
+ it "does not add thinking config when thinking_level is default" do
+ model.update!(provider_params: { thinking_level: "default" })
+
+ response = gemini_mock.response("No thinking config").to_json
+ req_body = nil
+
+ llm = DiscourseAi::Completions::Llm.proxy(model)
+ url = "#{model.url}:generateContent?key=123"
+
+ stub_request(:post, url).with(
+ body:
+ proc do |_req_body|
+ req_body = _req_body
+ true
+ end,
+ ).to_return(status: 200, body: response)
+
+ response = llm.generate("Hello", user: user)
+ parsed = JSON.parse(req_body, symbolize_names: true)
+
+ expect(parsed.dig(:generationConfig, :thinkingConfig)).to be_nil
+ end
+
+ it "strips temperature when thinking_level is set" do
+ model.update!(provider_params: { enable_thinking: true, thinking_level: "high" })
+
+ response = gemini_mock.response("Stripped temp").to_json
+ req_body = nil
+
+ llm = DiscourseAi::Completions::Llm.proxy(model)
+ url = "#{model.url}:generateContent?key=123"
+
+ stub_request(:post, url).with(
+ body:
+ proc do |_req_body|
+ req_body = _req_body
+ true
+ end,
+ ).to_return(status: 200, body: response)
+
+ response = llm.generate("Hello", user: user, temperature: 0.5)
+ parsed = JSON.parse(req_body, symbolize_names: true)
+
+ expect(parsed.dig(:generationConfig, :temperature)).to be_nil
+ end
+
+ it "strips temperature when enable_thinking is set" do
+ model.update!(provider_params: { enable_thinking: "true", thinking_tokens: "10000" })
+
+ response = gemini_mock.response("Stripped temp").to_json
+ req_body = nil
+
+ llm = DiscourseAi::Completions::Llm.proxy(model)
+ url = "#{model.url}:generateContent?key=123"
+
+ stub_request(:post, url).with(
+ body:
+ proc do |_req_body|
+ req_body = _req_body
+ true
+ end,
+ ).to_return(status: 200, body: response)
+
+ response = llm.generate("Hello", user: user, temperature: 0.5)
+ parsed = JSON.parse(req_body, symbolize_names: true)
+
+ expect(parsed.dig(:generationConfig, :temperature)).to be_nil
+ end
+
# by default gemini is meant to use AUTO mode, however new experimental models
# appear to require this to be explicitly set
it "Explicitly specifies tool config" do
diff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_responses_api_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_responses_api_spec.rb
index 85ae77ac70c..b187c69d954 100644
--- a/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_responses_api_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_responses_api_spec.rb
@@ -343,6 +343,82 @@ data: {"type":"response.reasoning_summary_part.added","sequence_number":3,"item_
)
end
+ it "accepts xhigh as reasoning_effort for responses API" do
+ model.update!(provider_params: { reasoning_effort: "xhigh" })
+
+ parsed_body = nil
+ stub_request(:post, "https://api.openai.com/v1/responses").with(
+ body:
+ proc do |req_body|
+ parsed_body = JSON.parse(req_body, symbolize_names: true)
+ true
+ end,
+ ).to_return(status: 200, body: { output: [] }.to_json)
+
+ prompt =
+ DiscourseAi::Completions::Prompt.new(
+ "You are a bot",
+ messages: [type: :user, content: "hello"],
+ )
+
+ dialect = DiscourseAi::Completions::Dialects::OpenAiResponses.new(prompt, model)
+
+ endpoint.perform_completion!(dialect, Discourse.system_user)
+
+ expect(parsed_body[:reasoning]).to include(effort: "xhigh", summary: "auto")
+ end
+
+ it "accepts none as reasoning_effort for responses API" do
+ model.update!(provider_params: { reasoning_effort: "none" })
+
+ parsed_body = nil
+ stub_request(:post, "https://api.openai.com/v1/responses").with(
+ body:
+ proc do |req_body|
+ parsed_body = JSON.parse(req_body, symbolize_names: true)
+ true
+ end,
+ ).to_return(status: 200, body: { output: [] }.to_json)
+
+ prompt =
+ DiscourseAi::Completions::Prompt.new(
+ "You are a bot",
+ messages: [type: :user, content: "hello"],
+ )
+
+ dialect = DiscourseAi::Completions::Dialects::OpenAiResponses.new(prompt, model)
+
+ endpoint.perform_completion!(dialect, Discourse.system_user)
+
+ expect(parsed_body[:reasoning]).to include(effort: "none", summary: "auto")
+ end
+
+ it "strips temperature and top_p when reasoning_effort is set" do
+ model.update!(provider_params: { reasoning_effort: "high" })
+
+ parsed_body = nil
+ stub_request(:post, "https://api.openai.com/v1/responses").with(
+ body:
+ proc do |req_body|
+ parsed_body = JSON.parse(req_body, symbolize_names: true)
+ true
+ end,
+ ).to_return(status: 200, body: { output: [] }.to_json)
+
+ prompt =
+ DiscourseAi::Completions::Prompt.new(
+ "You are a bot",
+ messages: [type: :user, content: "hello"],
+ )
+
+ dialect = DiscourseAi::Completions::Dialects::OpenAiResponses.new(prompt, model)
+
+ endpoint.perform_completion!(dialect, Discourse.system_user, { temperature: 0.7, top_p: 0.9 })
+
+ expect(parsed_body).not_to have_key(:temperature)
+ expect(parsed_body).not_to have_key(:top_p)
+ end
+
it "uses reasoning object format for responses API" do
model.update!(provider_params: { reasoning_effort: "minimal" })
diff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_spec.rb
index 9ec268acd3c..ba7f55ee46a 100644
--- a/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_spec.rb
@@ -1129,6 +1129,59 @@ TEXT
expect(parsed_body).not_to have_key(:reasoning)
end
+ it "accepts none as reasoning_effort" do
+ model.update!(provider_params: { reasoning_effort: "none" })
+
+ parsed_body = nil
+ stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
+ body:
+ proc do |req_body|
+ parsed_body = JSON.parse(req_body, symbolize_names: true)
+ true
+ end,
+ ).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
+
+ endpoint.perform_completion!(dialect, user)
+
+ expect(parsed_body[:reasoning_effort]).to eq("none")
+ end
+
+ it "accepts xhigh as reasoning_effort" do
+ model.update!(provider_params: { reasoning_effort: "xhigh" })
+
+ parsed_body = nil
+ stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
+ body:
+ proc do |req_body|
+ parsed_body = JSON.parse(req_body, symbolize_names: true)
+ true
+ end,
+ ).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
+
+ endpoint.perform_completion!(dialect, user)
+
+ expect(parsed_body[:reasoning_effort]).to eq("xhigh")
+ end
+
+ it "strips temperature and top_p when reasoning_effort is set" do
+ model.update!(provider_params: { reasoning_effort: "low" })
+
+ parsed_body = nil
+ stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
+ body:
+ proc do |req_body|
+ parsed_body = JSON.parse(req_body, symbolize_names: true)
+ true
+ end,
+ ).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
+
+ endpoint.perform_completion!(dialect, user, { temperature: 0.7, top_p: 0.9 })
+
+ expect(parsed_body[:reasoning_effort]).to eq("low")
+ expect(parsed_body).not_to have_key(:temperature)
+ expect(parsed_body).not_to have_key(:top_p)
+ end
+
it "omits reasoning parameters when not configured" do
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
diff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/vllm_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/vllm_spec.rb
index d586864463e..f448fc44421 100644
--- a/plugins/discourse-ai/spec/lib/completions/endpoints/vllm_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/vllm_spec.rb
@@ -3,7 +3,14 @@
require_relative "endpoint_compliance"
class VllmMock < EndpointMock
- def response(content)
+ def response(content, tool_call: false)
+ message_content =
+ if tool_call
+ { tool_calls: [content] }
+ else
+ { content: content }
+ end
+
{
id: "cmpl-6sZfAb30Rnv9Q7ufzFwvQsMpjZh8S",
object: "chat.completion",
@@ -15,7 +22,7 @@ class VllmMock < EndpointMock
total_tokens: 499,
},
choices: [
- { message: { role: "assistant", content: content }, finish_reason: "stop", index: 0 },
+ { message: { role: "assistant" }.merge(message_content), finish_reason: "stop", index: 0 },
],
}
end
@@ -23,16 +30,25 @@ class VllmMock < EndpointMock
def stub_response(prompt, response_text, tool_call: false)
WebMock
.stub_request(:post, "https://test.dev/v1/chat/completions")
- .with(body: model.default_options.merge(messages: prompt).to_json)
- .to_return(status: 200, body: JSON.dump(response(response_text)))
+ .with(body: request_body(prompt, tool_call: tool_call))
+ .to_return(status: 200, body: JSON.dump(response(response_text, tool_call: tool_call)))
end
- def stream_line(delta, finish_reason: nil)
+ def stream_line(delta, finish_reason: nil, tool_call: false)
+ message_content =
+ if tool_call
+ { tool_calls: [delta] }
+ else
+ { content: delta }
+ end
+
+"data: " << {
id: "cmpl-#{SecureRandom.hex}",
+ object: "chat.completion.chunk",
created: 1_681_283_881,
model: "mistralai/Mixtral-8x7B-Instruct-v0.1",
- choices: [{ delta: { content: delta } }],
+ choices: [{ delta: message_content }],
+ finish_reason: finish_reason,
index: 0,
}.to_json
end
@@ -41,9 +57,9 @@ class VllmMock < EndpointMock
chunks =
deltas.each_with_index.map do |_, index|
if index == (deltas.length - 1)
- stream_line(deltas[index], finish_reason: "stop_sequence")
+ stream_line(deltas[index], finish_reason: "stop_sequence", tool_call: tool_call)
else
- stream_line(deltas[index])
+ stream_line(deltas[index], tool_call: tool_call)
end
end
@@ -51,15 +67,71 @@ class VllmMock < EndpointMock
WebMock
.stub_request(:post, "https://test.dev/v1/chat/completions")
- .with(
- body:
- model
- .default_options
- .merge(messages: prompt, stream: true, stream_options: { include_usage: true })
- .to_json,
- )
+ .with(body: request_body(prompt, stream: true, tool_call: tool_call))
.to_return(status: 200, body: chunks)
end
+
+ def tool_deltas
+ [
+ { id: tool_id, function: {} },
+ { id: tool_id, function: { name: "get_weather", arguments: "" } },
+ { id: tool_id, function: { arguments: "" } },
+ { id: tool_id, function: { arguments: "{" } },
+ { id: tool_id, function: { arguments: " \"location\": \"Sydney\"" } },
+ { id: tool_id, function: { arguments: " ,\"unit\": \"c\" }" } },
+ ]
+ end
+
+ def tool_response
+ {
+ id: tool_id,
+ function: {
+ name: "get_weather",
+ arguments: { location: "Sydney", unit: "c" }.to_json,
+ },
+ }
+ end
+
+ def tool_id
+ "tool_0"
+ end
+
+ def tool_payload
+ {
+ type: "function",
+ function: {
+ name: "get_weather",
+ description: "Get the weather in a city",
+ parameters: {
+ type: "object",
+ properties: {
+ location: {
+ type: "string",
+ description: "the city name",
+ },
+ unit: {
+ type: "string",
+ description: "the unit of measurement celcius c or fahrenheit f",
+ enum: %w[c f],
+ },
+ },
+ required: %w[location unit],
+ },
+ },
+ }
+ end
+
+ def request_body(prompt, stream: false, tool_call: false)
+ model
+ .default_options
+ .merge(messages: prompt)
+ .tap do |b|
+ b[:stream] = true if stream
+ b[:tools] = [tool_payload] if tool_call
+ b[:stream_options] = { include_usage: true } if stream
+ end
+ .to_json
+ end
end
RSpec.describe DiscourseAi::Completions::Endpoints::Vllm do
@@ -92,6 +164,8 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Vllm do
describe "tool support" do
it "is able to invoke XML tools correctly" do
+ llm_model.update!(provider_params: { "disable_native_tools" => true })
+
xml = <<~XML
<function_calls>
<invoke>
@@ -251,6 +325,167 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Vllm do
expect(log.response_tokens).to eq(26)
end
+ describe "enable_thinking" do
+ it "sends chat_template_kwargs when enable_thinking is set" do
+ llm_model.update!(provider_params: { "enable_thinking" => true })
+
+ stub =
+ stub_request(:post, "https://test.dev/v1/chat/completions").with(
+ body: hash_including("chat_template_kwargs" => { "enable_thinking" => true }),
+ ).to_return(
+ status: 200,
+ body: {
+ choices: [{ message: { role: "assistant", content: "hello" } }],
+ usage: {
+ prompt_tokens: 10,
+ completion_tokens: 5,
+ },
+ }.to_json,
+ )
+
+ llm.generate("say hello", user: Discourse.system_user)
+
+ expect(stub).to have_been_requested
+ end
+
+ it "does not send chat_template_kwargs when enable_thinking is not set" do
+ stub =
+ stub_request(:post, "https://test.dev/v1/chat/completions")
+ .with { |request| !JSON.parse(request.body).key?("chat_template_kwargs") }
+ .to_return(
+ status: 200,
+ body: {
+ choices: [{ message: { role: "assistant", content: "hello" } }],
+ usage: {
+ prompt_tokens: 10,
+ completion_tokens: 5,
+ },
+ }.to_json,
+ )
+
+ llm.generate("say hello", user: Discourse.system_user)
+
+ expect(stub).to have_been_requested
+ end
+ end
+
+ describe "stream_options" do
+ it "includes stream_options with include_usage in streaming mode" do
+ stub =
+ stub_request(:post, "https://test.dev/v1/chat/completions").with(
+ body: hash_including("stream_options" => { "include_usage" => true }),
+ ).to_return(
+ status: 200,
+ body:
+ +"data: #{({ choices: [{ delta: { content: "hello" } }] }).to_json}\n\ndata: [DONE]",
+ )
+
+ llm.generate("say hello", user: Discourse.system_user) { |_| }
+
+ expect(stub).to have_been_requested
+ end
+ end
+
+ describe "reasoning_content" do
+ it "returns Thinking and content for non-streaming response with output_thinking" do
+ body = {
+ choices: [
+ {
+ message: {
+ role: "assistant",
+ content: "The answer is 4.",
+ reasoning_content: "Let me think step by step: 2+2=4",
+ },
+ },
+ ],
+ usage: {
+ prompt_tokens: 10,
+ completion_tokens: 20,
+ },
+ }
+
+ stub_request(:post, "https://test.dev/v1/chat/completions").to_return(
+ status: 200,
+ body: body.to_json,
+ )
+
+ result = llm.generate("what is 2+2?", user: Discourse.system_user, output_thinking: true)
+
+ expect(result).to be_an(Array)
+ expect(result.length).to eq(2)
+
+ thinking = result[0]
+ expect(thinking).to be_a(DiscourseAi::Completions::Thinking)
+ expect(thinking.message).to eq("Let me think step by step: 2+2=4")
+ expect(thinking.partial?).to eq(false)
+
+ expect(result[1]).to eq("The answer is 4.")
+ end
+
+ it "omits Thinking when output_thinking is false" do
+ body = {
+ choices: [
+ {
+ message: {
+ role: "assistant",
+ content: "The answer is 4.",
+ reasoning_content: "Let me think step by step: 2+2=4",
+ },
+ },
+ ],
+ usage: {
+ prompt_tokens: 10,
+ completion_tokens: 20,
+ },
+ }
+
+ stub_request(:post, "https://test.dev/v1/chat/completions").to_return(
+ status: 200,
+ body: body.to_json,
+ )
+
+ result = llm.generate("what is 2+2?", user: Discourse.system_user)
+
+ expect(result).to eq("The answer is 4.")
+ end
+
+ it "streams Thinking partials followed by content" do
+ chunks = []
+
+ chunks << "data: #{({ choices: [{ delta: { role: "assistant", reasoning_content: "Let me " } }] }).to_json}\n\n"
+ chunks << "data: #{({ choices: [{ delta: { reasoning_content: "think." } }] }).to_json}\n\n"
+ chunks << "data: #{({ choices: [{ delta: { content: "The answer" } }] }).to_json}\n\n"
+ chunks << "data: #{({ choices: [{ delta: { content: " is 4." } }], usage: { prompt_tokens: 10, completion_tokens: 20 } }).to_json}\n\n"
+ chunks << "data: [DONE]\n\n"
+
+ stub_request(:post, "https://test.dev/v1/chat/completions").to_return(
+ status: 200,
+ body: chunks.join,
+ )
+
+ partials = []
+ llm.generate("what is 2+2?", user: Discourse.system_user, output_thinking: true) do |partial|
+ partials << partial
+ end
+
+ thinking_partials = partials.select { |p| p.is_a?(DiscourseAi::Completions::Thinking) }
+ text_partials = partials.select { |p| p.is_a?(String) }
+
+ expect(thinking_partials.length).to eq(3)
+
+ expect(thinking_partials[0].message).to eq("Let me ")
+ expect(thinking_partials[0].partial?).to eq(true)
+
+ expect(thinking_partials[1].message).to eq("think.")
+ expect(thinking_partials[1].partial?).to eq(true)
+
+ expect(thinking_partials[2].message).to eq("Let me think.")
+ expect(thinking_partials[2].partial?).to eq(false)
+
+ expect(text_partials.join).to eq("The answer is 4.")
+ end
+ end
+
describe "#perform_completion!" do
context "when using regular mode" do
context "with tools" do
diff --git a/plugins/discourse-ai/spec/lib/completions/prompt_messages_builder_spec.rb b/plugins/discourse-ai/spec/lib/completions/prompt_messages_builder_spec.rb
index 1513858dd29..75c1c248ce4 100644
--- a/plugins/discourse-ai/spec/lib/completions/prompt_messages_builder_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/prompt_messages_builder_spec.rb
@@ -440,7 +440,7 @@ describe DiscourseAi::Completions::PromptMessagesBuilder do
end
it "handles uploads correctly in topic style messages (and times)" do
- freeze_time 31.days.ago
+ freeze_time 32.days.ago
# Use Discourse's upload format in the post raw content
upload_markdown = "![test|658x372](#{image_upload1.short_url})"
@@ -457,7 +457,7 @@ describe DiscourseAi::Completions::PromptMessagesBuilder do
upload2_markdown = "![test|658x372](#{image_upload2.short_url})"
- freeze_time 31.days.from_now
+ freeze_time 32.days.from_now
post2_with_upload =
Fabricate(
@@ -533,7 +533,7 @@ describe DiscourseAi::Completions::PromptMessagesBuilder do
end
it "handles uploads correctly in topic style messages (and times)" do
- freeze_time 31.days.ago
+ freeze_time 32.days.ago
# Use Discourse's upload format in the post raw content
upload_markdown = "![test1|658x372](#{image_upload1.short_url})"
@@ -551,7 +551,7 @@ describe DiscourseAi::Completions::PromptMessagesBuilder do
long_title = "A" * 40
upload2_markdown = "![#{long_title}|658x372](#{image_upload2.short_url})"
- freeze_time 31.days.from_now
+ freeze_time 32.days.from_now
post2_with_upload =
Fabricate(
diff --git a/plugins/discourse-ai/spec/lib/personas/tools/github_file_content_spec.rb b/plugins/discourse-ai/spec/lib/personas/tools/github_file_content_spec.rb
index 9eb685a22b7..aea6e4c92c2 100644
--- a/plugins/discourse-ai/spec/lib/personas/tools/github_file_content_spec.rb
+++ b/plugins/discourse-ai/spec/lib/personas/tools/github_file_content_spec.rb
@@ -110,6 +110,64 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubFileContent do
end
end
+ context "when file content contains invalid UTF-8 bytes" do
+ let(:invalid_utf8_tool) do
+ described_class.new(
+ { repo_name: "discourse/discourse-ai", file_paths: ["lib/binary.dat"], branch: "main" },
+ bot_user: nil,
+ llm: llm,
+ )
+ end
+
+ before do
+ binary_payload = +"line1\nabc\xFF\xFEdef\nline3\n"
+ binary_payload.force_encoding(Encoding::ASCII_8BIT)
+
+ stub_request(
+ :get,
+ "https://api.github.com/repos/discourse/discourse-ai/contents/lib/binary.dat?ref=main",
+ ).to_return(status: 200, body: { content: Base64.strict_encode64(binary_payload) }.to_json)
+ end
+
+ it "normalizes content before truncating" do
+ result = nil
+
+ expect { result = invalid_utf8_tool.invoke }.not_to raise_error
+ expect(result[:file_contents]).to include("File Path: lib/binary.dat:")
+ expect(result[:file_contents]).to include("abcdef")
+ expect(result[:file_contents]).to be_valid_encoding
+ expect(result[:file_contents].encoding).to eq(Encoding::UTF_8)
+ end
+ end
+
+ context "when file content contains unicode characters" do
+ let(:unicode_tool) do
+ described_class.new(
+ { repo_name: "discourse/discourse-ai", file_paths: ["lib/unicode.txt"], branch: "main" },
+ bot_user: nil,
+ llm: llm,
+ )
+ end
+
+ before do
+ stub_request(
+ :get,
+ "https://api.github.com/repos/discourse/discourse-ai/contents/lib/unicode.txt?ref=main",
+ ).to_return(
+ status: 200,
+ body: { content: Base64.strict_encode64("bonjour é\nこんにちは\n") }.to_json,
+ )
+ end
+
+ it "preserves valid UTF-8 content" do
+ result = unicode_tool.invoke
+
+ expect(result[:file_contents]).to include("File Path: lib/unicode.txt:")
+ expect(result[:file_contents]).to include("bonjour é")
+ expect(result[:file_contents]).to include("こんにちは")
+ end
+ end
+
context "when repo_name is invalid" do
let(:invalid_tool) do
described_class.new(
diff --git a/plugins/discourse-ai/spec/requests/admin/ai_llms_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_llms_controller_spec.rb
index 80ea0c6700b..bef81bd6f0a 100644
--- a/plugins/discourse-ai/spec/requests/admin/ai_llms_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/admin/ai_llms_controller_spec.rb
@@ -141,6 +141,16 @@ RSpec.describe DiscourseAi::Admin::AiLlmsController do
expect(model.display_name).to eq(valid_attrs[:display_name])
end
+ it "stores cache_write_cost" do
+ attrs = valid_attrs.merge(cache_write_cost: 0.25)
+
+ post "/admin/plugins/discourse-ai/ai-llms.json", params: { ai_llm: attrs }
+
+ expect(response.status).to eq(201)
+ expect(LlmModel.last.cache_write_cost).to eq(0.25)
+ expect(response.parsed_body["ai_llm"]["cache_write_cost"]).to eq(0.25)
+ end
+
it "stores allowed_attachment_types" do
attrs = valid_attrs.merge(allowed_attachment_types: %w[pdf docx])
@@ -279,6 +289,45 @@ RSpec.describe DiscourseAi::Admin::AiLlmsController do
expect(response.status).to eq(201)
expect(created_model.lookup_custom_param("disable_system_prompt")).to eq(true)
end
+
+ it "casts hash-form checkbox fields to booleans" do
+ post "/admin/plugins/discourse-ai/ai-llms.json",
+ params: {
+ ai_llm:
+ valid_attrs.merge(
+ provider: "anthropic",
+ provider_params: {
+ enable_reasoning: "true",
+ adaptive_thinking: "false",
+ },
+ ),
+ }
+
+ expect(response.status).to eq(201)
+ created_model = LlmModel.last
+ expect(created_model.provider_params["enable_reasoning"]).to eq(true)
+ expect(created_model.provider_params["adaptive_thinking"]).to eq(false)
+ end
+
+ it "sanitizes dependent params when parent is inactive" do
+ post "/admin/plugins/discourse-ai/ai-llms.json",
+ params: {
+ ai_llm:
+ valid_attrs.merge(
+ provider: "anthropic",
+ provider_params: {
+ enable_reasoning: false,
+ adaptive_thinking: true,
+ reasoning_tokens: 10_000,
+ },
+ ),
+ }
+
+ expect(response.status).to eq(201)
+ created_model = LlmModel.last
+ expect(created_model.provider_params["adaptive_thinking"]).to be_nil
+ expect(created_model.provider_params["reasoning_tokens"]).to be_nil
+ end
end
end
diff --git a/plugins/discourse-ai/test/javascripts/unit/lib/llm-provider-param-helpers-test.js b/plugins/discourse-ai/test/javascripts/unit/lib/llm-provider-param-helpers-test.js
new file mode 100644
index 00000000000..d95d534ade6
--- /dev/null
+++ b/plugins/discourse-ai/test/javascripts/unit/lib/llm-provider-param-helpers-test.js
@@ -0,0 +1,304 @@
+import { module, test } from "qunit";
+import {
+ isParamActive,
+ isProviderParamHidden,
+ normalizeProviderParams,
+} from "discourse/plugins/discourse-ai/discourse/lib/llm-provider-param-helpers";
+
+module("Discourse AI | Unit | Lib | llm-provider-param-helpers", function () {
+ module("isParamActive", function () {
+ test("returns false for null, undefined, and false", function (assert) {
+ assert.false(isParamActive(null));
+ assert.false(isParamActive(undefined));
+ assert.false(isParamActive(false));
+ });
+
+ test("returns false for string 'false' and 'default'", function (assert) {
+ assert.false(isParamActive("false"));
+ assert.false(isParamActive("default"));
+ });
+
+ test("returns true for true and truthy strings", function (assert) {
+ assert.true(isParamActive(true));
+ assert.true(isParamActive("true"));
+ assert.true(isParamActive("high"));
+ assert.true(isParamActive("low"));
+ assert.true(isParamActive("always"));
+ });
+
+ test("returns true for numbers", function (assert) {
+ assert.true(isParamActive(1));
+ assert.true(isParamActive(16000));
+ assert.true(isParamActive(0));
+ });
+
+ test("returns false for empty string", function (assert) {
+ assert.false(isParamActive(""));
+ });
+ });
+
+ module("isProviderParamHidden", function () {
+ test("returns false when no depends_on or hidden_if", function (assert) {
+ assert.false(
+ isProviderParamHidden({ type: "checkbox" }, { some_field: true })
+ );
+ });
+
+ module("depends_on", function () {
+ test("hidden when single dependency is inactive", function (assert) {
+ assert.true(
+ isProviderParamHidden(
+ { type: "number", depends_on: "enable_reasoning" },
+ { enable_reasoning: false }
+ )
+ );
+ });
+
+ test("visible when single dependency is active", function (assert) {
+ assert.false(
+ isProviderParamHidden(
+ { type: "number", depends_on: "enable_reasoning" },
+ { enable_reasoning: true }
+ )
+ );
+ });
+
+ test("hidden when any dependency in array is inactive", function (assert) {
+ assert.true(
+ isProviderParamHidden(
+ { type: "checkbox", depends_on: ["parent_a", "parent_b"] },
+ { parent_a: true, parent_b: null }
+ )
+ );
+ });
+
+ test("visible when all dependencies in array are active", function (assert) {
+ assert.false(
+ isProviderParamHidden(
+ { type: "checkbox", depends_on: ["parent_a", "parent_b"] },
+ { parent_a: true, parent_b: "high" }
+ )
+ );
+ });
+
+ test("hidden when dependency is 'default'", function (assert) {
+ assert.true(
+ isProviderParamHidden(
+ { type: "number", depends_on: "thinking_level" },
+ { thinking_level: "default" }
+ )
+ );
+ });
+
+ test("hidden when dependency key is missing from data", function (assert) {
+ assert.true(
+ isProviderParamHidden(
+ { type: "number", depends_on: "enable_reasoning" },
+ {}
+ )
+ );
+ });
+ });
+
+ module("hidden_if", function () {
+ test("hidden when single condition is active", function (assert) {
+ assert.true(
+ isProviderParamHidden(
+ { type: "number", hidden_if: "adaptive_thinking" },
+ { adaptive_thinking: true }
+ )
+ );
+ });
+
+ test("visible when single condition is inactive", function (assert) {
+ assert.false(
+ isProviderParamHidden(
+ { type: "number", hidden_if: "adaptive_thinking" },
+ { adaptive_thinking: false }
+ )
+ );
+ });
+
+ test("hidden when any condition in array is active", function (assert) {
+ assert.true(
+ isProviderParamHidden(
+ {
+ type: "checkbox",
+ hidden_if: ["enable_reasoning", "adaptive_thinking"],
+ },
+ { enable_reasoning: false, adaptive_thinking: true }
+ )
+ );
+ });
+
+ test("visible when all conditions in array are inactive", function (assert) {
+ assert.false(
+ isProviderParamHidden(
+ {
+ type: "checkbox",
+ hidden_if: ["enable_reasoning", "adaptive_thinking"],
+ },
+ { enable_reasoning: false, adaptive_thinking: "default" }
+ )
+ );
+ });
+ });
+
+ module("depends_on + hidden_if combined", function () {
+ test("hidden when dependency is inactive (depends_on takes priority)", function (assert) {
+ assert.true(
+ isProviderParamHidden(
+ {
+ type: "number",
+ depends_on: "enable_reasoning",
+ hidden_if: "adaptive_thinking",
+ },
+ { enable_reasoning: false, adaptive_thinking: false }
+ )
+ );
+ });
+
+ test("hidden when hidden_if condition is active", function (assert) {
+ assert.true(
+ isProviderParamHidden(
+ {
+ type: "number",
+ depends_on: "enable_reasoning",
+ hidden_if: "adaptive_thinking",
+ },
+ { enable_reasoning: true, adaptive_thinking: true }
+ )
+ );
+ });
+
+ test("visible when dependency active and hidden_if inactive", function (assert) {
+ assert.false(
+ isProviderParamHidden(
+ {
+ type: "number",
+ depends_on: "enable_reasoning",
+ hidden_if: "adaptive_thinking",
+ },
+ { enable_reasoning: true, adaptive_thinking: false }
+ )
+ );
+ });
+ });
+ });
+
+ module("normalizeProviderParams", function () {
+ test("returns empty object for null/undefined input", function (assert) {
+ assert.deepEqual(normalizeProviderParams(null), {});
+ assert.deepEqual(normalizeProviderParams(undefined), {});
+ });
+
+ test("normalizes string shorthand to {type} object", function (assert) {
+ const result = normalizeProviderParams({
+ disable_native_tools: "checkbox",
+ disable_system_prompt: "checkbox",
+ });
+
+ assert.deepEqual(result.disable_native_tools, { type: "checkbox" });
+ assert.deepEqual(result.disable_system_prompt, { type: "checkbox" });
+ });
+
+ test("normalizes enum with values into id/name pairs", function (assert) {
+ const result = normalizeProviderParams({
+ effort: {
+ type: "enum",
+ values: ["default", "low", "medium", "high", "max"],
+ default: "default",
+ },
+ });
+
+ assert.strictEqual(result.effort.type, "enum");
+ assert.strictEqual(result.effort.default, "default");
+ assert.deepEqual(result.effort.values, [
+ { id: "default", name: "default" },
+ { id: "low", name: "low" },
+ { id: "medium", name: "medium" },
+ { id: "high", name: "high" },
+ { id: "max", name: "max" },
+ ]);
+ });
+
+ test("preserves depends_on and hidden_if metadata", function (assert) {
+ const result = normalizeProviderParams({
+ reasoning_tokens: {
+ type: "number",
+ depends_on: "enable_reasoning",
+ hidden_if: "adaptive_thinking",
+ },
+ });
+
+ assert.strictEqual(
+ result.reasoning_tokens.depends_on,
+ "enable_reasoning"
+ );
+ assert.strictEqual(
+ result.reasoning_tokens.hidden_if,
+ "adaptive_thinking"
+ );
+ });
+
+ test("preserves array form of hidden_if", function (assert) {
+ const result = normalizeProviderParams({
+ disable_temperature: {
+ type: "checkbox",
+ hidden_if: ["enable_reasoning", "adaptive_thinking"],
+ },
+ });
+
+ assert.deepEqual(result.disable_temperature.hidden_if, [
+ "enable_reasoning",
+ "adaptive_thinking",
+ ]);
+ });
+
+ test("defaults type to 'text' for objects without type", function (assert) {
+ const result = normalizeProviderParams({
+ some_field: { depends_on: "parent" },
+ });
+
+ assert.strictEqual(result.some_field.type, "text");
+ });
+
+ test("defaults values to empty array for non-enum", function (assert) {
+ const result = normalizeProviderParams({
+ some_field: { type: "number" },
+ });
+
+ assert.deepEqual(result.some_field.values, []);
+ });
+
+ test("handles mixed param types in a single provider", function (assert) {
+ const result = normalizeProviderParams({
+ enable_reasoning: "checkbox",
+ adaptive_thinking: {
+ type: "checkbox",
+ depends_on: "enable_reasoning",
+ },
+ reasoning_tokens: {
+ type: "number",
+ depends_on: "enable_reasoning",
+ hidden_if: "adaptive_thinking",
+ },
+ effort: {
+ type: "enum",
+ values: ["default", "low", "high"],
+ default: "default",
+ },
+ });
+
+ assert.strictEqual(result.enable_reasoning.type, "checkbox");
+ assert.strictEqual(result.adaptive_thinking.type, "checkbox");
+ assert.strictEqual(
+ result.adaptive_thinking.depends_on,
+ "enable_reasoning"
+ );
+ assert.strictEqual(result.reasoning_tokens.type, "number");
+ assert.strictEqual(result.effort.type, "enum");
+ assert.strictEqual(result.effort.values.length, 3);
+ });
+ });
+});