Skip to content

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

FEATURE: support thinking summary on responses API (#36013)

Same27f493995dc
diff --git a/lib/demon/sidekiq.rb b/lib/demon/sidekiq.rb
index 05b59e09a17..7b010d98fec 100644
--- a/lib/demon/sidekiq.rb
+++ b/lib/demon/sidekiq.rb
@@ -68,7 +68,10 @@ class Demon::Sidekiq < ::Demon::Base
@@last_sidekiq_rss_memory_check = Time.now.to_i
end
- DEFAULT_MAX_ALLOWED_SIDEKIQ_RSS_MEGABYTES = 500
+ # Given Discourse AI a steady state during streaming is closer
+ # to 700MB given tokenization overhead. Set the default a bit higher
+ # so only outliers get restarted.
+ DEFAULT_MAX_ALLOWED_SIDEKIQ_RSS_MEGABYTES = 1000
def self.max_allowed_sidekiq_rss_bytes
[ENV["UNICORN_SIDEKIQ_MAX_RSS"].to_i, DEFAULT_MAX_ALLOWED_SIDEKIQ_RSS_MEGABYTES].max.megabytes
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-personas/new.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-personas/new.js
index 826799e93b6..fed786d621d 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-personas/new.js
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-personas/new.js
@@ -11,7 +11,7 @@ export default class AdminPluginsShowDiscourseAiPersonasNew extends DiscourseRou
record.set("rag_chunk_overlap_tokens", 10);
record.set("rag_conversation_chunks", 10);
record.set("allow_personal_messages", true);
- record.set("tool_details", false);
+ record.set("show_thinking", false);
return record;
}
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_personas_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_personas_controller.rb
index e9fdef40de6..119e57f8d42 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_personas_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_personas_controller.rb
@@ -258,7 +258,7 @@ module DiscourseAi
:allow_chat_direct_messages,
:allow_topic_mentions,
:allow_personal_messages,
- :tool_details,
+ :show_thinking,
:forced_tool_count,
:force_default_llm,
allowed_group_ids: [],
@@ -355,7 +355,7 @@ module DiscourseAi
},
allow_personal_messages: {
},
- tool_details: {
+ show_thinking: {
type: :large_text,
},
forced_tool_count: {
diff --git a/plugins/discourse-ai/app/jobs/regular/stream_discover_reply.rb b/plugins/discourse-ai/app/jobs/regular/stream_discover_reply.rb
index da41f15b2cb..49e4a8895ca 100644
--- a/plugins/discourse-ai/app/jobs/regular/stream_discover_reply.rb
+++ b/plugins/discourse-ai/app/jobs/regular/stream_discover_reply.rb
@@ -36,7 +36,7 @@ module Jobs
context =
DiscourseAi::Personas::BotContext.new(
messages: [{ type: :user, content: query }],
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "discover",
)
diff --git a/plugins/discourse-ai/app/models/ai_persona.rb b/plugins/discourse-ai/app/models/ai_persona.rb
index 1a70426b409..5d7d98eefc7 100644
--- a/plugins/discourse-ai/app/models/ai_persona.rb
+++ b/plugins/discourse-ai/app/models/ai_persona.rb
@@ -3,6 +3,8 @@
class AiPersona < ActiveRecord::Base
# TODO remove this line 01-10-2025
self.ignored_columns = %i[default_llm question_consolidator_llm]
+ # TODO remove tool_details from ignored_columns 01-02-2026
+ self.ignored_columns += %i[tool_details]
# places a hard limit, so per site we cache a maximum of 500 classes
MAX_PERSONAS_PER_SITE = 500
@@ -206,7 +208,7 @@ class AiPersona < ActiveRecord::Base
name
description
allowed_group_ids
- tool_details
+ show_thinking
enabled
]
@@ -426,7 +428,7 @@ end
# rag_chunk_tokens :integer default(374), not null
# rag_chunk_overlap_tokens :integer default(10), not null
# rag_conversation_chunks :integer default(10), not null
-# tool_details :boolean default(TRUE), not null
+# show_thinking :boolean default(TRUE), not null
# tools :json not null
# forced_tool_count :integer default(-1), not null
# allow_chat_channel_mentions :boolean default(FALSE), not null
diff --git a/plugins/discourse-ai/app/serializers/localized_ai_persona_serializer.rb b/plugins/discourse-ai/app/serializers/localized_ai_persona_serializer.rb
index 90e14c0d563..7f3815d8af3 100644
--- a/plugins/discourse-ai/app/serializers/localized_ai_persona_serializer.rb
+++ b/plugins/discourse-ai/app/serializers/localized_ai_persona_serializer.rb
@@ -24,7 +24,7 @@ class LocalizedAiPersonaSerializer < ApplicationSerializer
:rag_conversation_chunks,
:rag_llm_model_id,
:question_consolidator_llm_id,
- :tool_details,
+ :show_thinking,
:forced_tool_count,
:allow_chat_channel_mentions,
:allow_chat_direct_messages,
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-persona.js b/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-persona.js
index 042bc786d0b..46f7cfc954e 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-persona.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-persona.js
@@ -27,7 +27,7 @@ const CREATE_ATTRIBUTES = [
"rag_llm_model_id",
"question_consolidator_llm_id",
"allow_chat",
- "tool_details",
+ "show_thinking",
"forced_tool_count",
"allow_personal_messages",
"allow_topic_mentions",
@@ -57,7 +57,7 @@ const SYSTEM_ATTRIBUTES = [
"rag_conversation_chunks",
"rag_llm_model_id",
"question_consolidator_llm_id",
- "tool_details",
+ "show_thinking",
"allow_personal_messages",
"allow_topic_mentions",
"allow_chat_channel_mentions",
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-persona-editor.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-persona-editor.gjs
index f409d5fc34f..6943758aea3 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-persona-editor.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-persona-editor.gjs
@@ -514,16 +514,6 @@ export default class PersonaEditor extends Component {
{{/if}}
{{#if (gt data.tools.length 0)}}
- <form.Field
- @name="tool_details"
- @title={{i18n "discourse_ai.ai_persona.tool_details"}}
- @tooltip={{i18n "discourse_ai.ai_persona.tool_details_help"}}
- @format="large"
- as |field|
- >
- <field.Checkbox />
- </form.Field>
-
<AiPersonaToolOptions
@form={{form}}
@data={{data}}
@@ -531,6 +521,16 @@ export default class PersonaEditor extends Component {
@allTools={{@personas.resultSetMeta.tools}}
/>
{{/if}}
+
+ <form.Field
+ @name="show_thinking"
+ @title={{i18n "discourse_ai.ai_persona.show_thinking"}}
+ @tooltip={{i18n "discourse_ai.ai_persona.show_thinking_help"}}
+ @format="large"
+ as |field|
+ >
+ <field.Checkbox />
+ </form.Field>
</form.Section>
{{#if this.siteSettings.ai_embeddings_enabled}}
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index eddb0eb7a12..4100011769c 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -468,8 +468,8 @@ en:
low: Low quality - cheapest (256x256)
medium: Medium quality (512x512)
high: High quality - slowest (1024x1024)
- tool_details: Show tool details
- tool_details_help: Will show end users details on which tools the language model has triggered.
+ show_thinking: Show thinking
+ show_thinking_help: Will show end users the internal thinking and tool calls of the language model.
mentionable: Allow mentions
mentionable_help: If enabled, users in allowed groups can mention this user in posts, the AI will respond as this persona.
user: User
diff --git a/plugins/discourse-ai/db/migrate/20251113040027_add_show_thinking_to_ai_personas.rb b/plugins/discourse-ai/db/migrate/20251113040027_add_show_thinking_to_ai_personas.rb
new file mode 100644
index 00000000000..4c594401f14
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20251113040027_add_show_thinking_to_ai_personas.rb
@@ -0,0 +1,12 @@
+# frozen_string_literal: true
+
+class AddShowThinkingToAiPersonas < ActiveRecord::Migration[7.1]
+ def change
+ add_column :ai_personas, :show_thinking, :boolean, default: true, null: false
+
+ execute <<~SQL
+ UPDATE ai_personas
+ SET show_thinking = tool_details
+ SQL
+ end
+end
diff --git a/plugins/discourse-ai/db/post_migrate/20251113040028_migrate_tool_details_to_show_thinking.rb b/plugins/discourse-ai/db/post_migrate/20251113040028_migrate_tool_details_to_show_thinking.rb
new file mode 100644
index 00000000000..53573d5635e
--- /dev/null
+++ b/plugins/discourse-ai/db/post_migrate/20251113040028_migrate_tool_details_to_show_thinking.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+class MigrateToolDetailsToShowThinking < ActiveRecord::Migration[7.1]
+ def up
+ execute <<~SQL
+ UPDATE ai_personas
+ SET show_thinking = tool_details
+ WHERE show_thinking != tool_details
+ SQL
+
+ # needs to be nullable to avoid issues inserting new rows
+ change_column_null :ai_personas, :tool_details, true
+ change_column_default :ai_personas, :tool_details, nil
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/discourse-ai/evals/lib/runners/ai_helper.rb b/plugins/discourse-ai/evals/lib/runners/ai_helper.rb
index 195e6bc456c..0b168ee3483 100644
--- a/plugins/discourse-ai/evals/lib/runners/ai_helper.rb
+++ b/plugins/discourse-ai/evals/lib/runners/ai_helper.rb
@@ -71,7 +71,7 @@ module DiscourseAi
context =
DiscourseAi::Personas::BotContext.new(
user: user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "ai_helper:#{helper_mode}",
messages: [{ type: :user, content: user_input }],
format_dates: helper_mode == "smart_dates",
diff --git a/plugins/discourse-ai/evals/lib/runners/discoveries.rb b/plugins/discourse-ai/evals/lib/runners/discoveries.rb
index f2e65abd758..c51e2e6b62d 100644
--- a/plugins/discourse-ai/evals/lib/runners/discoveries.rb
+++ b/plugins/discourse-ai/evals/lib/runners/discoveries.rb
@@ -36,7 +36,7 @@ module DiscourseAi
context =
DiscourseAi::Personas::BotContext.new(
user: user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "discover",
messages: [{ type: :user, content: query }],
)
diff --git a/plugins/discourse-ai/evals/lib/runners/hyde.rb b/plugins/discourse-ai/evals/lib/runners/hyde.rb
index d13bcc65926..96cf667f335 100644
--- a/plugins/discourse-ai/evals/lib/runners/hyde.rb
+++ b/plugins/discourse-ai/evals/lib/runners/hyde.rb
@@ -39,7 +39,7 @@ module DiscourseAi
context =
DiscourseAi::Personas::BotContext.new(
user: user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "semantic_search_hyde",
messages: [{ type: :user, content: query }],
)
diff --git a/plugins/discourse-ai/evals/lib/runners/inference.rb b/plugins/discourse-ai/evals/lib/runners/inference.rb
index aaf30de8fbf..61f514a18fa 100644
--- a/plugins/discourse-ai/evals/lib/runners/inference.rb
+++ b/plugins/discourse-ai/evals/lib/runners/inference.rb
@@ -141,7 +141,7 @@ module DiscourseAi
def build_ctx
DiscourseAi::Personas::BotContext.new(
user: Discourse.system_user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "evals/inference/#{operation}",
)
end
diff --git a/plugins/discourse-ai/evals/lib/runners/spam.rb b/plugins/discourse-ai/evals/lib/runners/spam.rb
index 07fd374ea48..213728cf457 100644
--- a/plugins/discourse-ai/evals/lib/runners/spam.rb
+++ b/plugins/discourse-ai/evals/lib/runners/spam.rb
@@ -25,7 +25,7 @@ module DiscourseAi
DiscourseAi::Personas::BotContext
.new(
user: user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "evals/spam",
messages: [{ type: :user, content: content }],
)
diff --git a/plugins/discourse-ai/evals/lib/runners/summarization.rb b/plugins/discourse-ai/evals/lib/runners/summarization.rb
index f03faa2ae10..9c5ad08512f 100644
--- a/plugins/discourse-ai/evals/lib/runners/summarization.rb
+++ b/plugins/discourse-ai/evals/lib/runners/summarization.rb
@@ -37,7 +37,7 @@ module DiscourseAi
context =
DiscourseAi::Personas::BotContext.new(
user: user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "evals/#{feature_name}",
resource_url: "#{Discourse.base_path}/t/-/1",
messages: strategy.as_llm_messages(content),
diff --git a/plugins/discourse-ai/evals/lib/runners/translation.rb b/plugins/discourse-ai/evals/lib/runners/translation.rb
index 57957f6e7b1..888985d1cf4 100644
--- a/plugins/discourse-ai/evals/lib/runners/translation.rb
+++ b/plugins/discourse-ai/evals/lib/runners/translation.rb
@@ -69,7 +69,7 @@ module DiscourseAi
context =
DiscourseAi::Personas::BotContext.new(
user: system_user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "translation/#{operation}",
messages: [{ type: :user, content: content }],
)
@@ -84,7 +84,7 @@ module DiscourseAi
context =
DiscourseAi::Personas::BotContext.new(
user: system_user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "translation/#{operation}",
messages: [{ type: :user, content: payload }],
)
diff --git a/plugins/discourse-ai/lib/ai_bot/playground.rb b/plugins/discourse-ai/lib/ai_bot/playground.rb
index 07c4984bf64..f2401e2603b 100644
--- a/plugins/discourse-ai/lib/ai_bot/playground.rb
+++ b/plugins/discourse-ai/lib/ai_bot/playground.rb
@@ -330,7 +330,7 @@ module DiscourseAi
instruction_message: instruction_message,
),
user: message.user,
- skip_tool_details: true,
+ skip_show_thinking: true,
cancel_manager: DiscourseAi::Completions::CancelManager.new,
)
@@ -353,8 +353,8 @@ module DiscourseAi
new_prompts =
bot.reply(context) do |partial, placeholder, type|
- # no support for tools or thinking by design
- next if type == :thinking || type == :tool_details || type == :partial_tool
+ # no support for thinking by design
+ next if type == :thinking || type == :partial_tool
streamer << partial
end
@@ -486,18 +486,19 @@ module DiscourseAi
)
end
- context.skip_tool_details ||= !bot.persona.class.tool_details
+ context.skip_show_thinking ||= !bot.persona.class.show_thinking
post_streamer = PostStreamer.new(delay: Rails.env.test? ? 0 : 0.5) if stream_reply
started_thinking = false
new_custom_prompts =
bot.reply(context) do |partial, placeholder, type|
- if type == :thinking && !started_thinking
- reply << "<details><summary>#{I18n.t("discourse_ai.ai_bot.thinking")}</summary>"
- started_thinking = true
- end
+ next if (partial.to_s == "" && placeholder.to_s != "" && context.skip_show_thinking)
+ next if type == :structured_output && !partial.finished?
- if type != :thinking && started_thinking
+ if should_start_thinking?(partial:, context:, type:, started_thinking:, placeholder:)
+ reply << "<details><summary>#{I18n.t("discourse_ai.ai_bot.thinking")}</summary>\n\n"
+ started_thinking = true
+ elsif should_stop_thinking?(partial:, context:, type:, started_thinking:, placeholder:)
reply << "</details>\n\n"
started_thinking = false
end
@@ -506,7 +507,7 @@ module DiscourseAi
raw = reply.dup
raw << "\n\n" << placeholder if placeholder.present?
- if blk && type != :tool_details && type != :partial_tool && type != :partial_invoke
+ if blk && type != :thinking && type != :partial_tool && type != :partial_invoke
blk.call(partial)
end
@@ -596,6 +597,24 @@ module DiscourseAi
private
+ def should_stop_thinking?(partial:, context:, type:, started_thinking:, placeholder:)
+ return false if context.skip_show_thinking
+ return false if !started_thinking
+ return false if partial.blank? && placeholder.blank?
+ return true if type.nil? || type == :structured_output || type == :custom_raw
+
+ false
+ end
+
+ def should_start_thinking?(partial:, context:, type:, started_thinking:, placeholder:)
+ return false if context.skip_show_thinking
+ return false if started_thinking
+ return false if partial.blank? && placeholder.blank?
+ return false if type.nil? || type == :structured_output || type == :custom_raw
+
+ true
+ end
+
def available_bot_users
@available_bots ||=
User.joins("INNER JOIN llm_models llm ON llm.user_id = users.id").where(active: true)
diff --git a/plugins/discourse-ai/lib/ai_helper/assistant.rb b/plugins/discourse-ai/lib/ai_helper/assistant.rb
index 5dfe3c488ca..7306f7fcee6 100644
--- a/plugins/discourse-ai/lib/ai_helper/assistant.rb
+++ b/plugins/discourse-ai/lib/ai_helper/assistant.rb
@@ -118,7 +118,7 @@ module DiscourseAi
context =
DiscourseAi::Personas::BotContext.new(
user: user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "ai_helper",
messages: [{ type: :user, content: user_input }],
format_dates: helper_mode == REPLACE_DATES,
@@ -253,7 +253,7 @@ module DiscourseAi
context =
DiscourseAi::Personas::BotContext.new(
user: user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: IMAGE_CAPTION,
messages: [
{
diff --git a/plugins/discourse-ai/lib/ai_moderation/spam_scanner.rb b/plugins/discourse-ai/lib/ai_moderation/spam_scanner.rb
index 5e5a28746eb..25cd30fef6e 100644
--- a/plugins/discourse-ai/lib/ai_moderation/spam_scanner.rb
+++ b/plugins/discourse-ai/lib/ai_moderation/spam_scanner.rb
@@ -306,7 +306,7 @@ module DiscourseAi
DiscourseAi::Personas::BotContext
.new(
user: user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: feature_name,
messages: messages,
bypass_response_format: bypass_response_format,
diff --git a/plugins/discourse-ai/lib/automation/llm_tagger.rb b/plugins/discourse-ai/lib/automation/llm_tagger.rb
index 03e4c6154bf..690ccdedd0b 100644
--- a/plugins/discourse-ai/lib/automation/llm_tagger.rb
+++ b/plugins/discourse-ai/lib/automation/llm_tagger.rb
@@ -64,7 +64,7 @@ module DiscourseAi
bot_ctx =
DiscourseAi::Personas::BotContext.new(
user: Discourse.system_user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "llm_tagger",
messages: [{ type: :user, content: input }],
)
diff --git a/plugins/discourse-ai/lib/automation/llm_triage.rb b/plugins/discourse-ai/lib/automation/llm_triage.rb
index 3e13d992f53..9d240c69d9d 100644
--- a/plugins/discourse-ai/lib/automation/llm_triage.rb
+++ b/plugins/discourse-ai/lib/automation/llm_triage.rb
@@ -75,7 +75,7 @@ module DiscourseAi
bot_ctx =
DiscourseAi::Personas::BotContext.new(
user: Discourse.system_user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "llm_triage",
messages: [{ type: :user, content: input }],
)
diff --git a/plugins/discourse-ai/lib/automation/report_runner.rb b/plugins/discourse-ai/lib/automation/report_runner.rb
index ea35e8091fa..835557f99c9 100644
--- a/plugins/discourse-ai/lib/automation/report_runner.rb
+++ b/plugins/discourse-ai/lib/automation/report_runner.rb
@@ -139,7 +139,7 @@ module DiscourseAi
report_ctx =
DiscourseAi::Personas::BotContext.new(
user: Discourse.system_user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "ai_report",
messages: [{ type: :user, content: input }],
)
diff --git a/plugins/discourse-ai/lib/completions/anthropic_message_processor.rb b/plugins/discourse-ai/lib/completions/anthropic_message_processor.rb
index a8ba9b4aeb7..75f91ab3ffb 100644
--- a/plugins/discourse-ai/lib/completions/anthropic_message_processor.rb
+++ b/plugins/discourse-ai/lib/completions/anthropic_message_processor.rb
@@ -1,6 +1,8 @@
# frozen_string_literal: true
class DiscourseAi::Completions::AnthropicMessageProcessor
+ PROVIDER_KEY = :anthropic
+
class AnthropicToolCall
attr_reader :name, :raw_json, :id
@@ -73,11 +75,12 @@ class DiscourseAi::Completions::AnthropicMessageProcessor
) if tool_name
elsif parsed[:type] == "content_block_start" && parsed.dig(:content_block, :type) == "thinking"
if @output_thinking
+ provider_info = { PROVIDER_KEY => { signature: +"", redacted: false } }
@thinking =
DiscourseAi::Completions::Thinking.new(
message: +parsed.dig(:content_block, :thinking).to_s,
- signature: +"",
partial: true,
+ provider_info: provider_info,
)
result = @thinking.dup
end
@@ -89,7 +92,11 @@ class DiscourseAi::Completions::AnthropicMessageProcessor
end
elsif parsed[:type] == "content_block_delta" && parsed.dig(:delta, :type) == "signature_delta"
if @output_thinking
- @thinking.signature << parsed.dig(:delta, :signature) if @thinking
+ if @thinking
+ info = (@thinking.provider_info[PROVIDER_KEY] ||= { signature: +"", redacted: false })
+ info[:signature] ||= +""
+ info[:signature] << parsed.dig(:delta, :signature)
+ end
end
elsif parsed[:type] == "content_block_stop" && @thinking
@thinking.partial = false
@@ -105,8 +112,13 @@ class DiscourseAi::Completions::AnthropicMessageProcessor
result =
DiscourseAi::Completions::Thinking.new(
message: nil,
- signature: parsed.dig(:content_block, :data),
- redacted: true,
+ partial: false,
+ provider_info: {
+ PROVIDER_KEY => {
+ redacted_signature: parsed.dig(:content_block, :data),
+ redacted: true,
+ },
+ },
)
end
else
@@ -152,15 +164,24 @@ class DiscourseAi::Completions::AnthropicMessageProcessor
if @output_thinking
DiscourseAi::Completions::Thinking.new(
message: data[:thinking],
- signature: data[:signature],
+ provider_info: {
+ PROVIDER_KEY => {
+ signature: data[:signature],
+ redacted: false,
+ },
+ },
)
end
elsif data[:type] == "redacted_thinking"
if @output_thinking
DiscourseAi::Completions::Thinking.new(
message: nil,
- signature: data[:data],
- redacted: true,
+ provider_info: {
+ PROVIDER_KEY => {
+ redacted_signature: data[:data],
+ redacted: true,
+ },
+ },
)
end
else
diff --git a/plugins/discourse-ai/lib/completions/dialects/chat_gpt.rb b/plugins/discourse-ai/lib/completions/dialects/chat_gpt.rb
index d0899ffc265..2dd07159e6c 100644
--- a/plugins/discourse-ai/lib/completions/dialects/chat_gpt.rb
+++ b/plugins/discourse-ai/lib/completions/dialects/chat_gpt.rb
@@ -52,8 +52,34 @@ module DiscourseAi
!!@disable_native_tools = llm_model.lookup_custom_param("disable_native_tools")
end
+ def translate
+ result = super
+ result = hoist_reasoning(result) if responses_api?
+ result
+ end
+
private
+ def hoist_reasoning(messages)
+ new_messages = []
+ messages.each do |msg|
+ if msg[:content].is_a?(Array)
+ reasoning = []
+ msg[:content].delete_if do |item|
+ if item.is_a?(Hash) && item[:type] == "reasoning"
+ reasoning << item
+ true
+ else
+ false
+ end
+ end
+ reasoning.each { |reason| new_messages << reason } if reasoning.present?
+ end
+ new_messages << msg
+ end
+ new_messages
+ end
+
def tools_dialect
if disable_native_tools?
super
@@ -121,6 +147,11 @@ module DiscourseAi
def message_for_role(role, msg)
content_array = []
+ reasoning_data = open_ai_reasoning_data(msg)
+
+ if responses_api? && reasoning_data.present?
+ content_array << { type: "thinking", message: msg }
+ end
user_message = { role: }
@@ -142,9 +173,14 @@ module DiscourseAi
content: content_array.flatten,
image_encoder: ->(details) { image_node(details) },
text_encoder: ->(text) { text_node(text, role) },
+ other_encoder: ->(hash) { thinking_signature_node(hash) },
allow_vision:,
)
+ if responses_api? && role == "assistant" && reasoning_data&.dig(:next_message_id)
+ user_message[:id] = reasoning_data[:next_message_id]
+ end
+
user_message[:content] = no_array_if_only_text(content_array)
user_message
end
@@ -157,6 +193,27 @@ module DiscourseAi
end
end
+ def thinking_signature_node(hash)
+ return unless responses_api?
+
+ message = hash[:message]
+ reasoning_data = open_ai_reasoning_data(message)
+ return if reasoning_data.blank?
+
+ {
+ type: "reasoning",
+ id: reasoning_data[:reasoning_id],
+ encrypted_content: reasoning_data[:encrypted_content],
+ summary: [type: :summary_text, text: message[:thinking].to_s],
+ }.compact
+ end
+
+ def open_ai_reasoning_data(message)
+ info = message[:thinking_provider_info]
+ return if info.blank?
+ info[:open_ai_responses] || info["open_ai_responses"]
+ end
+
def text_node(text, role)
if responses_api?
{ type: role == "user" ? "input_text" : "output_text", text: text }
diff --git a/plugins/discourse-ai/lib/completions/dialects/claude.rb b/plugins/discourse-ai/lib/completions/dialects/claude.rb
index 0ad75624927..65a41867f16 100644
--- a/plugins/discourse-ai/lib/completions/dialects/claude.rb
+++ b/plugins/discourse-ai/lib/completions/dialects/claude.rb
@@ -88,20 +88,19 @@ module DiscourseAi
def model_msg(msg)
content_array = []
- if msg[:thinking] || msg[:redacted_thinking_signature]
- if msg[:thinking]
+ anthropic = anthropic_reasoning(msg)
+
+ if anthropic.present?
+ if msg[:thinking] && anthropic[:signature]
content_array << {
type: "thinking",
thinking: msg[:thinking],
- signature: msg[:thinking_signature],
+ signature: anthropic[:signature],
}
end
- if msg[:redacted_thinking_signature]
- content_array << {
- type: "redacted_thinking",
- data: msg[:redacted_thinking_signature],
- }
+ if anthropic[:redacted_signature]
+ content_array << { type: "redacted_thinking", data: anthropic[:redacted_signature] }
end
end
@@ -118,6 +117,12 @@ module DiscourseAi
{ role: "assistant", content: no_array_if_only_text(content_array) }
end
+ def anthropic_reasoning(message)
+ info = message[:thinking_provider_info]
+ return if info.blank?
+ info[:anthropic] || info["anthropic"]
+ end
+
def system_msg(msg)
msg = { role: "system", content: msg[:content] }
diff --git a/plugins/discourse-ai/lib/completions/dialects/claude_tools.rb b/plugins/discourse-ai/lib/completions/dialects/claude_tools.rb
index 48ef02327a5..6aa0edbe5cc 100644
--- a/plugins/discourse-ai/lib/completions/dialects/claude_tools.rb
+++ b/plugins/discourse-ai/lib/completions/dialects/claude_tools.rb
@@ -22,20 +22,19 @@ module DiscourseAi
call_details = JSON.parse(raw_message[:content], symbolize_names: true)
result = []
- if raw_message[:thinking] || raw_message[:redacted_thinking_signature]
- if raw_message[:thinking]
+ anthropic = anthropic_reasoning(raw_message)
+
+ if anthropic.present?
+ if raw_message[:thinking] && anthropic[:signature]
result << {
type: "thinking",
thinking: raw_message[:thinking],
- signature: raw_message[:thinking_signature],
+ signature: anthropic[:signature],
}
end
- if raw_message[:redacted_thinking_signature]
- result << {
- type: "redacted_thinking",
- data: raw_message[:redacted_thinking_signature],
- }
+ if anthropic[:redacted_signature]
+ result << { type: "redacted_thinking", data: anthropic[:redacted_signature] }
end
end
@@ -57,6 +56,12 @@ module DiscourseAi
private
+ def anthropic_reasoning(message)
+ info = message[:thinking_provider_info]
+ return if info.blank?
+ info[:anthropic] || info["anthropic"]
+ end
+
attr_reader :raw_tools
end
end
diff --git a/plugins/discourse-ai/lib/completions/endpoints/base.rb b/plugins/discourse-ai/lib/completions/endpoints/base.rb
index 8a91acc19ab..ef6eed66227 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/base.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/base.rb
@@ -113,7 +113,7 @@ module DiscourseAi
wrapped = [result] if !result.is_a?(Array)
wrapped.each do |partial|
blk.call(partial)
- break cancel_manager&.cancelled?
+ break if cancel_manager&.cancelled?
end
return result
end
@@ -270,6 +270,9 @@ module DiscourseAi
# signal last partial output which will get parsed
# by best effort json parser
blk.call("")
+ else
+ # got to signal the end of structured output
+ blk.call(structured_output)
end
end
call_status = :success
diff --git a/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb b/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb
index 52d698efd17..e57ff201ce7 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb
@@ -80,12 +80,12 @@ module DiscourseAi
def prepare_payload(prompt, model_params, dialect)
payload = default_options.merge(model_params).merge(messages: prompt)
- if reasoning_effort
- if responses_api?
- payload.merge!({ reasoning: { effort: reasoning_effort } })
- else
- payload.merge!({ reasoning_effort: reasoning_effort })
- end
+ if responses_api?
+ hash = { summary: "auto" }
+ hash[:effort] = reasoning_effort if reasoning_effort
+ payload.merge!({ reasoning: hash })
+ elsif reasoning_effort
+ payload.merge!({ reasoning_effort: reasoning_effort })
end
if @streaming_mode
@@ -118,7 +118,11 @@ module DiscourseAi
end
end
- convert_payload_to_responses_api!(payload) if responses_api?
+ if responses_api?
+ convert_payload_to_responses_api!(payload)
+ payload[:include] ||= []
+ payload[:include] << "reasoning.encrypted_content"
+ end
payload
end
@@ -132,6 +136,15 @@ module DiscourseAi
payload[:input] = payload.delete(:messages)
completion_tokens = payload.delete(:max_completion_tokens) || payload.delete(:max_tokens)
payload[:max_output_tokens] = completion_tokens if completion_tokens
+ if payload[:response_format]
+ format = payload.delete(:response_format)
+ if format && format[:json_schema]
+ payload[:text] ||= {}
+ payload[:text][:format] = format[:json_schema]
+ payload[:text][:format][:type] ||= "json_schema"
+ end
+ end
+
# not supported in responses api
payload.delete(:stream_options)
end
@@ -188,7 +201,10 @@ module DiscourseAi
def processor
@processor ||=
if responses_api?
- OpenAiResponsesMessageProcessor.new(partial_tool_calls: partial_tool_calls)
+ OpenAiResponsesMessageProcessor.new(
+ partial_tool_calls: partial_tool_calls,
+ output_thinking: output_thinking,
+ )
else
OpenAiMessageProcessor.new(partial_tool_calls: partial_tool_calls)
end
diff --git a/plugins/discourse-ai/lib/completions/open_ai_responses_message_processor.rb b/plugins/discourse-ai/lib/completions/open_ai_responses_message_processor.rb
index 51381df7851..a0a673b34a5 100644
--- a/plugins/discourse-ai/lib/completions/open_ai_responses_message_processor.rb
+++ b/plugins/discourse-ai/lib/completions/open_ai_responses_message_processor.rb
@@ -1,9 +1,11 @@
# frozen_string_literal: true
module DiscourseAi::Completions
class OpenAiResponsesMessageProcessor
+ PROVIDER_KEY = :open_ai_responses
+
attr_reader :prompt_tokens, :completion_tokens, :cached_tokens
- def initialize(partial_tool_calls: false)
+ def initialize(partial_tool_calls: false, output_thinking: false)
@tool = nil # currently streaming ToolCall
@tool_arguments = +""
@prompt_tokens = nil
@@ -12,6 +14,10 @@ module DiscourseAi::Completions
@partial_tool_calls = partial_tool_calls
@streaming_parser = nil # JsonStreamingTracker, if used
@has_new_data = false
+ @output_thinking = output_thinking
+ @reasoning_contexts = {}
+ @pending_reasonings = []
+ @has_first_summary_part = false
end
# @param json [Hash] full JSON response from responses.create / retrieve
@@ -19,14 +25,23 @@ module DiscourseAi::Completions
def process_message(json)
result = []
+ pending_reasonings = []
+
(json[:output] || []).each do |item|
type = item[:type]
case type
+ when "reasoning"
+ if @output_thinking
+ thinking = build_thinking_from_reasoning(item)
+ pending_reasonings << thinking
+ result << thinking
+ end
when "function_call"
result << build_tool_call_from_item(item)
when "message"
text = extract_text(item)
+ attach_message_id_to_reasonings(pending_reasonings, item[:id])
result << text if text
end
end
@@ -45,18 +60,34 @@ module DiscourseAi::Completions
when "response.output_text.delta"
delta = json[:delta] || json["delta"]
rval = delta if !delta.empty?
+ when "response.reasoning_summary_part.added"
+ rval = build_partial_reasoning_delta(json, prefix: "\n\n") if @has_first_summary_part
+ when "response.reasoning_summary_text.delta"
+ rval = build_partial_reasoning_delta(json)
+ when "response.reasoning_summary_part.done"
+ @has_first_summary_part = true
when "response.output_item.added"
item = json[:item]
- if item && item[:type] == "function_call"
- handle_tool_stream(:start, item) { |finished| rval = finished }
+ if item
+ if item[:type] == "function_call"
+ handle_tool_stream(:start, item) { |finished| rval = finished }
+ elsif item[:type] == "reasoning" && @output_thinking
+ register_reasoning_context(item)
+ end
end
when "response.function_call_arguments.delta"
delta = json[:delta]
handle_tool_stream(:progress, delta) { |finished| rval = finished } if delta
when "response.output_item.done"
item = json[:item]
- if item && item[:type] == "function_call"
- handle_tool_stream(:done, item) { |finished| rval = finished }
+ if item
+ if item[:type] == "function_call"
+ handle_tool_stream(:done, item) { |finished| rval = finished }
+ elsif item[:type] == "reasoning" && @output_thinking
+ return finalize_reasoning_context(item)
+ elsif item[:type] == "message"
+ attach_message_id_to_pending_stream_reasonings(item[:id])
+ end
end
end
@@ -99,6 +130,24 @@ module DiscourseAi::Completions
.join
end
+ def build_thinking_from_reasoning(item)
+ provider_payload = {
+ reasoning_id: item[:id],
+ encrypted_content: item[:encrypted_content],
+ }.compact
+
+ summary_text = (item.dig(:summary) || []).map { |s| s[:text].to_s }.join("\n\n")
+
+ # worth considering if we return multiple Thinking objects for each summary part?
+ Thinking.new(
+ message: summary_text,
+ partial: false,
+ provider_info: {
+ PROVIDER_KEY => provider_payload,
+ },
+ )
+ end
+
def build_tool_call_from_item(item)
id = item[:call_id]
name = item[:name]
@@ -156,5 +205,66 @@ module DiscourseAi::Completions
@completion_tokens ||= usage[:output_tokens]
@cached_tokens ||= cached_tokens
end
+
+ def build_partial_reasoning_delta(json, prefix: nil)
+ return unless @output_thinking
+
+ delta = json[:delta]
+ context = @reasoning_contexts[json[:item_id]]
+ if context
+ delta = prefix + delta.to_s if prefix
+ context[:summary] << delta.to_s
+ end
+
+ Thinking.new(message: delta, partial: true)
+ end
+
+ def register_reasoning_context(item)
+ @reasoning_contexts[item[:id]] ||= { summary: +"", encrypted_content: nil, thinking: nil }
+ end
+
+ def finalize_reasoning_context(item)
+ context = @reasoning_contexts.delete(item[:id]) || { summary: +"", thinking: nil }
+ summary = context[:summary].presence || item.dig(:summary, 0, :text).to_s || +""
+
+ thinking =
+ Thinking.new(
+ message: summary,
+ partial: false,
+ provider_info: {
+ PROVIDER_KEY => {
+ reasoning_id: item[:id],
+ encrypted_content: item[:encrypted_content],
+ }.compact,
+ },
+ )
+
+ context[:thinking] = thinking
+ @pending_reasonings << context
+ thinking
+ end
+
+ def attach_message_id_to_reasonings(queue, message_id)
+ return if queue.empty? || message_id.blank?
+
+ queue.each { |thinking| assign_message_id(thinking, message_id) }
+
+ queue.clear
+ end
+
+ def attach_message_id_to_pending_stream_reasonings(message_id)
+ return if @pending_reasonings.empty? || message_id.blank?
+
+ while (context = @pending_reasonings.first)
+ break unless context[:thinking]
+ assign_message_id(context[:thinking], message_id)
+ @pending_reasonings.shift
+ end
+ end
+
+ def assign_message_id(thinking, message_id)
+ data = thinking.provider_info[PROVIDER_KEY] ||= {}
+ data[:next_message_id] = message_id
+ end
end
end
diff --git a/plugins/discourse-ai/lib/completions/prompt.rb b/plugins/discourse-ai/lib/completions/prompt.rb
index 0641b64f1ea..82ec4f7c9fc 100644
--- a/plugins/discourse-ai/lib/completions/prompt.rb
+++ b/plugins/discourse-ai/lib/completions/prompt.rb
@@ -71,22 +71,17 @@ module DiscourseAi
def push_model_response(response)
response = [response] if !response.is_a? Array
- thinking, thinking_signature, redacted_thinking_signature = nil
+ thinking_text = nil
+ thinking_provider_info = {}
response.each do |message|
if message.is_a?(Thinking)
- # we can safely skip partials here
next if message.partial?
- if message.redacted
- redacted_thinking_signature = message.signature
- else
- thinking = message.message
- thinking_signature = message.signature
- end
+ thinking_text = message.message if message.message.present?
+ thinking_provider_info =
+ Thinking.merge_provider_info(thinking_provider_info, message.provider_info)
elsif message.is_a?(ToolCall)
next if message.partial?
- # this is a bit surprising about the API
- # needing to add arguments is not ideal
push(
type: :tool_call,
content: { arguments: message.parameters }.to_json,
@@ -100,33 +95,25 @@ module DiscourseAi
end
end
- # anthropic rules are that we attach thinking to last for the response
- # it is odd, I wonder if long term we just keep thinking as a separate object
- if thinking || redacted_thinking_signature
- messages.last[:thinking] = thinking
- messages.last[:thinking_signature] = thinking_signature
- messages.last[:redacted_thinking_signature] = redacted_thinking_signature
+ if thinking_text || thinking_provider_info.present?
+ messages.last[:thinking] = thinking_text if thinking_text
+ if thinking_provider_info.present?
+ messages.last[:thinking_provider_info] = thinking_provider_info
+ end
end
end
- def push(
- type:,
- content:,
- id: nil,
- name: nil,
- thinking: nil,
- thinking_signature: nil,
- redacted_thinking_signature: nil
- )
+ def push(type:, content:, id: nil, name: nil, thinking: nil, thinking_provider_info: nil)
return if type == :system
new_message = { type: type, content: content }
new_message[:name] = name.to_s if name
new_message[:id] = id.to_s if id
new_message[:thinking] = thinking if thinking
- new_message[:thinking_signature] = thinking_signature if thinking_signature
- new_message[
- :redacted_thinking_signature
- ] = redacted_thinking_signature if redacted_thinking_signature
+ if thinking_provider_info
+ new_message[:thinking_provider_info] = Thinking.normalize_provider_info(
+ thinking_provider_info,
+ )
+ end
validate_message(new_message)
validate_turn(messages.last, new_message)
@@ -199,6 +186,7 @@ module DiscourseAi
id
name
thinking
+ thinking_provider_info
thinking_signature
redacted_thinking_signature
]
diff --git a/plugins/discourse-ai/lib/completions/prompt_messages_builder.rb b/plugins/discourse-ai/lib/completions/prompt_messages_builder.rb
index 1f5219179d0..581cc25c6b0 100644
--- a/plugins/discourse-ai/lib/completions/prompt_messages_builder.rb
+++ b/plugins/discourse-ai/lib/completions/prompt_messages_builder.rb
@@ -220,13 +220,27 @@ module DiscourseAi
message[:name] = name.to_s if name
message[:id] = id.to_s if id
if thinking
- message[:thinking] = thinking["thinking"] if thinking["thinking"]
- message[:thinking_signature] = thinking["thinking_signature"] if thinking[
- "thinking_signature"
- ]
- message[:redacted_thinking_signature] = thinking[
- "redacted_thinking_signature"
- ] if thinking["redacted_thinking_signature"]
+ if thinking["message"] || thinking["provider_info"]
+ message[:thinking] = thinking["message"] if thinking["message"]
+ provider_info =
+ DiscourseAi::Completions::Thinking.normalize_provider_info(thinking["provider_info"])
+ message[:thinking_provider_info] = provider_info if provider_info.present?
+ else
+ legacy_provider_info = {}
+ if thinking["thinking_signature"]
+ legacy_provider_info[:anthropic] ||= {}
+ legacy_provider_info[:anthropic][:signature] = thinking["thinking_signature"]
+ end
+ if thinking["redacted_thinking_signature"]
+ legacy_provider_info[:anthropic] ||= {}
+ legacy_provider_info[:anthropic][:redacted_signature] = thinking[
+ "redacted_thinking_signature"
+ ]
+ end
+
+ message[:thinking] = thinking["thinking"] if thinking["thinking"]
+ message[:thinking_provider_info] = legacy_provider_info if legacy_provider_info.present?
+ end
end
@raw_messages << message
diff --git a/plugins/discourse-ai/lib/completions/structured_output.rb b/plugins/discourse-ai/lib/completions/structured_output.rb
index b2e39b8f56d..1f726899adc 100644
--- a/plugins/discourse-ai/lib/completions/structured_output.rb
+++ b/plugins/discourse-ai/lib/completions/structured_output.rb
@@ -26,7 +26,12 @@ module DiscourseAi
def to_s
# we may want to also normalize the JSON here for the broken case
- @raw_response
+ @raw_response.to_s
+ end
+
+ # require for any implicity string conversions
+ def to_str
+ to_s
end
attr_reader :last_chunk_buffer
@@ -41,6 +46,10 @@ module DiscourseAi
@done = true
end
+ def finished?
+ @done
+ end
+
def broken?
@partial_json_tracker.broken?
end
diff --git a/plugins/discourse-ai/lib/completions/thinking.rb b/plugins/discourse-ai/lib/completions/thinking.rb
index eb9e6275c89..5e444f0035b 100644
--- a/plugins/discourse-ai/lib/completions/thinking.rb
+++ b/plugins/discourse-ai/lib/completions/thinking.rb
@@ -3,36 +3,94 @@
module DiscourseAi
module Completions
class Thinking
- attr_accessor :message, :signature, :redacted, :partial
+ attr_accessor :message, :partial
+ attr_reader :provider_info
- def initialize(message:, signature: nil, redacted: false, partial: false)
+ def initialize(message:, partial: false, provider_info: {})
@message = message
- @signature = signature
- @redacted = redacted
@partial = partial
+ self.provider_info = provider_info
end
def partial?
!!@partial
end
+ def provider_info=(info)
+ @provider_info = self.class.normalize_provider_info(info)
+ end
+
+ def provider_info_for(key)
+ provider_info[key.to_sym]
+ end
+
+ def merge_provider_info!(info)
+ @provider_info = self.class.merge_provider_info(@provider_info, info)
+ end
+
+ def serialized_provider_info
+ self.class.deep_stringify_keys(provider_info)
+ end
+
+ def as_json(_opts = nil)
+ { "message" => message, "provider_info" => serialized_provider_info }
+ end
+
def ==(other)
- message == other.message && signature == other.signature && redacted == other.redacted &&
- partial == other.partial
+ message == other.message && partial == other.partial && provider_info == other.provider_info
end
def dup
- Thinking.new(
- message: message.dup,
- signature: signature.dup,
- redacted: redacted,
- partial: partial,
- )
+ Thinking.new(message: message&.dup, partial: partial, provider_info: provider_info.deep_dup)
end
def to_s
- "#{message} - #{signature} - #{redacted} - #{partial}"
+ "#{message} - #{provider_info.inspect} - #{partial}"
+ end
+
+ def self.merge_provider_info(existing, incoming)
+ normalize_provider_info(existing).deep_merge(normalize_provider_info(incoming))
+ end
+
+ def self.normalize_provider_info(info)
+ return {} if info.blank?
+
+ info.each_with_object({}) do |(key, value), memo|
+ memo[normalize_key(key)] = normalize_value(value)
+ end
+ end
+
+ def self.deep_stringify_keys(info)
+ return {} if info.blank?
+
+ info.each_with_object({}) do |(key, value), memo|
+ memo[key.to_s] = if value.is_a?(Hash)
+ deep_stringify_keys(value)
+ elsif value.is_a?(Array)
+ value.map { |item| item.is_a?(Hash) ? deep_stringify_keys(item) : item }
+ else
+ value
+ end
+ end
+ end
+
+ def self.normalize_key(key)
+ key.is_a?(Symbol) ? key : key.to_sym
+ rescue StandardError
+ key
+ end
+ private_class_method :normalize_key
+
+ def self.normalize_value(value)
+ if value.is_a?(Hash)
+ normalize_provider_info(value)
+ elsif value.is_a?(Array)
+ value.map { |item| item.is_a?(Hash) ? normalize_provider_info(item) : item }
+ else
+ value
+ end
end
+ private_class_method :normalize_value
end
end
end
diff --git a/plugins/discourse-ai/lib/discord/bot/persona_replier.rb b/plugins/discourse-ai/lib/discord/bot/persona_replier.rb
index f6e9bcdd9ba..807ffd834f2 100644
--- a/plugins/discourse-ai/lib/discord/bot/persona_replier.rb
+++ b/plugins/discourse-ai/lib/discord/bot/persona_replier.rb
@@ -23,7 +23,7 @@ module DiscourseAi
reply = +""
full_reply =
@bot.reply(
- { conversation_context: [{ type: :user, content: @query }], skip_tool_details: true },
+ { conversation_context: [{ type: :user, content: @query }], skip_show_thinking: true },
) do |partial, _something|
reply << partial
next if reply.blank?
diff --git a/plugins/discourse-ai/lib/embeddings/semantic_search.rb b/plugins/discourse-ai/lib/embeddings/semantic_search.rb
index 7d4e89f7e43..c93ae1a4066 100644
--- a/plugins/discourse-ai/lib/embeddings/semantic_search.rb
+++ b/plugins/discourse-ai/lib/embeddings/semantic_search.rb
@@ -130,7 +130,7 @@ module DiscourseAi
context =
DiscourseAi::Personas::BotContext.new(
user: @guardian.user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "semantic_search_hyde",
messages: [{ type: :user, content: search_term }],
)
diff --git a/plugins/discourse-ai/lib/personas/bot.rb b/plugins/discourse-ai/lib/personas/bot.rb
index 0274515b7f9..f130d4f69c4 100644
--- a/plugins/discourse-ai/lib/personas/bot.rb
+++ b/plugins/discourse-ai/lib/personas/bot.rb
@@ -54,6 +54,8 @@ module DiscourseAi
unless context.is_a?(BotContext)
raise ArgumentError, "context must be an instance of BotContext"
end
+ update_blk ||= proc {}
+
context.cancel_manager ||= DiscourseAi::Completions::CancelManager.new
current_llm = llm
prompt = persona.craft_prompt(context, llm: current_llm)
@@ -85,6 +87,7 @@ module DiscourseAi
allow_partial_tool_calls = persona.allow_partial_tool_calls?
existing_tools = Set.new
current_thinking = []
+ thinking_placeholder = nil
result =
current_llm.generate(
@@ -144,15 +147,21 @@ module DiscourseAi
Rails.logger.warn("DiscourseAi: Tool not found: #{partial.name}")
else
if partial.is_a?(DiscourseAi::Completions::Thinking)
- if partial.partial? && partial.message.present?
- update_blk.call(partial.message, nil, :thinking)
+ thinking = partial
+
+ if thinking.partial? && thinking.message.present? && !context.skip_show_thinking
+ thinking_placeholder ||= +""
+ thinking_placeholder << thinking.message
+ update_blk.call("", thinking_placeholder, :thinking)
end
- if !partial.partial?
- # this will be dealt with later
- raw_context << partial
- current_thinking << partial
+
+ if !thinking.partial?
+ raw_context << thinking
+ current_thinking << thinking
+ thinking_placeholder = nil
+ update_blk.call(thinking.message, nil, :thinking) if thinking.message.present?
end
- elsif update_blk.present?
+ else
if partial.is_a?(DiscourseAi::Completions::StructuredOutput)
update_blk.call(partial, nil, :structured_output)
else
@@ -192,23 +201,34 @@ module DiscourseAi
def embed_thinking(raw_context)
embedded_thinking = []
- thinking_info = nil
+ thinking_bundle = nil
+
raw_context.each do |context|
if context.is_a?(DiscourseAi::Completions::Thinking)
- thinking_info ||= {}
- if context.redacted
- thinking_info[:redacted_thinking_signature] = context.signature
- else
- thinking_info[:thinking] = context.message
- thinking_info[:thinking_signature] = context.signature
- end
- else
- if thinking_info
- context = context.dup
- context[4] = thinking_info
- end
- embedded_thinking << context
+ thinking_bundle ||= { message: nil, provider_info: {} }
+ thinking_bundle[:message] = context.message if context.message.present?
+ thinking_bundle[
+ :provider_info
+ ] = DiscourseAi::Completions::Thinking.merge_provider_info(
+ thinking_bundle[:provider_info],
+ context.provider_info,
+ )
+ next
end
+
+ if thinking_bundle
+ context = context.dup
+ context[4] = {
+ "message" => thinking_bundle[:message],
+ "provider_info" =>
+ DiscourseAi::Completions::Thinking.deep_stringify_keys(
+ thinking_bundle[:provider_info],
+ ),
+ }.compact
+ thinking_bundle = nil
+ end
+
+ embedded_thinking << context
end
embedded_thinking
@@ -234,14 +254,20 @@ module DiscourseAi
}
if current_thinking.present?
+ thinking_message = nil
+ provider_payload = {}
+
current_thinking.each do |thinking|
- if thinking.redacted
- tool_call_message[:redacted_thinking_signature] = thinking.signature
- else
- tool_call_message[:thinking] = thinking.message
- tool_call_message[:thinking_signature] = thinking.signature
- end
+ thinking_message = thinking.message if thinking.message.present?
+ provider_payload =
+ DiscourseAi::Completions::Thinking.merge_provider_info(
+ provider_payload,
+ thinking.provider_info,
+ )
end
+
+ tool_call_message[:thinking] = thinking_message if thinking_message
+ tool_call_message[:thinking_provider_info] = provider_payload if provider_payload.present?
end
tool_message = {
@@ -259,9 +285,9 @@ module DiscourseAi
end
def invoke_tool(tool, context, &update_blk)
- show_placeholder = !context.skip_tool_details && !tool.class.allow_partial_tool_calls?
+ show_placeholder = !context.skip_show_thinking && !tool.class.allow_partial_tool_calls?
- update_blk.call("", build_placeholder(tool.summary, "")) if show_placeholder
+ update_blk.call("", build_placeholder(tool.summary, ""), :thinking) if show_placeholder
result =
tool.invoke do |progress, render_raw|
@@ -270,14 +296,17 @@ module DiscourseAi
show_placeholder = false
elsif show_placeholder
placeholder = build_placeholder(tool.summary, progress)
- update_blk.call("", placeholder)
+ update_blk.call("", placeholder, :thinking)
end
end
if show_placeholder
tool_details = build_placeholder(tool.summary, tool.details, custom_raw: tool.custom_raw)
- update_blk.call(tool_details, nil, :tool_details)
+ update_blk.call(tool_details, nil, :thinking)
elsif tool.custom_raw.present?
+ # we also rendered a placeholder for custom raw. Place something generic there
+ tool_details = build_placeholder(tool.summary, tool.details, custom_raw: "")
+ update_blk.call(tool_details, nil, :thinking)
update_blk.call(tool.custom_raw, nil, :custom_raw)
end
@@ -293,21 +322,12 @@ module DiscourseAi
end
def build_placeholder(summary, details, custom_raw: nil)
- placeholder = +(<<~HTML)
- <details>
- <summary>#{summary}</summary>
- <p>#{details}</p>
- </details>
- HTML
+ # No nested details blocks - just output as plain text within thinking block
+ placeholder = +"**#{summary}**\n#{details}\n\n"
if custom_raw
- placeholder << "\n"
placeholder << custom_raw
- else
- # we need this for cursor placeholder to work
- # doing this in CSS is very hard
- # if changing test with a custom tool such as search
- placeholder << "<span></span>\n\n"
+ placeholder << "\n\n"
end
placeholder
diff --git a/plugins/discourse-ai/lib/personas/bot_context.rb b/plugins/discourse-ai/lib/personas/bot_context.rb
index a42e7e96537..e87235139d0 100644
--- a/plugins/discourse-ai/lib/personas/bot_context.rb
+++ b/plugins/discourse-ai/lib/personas/bot_context.rb
@@ -9,7 +9,7 @@ module DiscourseAi
:private_message,
:custom_instructions,
:user,
- :skip_tool_details,
+ :skip_show_thinking,
:participants,
:chosen_tools,
:message_id,
@@ -29,7 +29,7 @@ module DiscourseAi
topic: nil,
participants: nil,
user: nil,
- skip_tool_details: nil,
+ skip_show_thinking: nil,
messages: [],
custom_instructions: nil,
site_url: nil,
@@ -48,7 +48,7 @@ module DiscourseAi
)
@participants = participants
@user = user
- @skip_tool_details = skip_tool_details
+ @skip_show_thinking = skip_show_thinking
@messages = messages
@custom_instructions = custom_instructions
@format_dates = format_dates
@@ -151,7 +151,7 @@ module DiscourseAi
site_url: @site_url,
site_title: @site_title,
site_description: @site_description,
- skip_tool_details: @skip_tool_details,
+ skip_show_thinking: @skip_show_thinking,
feature_name: @feature_name,
resource_url: @resource_url,
inferred_concepts: @inferred_concepts,
diff --git a/plugins/discourse-ai/lib/personas/tools/create_artifact.rb b/plugins/discourse-ai/lib/personas/tools/create_artifact.rb
index cd7c517be40..c478b0511ec 100644
--- a/plugins/discourse-ai/lib/personas/tools/create_artifact.rb
+++ b/plugins/discourse-ai/lib/personas/tools/create_artifact.rb
@@ -99,18 +99,12 @@ module DiscourseAi
HTML
self.custom_raw = <<~HTML
- <details>
- <summary>Thinking...</summary>
-
-
### Specification
````
#{specification}
````
#{source}
-
- </details>
HTML
end
diff --git a/plugins/discourse-ai/lib/personas/tools/update_artifact.rb b/plugins/discourse-ai/lib/personas/tools/update_artifact.rb
index 46038d7ab02..a00b7859846 100644
--- a/plugins/discourse-ai/lib/personas/tools/update_artifact.rb
+++ b/plugins/discourse-ai/lib/personas/tools/update_artifact.rb
@@ -98,17 +98,12 @@ module DiscourseAi
HTML
self.custom_raw = <<~HTML
- <details>
- <summary>Thinking...</summary>
-
- ### Instructions
- ````
- #{instructions}
- ````
-
- #{source}
+ ### Instructions
+ ````
+ #{instructions}
+ ````
- </details>
+ #{source}
HTML
end
diff --git a/plugins/discourse-ai/lib/summarization/fold_content.rb b/plugins/discourse-ai/lib/summarization/fold_content.rb
index 6e0ca35bf4e..225052e1186 100644
--- a/plugins/discourse-ai/lib/summarization/fold_content.rb
+++ b/plugins/discourse-ai/lib/summarization/fold_content.rb
@@ -147,7 +147,7 @@ module DiscourseAi
context =
DiscourseAi::Personas::BotContext.new(
user: user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: strategy.feature,
resource_url: "#{Discourse.base_path}/t/-/#{strategy.target.id}",
messages: strategy.as_llm_messages(content_in_window),
diff --git a/plugins/discourse-ai/lib/translation/base_translator.rb b/plugins/discourse-ai/lib/translation/base_translator.rb
index 986419dcead..5f00625badb 100644
--- a/plugins/discourse-ai/lib/translation/base_translator.rb
+++ b/plugins/discourse-ai/lib/translation/base_translator.rb
@@ -40,7 +40,7 @@ module DiscourseAi
context =
DiscourseAi::Personas::BotContext.new(
user: translation_user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "translation",
messages: [{ type: :user, content: formatted_content(text) }],
topic: @topic,
diff --git a/plugins/discourse-ai/lib/translation/language_detector.rb b/plugins/discourse-ai/lib/translation/language_detector.rb
index 2262f68a8b2..8a675ee0ec7 100644
--- a/plugins/discourse-ai/lib/translation/language_detector.rb
+++ b/plugins/discourse-ai/lib/translation/language_detector.rb
@@ -40,7 +40,7 @@ module DiscourseAi
context =
DiscourseAi::Personas::BotContext.new(
user: ai_persona.user || Discourse.system_user,
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "translation",
messages: [{ type: :user, content: @text }],
topic: @topic,
diff --git a/plugins/discourse-ai/spec/evals/workbench_spec.rb b/plugins/discourse-ai/spec/evals/workbench_spec.rb
index bc399d83696..5a354f2b289 100644
--- a/plugins/discourse-ai/spec/evals/workbench_spec.rb
+++ b/plugins/discourse-ai/spec/evals/workbench_spec.rb
@@ -188,7 +188,7 @@ RSpec.describe DiscourseAi::Evals::Workbench do
persona.examples = base.examples
persona.temperature = base.respond_to?(:temperature) ? base.temperature : nil
persona.top_p = base.respond_to?(:top_p) ? base.top_p : nil
- persona.tool_details = true
+ persona.show_thinking = true
persona.tools ||= []
persona.save!(validate: false)
end
diff --git a/plugins/discourse-ai/spec/fabricators/ai_persona_fabricator.rb b/plugins/discourse-ai/spec/fabricators/ai_persona_fabricator.rb
index 4b3c3f02d7a..f299fdfb63c 100644
--- a/plugins/discourse-ai/spec/fabricators/ai_persona_fabricator.rb
+++ b/plugins/discourse-ai/spec/fabricators/ai_persona_fabricator.rb
@@ -3,4 +3,5 @@ Fabricator(:ai_persona) do
name { sequence(:name) { |i| "persona_#{i}" } }
description "I am a test bot"
system_prompt "You are a test bot"
+ show_thinking false
end
diff --git a/plugins/discourse-ai/spec/lib/completions/anthropic_message_processor_spec.rb b/plugins/discourse-ai/spec/lib/completions/anthropic_message_processor_spec.rb
index f6594d8d0e8..45f01e68206 100644
--- a/plugins/discourse-ai/spec/lib/completions/anthropic_message_processor_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/anthropic_message_processor_spec.rb
@@ -69,7 +69,7 @@ describe DiscourseAi::Completions::AnthropicMessageProcessor do
# Verify the final complete thinking object
expect(final_result).to be_a(DiscourseAi::Completions::Thinking)
expect(final_result.message).to eq("First part of thinking and second part")
- expect(final_result.signature).to eq("thinking-sig-123")
+ expect(final_result.provider_info[:anthropic][:signature]).to eq("thinking-sig-123")
expect(final_result.partial?).to eq(false)
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 7d9339e5815..c6b15482091 100644
--- a/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb
@@ -483,8 +483,12 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic do
id: "user1",
content: "hello",
thinking: "I am thinking",
- thinking_signature: "signature",
- redacted_thinking_signature: "redacted_signature",
+ thinking_provider_info: {
+ anthropic: {
+ signature: "signature",
+ redacted_signature: "redacted_signature",
+ },
+ },
)
result = llm.generate(prompt, user: Discourse.system_user)
@@ -555,11 +559,10 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic do
# First item should be a Thinking object
expect(result[0]).to be_a(DiscourseAi::Completions::Thinking)
expect(result[0].message).to eq("This is my thinking process about prime numbers...")
- expect(result[0].signature).to eq("abc123signature")
+ expect(result[0].provider_info[:anthropic][:signature]).to eq("abc123signature")
expect(result[1]).to be_a(DiscourseAi::Completions::Thinking)
- expect(result[1].signature).to eq("abd456signature")
- expect(result[1].redacted).to eq(true)
+ expect(result[1].provider_info[:anthropic][:redacted_signature]).to eq("abd456signature")
# Second item should be the text response
expect(result[2]).to eq("Yes, there are infinitely many prime numbers where n mod 4 = 3.")
@@ -643,7 +646,16 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic do
end
expected_thinking = [
- DiscourseAi::Completions::Thinking.new(message: "", signature: "", partial: true),
+ DiscourseAi::Completions::Thinking.new(
+ message: "",
+ partial: true,
+ provider_info: {
+ anthropic: {
+ signature: "",
+ redacted: false,
+ },
+ },
+ ),
DiscourseAi::Completions::Thinking.new(
message: "Let me solve this step by step:\n\n1. First break down 27 * 453",
partial: true,
@@ -652,10 +664,24 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic do
DiscourseAi::Completions::Thinking.new(
message:
"Let me solve this step by step:\n\n1. First break down 27 * 453\n2. 453 = 400 + 50 + 3",
- signature: "EqQBCgIYAhIM1gbcDa9GJwZA2b3hGgxBdjrkzLoky3dl1pkiMOYds...",
partial: false,
+ provider_info: {
+ anthropic: {
+ signature: "EqQBCgIYAhIM1gbcDa9GJwZA2b3hGgxBdjrkzLoky3dl1pkiMOYds...",
+ redacted: false,
+ },
+ },
+ ),
+ DiscourseAi::Completions::Thinking.new(
+ message: nil,
+ partial: false,
+ provider_info: {
+ anthropic: {
+ redacted_signature: "AAA==",
+ redacted: true,
+ },
+ },
),
- DiscourseAi::Completions::Thinking.new(message: nil, signature: "AAA==", redacted: true),
]
expect(thinking_chunks).to eq(expected_thinking)
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 41a10351ce6..5fc08561bea 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
@@ -32,6 +32,104 @@ RSpec.describe DiscourseAi::Completions::Endpoints::OpenAi do
before { enable_current_plugin }
+ it "can retain thinking tokens during streaming completions" do
+ response_payload = <<~TEXT
+ event: response.created
+ data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_0e7bcfab8fc907240069152d0ff4cc819281594994abcec45f","object":"response","created_at":1762995472,"status":"in_progress","background":false,"error":null,"incomplete_details":null,"instructions":null,"max_output_tokens":128000,"max_tool_calls":null,"model":"gpt-5-mini-2025-08-07","output":[],"parallel_tool_calls":true,"previous_response_id":null,"prompt_cache_key":null,"prompt_cache_retention":null,"reasoning":{"effort":"low","summary":"detailed"},"safety_identifier":null,"service_tier":"auto","store":true,"temperature":1.0,"text":{"format":{"type":"text"},"verbosity":"medium"},"tool_choice":"auto","tools":[],"top_logprobs":0,"top_p":1.0,"truncation":"disabled","usage":null,"user":null,"metadata":{}}}
+
+ event: response.in_progress
+ data: {"type":"response.in_progress","sequence_number":1,"response":{"id":"resp_0e7bcfab8fc907240069152d0ff4cc819281594994abcec45f","object":"response","created_at":1762995472,"status":"in_progress","background":false,"error":null,"incomplete_details":null,"instructions":null,"max_output_tokens":128000,"max_tool_calls":null,"model":"gpt-5-mini-2025-08-07","output":[],"parallel_tool_calls":true,"previous_response_id":null,"prompt_cache_key":null,"prompt_cache_retention":null,"reasoning":{"effort":"low","summary":"detailed"},"safety_identifier":null,"service_tier":"auto","store":true,"temperature":1.0,"text":{"format":{"type":"text"},"verbosity":"medium"},"tool_choice":"auto","tools":[],"top_logprobs":0,"top_p":1.0,"truncation":"disabled","usage":null,"user":null,"metadata":{}}}
+
+ event: response.output_item.added
+ data: {"type":"response.output_item.added","sequence_number":2,"output_index":0,"item":{"id":"rs_0391d4281ead19e40069142428f734819da32f5c13bd277a25","type":"reasoning","encrypted_content":"ABC","summary":[]}}
+
+ event: response.reasoning_summary_part.added
+data: {"type":"response.reasoning_summary_part.added","sequence_number":3,"item_id":"rs_0391d4281ead19e40069142428f734819da32f5c13bd277a25","output_index":0,"summary_index":0,"part":{"type":"summary_text","text":""}}
+
+ event: response.reasoning_summary_text.delta
+ data: {"type":"response.reasoning_summary_text.delta","sequence_number":4,"item_id":"rs_0391d4281ead19e40069142428f734819da32f5c13bd277a25","output_index":0,"summary_index":0,"delta":"**Craft","obfuscation":"pvmKQ7xIR"}
+
+ event: response.reasoning_summary_text.delta
+ data: {"type":"response.reasoning_summary_text.delta","sequence_number":5,"item_id":"rs_0391d4281ead19e40069142428f734819da32f5c13bd277a25","output_index":0,"summary_index":0,"delta":"ing","obfuscation":"pvmKQ7xIR"}
+
+ event: response.output_item.done
+ data: {"type":"response.output_item.done","sequence_number":3,"output_index":0,"item":{"id":"rs_0391d4281ead19e40069142428f734819da32f5c13bd277a25","type":"reasoning","encrypted_content": "ABC","summary":[{"type":"summary_text","text":"**Crafting"}]}}
+
+ event: response.output_item.added
+ data: {"type":"response.output_item.added","sequence_number":4,"output_index":1,"item":{"id":"msg_0e7bcfab8fc907240069152d1173f48192a1f37340a24e4fba","type":"message","status":"in_progress","content":[],"role":"assistant"}}
+
+ event: response.content_part.added
+ data: {"type":"response.content_part.added","sequence_number":5,"item_id":"msg_0e7bcfab8fc907240069152d1173f48192a1f37340a24e4fba","output_index":1,"content_index":0,"part":{"type":"output_text","annotations":[],"logprobs":[],"text":""}}
+
+ event: response.output_text.delta
+ data: {"type":"response.output_text.delta","sequence_number":6,"item_id":"msg_0e7bcfab8fc907240069152d1173f48192a1f37340a24e4fba","output_index":1,"content_index":0,"delta":"hello","logprobs":[],"obfuscation":"UYDTgfVef9F"}
+
+ event: response.output_text.done
+ data: {"type":"response.output_text.done","sequence_number":7,"item_id":"msg_0e7bcfab8fc907240069152d1173f48192a1f37340a24e4fba","output_index":1,"content_index":0,"text":"hello","logprobs":[]}
+
+ event: response.content_part.done
+ data: {"type":"response.content_part.done","sequence_number":8,"item_id":"msg_0e7bcfab8fc907240069152d1173f48192a1f37340a24e4fba","output_index":1,"content_index":0,"part":{"type":"output_text","annotations":[],"logprobs":[],"text":"hello"}}
+
+ event: response.output_item.done
+ data: {"type":"response.output_item.done","sequence_number":9,"output_index":1,"item":{"id":"msg_0e7bcfab8fc907240069152d1173f48192a1f37340a24e4fba","type":"message","status":"completed","content":[{"type":"output_text","annotations":[],"logprobs":[],"text":"hello"}],"role":"assistant"}}
+
+ event: response.completed
+ data: {"type":"response.completed","sequence_number":10,"response":{"id":"resp_0e7bcfab8fc907240069152d0ff4cc819281594994abcec45f","object":"response","created_at":1762995472,"status":"completed","background":false,"error":null,"incomplete_details":null,"instructions":null,"max_output_tokens":128000,"max_tool_calls":null,"model":"gpt-5-mini-2025-08-07","output":[{"id":"rs_0e7bcfab8fc907240069152d106c1c8192b415643fda2103a5","type":"reasoning","encrypted_content":"ABC","summary":[]},{"id":"msg_0e7bcfab8fc907240069152d1173f48192a1f37340a24e4fba","type":"message","status":"completed","content":[{"type":"output_text","annotations":[],"logprobs":[],"text":"hello"}],"role":"assistant"}],"parallel_tool_calls":true,"previous_response_id":null,"prompt_cache_key":null,"prompt_cache_retention":null,"reasoning":{"effort":"low","summary":"detailed"},"safety_identifier":null,"service_tier":"default","store":true,"temperature":1.0,"text":{"format":{"type":"text"},"verbosity":"medium"},"tool_choice":"auto","tools":[],"top_logprobs":0,"top_p":1.0,"truncation":"disabled","usage":{"input_tokens":26,"input_tokens_details":{"cached_tokens":0},"output_tokens":7,"output_tokens_details":{"reasoning_tokens":0},"total_tokens":33},"user":null,"metadata":{}}}
+ TEXT
+
+ partials = []
+
+ body = nil
+ stub_request(:post, "https://api.openai.com/v1/responses").with(
+ body: ->(b) do
+ body = JSON.parse(b, symbolize_names: true)
+ true
+ end,
+ ).to_return(status: 200, body: response_payload)
+
+ model
+ .to_llm
+ .generate("Say: Hello World", user: Discourse.system_user, output_thinking: true) do |partial|
+ partials << partial
+ end
+
+ expect(body[:include]).to eq(["reasoning.encrypted_content"])
+ expect(body[:reasoning][:summary]).to eq("auto")
+
+ expect(partials.length).to eq(4)
+
+ expect(partials[0]).to eq(
+ DiscourseAi::Completions::Thinking.new(message: "**Craft", partial: true),
+ )
+
+ expect(partials[1]).to eq(DiscourseAi::Completions::Thinking.new(message: "ing", partial: true))
+ final_thinking =
+ DiscourseAi::Completions::Thinking.new(
+ message: "**Crafting",
+ partial: false,
+ provider_info: {
+ open_ai_responses: {
+ reasoning_id: "rs_0391d4281ead19e40069142428f734819da32f5c13bd277a25",
+ encrypted_content: "ABC",
+ next_message_id: "msg_0e7bcfab8fc907240069152d1173f48192a1f37340a24e4fba",
+ },
+ },
+ )
+ expect(partials[2]).to eq(final_thinking)
+ expect(partials[2].provider_info[:open_ai_responses]).to include(
+ reasoning_id: "rs_0391d4281ead19e40069142428f734819da32f5c13bd277a25",
+ next_message_id: "msg_0e7bcfab8fc907240069152d1173f48192a1f37340a24e4fba",
+ )
+ expect(partials[3]).to eq("hello")
+
+ log = AiApiAuditLog.last
+
+ expect(log).to be_present
+ expect(log.request_tokens).to eq(26)
+ expect(log.response_tokens).to eq(7)
+ expect(log.cached_tokens).to eq(0)
+ end
+
it "can perform simple streaming completion" do
response_payload = <<~TEXT
event: response.created
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 21902795ee3..ba80be56940 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
@@ -1014,7 +1014,7 @@ TEXT
endpoint.perform_completion!(dialect, user)
- expect(parsed_body[:reasoning]).to eq({ effort: "minimal" })
+ expect(parsed_body[:reasoning]).to include(effort: "minimal", summary: "auto")
expect(parsed_body).not_to have_key(:reasoning_effort)
end
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
index 1c57b5fd46d..2200d8af35c 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
@@ -118,7 +118,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
JS
tool_name = "custom-#{custom_tool.id}"
- ai_persona.update!(tools: [[tool_name, nil, true]], tool_details: false)
+ ai_persona.update!(tools: [[tool_name, nil, true]], show_thinking: false)
reply_post = nil
prompts = nil
@@ -135,7 +135,9 @@ RSpec.describe DiscourseAi::AiBot::Playground do
upload = Upload.find(upload_id)
- expect(reply_post.raw).to eq("![image](#{upload.short_url})")
+ expect(reply_post.raw).to match(
+ /\A\*\*searching for things\*\*\s+!\[image\]\(#{Regexp.escape(upload.short_url)}\)\s*\z/,
+ )
end
it "can force usage of a tool" do
@@ -172,6 +174,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
end
it "uses custom tool in conversation" do
+ ai_persona.update!(show_thinking: true)
persona_klass = AiPersona.all_personas.find { |p| p.name == ai_persona.name }
bot = DiscourseAi::Personas::Bot.as(bot_user, persona: persona_klass.new)
playground = described_class.new(bot)
@@ -186,11 +189,12 @@ RSpec.describe DiscourseAi::AiBot::Playground do
end
expected = <<~TXT.strip
- <details>
- <summary>searching for things</summary>
- <p>did stuff</p>
+ <details><summary>#{I18n.t("discourse_ai.ai_bot.thinking")}</summary>
+
+ **searching for things**
+ did stuff
+
</details>
- <span></span>
custom tool did stuff (maybe)
TXT
@@ -408,18 +412,19 @@ RSpec.describe DiscourseAi::AiBot::Playground do
guardian: guardian,
)
+ anthropic_info = { anthropic: { signature: "thinking-signature-123" } }
thinking_partial =
DiscourseAi::Completions::Thinking.new(
message: "I should say hello",
- signature: "thinking-signature-123",
partial: true,
+ provider_info: anthropic_info,
)
thinking =
DiscourseAi::Completions::Thinking.new(
message: "I should say hello",
- signature: "thinking-signature-123",
partial: false,
+ provider_info: anthropic_info,
)
DiscourseAi::Completions::Llm.with_prepared_responses(
[[thinking_partial, thinking, "wo", "rld"]],
@@ -879,19 +884,23 @@ RSpec.describe DiscourseAi::AiBot::Playground do
it "preserves thinking context between replies and correctly renders" do
thinking_progress =
DiscourseAi::Completions::Thinking.new(message: "I should say hello", partial: true)
+ anthropic_info = { anthropic: { signature: "thinking-signature-123" } }
thinking =
DiscourseAi::Completions::Thinking.new(
message: "I should say hello",
- signature: "thinking-signature-123",
partial: false,
+ provider_info: anthropic_info,
)
thinking_redacted =
DiscourseAi::Completions::Thinking.new(
message: nil,
- signature: "thinking-redacted-signature-123",
partial: false,
- redacted: true,
+ provider_info: {
+ anthropic: {
+ redacted_signature: "thinking-redacted-signature-123",
+ },
+ },
)
first_responses = [[thinking_progress, thinking, thinking_redacted, "Hello Sam"]]
@@ -923,8 +932,12 @@ RSpec.describe DiscourseAi::AiBot::Playground do
type: :model,
content: "Hello Sam",
thinking: "I should say hello",
- thinking_signature: "thinking-signature-123",
- redacted_thinking_signature: "thinking-redacted-signature-123",
+ thinking_provider_info: {
+ anthropic: {
+ signature: "thinking-signature-123",
+ redacted_signature: "thinking-redacted-signature-123",
+ },
+ },
},
{ type: :user, content: "Say Cat", id: user.username },
],
@@ -992,8 +1005,8 @@ RSpec.describe DiscourseAi::AiBot::Playground do
expect(last_post.raw).to include("I found stuff")
end
- it "supports disabling tool details" do
- persona = Fabricate(:ai_persona, tool_details: false, tools: ["Search"])
+ it "supports disabling thinking" do
+ persona = Fabricate(:ai_persona, show_thinking: false, tools: ["Search"])
bot = DiscourseAi::Personas::Bot.as(bot_user, persona: persona.class_instance.new)
playground = described_class.new(bot)
@@ -1069,8 +1082,8 @@ RSpec.describe DiscourseAi::AiBot::Playground do
)
end
- it "properly returns an image when skipping tool details" do
- persona.update!(tool_details: false)
+ it "properly returns an image when skipping thinking" do
+ persona.update!(show_thinking: false)
WebMock.stub_request(:post, SiteSetting.ai_openai_image_generation_url).to_return(
status: 200,
diff --git a/plugins/discourse-ai/spec/lib/translation/base_translator_spec.rb b/plugins/discourse-ai/spec/lib/translation/base_translator_spec.rb
index 2e439b3d795..9eb09e58675 100644
--- a/plugins/discourse-ai/spec/lib/translation/base_translator_spec.rb
+++ b/plugins/discourse-ai/spec/lib/translation/base_translator_spec.rb
@@ -52,7 +52,7 @@ describe DiscourseAi::Translation::BaseTranslator do
expect(DiscourseAi::Personas::BotContext).to have_received(:new).with(
user: an_instance_of(User),
- skip_tool_details: true,
+ skip_show_thinking: true,
feature_name: "translation",
messages: [{ type: :user, content: expected_content }],
topic: topic,
diff --git a/plugins/discourse-ai/spec/requests/admin/ai_personas_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_personas_controller_spec.rb
index 88376a39f0e..1b61a515234 100644
--- a/plugins/discourse-ai/spec/requests/admin/ai_personas_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/admin/ai_personas_controller_spec.rb
@@ -931,7 +931,7 @@ RSpec.describe DiscourseAi::Admin::AiPersonasController do
# this simplifies function calls
fake_endpoint.chunk_count = 1
- ai_persona.update!(tools: ["Categories"])
+ ai_persona.update!(tools: ["Categories"], show_thinking: true)
# lets also unstage the user and add the user to tl0
# this will ensure there are no feedback loops
diff --git a/plugins/discourse-ai/test/javascripts/unit/models/ai-persona-test.js b/plugins/discourse-ai/test/javascripts/unit/models/ai-persona-test.js
index 8b11c3c0657..2d393cf17cf 100644
--- a/plugins/discourse-ai/test/javascripts/unit/models/ai-persona-test.js
+++ b/plugins/discourse-ai/test/javascripts/unit/models/ai-persona-test.js
@@ -49,7 +49,7 @@ module("Discourse AI | Unit | Model | ai-persona", function () {
rag_llm_model_id: 1,
question_consolidator_llm_id: 2,
allow_chat: false,
- tool_details: true,
+ show_thinking: true,
forced_tool_count: -1,
allow_personal_messages: true,
allow_topic_mentions: true,