Skip to content

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

FEATURE: add native structured output support for Claude 4+ (#37975)

Sam8eec9465f6ae
diff --git a/plugins/discourse-ai/app/models/llm_model.rb b/plugins/discourse-ai/app/models/llm_model.rb
index 363dd87b393..b2555994e58 100644
--- a/plugins/discourse-ai/app/models/llm_model.rb
+++ b/plugins/discourse-ai/app/models/llm_model.rb
@@ -59,6 +59,7 @@ class LlmModel < ActiveRecord::Base
role_arn: :text,
region: :text,
disable_native_tools: :checkbox,
+ disable_native_structured_output: :checkbox,
disable_temperature: :checkbox,
disable_top_p: :checkbox,
enable_reasoning: :checkbox,
@@ -76,6 +77,7 @@ class LlmModel < ActiveRecord::Base
},
anthropic: {
disable_native_tools: :checkbox,
+ disable_native_structured_output: :checkbox,
disable_temperature: :checkbox,
disable_top_p: :checkbox,
enable_reasoning: :checkbox,
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index a557e673f03..dabfc72e173 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -847,6 +847,7 @@ en:
disable_system_prompt: "Disable system message in prompts"
enable_native_tool: "Enable native tool support"
disable_native_tools: "Disable native tool support (use XML based tools)"
+ disable_native_structured_output: "Disable native structured output (use assistant message prefilling instead, required for Claude 3.x and older)"
provider_order: "Provider order (comma delimited list)"
provider_quantizations: "Order of provider quantizations (comma delimited list eg: fp16,fp8)"
disable_streaming: "Disable streaming completions (convert streaming to non streaming requests)"
diff --git a/plugins/discourse-ai/db/migrate/20260223032030_disable_native_structured_output_for_old_claude_models.rb b/plugins/discourse-ai/db/migrate/20260223032030_disable_native_structured_output_for_old_claude_models.rb
new file mode 100644
index 00000000000..6e241edc065
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20260223032030_disable_native_structured_output_for_old_claude_models.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+class DisableNativeStructuredOutputForOldClaudeModels < ActiveRecord::Migration[7.2]
+ def up
+ # Native structured output (output_config.format) is only supported on Claude 4+ models.
+ # Set the disable flag for all existing old Claude models so they fall back to assistant
+ # message prefilling for JSON output.
+ execute <<~SQL
+ UPDATE llm_models
+ SET provider_params = COALESCE(provider_params, '{}'::jsonb) || '{"disable_native_structured_output": true}'::jsonb
+ WHERE provider IN ('anthropic', 'aws_bedrock')
+ AND (
+ name LIKE 'claude-2%'
+ OR name LIKE 'claude-instant%'
+ OR name LIKE 'claude-3-%'
+ OR name LIKE 'claude-3.%'
+ OR name LIKE 'anthropic.claude-v2%'
+ OR name LIKE 'anthropic.claude-instant%'
+ OR name LIKE 'anthropic.claude-3-%'
+ )
+ SQL
+ end
+
+ def down
+ execute <<~SQL
+ UPDATE llm_models
+ SET provider_params = provider_params - 'disable_native_structured_output'
+ WHERE provider IN ('anthropic', 'aws_bedrock')
+ SQL
+ end
+end
diff --git a/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb b/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb
index 30836d5bd85..19e173e82be 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb
@@ -5,18 +5,12 @@ module DiscourseAi
module Endpoints
class Anthropic < Base
include AnthropicPromptCache
+ include AnthropicShared
+
def self.can_contact?(llm_model)
llm_model.provider == "anthropic"
end
- def normalize_model_params(model_params)
- # max_tokens, temperature, stop_sequences are already supported
- 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")
- model_params
- end
-
def default_options(dialect)
mapped_model =
case llm_model.name
@@ -69,81 +63,15 @@ module DiscourseAi
options
end
- def provider_id
- AiApiAuditLog::Provider::Anthropic
- end
-
private
- def xml_tags_to_strip(dialect)
- if dialect.prompt.has_tools?
- %w[thinking search_quality_reflection search_quality_score]
- else
- []
- end
- end
-
- # this is an approximation, we will update it later if request goes through
- def prompt_size(prompt)
- tokenizer.size(prompt.system_prompt.to_s + " " + prompt.messages.to_s)
- end
-
def model_uri
URI(llm_model.url)
end
- def xml_tools_enabled?
- !@native_tool_support
- end
-
def prepare_payload(prompt, model_params, dialect)
- @native_tool_support = dialect.native_tool_support?
-
- payload =
- default_options(dialect).merge(model_params.except(:response_format)).merge(
- messages: prompt.messages,
- )
-
- # Handle tools first
- if prompt.has_tools?
- payload[:tools] = prompt.tools
- if dialect.tool_choice.present?
- if dialect.tool_choice == :none
- payload[:tool_choice] = { type: "none" }
- else
- payload[:tool_choice] = { type: "tool", name: prompt.tool_choice }
- end
- end
- end
-
- # Apply prompt caching if enabled
- apply_anthropic_cache_control!(payload, prompt) if should_apply_prompt_caching?(prompt)
-
- # Set system prompt if not already set by caching
- payload[:system] = prompt.system_prompt if prompt.system_prompt.present? &&
- !payload[:system]
+ payload = prepare_claude_payload(prompt, model_params, dialect)
payload[:stream] = true if @streaming_mode
-
- prefilled_message = +""
-
- # Handle tool choice prefilling
- if dialect.tool_choice == :none && prompt.has_tools?
- # prefill prompt to nudge LLM to generate a response that is useful.
- # without this LLM (even 3.7) can get confused and start text preambles for a tool calls.
- prefilled_message << dialect.no_more_tool_calls_text
- end
-
- # Prefill prompt to force JSON output.
- if model_params[:response_format].present?
- prefilled_message << " " if !prefilled_message.empty?
- prefilled_message << "{"
- @forced_json_through_prefill = true
- end
-
- if !prefilled_message.empty?
- payload[:messages] << { role: "assistant", content: prefilled_message }
- end
-
payload
end
@@ -164,34 +92,12 @@ module DiscourseAi
.compact
end
- def decode(response_data)
- processor.process_message(response_data)
- end
-
def processor
- @processor ||=
- DiscourseAi::Completions::AnthropicMessageProcessor.new(
- streaming_mode: @streaming_mode,
- partial_tool_calls: partial_tool_calls,
- output_thinking: output_thinking,
- )
- end
-
- def has_tool?(_response_data)
- processor.tool_calls.present?
- end
-
- def tool_calls
- processor.to_tool_calls
+ claude_processor
end
def final_log_update(log)
- log.request_tokens = processor.input_tokens if processor.input_tokens
- log.response_tokens = processor.output_tokens if processor.output_tokens
- log.cache_read_tokens =
- processor.cache_read_input_tokens if processor.cache_read_input_tokens
- log.cache_write_tokens =
- processor.cache_creation_input_tokens if processor.cache_creation_input_tokens
+ update_log_from_claude_processor(log)
end
end
end
diff --git a/plugins/discourse-ai/lib/completions/endpoints/anthropic_shared.rb b/plugins/discourse-ai/lib/completions/endpoints/anthropic_shared.rb
new file mode 100644
index 00000000000..2bda2a4fb7b
--- /dev/null
+++ b/plugins/discourse-ai/lib/completions/endpoints/anthropic_shared.rb
@@ -0,0 +1,117 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Completions
+ module Endpoints
+ 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")
+ model_params
+ end
+
+ def provider_id
+ AiApiAuditLog::Provider::Anthropic
+ end
+
+ def xml_tags_to_strip(dialect)
+ if dialect.prompt.has_tools?
+ %w[thinking search_quality_reflection search_quality_score]
+ else
+ []
+ end
+ end
+
+ private
+
+ def prompt_size(prompt)
+ tokenizer.size(prompt.system_prompt.to_s + " " + prompt.messages.to_s)
+ end
+
+ def xml_tools_enabled?
+ !@native_tool_support
+ end
+
+ def supports_native_structured_output?
+ !llm_model.lookup_custom_param("disable_native_structured_output")
+ end
+
+ def decode(response_data)
+ processor.process_message(response_data)
+ end
+
+ def claude_processor
+ @processor ||=
+ DiscourseAi::Completions::AnthropicMessageProcessor.new(
+ streaming_mode: @streaming_mode,
+ partial_tool_calls: partial_tool_calls,
+ output_thinking: output_thinking,
+ )
+ end
+
+ def update_log_from_claude_processor(log)
+ log.request_tokens = processor.input_tokens if processor.input_tokens
+ log.response_tokens = processor.output_tokens if processor.output_tokens
+ log.cache_read_tokens =
+ processor.cache_read_input_tokens if processor.cache_read_input_tokens
+ log.cache_write_tokens =
+ processor.cache_creation_input_tokens if processor.cache_creation_input_tokens
+ end
+
+ def prepare_claude_payload(prompt, model_params, dialect)
+ @native_tool_support = dialect.native_tool_support?
+
+ payload =
+ default_options(dialect).merge(model_params.except(:response_format)).merge(
+ messages: prompt.messages,
+ )
+
+ if prompt.has_tools?
+ payload[:tools] = prompt.tools
+ apply_tool_choice(payload, dialect, prompt)
+ end
+
+ apply_anthropic_cache_control!(payload, prompt) if should_apply_prompt_caching?(prompt)
+
+ 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?
+ json_schema = response_format.dig(:json_schema, :schema)
+ if json_schema.present?
+ payload[:output_config] ||= {}
+ payload[:output_config][:format] = { type: "json_schema", schema: json_schema }
+ end
+ else
+ payload[:messages] << { role: "assistant", content: "{" }
+ @forced_json_through_prefill = true
+ end
+ end
+
+ payload
+ end
+
+ def apply_tool_choice(payload, dialect, prompt)
+ return if dialect.tool_choice.blank?
+ if dialect.tool_choice == :none
+ payload[:tool_choice] = { type: "none" }
+ 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
+ end
+ 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 d8e217514da..7a33ea33be7 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rb
@@ -7,23 +7,13 @@ module DiscourseAi
module Endpoints
class AwsBedrock < Base
include AnthropicPromptCache
+ include AnthropicShared
attr_reader :dialect
def self.can_contact?(llm_model)
llm_model.provider == "aws_bedrock"
end
- def normalize_model_params(model_params)
- model_params = model_params.dup
-
- # max_tokens, temperature, stop_sequences, top_p are already supported
- #
- 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")
-
- model_params
- end
-
def default_options(dialect)
options =
if dialect.is_a?(DiscourseAi::Completions::Dialects::Claude)
@@ -57,18 +47,6 @@ module DiscourseAi
options
end
- def provider_id
- AiApiAuditLog::Provider::Anthropic
- end
-
- def xml_tags_to_strip(dialect)
- if dialect.prompt.has_tools?
- %w[thinking search_quality_reflection search_quality_score]
- else
- []
- end
- end
-
private
def bedrock_model_id
@@ -110,11 +88,6 @@ module DiscourseAi
end
end
- def prompt_size(prompt)
- # approximation
- tokenizer.size(prompt.system_prompt.to_s + " " + prompt.messages.to_s)
- end
-
def model_uri
region = llm_model.lookup_custom_param("region")
@@ -131,62 +104,28 @@ module DiscourseAi
end
def prepare_payload(prompt, model_params, dialect)
- @native_tool_support = dialect.native_tool_support?
@dialect = dialect
- payload = nil
-
if dialect.is_a?(DiscourseAi::Completions::Dialects::Claude)
- payload =
- default_options(dialect).merge(model_params.except(:response_format)).merge(
- messages: prompt.messages,
- )
-
- # Handle tools first
- if prompt.has_tools?
- payload[:tools] = prompt.tools
- if dialect.tool_choice.present?
- if dialect.tool_choice == :none
- # not supported on bedrock as of 2025-03-24
- # retest in 6 months
- # payload[:tool_choice] = { type: "none" }
- else
- payload[:tool_choice] = { type: "tool", name: prompt.tool_choice }
- end
- end
- end
-
- # Apply prompt caching if enabled (only for Anthropic models)
- apply_anthropic_cache_control!(payload, prompt) if should_apply_prompt_caching?(prompt)
-
- # Set system prompt if not already set by caching
- payload[:system] = prompt.system_prompt if prompt.system_prompt.present? &&
- !payload[:system]
-
- prefilled_message = +""
-
- # Handle tool choice prefilling
- if dialect.tool_choice == :none && prompt.has_tools?
- # prefill prompt to nudge LLM to generate a response that is useful, instead of trying to call a tool
- prefilled_message << dialect.no_more_tool_calls_text
- end
-
- # Prefill prompt to force JSON output.
- if model_params[:response_format].present?
- prefilled_message << " " if !prefilled_message.empty?
- prefilled_message << "{"
- @forced_json_through_prefill = true
- end
-
- if !prefilled_message.empty?
- payload[:messages] << { role: "assistant", content: prefilled_message }
- end
+ prepare_claude_payload(prompt, model_params, dialect)
elsif dialect.is_a?(DiscourseAi::Completions::Dialects::Nova)
- payload = prompt.to_payload(default_options(dialect).merge(model_params))
+ prompt.to_payload(default_options(dialect).merge(model_params))
else
raise "Unsupported dialect"
end
- payload
+ 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)
@@ -239,10 +178,6 @@ module DiscourseAi
.compact
end
- def decode(response_data)
- processor.process_message(response_data)
- end
-
def bedrock_decode(chunk)
@decoder ||= Aws::EventStream::Decoder.new
@@ -282,36 +217,24 @@ module DiscourseAi
end
def final_log_update(log)
- log.request_tokens = processor.input_tokens if processor.input_tokens
- log.response_tokens = processor.output_tokens if processor.output_tokens
log.raw_response_payload = @raw_response if @raw_response
- # Handle cache tokens for Anthropic models
if dialect.is_a?(DiscourseAi::Completions::Dialects::Claude)
- log.cache_read_tokens =
- processor.cache_read_input_tokens if processor.cache_read_input_tokens
- log.cache_write_tokens =
- processor.cache_creation_input_tokens if processor.cache_creation_input_tokens
+ update_log_from_claude_processor(log)
+ else
+ log.request_tokens = processor.input_tokens if processor.input_tokens
+ log.response_tokens = processor.output_tokens if processor.output_tokens
end
end
def processor
if dialect.is_a?(DiscourseAi::Completions::Dialects::Claude)
- @processor ||=
- DiscourseAi::Completions::AnthropicMessageProcessor.new(
- streaming_mode: @streaming_mode,
- partial_tool_calls: partial_tool_calls,
- output_thinking: output_thinking,
- )
+ claude_processor
else
@processor ||=
DiscourseAi::Completions::NovaMessageProcessor.new(streaming_mode: @streaming_mode)
end
end
-
- def xml_tools_enabled?
- !@native_tool_support
- 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 80b36c3c9ab..1681f114f0e 100644
--- a/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb
@@ -1128,18 +1128,75 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic do
# Verify that tool_choice is set to { type: "none" }
expect(parsed_body[:tool_choice]).to eq({ type: "none" })
- # Verify that an assistant message with no_more_tool_calls_text was added
+ # Verify no assistant prefill message was added
messages = parsed_body[:messages]
- expect(messages.length).to eq(2) # user message + added assistant message
+ expect(messages.length).to eq(1)
- last_message = messages.last
- expect(last_message[:role]).to eq("assistant")
+ expect(result).to eq("I won't use any tools. Here's a direct response instead.")
+ end
+ end
- expect(last_message[:content]).to eq(
- DiscourseAi::Completions::Dialects::Dialect.no_more_tool_calls_text,
- )
+ describe "tool_choice :none with response_format" do
+ it "sets tool_choice none and appends assistant prefill when structured output is disabled" do
+ model.update!(provider_params: { disable_native_structured_output: true })
- expect(result).to eq("I won't use any tools. Here's a direct response instead.")
+ schema = {
+ type: "json_schema",
+ json_schema: {
+ name: "reply",
+ schema: {
+ type: "object",
+ properties: {
+ key: {
+ type: "string",
+ },
+ },
+ required: ["key"],
+ additionalProperties: false,
+ },
+ strict: true,
+ },
+ }
+
+ prompt =
+ DiscourseAi::Completions::Prompt.new(
+ "You are a bot",
+ messages: [type: :user, id: "user1", content: "reply as json"],
+ tools: [echo_tool],
+ tool_choice: :none,
+ )
+
+ response_body = {
+ id: "msg_01RdJkxCbsEj9VFyFYAkfy2S",
+ type: "message",
+ role: "assistant",
+ model: "claude-3-haiku-20240307",
+ content: [{ type: "text", text: "\"key\":\"value\"}" }],
+ stop_reason: "end_turn",
+ 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, response_format: schema)
+
+ expect(parsed_body[:tool_choice]).to eq({ type: "none" })
+ expect(parsed_body).not_to have_key(:output_config)
+
+ messages = parsed_body[:messages]
+ expect(messages.length).to eq(2)
+ expect(messages[0][:role]).to eq("user")
+ expect(messages[1]).to eq({ role: "assistant", content: "{" })
end
end
@@ -1192,7 +1249,7 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic do
end
end
- describe "structured output via prefilling" do
+ describe "structured output via output_config" do
it "forces the response to be a JSON and using the given JSON schema" do
schema = {
type: "json_schema",
@@ -1219,6 +1276,9 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic do
event: content_block_start
data: {"type": "content_block_start", "index":0, "content_block": {"type": "text", "text": ""}}
+ event: content_block_delta
+ data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "{"}}
+
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "\\""}}
@@ -1286,14 +1346,93 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic do
expected_body = {
model: "claude-3-opus-20240229",
max_tokens: 4096,
- messages: [{ role: "user", content: "user1: hello" }, { role: "assistant", content: "{" }],
+ messages: [{ role: "user", content: "user1: hello" }],
system: "You are hello bot",
stream: true,
+ output_config: {
+ format: {
+ type: "json_schema",
+ schema: schema[:json_schema][:schema],
+ },
+ },
}
expect(parsed_body).to eq(expected_body)
end
end
+ describe "structured output via prefilling when native structured output is disabled" do
+ it "falls back to assistant message prefill" do
+ model.update!(provider_params: { disable_native_structured_output: true })
+
+ schema = {
+ type: "json_schema",
+ json_schema: {
+ name: "reply",
+ schema: {
+ type: "object",
+ properties: {
+ key: {
+ type: "string",
+ },
+ },
+ required: ["key"],
+ additionalProperties: false,
+ },
+ strict: true,
+ },
+ }
+
+ body = (<<~STRING).strip
+ event: message_start
+ data: {"type": "message_start", "message": {"id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY", "type": "message", "role": "assistant", "content": [], "model": "claude-3-opus-20240229", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 25, "output_tokens": 1}}}
+
+ event: content_block_start
+ data: {"type": "content_block_start", "index":0, "content_block": {"type": "text", "text": ""}}
+
+ event: content_block_delta
+ data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "\\""}}
+
+ event: content_block_delta
+ data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "key\\":\\""}}
+
+ event: content_block_delta
+ data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "value\\"}"}}
+
+ event: content_block_stop
+ data: {"type": "content_block_stop", "index": 0}
+
+ event: message_delta
+ data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence":null, "usage":{"output_tokens": 15}}}
+
+ event: message_stop
+ data: {"type": "message_stop"}
+ STRING
+
+ 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: body)
+
+ structured_output = nil
+ llm.generate(
+ prompt,
+ user: Discourse.system_user,
+ feature_name: "testing",
+ response_format: schema,
+ ) { |partial, cancel| structured_output = partial }
+
+ expect(structured_output.read_buffered_property(:key)).to eq("value")
+
+ messages = parsed_body[:messages]
+ expect(messages.last).to eq({ role: "assistant", content: "{" })
+ expect(parsed_body).not_to have_key(:output_config)
+ end
+ end
+
describe "effort parameter" do
it "includes effort in output_config when set to low, medium, or high" do
model.update!(provider_params: { effort: "high" })
@@ -1428,5 +1567,65 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic do
llm.generate(prompt, user: Discourse.system_user)
expect(parsed_body).not_to have_key(:output_config)
end
+
+ it "merges effort and structured output format in output_config" do
+ model.update!(provider_params: { effort: "high" })
+
+ schema = {
+ type: "json_schema",
+ json_schema: {
+ name: "reply",
+ schema: {
+ type: "object",
+ properties: {
+ key: {
+ type: "string",
+ },
+ },
+ required: ["key"],
+ additionalProperties: false,
+ },
+ strict: true,
+ },
+ }
+
+ body = (<<~STRING).strip
+ event: message_start
+ data: {"type": "message_start", "message": {"id": "msg_123", "type": "message", "role": "assistant", "content": [], "model": "claude-3-opus-20240229", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 25, "output_tokens": 1}}}
+
+ event: content_block_start
+ data: {"type": "content_block_start", "index":0, "content_block": {"type": "text", "text": ""}}
+
+ event: content_block_delta
+ data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "{"}}
+
+ event: content_block_delta
+ data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "\\"key\\":\\"value\\"}"}}
+
+ event: content_block_stop
+ data: {"type": "content_block_stop", "index": 0}
+
+ event: message_delta
+ data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence":null, "usage":{"output_tokens": 15}}}
+
+ event: message_stop
+ data: {"type": "message_stop"}
+ STRING
+
+ 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: body)
+
+ llm.generate(prompt, user: Discourse.system_user, response_format: schema) { |partial| }
+
+ expect(parsed_body[:output_config]).to eq(
+ { effort: "high", format: { type: "json_schema", schema: schema[:json_schema][:schema] } },
+ )
+ end
end
end
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 a62d3ccf594..ae675c0ebff 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
@@ -489,11 +489,10 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
end
describe "disabled tool use" do
- it "handles tool_choice: :none by adding a prefill message instead of using tool_choice param" do
+ it "handles tool_choice: :none by adding a user message instead of using tool_choice param" do
proxy = DiscourseAi::Completions::Llm.proxy(model)
request = nil
- # Create a prompt with tool_choice: :none
prompt =
DiscourseAi::Completions::Prompt.new(
"You are a helpful assistant",
@@ -510,7 +509,6 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
tool_choice: :none,
)
- # Mock response from Bedrock
content = {
content: [text: "I won't use any tools. Here's a direct response instead."],
usage: {
@@ -531,22 +529,98 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
proxy.generate(prompt, user: user)
- # Parse the request body
request_body = JSON.parse(request.body)
- # Verify that tool_choice is NOT present (not supported in Bedrock)
expect(request_body).not_to have_key("tool_choice")
- # Verify that an assistant message was added with no_more_tool_calls_text
messages = request_body["messages"]
- expect(messages.length).to eq(2) # user message + added assistant message
+ expect(messages.length).to eq(2)
last_message = messages.last
- expect(last_message["role"]).to eq("assistant")
+ expect(last_message["role"]).to eq("user")
expect(last_message["content"]).to eq(
- DiscourseAi::Completions::Dialects::Dialect.no_more_tool_calls_text,
+ DiscourseAi::Completions::Dialects::Dialect.no_more_tool_calls_text_user,
+ )
+ end
+ end
+
+ describe "tool_choice :none with response_format" do
+ it "injects user message workaround and assistant prefill when structured output is disabled" do
+ model.update!(
+ provider_params: model.provider_params.merge("disable_native_structured_output" => true),
+ )
+
+ schema = {
+ type: "json_schema",
+ json_schema: {
+ name: "reply",
+ schema: {
+ type: "object",
+ properties: {
+ key: {
+ type: "string",
+ },
+ },
+ required: ["key"],
+ additionalProperties: false,
+ },
+ strict: true,
+ },
+ }
+
+ prompt =
+ DiscourseAi::Completions::Prompt.new(
+ "You are a helpful assistant",
+ messages: [{ type: :user, content: "reply as json" }],
+ tools: [
+ {
+ name: "echo",
+ description: "echo something",
+ parameters: [
+ { name: "text", type: "string", description: "text to echo", required: true },
+ ],
+ },
+ ],
+ tool_choice: :none,
+ )
+
+ proxy = DiscourseAi::Completions::Llm.proxy(model)
+ request = nil
+
+ content = {
+ content: [text: "\"key\":\"value\"}"],
+ usage: {
+ input_tokens: 25,
+ output_tokens: 15,
+ },
+ }.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(prompt, user: user, response_format: schema)
+
+ request_body = JSON.parse(request.body)
+
+ expect(request_body).not_to have_key("tool_choice")
+ expect(request_body).not_to have_key("output_config")
+
+ messages = request_body["messages"]
+ expect(messages.length).to eq(3)
+ 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" => "{" })
end
end
@@ -869,7 +943,7 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
end
end
- describe "structured output via prefilling" do
+ describe "structured output via output_config" do
it "forces the response to be a JSON and using the given JSON schema" do
schema = {
type: "json_schema",
@@ -892,7 +966,7 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
messages =
[
{ type: "message_start", message: { usage: { input_tokens: 9 } } },
- { type: "content_block_delta", delta: { text: "\"" } },
+ { type: "content_block_delta", delta: { text: "{\"" } },
{ type: "content_block_delta", delta: { text: "key" } },
{ type: "content_block_delta", delta: { text: "\":\"" } },
{ type: "content_block_delta", delta: { text: "Hello!" } },
@@ -922,11 +996,14 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
expected = {
"max_tokens" => 4096,
"anthropic_version" => "bedrock-2023-05-31",
- "messages" => [
- { "role" => "user", "content" => "hello world" },
- { "role" => "assistant", "content" => "{" },
- ],
+ "messages" => [{ "role" => "user", "content" => "hello world" }],
"system" => "You are a helpful bot",
+ "output_config" => {
+ "format" => {
+ "type" => "json_schema",
+ "schema" => schema[:json_schema][:schema].deep_stringify_keys,
+ },
+ },
}
expect(JSON.parse(request.body)).to eq(expected)
@@ -962,7 +1039,7 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
messages =
[
{ type: "message_start", message: { usage: { input_tokens: 9 } } },
- { type: "content_block_delta", delta: { text: "\"" } },
+ { type: "content_block_delta", delta: { text: "{\"" } },
{ type: "content_block_delta", delta: { text: "key" } },
{ type: "content_block_delta", delta: { text: "\":" } },
{ type: "content_block_delta", delta: { text: " [\"" } },
@@ -1000,11 +1077,14 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
expected = {
"max_tokens" => 4096,
"anthropic_version" => "bedrock-2023-05-31",
- "messages" => [
- { "role" => "user", "content" => "hello world" },
- { "role" => "assistant", "content" => "{" },
- ],
+ "messages" => [{ "role" => "user", "content" => "hello world" }],
"system" => "You are a helpful bot",
+ "output_config" => {
+ "format" => {
+ "type" => "json_schema",
+ "schema" => schema[:json_schema][:schema].deep_stringify_keys,
+ },
+ },
}
expect(JSON.parse(request.body)).to eq(expected)
@@ -1017,6 +1097,63 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
end
end
+ describe "structured output via prefilling when native structured output is disabled" do
+ it "falls back to assistant message prefill" do
+ model.update!(
+ provider_params: model.provider_params.merge("disable_native_structured_output" => true),
+ )
+ schema = {
+ type: "json_schema",
+ json_schema: {
+ name: "reply",
+ schema: {
+ type: "object",
+ properties: {
+ key: {
+ type: "string",
+ },
+ },
+ required: ["key"],
+ additionalProperties: false,
+ },
+ strict: true,
+ },
+ }
+
+ messages =
+ [
+ { type: "message_start", message: { usage: { input_tokens: 9 } } },
+ { type: "content_block_delta", delta: { text: "\"key\":\"value\"}" } },
+ { type: "message_delta", delta: { usage: { output_tokens: 25 } } },
+ ].map { |message| encode_message(message) }
+
+ proxy = DiscourseAi::Completions::Llm.proxy(model)
+ request = nil
+ bedrock_mock.with_chunk_array_support do
+ stub_request(
+ :post,
+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-sonnet-20240229-v1:0/invoke-with-response-stream",
+ )
+ .with do |inner_request|
+ request = inner_request
+ true
+ end
+ .to_return(status: 200, body: messages)
+
+ structured_output = nil
+ proxy.generate("hello world", response_format: schema, user: user) do |partial|
+ structured_output = partial
+ end
+
+ request_body = JSON.parse(request.body)
+ expect(request_body["messages"].last).to eq({ "role" => "assistant", "content" => "{" })
+ expect(request_body).not_to have_key("output_config")
+
+ expect(structured_output.read_buffered_property(:key)).to eq("value")
+ end
+ end
+ end
+
describe "prompt caching for Anthropic models" do
it "applies caching in always mode for Claude models" do
params = model.provider_params || {}
@@ -1202,5 +1339,61 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock do
expect(request_body).not_to have_key("output_config")
expect(request_body).not_to have_key("anthropic_beta")
end
+
+ it "merges effort and structured output format in output_config" do
+ model.update!(provider_params: { access_key_id: "123", region: "us-east-1", effort: "high" })
+
+ schema = {
+ type: "json_schema",
+ json_schema: {
+ name: "reply",
+ schema: {
+ type: "object",
+ properties: {
+ key: {
+ type: "string",
+ },
+ },
+ required: ["key"],
+ additionalProperties: false,
+ },
+ strict: true,
+ },
+ }
+
+ messages =
+ [
+ { type: "message_start", message: { usage: { input_tokens: 9 } } },
+ { type: "content_block_delta", delta: { text: "{\"key\":\"value\"}" } },
+ { type: "message_delta", delta: { usage: { output_tokens: 25 } } },
+ ].map { |message| encode_message(message) }
+
+ proxy = DiscourseAi::Completions::Llm.proxy(model)
+ request = nil
+ bedrock_mock.with_chunk_array_support do
+ stub_request(
+ :post,
+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-sonnet-20240229-v1:0/invoke-with-response-stream",
+ )
+ .with do |inner_request|
+ request = inner_request
+ true
+ end
+ .to_return(status: 200, body: messages)
+
+ proxy.generate("hello world", response_format: schema, user: user) { |partial| }
+
+ request_body = JSON.parse(request.body)
+ expect(request_body["output_config"]).to eq(
+ {
+ "effort" => "high",
+ "format" => {
+ "type" => "json_schema",
+ "schema" => schema[:json_schema][:schema].deep_stringify_keys,
+ },
+ },
+ )
+ end
+ end
end
end
diff --git a/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb b/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb
index 9c549d2275e..865685c6dce 100644
--- a/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb
+++ b/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb
@@ -229,6 +229,28 @@ RSpec.describe "AI Composer helper", type: :system do
expect(composer.composer_input.value).to eq(proofread_text)
end
end
+
+ it "applies confirmed changes directly in the rich text editor" do
+ visit("/latest")
+ page.find("#create-topic").click
+
+ composer.toggle_rich_editor
+ expect(composer).to have_rich_editor_active
+
+ composer.focus
+ composer.type_content(input)
+
+ composer.click_toolbar_button("ai-helper-trigger")
+ expect(ai_helper_menu).to have_context_menu
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([proofread_text]) do
+ ai_helper_menu.select_helper_model(mode)
+ expect(diff_modal).to have_diff("spain", "Spain,")
+ diff_modal.confirm_changes
+ expect(composer.rich_editor).to have_css("p", text: proofread_text)
+ expect(composer.rich_editor).to have_no_text(input)
+ end
+ end
end
end