A platform for community discussion. Free, open, simple.
FEATURE: native support for attachments in llms (#36415)
Sam34bfe83bfdb3
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rbindex b46d476715b..de1fcc2653d 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb@@ -216,6 +216,7 @@ module DiscourseAi:input_cost,:cached_input_cost,:output_cost,+ allowed_attachment_types: [],)provider = updating ? updating.provider : permitted[:provider]diff --git a/plugins/discourse-ai/app/models/llm_model.rb b/plugins/discourse-ai/app/models/llm_model.rbindex ddc3d59355f..2b854b2b905 100644--- a/plugins/discourse-ai/app/models/llm_model.rb+++ b/plugins/discourse-ai/app/models/llm_model.rb@@ -3,6 +3,13 @@class LlmModel < ActiveRecord::BaseFIRST_BOT_USER_ID = -1200BEDROCK_PROVIDER_NAME = "aws_bedrock"+ DEFAULT_ALLOWED_ATTACHMENT_TYPES = [].freeze+ ATTACHMENT_TYPE_ALIASES = {+ "md" => "markdown",+ "markdown" => "markdown",+ "htm" => "html",+ "text" => "txt",+ }.freezehas_many :llm_quotas, dependent: :destroyhas_one :llm_credit_allocation, dependent: :destroy@@ -76,7 +83,6 @@ class LlmModel < ActiveRecord::Basedisable_temperature: :checkbox,disable_top_p: :checkbox,disable_streaming: :checkbox,- enable_responses_api: :checkbox,reasoning_effort: {type: :enum,values: %w[default minimal low medium high],@@ -106,7 +112,6 @@ class LlmModel < ActiveRecord::Base},azure: {disable_native_tools: :checkbox,- enable_responses_api: :checkbox,reasoning_effort: {type: :enum,values: %w[default minimal low medium high],@@ -192,6 +197,21 @@ class LlmModel < ActiveRecord::Basetokenizer.constantizeend+ def allowed_attachment_types+ (self[:allowed_attachment_types].presence || DEFAULT_ALLOWED_ATTACHMENT_TYPES).map(&:downcase)+ end++ def allowed_attachment_types=(value)+ normalized =+ Array(value)+ .map { |v| v.to_s.downcase.strip }+ .map { |v| ATTACHMENT_TYPE_ALIASES[v] || v }+ .reject(&:blank?)+ .uniq+ normalized = DEFAULT_ALLOWED_ATTACHMENT_TYPES if normalized.empty?+ self[:allowed_attachment_types] = normalized+ end+def lookup_custom_param(key)provider_params&.dig(key)end@@ -259,23 +279,24 @@ end## Table name: llm_models#-# id :bigint not null, primary key-# api_key :string-# cache_write_cost :float default(0.0)-# cached_input_cost :float-# display_name :string-# enabled_chat_bot :boolean default(FALSE), not null-# input_cost :float-# max_output_tokens :integer-# max_prompt_tokens :integer not null-# name :string not null-# output_cost :float-# provider :string not null-# provider_params :jsonb-# tokenizer :string not null-# url :string-# vision_enabled :boolean default(FALSE), not null-# created_at :datetime not null-# updated_at :datetime not null-# user_id :integer+# id :bigint not null, primary key+# allowed_attachment_types :text default([]), not null, is an Array+# api_key :string+# cache_write_cost :float default(0.0)+# cached_input_cost :float+# display_name :string+# enabled_chat_bot :boolean default(FALSE), not null+# input_cost :float+# max_output_tokens :integer+# max_prompt_tokens :integer not null+# name :string not null+# output_cost :float+# provider :string not null+# provider_params :jsonb+# tokenizer :string not null+# url :string+# vision_enabled :boolean default(FALSE), not null+# created_at :datetime not null+# updated_at :datetime not null+# user_id :integer#diff --git a/plugins/discourse-ai/app/serializers/llm_model_serializer.rb b/plugins/discourse-ai/app/serializers/llm_model_serializer.rbindex 5ea8c7c2e42..e61cc8bd102 100644--- a/plugins/discourse-ai/app/serializers/llm_model_serializer.rb+++ b/plugins/discourse-ai/app/serializers/llm_model_serializer.rb@@ -23,7 +23,8 @@ class LlmModelSerializer < ApplicationSerializer:cached_input_cost,:cache_write_cost,:used_by,- :seeded+ :seeded,+ :allowed_attachment_typeshas_one :user, serializer: BasicUserSerializer, embed: :objecthas_many :llm_quotas, serializer: LlmQuotaSerializer, embed: :objectsdiff --git a/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-llm.js b/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-llm.jsindex 4a142e6a43b..e57ef069b2e 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-llm.js+++ b/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-llm.js@@ -19,7 +19,8 @@ export default class AiLlm extends RestModel {"input_cost","cached_input_cost","cache_write_cost",- "output_cost"+ "output_cost",+ "allowed_attachment_types");}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-llm-attachment-types.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-llm-attachment-types.gjsnew file mode 100644index 00000000000..e26975795f7--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-llm-attachment-types.gjs@@ -0,0 +1,55 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { hash } from "@ember/helper";+import { action } from "@ember/object";+import { uniqueItemsFromArray } from "discourse/lib/array-tools";+import ListSetting from "discourse/select-kit/components/list-setting";+import { i18n } from "discourse-i18n";++const DEFAULT_CHOICES = [+ "pdf",+ "txt",+ "doc",+ "docx",+ "rtf",+ "html",+ "markdown",+];++/**+ * @component ai-llm-attachment-types+ * @param {string[]} [this.args.value]+ * @param {Function} [this.args.onChange]+ */+export default class AiLlmAttachmentTypes extends Component {+ @tracked currentValue = this.args.value || [];++ get settingChoices() {+ return uniqueItemsFromArray([+ ...DEFAULT_CHOICES,+ ...this.currentValue,+ ]).sort();+ }++ @action+ handleChange(newValues) {+ const normalized = (newValues || [])+ .map((v) => v.toString().toLowerCase().trim())+ .filter(Boolean);+ this.currentValue = uniqueItemsFromArray(normalized);+ this.args.onChange?.(this.currentValue);+ }++ <template>+ <ListSetting+ @value={{this.currentValue}}+ @settingName="allowed_attachment_types"+ @choices={{this.settingChoices}}+ @onChange={{this.handleChange}}+ @allowAny={{true}}+ @options={{hash+ noneLabel=(i18n "discourse_ai.llms.attachment_types_placeholder")+ }}+ />+ </template>+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-llm-editor-form.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-llm-editor-form.gjsindex 607b591ed68..78492ac611d 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-llm-editor-form.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-llm-editor-form.gjs@@ -17,6 +17,7 @@ import {} from "discourse/lib/array-tools";import { eq, gt } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";+import AiLlmAttachmentTypes from "discourse/plugins/discourse-ai/discourse/components/ai-llm-attachment-types";import DurationSelector from "./ai-quota-duration-selector";import AiLlmQuotaModal from "./modal/ai-llm-quota-modal";@@ -62,6 +63,7 @@ export default class AiLlmEditorForm extends Component {cached_input_cost: modelInfo.cached_input_cost,vision_enabled: modelInfo.vision_enabled || false,cache_write_cost: modelInfo.cache_write_cost,+ allowed_attachment_types: [],};}@@ -87,6 +89,7 @@ export default class AiLlmEditorForm extends Component {model.provider_params),llm_quotas: model.llm_quotas,+ allowed_attachment_types: model.allowed_attachment_types || [],};}@@ -491,6 +494,23 @@ export default class AiLlmEditorForm extends Component {<field.Checkbox /></form.Field>+ <form.Field+ @name="allowed_attachment_types"+ @title={{i18n "discourse_ai.llms.allowed_attachment_types"}}+ @tooltip={{i18n "discourse_ai.llms.hints.allowed_attachment_types"}}+ @format="large"+ as |field|+ >+ <field.Label />+ <field.Custom>+ <AiLlmAttachmentTypes+ @value={{field.value}}+ @onChange={{field.set}}+ />+ </field.Custom>+ <field.Hint />+ </form.Field>+<form.Field@name="enabled_chat_bot"@title={{i18n "discourse_ai.llms.enabled_chat_bot"}}diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex fe0ea58a1d7..0d2b3a9c091 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -643,6 +643,8 @@ en:api_key: "API Key of the service hosting the model"enabled_chat_bot: "Allow AI bot selector"vision_enabled: "Vision enabled"+ allowed_attachment_types: "Allowed attachments"+ attachment_types_placeholder: "Select or type extensions (e.g., pdf, txt, docx)"ai_bot_user: "AI bot User"cost_input: "Input cost"cost_cached_input: "Cached input cost"@@ -743,6 +745,7 @@ en:display_name: "The name used to reference this model across your site's interface."name: "We include this in the API call to specify which model we'll use"vision_enabled: "If enabled, the AI will attempt to understand images. It depends on the model being used supporting vision. Supported by latest models from Anthropic, Google, and OpenAI."+ allowed_attachment_types: "Choose which attachment types are forwarded to the model. Leave blank to disallow attachments. Images are controlled via vision."enabled_chat_bot: "If enabled, users can select this model when creating PMs with the AI bot"cost_input: "The input cost per 1M tokens for this model"cost_cached_input: "The cached input cost per 1M tokens for this model (when reading from prompt cache)"@@ -784,7 +787,6 @@ en:reasoning_tokens: "Number of tokens used for reasoning"disable_temperature: "Disable temperature (some thinking models don't support temperature)"disable_top_p: "Disable top P (some thinking models don't support top P)"- enable_responses_api: "Enable responses API (required on certain OpenAI models)"prompt_caching: "Prompt caching mode"prompt_caching_never: "Never - Do not use prompt caching"prompt_caching_tool_results: "Tool Results - Cache when tool results are present (recommended)"diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex ba15017294d..94dffcf9617 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -11,7 +11,6 @@ en:other: "<a href='%{base_path}/admin/plugins/discourse-ai/ai-llms/%{target}/edit'>%{model_name}</a> needs attention. Over the last %{count} hours, it failed to respond %{failed_calls} out of %{total_calls} times."ai_credit_soft_limit: "%{model_name} has only %{percentage_remaining}% of credits remaining. Credits will reset at %{reset_date}. <a href='%{url}'>View AI models</a>"ai_credit_hard_limit: "You have run out of AI credits for %{model_name}. AI features will be unavailable until %{reset_date}. <a href='%{url}'>View AI models</a>"-discourse_automation:ai:flag_types:diff --git a/plugins/discourse-ai/db/migrate/20251202090012_add_allowed_attachment_types_to_llm_models.rb b/plugins/discourse-ai/db/migrate/20251202090012_add_allowed_attachment_types_to_llm_models.rbnew file mode 100644index 00000000000..981515f4b95--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20251202090012_add_allowed_attachment_types_to_llm_models.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++class AddAllowedAttachmentTypesToLlmModels < ActiveRecord::Migration[7.0]+ def up+ add_column :llm_models, :allowed_attachment_types, :text, array: true, default: [], null: false+ end++ def down+ remove_column :llm_models, :allowed_attachment_types+ end+enddiff --git a/plugins/discourse-ai/lib/completions/dialects/chat_gpt.rb b/plugins/discourse-ai/lib/completions/dialects/chat_gpt.rbindex 2dd07159e6c..d8632def6ee 100644--- a/plugins/discourse-ai/lib/completions/dialects/chat_gpt.rb+++ b/plugins/discourse-ai/lib/completions/dialects/chat_gpt.rb@@ -6,13 +6,14 @@ module DiscourseAiclass ChatGpt < Dialectclass << selfdef can_translate?(llm_model)+ return false if llm_model.url.to_s.include?("/v1/responses")+llm_model.provider == "open_router" || llm_model.provider == "open_ai" ||llm_model.provider == "azure"endendVALID_ID_REGEX = /\A[a-zA-Z0-9_]+\z/-def native_tool_support?llm_model.provider == "open_ai" || llm_model.provider == "azure"end@@ -20,19 +21,12 @@ module DiscourseAidef embed_user_ids?return @embed_user_ids if defined?(@embed_user_ids)- @embed_user_ids = true if responses_api?-@embed_user_ids ||=prompt.messages.any? do |m|m[:id] && m[:type] == :user && !m[:id].to_s.match?(VALID_ID_REGEX)endend- def responses_api?- return @responses_api if defined?(@responses_api)- @responses_api = llm_model.lookup_custom_param("enable_responses_api")- end-def max_prompt_tokens# provide a buffer of 120 tokens - our function counting is not# 100% accurate and getting numbers to align exactly is very hard@@ -52,43 +46,13 @@ 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_dialectif disable_native_tools?superelse- @tools_dialect ||=- DiscourseAi::Completions::Dialects::OpenAiTools.new(- prompt.tools,- responses_api: responses_api?,- )+ @tools_dialect ||= DiscourseAi::Completions::Dialects::OpenAiTools.new(prompt.tools)endend@@ -147,11 +111,6 @@ module DiscourseAidef 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 }- enduser_message = { role: }@@ -165,22 +124,20 @@ module DiscourseAicontent_array << msg[:content]- allow_vision = vision_support?- allow_vision = false if responses_api? && role == "assistant"+ allow_images = vision_support?content_array =to_encoded_content_array(content: content_array.flatten,- image_encoder: ->(details) { image_node(details) },+ upload_encoder: ->(details) { upload_node(details) },text_encoder: ->(text) { text_node(text, role) },- other_encoder: ->(hash) { thinking_signature_node(hash) },- allow_vision:,+ other_encoder: ->(hash) { hash },+ allow_images:,+ allow_documents: true,+ allowed_attachment_types: llm_model.allowed_attachment_types,+ upload_filter: ->(encoded) { document_allowed?(encoded) },)- 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_messageend@@ -193,42 +150,31 @@ module DiscourseAiendend- 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"]+ def text_node(text, role)+ { type: "text", text: text }end- def text_node(text, role)- if responses_api?- { type: role == "user" ? "input_text" : "output_text", text: text }+ def upload_node(details)+ if details[:mime_type] == "application/pdf" || details[:kind] == :document+ file_node(details)else- { type: "text", text: text }+ image_node(details)endenddef image_node(details)encoded_image = "data:#{details[:mime_type]};base64,#{details[:base64]}"- if responses_api?- { type: "input_image", image_url: encoded_image }- else- { type: "image_url", image_url: { url: encoded_image } }- end+ { type: "image_url", image_url: { url: encoded_image } }+ end++ def file_node(details)+ {+ type: "file",+ file: {+ filename: details[:filename] || "document.pdf",+ file_data: "data:#{details[:mime_type]};base64,#{details[:base64]}",+ },+ }enddef per_message_overheaddiff --git a/plugins/discourse-ai/lib/completions/dialects/claude.rb b/plugins/discourse-ai/lib/completions/dialects/claude.rbindex 65a41867f16..7166e151a3a 100644--- a/plugins/discourse-ai/lib/completions/dialects/claude.rb+++ b/plugins/discourse-ai/lib/completions/dialects/claude.rb@@ -108,10 +108,11 @@ module DiscourseAicontent_array =to_encoded_content_array(content: [content_array, msg[:content]].flatten,- image_encoder: ->(details) {},+ upload_encoder: ->(_details) {},text_encoder: ->(text) { { type: "text", text: text } },other_encoder: ->(details) { details },- allow_vision: false,+ allow_images: false,+ allow_documents: false,){ role: "assistant", content: no_array_if_only_text(content_array) }@@ -141,9 +142,12 @@ module DiscourseAicontent_array =to_encoded_content_array(content: content_array,- image_encoder: ->(details) { image_node(details) },+ upload_encoder: ->(details) { upload_node(details) },text_encoder: ->(text) { { type: "text", text: text } },- allow_vision: vision_support?,+ allow_images: vision_support?,+ allow_documents: true,+ allowed_attachment_types: llm_model.allowed_attachment_types,+ upload_filter: ->(encoded) { document_allowed?(encoded) },){ role: "user", content: no_array_if_only_text(content_array) }@@ -168,6 +172,23 @@ module DiscourseAitype: "image",}end++ def upload_node(details)+ return if details.blank?++ if details[:kind] == :document || details[:mime_type] == "application/pdf"+ {+ type: "document",+ source: {+ type: "base64",+ data: details[:base64],+ media_type: details[:mime_type],+ },+ }+ else+ image_node(details)+ end+ endendendenddiff --git a/plugins/discourse-ai/lib/completions/dialects/dialect.rb b/plugins/discourse-ai/lib/completions/dialects/dialect.rbindex 193e0a59ee4..3ba9d96245d 100644--- a/plugins/discourse-ai/lib/completions/dialects/dialect.rb+++ b/plugins/discourse-ai/lib/completions/dialects/dialect.rb@@ -11,6 +11,7 @@ module DiscourseAidef all_dialects[+ DiscourseAi::Completions::Dialects::OpenAiResponses,DiscourseAi::Completions::Dialects::ChatGpt,DiscourseAi::Completions::Dialects::Gemini,DiscourseAi::Completions::Dialects::Claude,@@ -300,10 +301,13 @@ module DiscourseAidef to_encoded_content_array(content:,- image_encoder:,+ upload_encoder:,text_encoder:,other_encoder: nil,- allow_vision:+ allow_images:,+ allow_documents: false,+ allowed_attachment_types: nil,+ upload_filter: nil)content = [content] if !content.is_a?(Array)@@ -314,15 +318,29 @@ module DiscourseAiif c.is_a?(String)current_string << celsif c.is_a?(Hash) && c.key?(:upload_id)- # this ensurse we skip uploads if vision is not supported- if allow_vision- if !current_string.empty?- result << text_encoder.call(current_string)- current_string = +""- end- encoded = prompt.encode_upload(c[:upload_id])- result << image_encoder.call(encoded) if encoded+ next if !allow_images && !allow_documents++ encoded =+ prompt.encode_upload(+ c[:upload_id],+ allow_documents: allow_documents,+ allowed_attachment_types: allowed_attachment_types,+ )+ next if encoded.blank?++ is_image = encoded[:kind] == :image+ is_document = encoded[:kind] == :document++ next if is_image && !allow_images+ next if is_document && !allow_documents+ next if upload_filter && !upload_filter.call(encoded)++ if !current_string.empty?+ result << text_encoder.call(current_string)+ current_string = +""end++ result << upload_encoder.call(encoded)elsif other_encoderencoded = other_encoder.call(c)result << encoded if encoded@@ -332,6 +350,30 @@ module DiscourseAiresult << text_encoder.call(current_string) if !current_string.empty?resultend++ def attachment_type_for(encoded)+ ext = File.extname(encoded[:filename].to_s).delete_prefix(".").downcase+ mime = encoded[:mime_type].to_s++ return "pdf" if ext == "pdf" || mime.include?("pdf")+ return "docx" if ext == "docx"+ return "doc" if ext == "doc"+ return "txt" if ext == "txt" || mime.include?("text/plain")+ return "rtf" if ext == "rtf"+ return "html" if %w[html htm].include?(ext) || mime.include?("html")+ return "markdown" if %w[md markdown].include?(ext) || mime.include?("markdown")++ "file"+ end++ def document_allowed?(encoded)+ return true if encoded[:kind] != :document++ allowed_types = llm_model.allowed_attachment_types+ return false if allowed_types.blank?++ allowed_types.include?(attachment_type_for(encoded))+ endendendenddiff --git a/plugins/discourse-ai/lib/completions/dialects/gemini.rb b/plugins/discourse-ai/lib/completions/dialects/gemini.rbindex e3b51dd1ff4..a718c545789 100644--- a/plugins/discourse-ai/lib/completions/dialects/gemini.rb+++ b/plugins/discourse-ai/lib/completions/dialects/gemini.rb@@ -109,9 +109,12 @@ module DiscourseAicontent_array =to_encoded_content_array(content: content_array,- image_encoder: ->(details) { image_node(details) },+ upload_encoder: ->(details) { upload_node(details) },text_encoder: ->(text) { { text: text } },- allow_vision: vision_support? && beta_api?,+ allow_images: vision_support? && beta_api?,+ allow_documents: true,+ allowed_attachment_types: llm_model.allowed_attachment_types,+ upload_filter: ->(encoded) { document_allowed?(encoded) },)if beta_api?@@ -125,6 +128,10 @@ module DiscourseAi{ inlineData: { mimeType: details[:mime_type], data: details[:base64] } }end+ def upload_node(details)+ image_node(details)+ end+def tool_call_msg(msg)if native_tool_support?call_details = JSON.parse(msg[:content], symbolize_names: true)diff --git a/plugins/discourse-ai/lib/completions/dialects/open_ai_responses.rb b/plugins/discourse-ai/lib/completions/dialects/open_ai_responses.rbnew file mode 100644index 00000000000..ad92fecc7cc--- /dev/null+++ b/plugins/discourse-ai/lib/completions/dialects/open_ai_responses.rb@@ -0,0 +1,216 @@+# frozen_string_literal: true++module DiscourseAi+ module Completions+ module Dialects+ class OpenAiResponses < Dialect+ class << self+ def can_translate?(llm_model)+ llm_model.url.to_s.include?("/v1/responses") &&+ %w[open_ai azure].include?(llm_model.provider)+ end+ end++ VALID_ID_REGEX = /\A[a-zA-Z0-9_]+\z/++ def native_tool_support?+ true+ end++ def max_prompt_tokens+ buffer = (opts[:max_tokens] || 2500) + 50++ if tools.present?+ @function_size ||= llm_model.tokenizer_class.size(tools.to_json.to_s)+ buffer += @function_size+ end++ llm_model.max_prompt_tokens - buffer+ end++ def translate+ hoist_reasoning(super)+ end++ def disable_native_tools?+ return @disable_native_tools if defined?(@disable_native_tools)+ !!@disable_native_tools = llm_model.lookup_custom_param("disable_native_tools")+ end++ private++ def tools_dialect+ if disable_native_tools?+ super+ else+ @tools_dialect ||=+ DiscourseAi::Completions::Dialects::OpenAiTools.new(prompt.tools, responses_api: true)+ end+ end++ def embed_user_ids?+ return @embed_user_ids if defined?(@embed_user_ids)++ @embed_user_ids ||=+ prompt.messages.any? do |m|+ m[:id] && m[:type] == :user && !m[:id].to_s.match?(VALID_ID_REGEX)+ end+ end++ def system_msg(msg)+ content = msg[:content]+ if disable_native_tools? && tools_dialect.instructions.present?+ content = content + "\n\n" + tools_dialect.instructions+ end++ { role: "developer", content: content }+ end++ def model_msg(msg)+ message_for_role("assistant", msg)+ end++ def user_msg(msg)+ message_for_role("user", msg)+ end++ def tool_call_msg(msg)+ if disable_native_tools?+ super+ else+ tools_dialect.from_raw_tool_call(msg)+ end+ end++ def tool_msg(msg)+ if disable_native_tools?+ super+ else+ tools_dialect.from_raw_tool(msg)+ end+ end++ def message_for_role(role, msg)+ content_array = []+ reasoning_data = open_ai_reasoning_data(msg)++ content_array << { type: "thinking", message: msg } if reasoning_data.present?++ user_message = { role: }++ if msg[:id]+ if embed_user_ids?+ content_array << "#{msg[:id]}: "+ else+ user_message[:name] = msg[:id]+ end+ end++ content_array << msg[:content]++ allow_images = vision_support?+ allow_images = false if role == "assistant"++ content_array =+ to_encoded_content_array(+ content: content_array.flatten,+ upload_encoder: ->(details) { upload_node(details) },+ text_encoder: ->(text) { text_node(text, role) },+ other_encoder: ->(hash) { thinking_signature_node(hash) },+ allow_images:,+ allow_documents: true,+ allowed_attachment_types: llm_model.allowed_attachment_types,+ upload_filter: ->(encoded) { document_allowed?(encoded) },+ )++ if 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++ def no_array_if_only_text(content_array)+ if content_array.size == 1 && content_array.first[:type] == "text"+ content_array.first[:text]+ else+ content_array+ end+ end++ def thinking_signature_node(hash)+ 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)+ { type: role == "user" ? "input_text" : "output_text", text: text }+ end++ def upload_node(details)+ if details[:mime_type] == "application/pdf" || details[:kind] == :document+ file_node(details)+ else+ image_node(details)+ end+ end++ def image_node(details)+ encoded_image = "data:#{details[:mime_type]};base64,#{details[:base64]}"+ { type: "input_image", image_url: encoded_image }+ end++ def file_node(details)+ {+ type: "input_file",+ filename: details[:filename] || "document.pdf",+ file_data: "data:#{details[:mime_type]};base64,#{details[:base64]}",+ }+ end++ def per_message_overhead+ 4+ end++ def calculate_message_token(context)+ llm_model.tokenizer_class.size(context[:content].to_s + context[:name].to_s)+ end++ 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+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb b/plugins/discourse-ai/lib/completions/endpoints/anthropic.rbindex d1cf2c6ebbd..1267ddbb5c2 100644--- a/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb@@ -5,8 +5,8 @@ module DiscourseAimodule Endpointsclass Anthropic < Baseinclude AnthropicPromptCache- def self.can_contact?(model_provider)- model_provider == "anthropic"+ def self.can_contact?(llm_model)+ llm_model.provider == "anthropic"enddef normalize_model_params(model_params)diff --git a/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rb b/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rbindex 7183d362208..2993aefaa52 100644--- a/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rb@@ -9,8 +9,8 @@ module DiscourseAiinclude AnthropicPromptCacheattr_reader :dialect- def self.can_contact?(model_provider)- model_provider == "aws_bedrock"+ def self.can_contact?(llm_model)+ llm_model.provider == "aws_bedrock"enddef normalize_model_params(model_params)diff --git a/plugins/discourse-ai/lib/completions/endpoints/base.rb b/plugins/discourse-ai/lib/completions/endpoints/base.rbindex 7b74bf2763b..ed1fde77b9c 100644--- a/plugins/discourse-ai/lib/completions/endpoints/base.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/base.rb@@ -16,10 +16,11 @@ module DiscourseAiTIMEOUT = 360class << self- def endpoint_for(provider_name)+ def endpoint_for(llm_model)endpoints = [DiscourseAi::Completions::Endpoints::AwsBedrock,DiscourseAi::Completions::Endpoints::OpenAi,+ DiscourseAi::Completions::Endpoints::OpenAiResponses,DiscourseAi::Completions::Endpoints::HuggingFace,DiscourseAi::Completions::Endpoints::Gemini,DiscourseAi::Completions::Endpoints::Vllm,@@ -35,11 +36,11 @@ module DiscourseAiendpoints << DiscourseAi::Completions::Endpoints::Fake if Rails.env.local?endpoints.detect(-> { raise DiscourseAi::Completions::Llm::UNKNOWN_MODEL }) do |ek|- ek.can_contact?(provider_name)+ ek.can_contact?(llm_model)endend- def can_contact?(_model_provider)+ def can_contact?(_llm_model)raise NotImplementedErrorendenddiff --git a/plugins/discourse-ai/lib/completions/endpoints/cohere.rb b/plugins/discourse-ai/lib/completions/endpoints/cohere.rbindex 258062a1fbf..8f571e09cdf 100644--- a/plugins/discourse-ai/lib/completions/endpoints/cohere.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/cohere.rb@@ -4,8 +4,8 @@ module DiscourseAimodule Completionsmodule Endpointsclass Cohere < Base- def self.can_contact?(model_provider)- model_provider == "cohere"+ def self.can_contact?(llm_model)+ llm_model.provider == "cohere"enddef normalize_model_params(model_params)diff --git a/plugins/discourse-ai/lib/completions/endpoints/fake.rb b/plugins/discourse-ai/lib/completions/endpoints/fake.rbindex 71d0ee4b4e9..edc0b1bdb3c 100644--- a/plugins/discourse-ai/lib/completions/endpoints/fake.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/fake.rb@@ -61,8 +61,8 @@ module DiscourseAiCongratulations, you've now seen a small sample of what Discourse's Markdown can do! For more intricate formatting, consider exploring the advanced styling options. Remember that the key to great formatting is not just the available tools, but also the **clarity** and **readability** it brings to your readers.TEXT- def self.can_contact?(model_provider)- model_provider == "fake"+ def self.can_contact?(llm_model)+ llm_model.provider == "fake"enddef self.with_fake_content(content)diff --git a/plugins/discourse-ai/lib/completions/endpoints/gemini.rb b/plugins/discourse-ai/lib/completions/endpoints/gemini.rbindex 97680fb29f9..5746a863594 100644--- a/plugins/discourse-ai/lib/completions/endpoints/gemini.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/gemini.rb@@ -4,8 +4,8 @@ module DiscourseAimodule Completionsmodule Endpointsclass Gemini < Base- def self.can_contact?(model_provider)- model_provider == "google"+ def self.can_contact?(llm_model)+ llm_model.provider == "google"enddef default_optionsdiff --git a/plugins/discourse-ai/lib/completions/endpoints/hugging_face.rb b/plugins/discourse-ai/lib/completions/endpoints/hugging_face.rbindex b0b14722baa..e076b0e3139 100644--- a/plugins/discourse-ai/lib/completions/endpoints/hugging_face.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/hugging_face.rb@@ -4,8 +4,8 @@ module DiscourseAimodule Completionsmodule Endpointsclass HuggingFace < Base- def self.can_contact?(model_provider)- model_provider == "hugging_face"+ def self.can_contact?(llm_model)+ llm_model.provider == "hugging_face"enddef normalize_model_params(model_params)diff --git a/plugins/discourse-ai/lib/completions/endpoints/mistral.rb b/plugins/discourse-ai/lib/completions/endpoints/mistral.rbindex 5414b3dfba2..b93f2f10164 100644--- a/plugins/discourse-ai/lib/completions/endpoints/mistral.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/mistral.rb@@ -4,8 +4,8 @@ module DiscourseAimodule Completionsmodule Endpointsclass Mistral < OpenAi- def self.can_contact?(model_provider)- model_provider == "mistral"+ def self.can_contact?(llm_model)+ llm_model.provider == "mistral"enddef provider_iddiff --git a/plugins/discourse-ai/lib/completions/endpoints/ollama.rb b/plugins/discourse-ai/lib/completions/endpoints/ollama.rbindex dd4ca2c7e80..768cb6a461b 100644--- a/plugins/discourse-ai/lib/completions/endpoints/ollama.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/ollama.rb@@ -4,8 +4,8 @@ module DiscourseAimodule Completionsmodule Endpointsclass Ollama < Base- def self.can_contact?(model_provider)- model_provider == "ollama"+ def self.can_contact?(llm_model)+ llm_model.provider == "ollama"enddef normalize_model_params(model_params)diff --git a/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb b/plugins/discourse-ai/lib/completions/endpoints/open_ai.rbindex 019e146d3e9..dcfb73ce29f 100644--- a/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb@@ -4,8 +4,9 @@ module DiscourseAimodule Completionsmodule Endpointsclass OpenAi < Base- def self.can_contact?(model_provider)- %w[open_ai azure groq].include?(model_provider)+ 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)@@ -80,13 +81,7 @@ module DiscourseAidef prepare_payload(prompt, model_params, dialect)payload = default_options.merge(model_params).merge(messages: prompt)- 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+ payload.merge!({ reasoning_effort: reasoning_effort }) if reasoning_effortif @streaming_modepayload[:stream] = true@@ -103,52 +98,20 @@ module DiscourseAiif dialect.tool_choice == :nonepayload[:tool_choice] = "none"else- if responses_api?- payload[:tool_choice] = { type: "function", name: dialect.tool_choice }- else- payload[:tool_choice] = {- type: "function",- function: {- name: dialect.tool_choice,- },- }- end+ payload[:tool_choice] = {+ type: "function",+ function: {+ name: dialect.tool_choice,+ },+ }endendendend- if responses_api?- convert_payload_to_responses_api!(payload)- payload[:include] ||= []- payload[:include] << "reasoning.encrypted_content"- end-payloadend- def responses_api?- return @responses_api if defined?(@responses_api)- @responses_api = llm_model.lookup_custom_param("enable_responses_api")- end-- def convert_payload_to_responses_api!(payload)- 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-def prepare_request(payload)headers = { "Content-Type" => "application/json" }api_key = llm_model.api_key@@ -199,15 +162,7 @@ module DiscourseAiprivatedef processor- @processor ||=- if responses_api?- OpenAiResponsesMessageProcessor.new(- partial_tool_calls: partial_tool_calls,- output_thinking: output_thinking,- )- else- OpenAiMessageProcessor.new(partial_tool_calls: partial_tool_calls)- end+ @processor ||= OpenAiMessageProcessor.new(partial_tool_calls: partial_tool_calls)endendenddiff --git a/plugins/discourse-ai/lib/completions/endpoints/open_ai_responses.rb b/plugins/discourse-ai/lib/completions/endpoints/open_ai_responses.rbnew file mode 100644index 00000000000..11aed3387ff--- /dev/null+++ b/plugins/discourse-ai/lib/completions/endpoints/open_ai_responses.rb@@ -0,0 +1,176 @@+# frozen_string_literal: true++module DiscourseAi+ module Completions+ module Endpoints+ class OpenAiResponses < Base+ 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++ 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+ { 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,+ &blk+ )+ @disable_native_tools = dialect.disable_native_tools?+ 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[minimal low medium high].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)+ end++ def prepare_payload(prompt, model_params, dialect)+ payload = default_options.merge(model_params).merge(messages: prompt)++ reasoning_payload = { summary: "auto" }+ reasoning_payload[:effort] = reasoning_effort if reasoning_effort+ payload.merge!(reasoning: reasoning_payload)++ if @streaming_mode+ payload[:stream] = true+ payload[:stream_options] = { include_usage: true } if llm_model.provider == "open_ai"+ end++ if !xml_tools_enabled?+ if dialect.tools.present?+ payload[:tools] = dialect.tools+ if dialect.tool_choice.present?+ if dialect.tool_choice == :none+ payload[:tool_choice] = "none"+ else+ payload[:tool_choice] = { type: "function", name: dialect.tool_choice }+ end+ end+ end+ end++ convert_payload_to_responses_api!(payload)+ payload[:include] ||= []+ payload[:include] << "reasoning.encrypted_content"++ payload+ end++ def convert_payload_to_responses_api!(payload)+ 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++ payload.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?+ !!@disable_native_tools+ end++ def processor+ @processor ||=+ OpenAiResponsesMessageProcessor.new(+ partial_tool_calls: partial_tool_calls,+ output_thinking: output_thinking,+ )+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/completions/endpoints/open_router.rb b/plugins/discourse-ai/lib/completions/endpoints/open_router.rbindex 081227992f6..1a0c68fba6a 100644--- a/plugins/discourse-ai/lib/completions/endpoints/open_router.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/open_router.rb@@ -4,8 +4,8 @@ module DiscourseAimodule Completionsmodule Endpointsclass OpenRouter < OpenAi- def self.can_contact?(model_provider)- %w[open_router].include?(model_provider)+ def self.can_contact?(llm_model)+ llm_model.provider == "open_router"enddef normalize_model_params(model_params)diff --git a/plugins/discourse-ai/lib/completions/endpoints/samba_nova.rb b/plugins/discourse-ai/lib/completions/endpoints/samba_nova.rbindex 9e6b38175fc..dbaf8265a9d 100644--- a/plugins/discourse-ai/lib/completions/endpoints/samba_nova.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/samba_nova.rb@@ -4,8 +4,8 @@ module DiscourseAimodule Completionsmodule Endpointsclass SambaNova < Base- def self.can_contact?(model_provider)- model_provider == "samba_nova"+ def self.can_contact?(llm_model)+ llm_model.provider == "samba_nova"enddef normalize_model_params(model_params)diff --git a/plugins/discourse-ai/lib/completions/endpoints/vllm.rb b/plugins/discourse-ai/lib/completions/endpoints/vllm.rbindex 6b371a09d47..2c6221e6ec6 100644--- a/plugins/discourse-ai/lib/completions/endpoints/vllm.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/vllm.rb@@ -4,8 +4,8 @@ module DiscourseAimodule Completionsmodule Endpointsclass Vllm < Base- def self.can_contact?(model_provider)- model_provider == "vllm"+ def self.can_contact?(llm_model)+ llm_model.provider == "vllm"enddef normalize_model_params(model_params)diff --git a/plugins/discourse-ai/lib/completions/llm.rb b/plugins/discourse-ai/lib/completions/llm.rbindex a5d51bae360..1c410afa704 100644--- a/plugins/discourse-ai/lib/completions/llm.rb+++ b/plugins/discourse-ai/lib/completions/llm.rb@@ -130,9 +130,6 @@ module DiscourseAimax_output_tokens: 128_000,endpoint: "https://api.openai.com/v1/responses",vision_enabled: true,- provider_params: {- enable_responses_api: true,- },},{name: "gpt-5-mini",@@ -143,9 +140,6 @@ module DiscourseAioutput_cost: 2.0,max_output_tokens: 128_000,endpoint: "https://api.openai.com/v1/responses",- provider_params: {- enable_responses_api: true,- },},{name: "gpt-5-nano",@@ -156,9 +150,6 @@ module DiscourseAioutput_cost: 0.40,max_output_tokens: 128_000,endpoint: "https://api.openai.com/v1/responses",- provider_params: {- enable_responses_api: true,- },},],tokenizer: DiscourseAi::Tokenizer::OpenAiTokenizer,@@ -349,8 +340,7 @@ module DiscourseAireturn new(dialect_klass, nil, llm_model, gateway: @canned_response)end- model_provider = llm_model.provider- gateway_klass = DiscourseAi::Completions::Endpoints::Base.endpoint_for(model_provider)+ gateway_klass = DiscourseAi::Completions::Endpoints::Base.endpoint_for(llm_model)new(dialect_klass, gateway_klass, llm_model)enddiff --git a/plugins/discourse-ai/lib/completions/prompt.rb b/plugins/discourse-ai/lib/completions/prompt.rbindex b6598f8ea31..ea376ece353 100644--- a/plugins/discourse-ai/lib/completions/prompt.rb+++ b/plugins/discourse-ai/lib/completions/prompt.rb@@ -138,7 +138,7 @@ module DiscourseAitools.present?end- def encoded_uploads(message)+ def encoded_uploads(message, allow_documents: false, allowed_attachment_types: nil)if message[:content].is_a?(Array)upload_ids =message[:content]@@ -147,23 +147,45 @@ module DiscourseAiend.compactif !upload_ids.empty?- return UploadEncoder.encode(upload_ids: upload_ids, max_pixels: max_pixels)+ allowed_kinds = allow_documents ? %i[image document] : %i[image]+ return(+ UploadEncoder.encode(+ upload_ids: upload_ids,+ max_pixels: max_pixels,+ allowed_kinds: allowed_kinds,+ allowed_attachment_types: allowed_attachment_types,+ )+ )endend[]end- def encode_upload(upload_id)- UploadEncoder.encode(upload_ids: [upload_id], max_pixels: max_pixels).first+ def encode_upload(upload_id, allow_documents: false, allowed_attachment_types: nil)+ allowed_kinds = allow_documents ? %i[image document] : %i[image]+ UploadEncoder.encode(+ upload_ids: [upload_id],+ max_pixels: max_pixels,+ allowed_kinds: allowed_kinds,+ allowed_attachment_types: allowed_attachment_types,+ ).firstend- def content_with_encoded_uploads(content)+ def content_with_encoded_uploads(+ content,+ allow_documents: false,+ allowed_attachment_types: nil+ )return [content] unless content.is_a?(Array)content.map do |c|if c.is_a?(Hash) && c.key?(:upload_id)- encode_upload(c[:upload_id])+ encode_upload(+ c[:upload_id],+ allow_documents: allow_documents,+ allowed_attachment_types: allowed_attachment_types,+ )elsecenddiff --git a/plugins/discourse-ai/lib/completions/upload_encoder.rb b/plugins/discourse-ai/lib/completions/upload_encoder.rbindex c2aecbaadff..0ac19d396f4 100644--- a/plugins/discourse-ai/lib/completions/upload_encoder.rb+++ b/plugins/discourse-ai/lib/completions/upload_encoder.rb@@ -3,11 +3,36 @@module DiscourseAimodule Completionsclass UploadEncoder- def self.encode(upload_ids:, max_pixels:)+ def self.encode(+ upload_ids:,+ max_pixels:,+ allowed_kinds: [:image],+ allowed_attachment_types: nil+ )uploads = []+ allowed_attachment_types = normalize_attachment_types(allowed_attachment_types)upload_ids.each do |upload_id|upload = Upload.find(upload_id)next if upload.blank?++ extension = upload.extension&.downcase+ kind = image_extension?(extension) ? :image : :document++ next if allowed_kinds.exclude?(kind)++ if kind == :document+ mime_type =+ MiniMime.lookup_by_filename(upload.original_filename)&.content_type ||+ "application/octet-stream"++ attachment_type = attachment_type_for(upload.extension, mime_type)+ next if disallowed_attachment?(allowed_attachment_types, attachment_type)++ payload = encode_document(upload, mime_type)+ uploads << payload if payload+ next+ end+next if upload.width.to_i == 0 || upload.height.to_i == 0desired_extension = upload.extension@@ -18,6 +43,59 @@ module DiscourseAi# this keeps it very simple format wise given everyone supports png and jpgnext if !%w[jpeg png].include?(desired_extension)+ payload = encode_image(upload, desired_extension, max_pixels)+ uploads << payload if payload+ end+ uploads+ end++ def self.attachment_type_for(extension, mime_type)+ ext = extension.to_s.delete_prefix(".").downcase+ mime = mime_type.to_s++ return "pdf" if ext == "pdf" || mime.include?("pdf")+ return "docx" if ext == "docx"+ return "doc" if ext == "doc"+ return "txt" if ext == "txt" || mime.include?("text/plain")+ return "rtf" if ext == "rtf"+ return "html" if %w[html htm].include?(ext) || mime.include?("html")+ return "markdown" if %w[md markdown].include?(ext) || mime.include?("markdown")++ "file"+ end++ class << self+ private++ def normalize_attachment_types(types)+ return nil if types.nil?++ Array(types).map(&:downcase)+ end++ def disallowed_attachment?(allowed_types, attachment_type)+ !allowed_types.nil? && !allowed_types.include?(attachment_type)+ end++ def image_extension?(ext)+ %w[jpg jpeg png gif webp].include?(ext)+ end++ def encode_document(upload, mime_type)+ path = fetch_path(upload)+ return if path.blank?++ encoded = Base64.strict_encode64(File.binread(path))++ {+ base64: encoded,+ mime_type: mime_type,+ kind: :document,+ filename: upload.original_filename,+ }+ end++ def encode_image(upload, desired_extension, max_pixels)original_pixels = upload.width * upload.heightimage = upload@@ -34,22 +112,39 @@ module DiscourseAiupload.get_optimized_image(upload.width, upload.height, format: desired_extension)end- next if !image+ return if !imagemime_type = MiniMime.lookup_by_filename("test.#{desired_extension}").content_type- path = Discourse.store.path_for(image)+ path = fetch_path(image)+ return if path.blank?++ encoded = Base64.strict_encode64(File.binread(path))++ {+ base64: encoded,+ mime_type: mime_type,+ kind: :image,+ filename: upload.original_filename,+ }+ end++ def fetch_path(upload)+ path = Discourse.store.path_for(upload)if path.blank?- # download is protected with a DistributedMutex- external_copy = Discourse.store.download_safe(image)+ external_copy = Discourse.store.download_safe(upload)+ path = external_copy&.path+ end+ if path.blank?+ external_copy = Discourse.store.download(upload)path = external_copy&.pathend- encoded = Base64.strict_encode64(File.read(path))+ return if path.blank?+ return unless File.exist?(path)- uploads << { base64: encoded, mime_type: mime_type }+ pathend- uploadsendendenddiff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rbindex cfffd1584a1..2f1d2a2c5da 100644--- a/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb@@ -10,6 +10,41 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic doUploadCreator.new(image100x100, "image.jpg").create_for(Discourse.system_user.id)end+ def minimal_pdf_content+ %PDF-1.4+ 1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj+ 2 0 obj<< /Type /Pages /Count 1 /Kids [3 0 R] >>endobj+ 3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>endobj+ 4 0 obj<< /Length 44 >>stream+ BT /F1 12 Tf 72 720 Td (Hello PDF) Tj ET+ endstream+ endobj+ xref+ 0 5+ 0000000000 65535 f+ 0000000010 00000 n+ 0000000060 00000 n+ 0000000111 00000 n+ 0000000200 00000 n+ trailer<< /Size 5 /Root 1 0 R >>+ startxref+ 268+ %%EOF+ end++ def build_pdf_upload+ SiteSetting.authorized_extensions = "*"+ file = Tempfile.new(%w[test-pdf .pdf])+ file.binmode+ file.write(minimal_pdf_content)+ file.rewind+ UploadCreator.new(file, "document.pdf").create_for(Discourse.system_user.id)+ ensure+ file.close! if file+ end+let(:prompt) doDiscourseAi::Completions::Prompt.new("You are hello bot",@@ -336,6 +371,76 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic doexpect(requested_body).to eq(request_body)end+ it "can send pdf documents via a completion prompt" do+ model.update!(allowed_attachment_types: %w[pdf])+ pdf_upload = build_pdf_upload++ prompt =+ DiscourseAi::Completions::Prompt.new(+ "You are pdf bot",+ messages: [type: :user, id: "user1", content: ["hello", { upload_id: pdf_upload.id }]],+ )++ encoded = prompt.encoded_uploads(prompt.messages.last, allow_documents: true)++ request_body = {+ model: "claude-3-opus-20240229",+ max_tokens: 4096,+ messages: [+ {+ role: "user",+ content: [+ { type: "text", text: "user1: hello" },+ {+ type: "document",+ source: {+ type: "base64",+ media_type: "application/pdf",+ data: encoded[0][:base64],+ },+ },+ ],+ },+ ],+ system: "You are pdf bot",+ }++ response_body = <<~STRING+ {+ "content": [+ {+ "text": "What a cool pdf",+ "type": "text"+ }+ ],+ "id": "msg_013Zva2CMHLNnXjNJJKqJ2EF",+ "model": "claude-3-opus-20240229",+ "role": "assistant",+ "stop_reason": "end_turn",+ "stop_sequence": null,+ "type": "message",+ "usage": {+ "input_tokens": 10,+ "output_tokens": 25+ }+ }+ STRING++ requested_body = nil+ stub_request(:post, url).with(+ body:+ proc do |req_body|+ requested_body = JSON.parse(req_body, symbolize_names: true)+ true+ end,+ ).to_return(status: 200, body: response_body)++ result = llm.generate(prompt, user: Discourse.system_user)++ expect(result).to eq("What a cool pdf")+ expect(requested_body).to eq(request_body)+ end+it "can support reasoning" dobody = <<~STRING{diff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/gemini_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/gemini_spec.rbindex 3ee29fe51b9..b66132caa54 100644--- a/plugins/discourse-ai/spec/lib/completions/endpoints/gemini_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/gemini_spec.rb@@ -139,6 +139,41 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Gemini doUploadCreator.new(image100x100, "image.jpg").create_for(Discourse.system_user.id)end+ def minimal_pdf_content+ %PDF-1.4+ 1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj+ 2 0 obj<< /Type /Pages /Count 1 /Kids [3 0 R] >>endobj+ 3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>endobj+ 4 0 obj<< /Length 44 >>stream+ BT /F1 12 Tf 72 720 Td (Hello PDF) Tj ET+ endstream+ endobj+ xref+ 0 5+ 0000000000 65535 f+ 0000000010 00000 n+ 0000000060 00000 n+ 0000000111 00000 n+ 0000000200 00000 n+ trailer<< /Size 5 /Root 1 0 R >>+ startxref+ 268+ %%EOF+ end++ def build_pdf_upload+ SiteSetting.authorized_extensions = "*"+ file = Tempfile.new(%w[test-pdf .pdf])+ file.binmode+ file.write(minimal_pdf_content)+ file.rewind+ UploadCreator.new(file, "document.pdf").create_for(Discourse.system_user.id)+ ensure+ file.close! if file+ end+let(:gemini_mock) { GeminiMock.new(endpoint) }let(:compliance) do@@ -439,6 +474,64 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Gemini doexpect(JSON.parse(req_body)).to eq(expected_prompt)end+ it "passes pdf documents using inlineData" do+ model.update!(allowed_attachment_types: %w[pdf])+ pdf_upload = build_pdf_upload++ prompt =+ DiscourseAi::Completions::Prompt.new(+ "You are pdf bot",+ messages: [type: :user, id: "user1", content: ["hello", { upload_id: pdf_upload.id }]],+ )++ encoded = prompt.encoded_uploads(prompt.messages.last, allow_documents: true)++ response = gemini_mock.response("PDF processed").to_json++ req_body = nil++ llm = DiscourseAi::Completions::Llm.proxy(model)+ url = "#{model.url}:generateContent?key=123"++ stub_request(:post, url).with(+ body:+ proc do |_req_body|+ req_body = _req_body+ true+ end,+ ).to_return(status: 200, body: response)++ response = llm.generate(prompt, user: user)++ expect(response).to eq("PDF processed")++ expected_prompt = {+ "generationConfig" => {+ },+ "safetySettings" => [+ { "category" => "HARM_CATEGORY_HARASSMENT", "threshold" => "BLOCK_NONE" },+ { "category" => "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold" => "BLOCK_NONE" },+ { "category" => "HARM_CATEGORY_HATE_SPEECH", "threshold" => "BLOCK_NONE" },+ { "category" => "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold" => "BLOCK_NONE" },+ ],+ "contents" => [+ {+ "role" => "user",+ "parts" => [+ { "text" => "user1: hello" },+ { "inlineData" => { "mimeType" => "application/pdf", "data" => encoded[0][:base64] } },+ ],+ },+ ],+ "systemInstruction" => {+ "role" => "system",+ "parts" => [{ "text" => "You are pdf bot" }],+ },+ }++ expect(JSON.parse(req_body)).to eq(expected_prompt)+ end+it "Can stream tool calls correctly" dorows = [{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.rbindex 9f90c1a58fb..c5c7e7df878 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@@ -1,17 +1,10 @@# frozen_string_literal: true-RSpec.describe DiscourseAi::Completions::Endpoints::OpenAi do+RSpec.describe DiscourseAi::Completions::Endpoints::OpenAiResponses dosubject(:endpoint) { described_class.new(model) }fab!(:model) do- Fabricate(- :llm_model,- provider: "open_ai",- url: "https://api.openai.com/v1/responses",- provider_params: {- enable_responses_api: true,- },- )+ Fabricate(:llm_model, provider: "open_ai", url: "https://api.openai.com/v1/responses")endlet(:prompt_with_tools) do@@ -337,4 +330,31 @@ data: {"type":"response.reasoning_summary_part.added","sequence_number":3,"item_expect(result.parameters).to eq({ string: "sam" })expect(result.id).to eq("call_UdxBpinIVc5nRZ0VnWJIgneA")end++ it "uses reasoning object format for responses API" do+ model.update!(provider_params: { reasoning_effort: "minimal" })++ parsed_body = nil+ stub_request(:post, "https://api.openai.com/v1/responses").with(+ body:+ proc do |req_body|+ parsed_body = JSON.parse(req_body, symbolize_names: true)+ true+ end,+ ).to_return(status: 200, body: { output: [] }.to_json)++ prompt =+ DiscourseAi::Completions::Prompt.new(+ "You are a bot",+ messages: [type: :user, content: "hello"],+ )++ dialect = DiscourseAi::Completions::Dialects::OpenAiResponses.new(prompt, model)++ endpoint.perform_completion!(dialect, Discourse.system_user)++ expect(parsed_body[:reasoning]).to include(effort: "minimal", summary: "auto")+ expect(parsed_body).not_to have_key(:reasoning_effort)+ expect(parsed_body).to have_key(:input)+ 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 5bff71bef02..9ec268acd3c 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@@ -174,6 +174,41 @@ RSpec.describe DiscourseAi::Completions::Endpoints::OpenAi doUploadCreator.new(image100x100, "image.jpg").create_for(Discourse.system_user.id)end+ def minimal_pdf_content+ %PDF-1.4+ 1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj+ 2 0 obj<< /Type /Pages /Count 1 /Kids [3 0 R] >>endobj+ 3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>endobj+ 4 0 obj<< /Length 44 >>stream+ BT /F1 12 Tf 72 720 Td (Hello PDF) Tj ET+ endstream+ endobj+ xref+ 0 5+ 0000000000 65535 f+ 0000000010 00000 n+ 0000000060 00000 n+ 0000000111 00000 n+ 0000000200 00000 n+ trailer<< /Size 5 /Root 1 0 R >>+ startxref+ 268+ %%EOF+ end++ def build_pdf_upload+ SiteSetting.authorized_extensions = "*"+ file = Tempfile.new(%w[test-pdf .pdf])+ file.binmode+ file.write(minimal_pdf_content)+ file.rewind+ UploadCreator.new(file, "document.pdf").create_for(Discourse.system_user.id)+ ensure+ file.close! if file+ end+before { enable_current_plugin }describe "max tokens for reasoning models" do@@ -534,6 +569,9 @@ RSpec.describe DiscourseAi::Completions::Endpoints::OpenAi dodescribe "image support" doit "can handle images" domodel = Fabricate(:llm_model, vision_enabled: true)+ model.update!(allowed_attachment_types: %w[pdf])+ model.reload+ expect(model.allowed_attachment_types).to eq(%w[pdf])llm = DiscourseAi::Completions::Llm.proxy(model)prompt =DiscourseAi::Completions::Prompt.new(@@ -577,6 +615,57 @@ RSpec.describe DiscourseAi::Completions::Endpoints::OpenAi do}expect(parsed_body).to eq(expected_body)end++ it "can handle pdf documents via input_file nodes" do+ model = Fabricate(:llm_model, vision_enabled: true)+ model.update!(allowed_attachment_types: %w[pdf])+ llm = DiscourseAi::Completions::Llm.proxy(model)++ pdf_upload = build_pdf_upload++ prompt =+ DiscourseAi::Completions::Prompt.new(+ "You are pdf bot",+ messages: [type: :user, id: "user1", content: ["hello", { upload_id: pdf_upload.id }]],+ )++ encoded = prompt.encoded_uploads(prompt.messages.last, allow_documents: true)++ 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: "thanks" }] }.to_json)++ completion = llm.generate(prompt, user: user)++ expect(completion).to eq("thanks")+ expected_body = {+ model: "gpt-4-turbo",+ messages: [+ { role: "system", content: "You are pdf bot" },+ {+ role: "user",+ content: [+ { type: "text", text: "hello" },+ {+ type: "file",+ file: {+ filename: "document.pdf",+ file_data: "data:#{encoded[0][:mime_type]};base64,#{encoded[0][:base64]}",+ },+ },+ ],+ name: "user1",+ },+ ],+ }+ expect(parsed_body).to eq(expected_body)+ endenddescribe "#perform_completion!" do@@ -1022,24 +1111,6 @@ TEXTlet(:prompt) { compliance.generic_prompt }let(:dialect) { compliance.dialect(prompt: prompt) }- it "uses reasoning object format for responses API" do- model.update!(provider_params: { enable_responses_api: true, reasoning_effort: "minimal" })-- parsed_body = nil- stub_request(:post, "https://api.openai.com/v1/chat/completions").with(- body:- proc do |req_body|- parsed_body = JSON.parse(req_body, symbolize_names: true)- true- end,- ).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)-- endpoint.perform_completion!(dialect, user)-- expect(parsed_body[:reasoning]).to include(effort: "minimal", summary: "auto")- expect(parsed_body).not_to have_key(:reasoning_effort)- end-it "uses reasoning_effort field for standard API" domodel.update!(provider_params: { reasoning_effort: "low" })diff --git a/plugins/discourse-ai/spec/lib/completions/prompt_spec.rb b/plugins/discourse-ai/spec/lib/completions/prompt_spec.rbindex 4dbd73d279d..98c8e81d807 100644--- a/plugins/discourse-ai/spec/lib/completions/prompt_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/prompt_spec.rb@@ -7,6 +7,36 @@ RSpec.describe DiscourseAi::Completions::Prompt dolet(:user_msg) { "Write something nice" }let(:username) { "username1" }let(:image100x100) { plugin_file_from_fixtures("100x100.jpg") }+ let(:pdf_upload) do+ SiteSetting.authorized_extensions = "*"+ file = Tempfile.new(%w[test-pdf .pdf])+ file.binmode+ file.write(<<~PDF)+ %PDF-1.4+ 1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj+ 2 0 obj<< /Type /Pages /Count 1 /Kids [3 0 R] >>endobj+ 3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>endobj+ 4 0 obj<< /Length 44 >>stream+ BT /F1 12 Tf 72 720 Td (Hello PDF) Tj ET+ endstream+ endobj+ xref+ 0 5+ 0000000000 65535 f+ 0000000010 00000 n+ 0000000060 00000 n+ 0000000111 00000 n+ 0000000200 00000 n+ trailer<< /Size 5 /Root 1 0 R >>+ startxref+ 268+ %%EOF+ file.rewind+ UploadCreator.new(file, "document.pdf").create_for(Discourse.system_user.id)+ ensure+ file.close! if file+ endbefore { enable_current_plugin }@@ -43,6 +73,18 @@ RSpec.describe DiscourseAi::Completions::Prompt doexpect(encoded[1][:mime_type]).to eq("image/jpeg")expect(encoded[2]).to eq("this was an image")end++ it "only encodes documents when explicitly allowed" do+ prompt.push(type: :user, content: ["this is a pdf", { upload_id: pdf_upload.id }])++ expect(prompt.encoded_uploads(prompt.messages.last)).to be_empty++ encoded = prompt.encoded_uploads(prompt.messages.last, allow_documents: true)++ expect(encoded.length).to eq(1)+ expect(encoded.first[:mime_type]).to eq("application/pdf")+ expect(encoded.first[:kind]).to eq(:document)+ endenddescribe "#push" dodiff --git a/plugins/discourse-ai/spec/requests/admin/ai_llms_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_llms_controller_spec.rbindex 1176d56e68e..b78f04bc77d 100644--- a/plugins/discourse-ai/spec/requests/admin/ai_llms_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/admin/ai_llms_controller_spec.rb@@ -140,6 +140,20 @@ RSpec.describe DiscourseAi::Admin::AiLlmsController doexpect(model.display_name).to eq(valid_attrs[:display_name])end+ it "stores allowed_attachment_types" do+ attrs = valid_attrs.merge(allowed_attachment_types: %w[pdf docx])++ post "/admin/plugins/discourse-ai/ai-llms.json", params: { ai_llm: attrs }++ expect(response.status).to eq(201)+ model = LlmModel.last+ expect(model.allowed_attachment_types).to contain_exactly("pdf", "docx")+ expect(response.parsed_body["ai_llm"]["allowed_attachment_types"]).to contain_exactly(+ "pdf",+ "docx",+ )+ end+it "logs staff action when creating an LLM model" do# Log the creationpost "/admin/plugins/discourse-ai/ai-llms.json", params: { ai_llm: valid_attrs }