A platform for community discussion. Free, open, simple.
FEATURE: Add service_tier support for OpenAI endpoints (#38359)
Samb2d5dcd89da9
diff --git a/plugins/discourse-ai/app/models/llm_model.rb b/plugins/discourse-ai/app/models/llm_model.rbindex a1caa4bb50a..f9d844c6ecf 100644--- a/plugins/discourse-ai/app/models/llm_model.rb+++ b/plugins/discourse-ai/app/models/llm_model.rb@@ -138,6 +138,11 @@ class LlmModel < ActiveRecord::Basehidden_if: :reasoning_effort,},disable_streaming: :checkbox,+ service_tier: {+ type: :enum,+ values: %w[default auto flex priority],+ default: "default",+ },},groq: {disable_native_tools: :checkbox,@@ -195,6 +200,11 @@ class LlmModel < ActiveRecord::Basehidden_if: :reasoning_effort,},disable_streaming: :checkbox,+ service_tier: {+ type: :enum,+ values: %w[default auto flex priority],+ default: "default",+ },},hugging_face: {disable_system_prompt: :checkbox,diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex 2fdb676e793..1446f654632 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -860,6 +860,7 @@ en:provider_quantizations: "Order of provider quantizations (comma delimited list eg: fp16,fp8)"disable_streaming: "Disable streaming completions (convert streaming to non streaming requests)"reasoning_effort: "Reasoning effort (only applicable to reasoning models)"+ service_tier: "Service tier (flex = lower cost/higher latency, priority = faster processing)"enable_reasoning: "Enable reasoning (only applicable to reasoning models)"adaptive_thinking: "Enable adaptive thinking (recommended for Claude 4.6 models)"enable_thinking: "Enable thinking (Gemini 2.5 models - uses token budget)"diff --git a/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb b/plugins/discourse-ai/lib/completions/endpoints/open_ai.rbindex 26b10439dbf..f747a9e2837 100644--- a/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb@@ -4,94 +4,38 @@ module DiscourseAimodule Completionsmodule Endpointsclass OpenAi < Base+ include OpenAiShared+def self.can_contact?(llm_model)%w[open_ai azure groq].include?(llm_model.provider) &&!llm_model.url.to_s.include?("/v1/responses")enddef normalize_model_params(model_params)- model_params = model_params.dup+ normalized = super# max_tokens is deprecated however we still need to support it# on older OpenAI models and older Azure models, so we will only normalize# if our model name starts with o (to denote all the reasoning models)if llm_model.name.starts_with?(/o|gpt-5/)- max_tokens = model_params.delete(:max_tokens)- model_params[:max_completion_tokens] = max_tokens if max_tokens- end-- # temperature is already supported- if model_params[:stop_sequences]- model_params[:stop] = model_params.delete(:stop_sequences)+ max_tokens = normalized.delete(:max_tokens)+ normalized[:max_completion_tokens] = max_tokens if max_tokensend- if reasoning_effort- model_params.delete(:temperature)- model_params.delete(:top_p)- else- model_params.delete(:top_p) if llm_model.lookup_custom_param("disable_top_p")- if llm_model.lookup_custom_param("disable_temperature")- model_params.delete(:temperature)- end- end-- model_params- end-- def default_options- { model: llm_model.name }- end-- def provider_id- AiApiAuditLog::Provider::OpenAI- end-- def perform_completion!(- dialect,- user,- model_params = {},- feature_name: nil,- feature_context: nil,- partial_tool_calls: false,- output_thinking: false,- cancel_manager: nil,- execution_context: nil,- &blk- )- @native_tool_support = dialect.native_tool_support?- super+ normalizedendprivate- def disable_streaming?- @disable_streaming ||= llm_model.lookup_custom_param("disable_streaming")- end-- def reasoning_effort- return @reasoning_effort if defined?(@reasoning_effort)- @reasoning_effort = llm_model.lookup_custom_param("reasoning_effort")- @reasoning_effort = nil if !%w[none minimal low medium high xhigh].include?(- @reasoning_effort,- )- @reasoning_effort- end-- def model_uri- if llm_model.url.to_s.starts_with?("srv://")- service = DiscourseAi::Utils::DnsSrv.lookup(llm_model.url.sub("srv://", ""))- api_endpoint = "https://#{service.target}:#{service.port}/v1/chat/completions"- else- api_endpoint = llm_model.url- end-- @uri ||= URI(api_endpoint)+ def srv_fallback_path+ "/v1/chat/completions"enddef prepare_payload(prompt, model_params, dialect)payload = default_options.merge(model_params).merge(messages: prompt)payload.merge!({ reasoning_effort: reasoning_effort }) if reasoning_effort+ payload[:service_tier] = service_tier if service_tierif @streaming_modepayload[:stream] = true@@ -122,55 +66,6 @@ module DiscourseAipayloadend- def prepare_request(payload)- headers = { "Content-Type" => "application/json" }- api_key = llm_model.api_key-- if llm_model.provider == "azure"- headers["api-key"] = api_key- else- headers["Authorization"] = "Bearer #{api_key}"- org_id = llm_model.lookup_custom_param("organization")- headers["OpenAI-Organization"] = org_id if org_id.present?- end-- Net::HTTP::Post.new(model_uri, headers).tap { |r| r.body = payload }- end-- def final_log_update(log)- log.request_tokens = processor.prompt_tokens if processor.prompt_tokens- log.response_tokens = processor.completion_tokens if processor.completion_tokens- log.cache_read_tokens = processor.cache_read_tokens if processor.cache_read_tokens- end-- def decode(response_raw)- processor.process_message(JSON.parse(response_raw, symbolize_names: true))- end-- def decode_chunk(chunk)- @decoder ||= JsonStreamDecoder.new- elements =- (@decoder << chunk)- .map { |parsed_json| processor.process_streamed_message(parsed_json) }- .flatten- .compact-- # Remove duplicate partial tool calls- # sometimes we stream weird chunks- seen_tools = Set.new- elements.select { |item| !item.is_a?(ToolCall) || seen_tools.add?(item) }- end-- def decode_chunk_finish- processor.finish- end-- def xml_tools_enabled?- !@native_tool_support- end-- private-def processor@processor ||= OpenAiMessageProcessor.new(partial_tool_calls: partial_tool_calls)enddiff --git a/plugins/discourse-ai/lib/completions/endpoints/open_ai_responses.rb b/plugins/discourse-ai/lib/completions/endpoints/open_ai_responses.rbindex 4a19d8a7482..a525cea9c15 100644--- a/plugins/discourse-ai/lib/completions/endpoints/open_ai_responses.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/open_ai_responses.rb@@ -4,79 +4,17 @@ module DiscourseAimodule Completionsmodule Endpointsclass OpenAiResponses < Base+ include OpenAiShared+def self.can_contact?(llm_model)%w[open_ai azure].include?(llm_model.provider) &&llm_model.url.to_s.include?("/v1/responses")end- def normalize_model_params(model_params)- model_params = model_params.dup-- if model_params[:stop_sequences]- model_params[:stop] = model_params.delete(:stop_sequences)- end-- if reasoning_effort- model_params.delete(:temperature)- model_params.delete(:top_p)- else- model_params.delete(:top_p) if llm_model.lookup_custom_param("disable_top_p")- if llm_model.lookup_custom_param("disable_temperature")- model_params.delete(:temperature)- end- end-- model_params- end-- def default_options- { model: llm_model.name }- end-- def provider_id- AiApiAuditLog::Provider::OpenAI- end-- def perform_completion!(- dialect,- user,- model_params = {},- feature_name: nil,- feature_context: nil,- partial_tool_calls: false,- output_thinking: false,- cancel_manager: nil,- execution_context: nil,- &blk- )- @native_tool_support = dialect.native_tool_support?- super- end-private- def disable_streaming?- @disable_streaming ||= llm_model.lookup_custom_param("disable_streaming")- end-- def reasoning_effort- return @reasoning_effort if defined?(@reasoning_effort)- @reasoning_effort = llm_model.lookup_custom_param("reasoning_effort")- @reasoning_effort = nil if !%w[none minimal low medium high xhigh].include?(- @reasoning_effort,- )- @reasoning_effort- end-- def model_uri- if llm_model.url.to_s.starts_with?("srv://")- service = DiscourseAi::Utils::DnsSrv.lookup(llm_model.url.sub("srv://", ""))- api_endpoint = "https://#{service.target}:#{service.port}/v1/responses"- else- api_endpoint = llm_model.url- end-- @uri ||= URI(api_endpoint)+ def srv_fallback_path+ "/v1/responses"enddef prepare_payload(prompt, model_params, dialect)@@ -85,6 +23,7 @@ module DiscourseAireasoning_payload = { summary: "auto" }reasoning_payload[:effort] = reasoning_effort if reasoning_effortpayload.merge!(reasoning: reasoning_payload)+ payload[:service_tier] = service_tier if service_tierif @streaming_modepayload[:stream] = true@@ -128,51 +67,6 @@ module DiscourseAipayload.delete(:stream_options)end- def prepare_request(payload)- headers = { "Content-Type" => "application/json" }- api_key = llm_model.api_key-- if llm_model.provider == "azure"- headers["api-key"] = api_key- else- headers["Authorization"] = "Bearer #{api_key}"- org_id = llm_model.lookup_custom_param("organization")- headers["OpenAI-Organization"] = org_id if org_id.present?- end-- Net::HTTP::Post.new(model_uri, headers).tap { |r| r.body = payload }- end-- def final_log_update(log)- log.request_tokens = processor.prompt_tokens if processor.prompt_tokens- log.response_tokens = processor.completion_tokens if processor.completion_tokens- log.cache_read_tokens = processor.cache_read_tokens if processor.cache_read_tokens- end-- def decode(response_raw)- processor.process_message(JSON.parse(response_raw, symbolize_names: true))- end-- def decode_chunk(chunk)- @decoder ||= JsonStreamDecoder.new- elements =- (@decoder << chunk)- .map { |parsed_json| processor.process_streamed_message(parsed_json) }- .flatten- .compact-- seen_tools = Set.new- elements.select { |item| !item.is_a?(ToolCall) || seen_tools.add?(item) }- end-- def decode_chunk_finish- processor.finish- end-- def xml_tools_enabled?- !@native_tool_support- end-def processor@processor ||=OpenAiResponsesMessageProcessor.new(diff --git a/plugins/discourse-ai/lib/completions/endpoints/open_ai_shared.rb b/plugins/discourse-ai/lib/completions/endpoints/open_ai_shared.rbnew file mode 100644index 00000000000..c783bd2724d--- /dev/null+++ b/plugins/discourse-ai/lib/completions/endpoints/open_ai_shared.rb@@ -0,0 +1,137 @@+# frozen_string_literal: true++module DiscourseAi+ module Completions+ module Endpoints+ module OpenAiShared+ def default_options+ { model: llm_model.name }+ end++ def provider_id+ AiApiAuditLog::Provider::OpenAI+ end++ def perform_completion!(+ dialect,+ user,+ model_params = {},+ feature_name: nil,+ feature_context: nil,+ partial_tool_calls: false,+ output_thinking: false,+ cancel_manager: nil,+ execution_context: nil,+ &blk+ )+ @native_tool_support = dialect.native_tool_support?+ super+ end++ def normalize_model_params(model_params)+ model_params = model_params.dup++ if model_params[:stop_sequences]+ model_params[:stop] = model_params.delete(:stop_sequences)+ end++ if reasoning_effort+ model_params.delete(:temperature)+ model_params.delete(:top_p)+ else+ model_params.delete(:top_p) if llm_model.lookup_custom_param("disable_top_p")+ if llm_model.lookup_custom_param("disable_temperature")+ model_params.delete(:temperature)+ end+ end++ model_params+ end++ private++ def disable_streaming?+ @disable_streaming ||= llm_model.lookup_custom_param("disable_streaming")+ end++ def reasoning_effort+ return @reasoning_effort if defined?(@reasoning_effort)+ @reasoning_effort = llm_model.lookup_custom_param("reasoning_effort")+ @reasoning_effort = nil if !%w[none minimal low medium high xhigh].include?(+ @reasoning_effort,+ )+ @reasoning_effort+ end++ def service_tier+ return @service_tier if defined?(@service_tier)+ @service_tier = llm_model.lookup_custom_param("service_tier")+ @service_tier = nil if !%w[auto flex priority].include?(@service_tier)+ @service_tier+ end++ def model_uri+ if llm_model.url.to_s.starts_with?("srv://")+ service = DiscourseAi::Utils::DnsSrv.lookup(llm_model.url.sub("srv://", ""))+ api_endpoint = "https://#{service.target}:#{service.port}#{srv_fallback_path}"+ else+ api_endpoint = llm_model.url+ end++ @uri ||= URI(api_endpoint)+ end++ def srv_fallback_path+ raise NotImplementedError+ end++ def prepare_request(payload)+ headers = { "Content-Type" => "application/json" }+ api_key = llm_model.api_key++ if llm_model.provider == "azure"+ headers["api-key"] = api_key+ else+ headers["Authorization"] = "Bearer #{api_key}"+ org_id = llm_model.lookup_custom_param("organization")+ headers["OpenAI-Organization"] = org_id if org_id.present?+ end++ Net::HTTP::Post.new(model_uri, headers).tap { |r| r.body = payload }+ end++ def final_log_update(log)+ log.request_tokens = processor.prompt_tokens if processor.prompt_tokens+ log.response_tokens = processor.completion_tokens if processor.completion_tokens+ log.cache_read_tokens = processor.cache_read_tokens if processor.cache_read_tokens+ end++ def decode(response_raw)+ processor.process_message(JSON.parse(response_raw, symbolize_names: true))+ end++ def decode_chunk(chunk)+ @decoder ||= JsonStreamDecoder.new+ elements =+ (@decoder << chunk)+ .map { |parsed_json| processor.process_streamed_message(parsed_json) }+ .flatten+ .compact++ # Remove duplicate partial tool calls+ # sometimes we stream weird chunks+ seen_tools = Set.new+ elements.select { |item| !item.is_a?(ToolCall) || seen_tools.add?(item) }+ end++ def decode_chunk_finish+ processor.finish+ end++ def xml_tools_enabled?+ !@native_tool_support+ end+ end+ end+ end+enddiff --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.rbindex b187c69d954..7dddfc5e975 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@@ -445,4 +445,31 @@ data: {"type":"response.reasoning_summary_part.added","sequence_number":3,"item_expect(parsed_body).not_to have_key(:reasoning_effort)expect(parsed_body).to have_key(:input)end++ it "includes service_tier in converted responses payload" do+ model.update!(provider_params: { service_tier: "flex" })++ parsed_body = nil+ stub_request(:post, "https://api.openai.com/v1/responses").with(+ body:+ proc do |req_body|+ parsed_body = JSON.parse(req_body, symbolize_names: true)+ true+ end,+ ).to_return(status: 200, body: { output: [] }.to_json)++ prompt =+ DiscourseAi::Completions::Prompt.new(+ "You are a bot",+ messages: [type: :user, content: "hello"],+ )++ dialect = DiscourseAi::Completions::Dialects::OpenAiResponses.new(prompt, model)++ endpoint.perform_completion!(dialect, Discourse.system_user)++ expect(parsed_body[:service_tier]).to eq("flex")+ expect(parsed_body).to have_key(:input)+ expect(parsed_body).not_to have_key(:messages)+ endenddiff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_spec.rbindex ba7f55ee46a..7180f2d7c46 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@@ -1198,4 +1198,119 @@ TEXTexpect(parsed_body).not_to have_key(:reasoning_effort)endend++ describe "service_tier payload" do+ let(:prompt) { compliance.generic_prompt }+ let(:dialect) { compliance.dialect(prompt: prompt) }++ it "includes service_tier when set to auto" do+ model.update!(provider_params: { service_tier: "auto" })++ parsed_body = nil+ stub_request(:post, "https://api.openai.com/v1/chat/completions").with(+ body:+ proc do |req_body|+ parsed_body = JSON.parse(req_body, symbolize_names: true)+ true+ end,+ ).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)++ endpoint.perform_completion!(dialect, user)++ expect(parsed_body[:service_tier]).to eq("auto")+ end++ it "includes service_tier when set to flex" do+ model.update!(provider_params: { service_tier: "flex" })++ parsed_body = nil+ stub_request(:post, "https://api.openai.com/v1/chat/completions").with(+ body:+ proc do |req_body|+ parsed_body = JSON.parse(req_body, symbolize_names: true)+ true+ end,+ ).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)++ endpoint.perform_completion!(dialect, user)++ expect(parsed_body[:service_tier]).to eq("flex")+ end++ it "includes service_tier when set to priority" do+ model.update!(provider_params: { service_tier: "priority" })++ parsed_body = nil+ stub_request(:post, "https://api.openai.com/v1/chat/completions").with(+ body:+ proc do |req_body|+ parsed_body = JSON.parse(req_body, symbolize_names: true)+ true+ end,+ ).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)++ endpoint.perform_completion!(dialect, user)++ expect(parsed_body[:service_tier]).to eq("priority")+ end++ it "omits service_tier when set to default" do+ model.update!(provider_params: { service_tier: "default" })++ parsed_body = nil+ stub_request(:post, "https://api.openai.com/v1/chat/completions").with(+ body:+ proc do |req_body|+ parsed_body = JSON.parse(req_body, symbolize_names: true)+ true+ end,+ ).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)++ endpoint.perform_completion!(dialect, user)++ expect(parsed_body).not_to have_key(:service_tier)+ end++ it "omits service_tier when not configured" do+ parsed_body = nil+ stub_request(:post, "https://api.openai.com/v1/chat/completions").with(+ body:+ proc do |req_body|+ parsed_body = JSON.parse(req_body, symbolize_names: true)+ true+ end,+ ).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)++ endpoint.perform_completion!(dialect, user)++ expect(parsed_body).not_to have_key(:service_tier)+ end++ it "includes service_tier for azure provider" do+ model.update!(+ provider: "azure",+ url:+ "https://test.openai.azure.com/openai/deployments/gpt-4/chat/completions?api-version=2024-02-15-preview",+ provider_params: {+ service_tier: "priority",+ },+ )++ parsed_body = nil+ stub_request(+ :post,+ "https://test.openai.azure.com/openai/deployments/gpt-4/chat/completions?api-version=2024-02-15-preview",+ ).with(+ body:+ proc do |req_body|+ parsed_body = JSON.parse(req_body, symbolize_names: true)+ true+ end,+ ).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)++ endpoint.perform_completion!(dialect, user)++ expect(parsed_body[:service_tier]).to eq("priority")+ end+ endend