Compare commits

..
Author SHA1 Message Date
Martin Brennan bf8b3a4b40 DEV: Test if site setting can be added without translation 2024-07-10 13:55:19 +10:00
544 changed files with 13277 additions and 29101 deletions
+6 -5
View File
@@ -1,7 +1,8 @@
< 3.4.0.beta3-dev: decf1bb49d737ea15308400f22f89d1d1e71d13d
< 3.4.0.beta1-dev: 9d887ad4ace8e33c3fe7dbb39237e882c08b4f0b
< 3.3.0.beta5-dev: 4d8090002f6dcd8e34d41033606bf131fa221475
< 3.3.0.beta2-dev: 61890b667c06299841ae88946f84a112f00060e1 < 3.3.0.beta2-dev: 61890b667c06299841ae88946f84a112f00060e1
< 3.3.0.beta1-dev: d94234d89f50733678a5c62809445198a9fda74b < 3.3.0.beta1-dev: a65c4076a63104b61d213534db7f89aa3c8acd9e
3.2.999: d94234d89f50733678a5c62809445198a9fda74b < 3.2.0.beta5-dev: c70f43f130fb98e4a1adb1afd9b621aaa49088e3
< 3.2.0.beta4-dev: 493b48477a9288f2f1b6f021954088705a6673d6
< 3.2.0.beta2-dev: 3bced1c6f525553fe2b5b79d29bd66c1cf2a47d5
3.1.999: c0415bb7eb878b1b7abf112d65cba981030df8df 3.1.999: c0415bb7eb878b1b7abf112d65cba981030df8df
< 3.2.0.beta1-dev: 3e7c99de894b03e9161d9481da118fe893991a1d
3.1.0.beta3: 057fbe1ce6
+1
View File
@@ -0,0 +1 @@
module.exports = require("@discourse/lint-configs/eslint");
-1
View File
@@ -1,4 +1,3 @@
node_modules node_modules
/gems /gems
/auto_generated /auto_generated
.env
-2
View File
@@ -1,2 +0,0 @@
engine-strict = true
auto-install-peers = false
+3 -1
View File
@@ -32,7 +32,8 @@ GEM
rack (3.1.6) rack (3.1.6)
rainbow (3.1.1) rainbow (3.1.1)
regexp_parser (2.9.2) regexp_parser (2.9.2)
rexml (3.3.9) rexml (3.3.1)
strscan
rubocop (1.64.1) rubocop (1.64.1)
json (~> 2.3) json (~> 2.3)
language_server-protocol (>= 3.17.0) language_server-protocol (>= 3.17.0)
@@ -69,6 +70,7 @@ GEM
rubocop (~> 1.61) rubocop (~> 1.61)
rubocop-rspec (~> 3, >= 3.0.1) rubocop-rspec (~> 3, >= 3.0.1)
ruby-progressbar (1.13.0) ruby-progressbar (1.13.0)
strscan (3.1.0)
syntax_tree (6.2.0) syntax_tree (6.2.0)
prettier_print (>= 1.2.0) prettier_print (>= 1.2.0)
tzinfo (2.0.6) tzinfo (2.0.6)
@@ -1,25 +1,16 @@
import DiscourseRoute from "discourse/routes/discourse"; import DiscourseRoute from "discourse/routes/discourse";
export default class AdminPluginsShowDiscourseAiLlmsNew extends DiscourseRoute { export default DiscourseRoute.extend({
queryParams = {
llmTemplate: { refreshModel: true },
};
async model() { async model() {
const record = this.store.createRecord("ai-llm"); const record = this.store.createRecord("ai-llm");
record.provider_params = {};
return record; return record;
} },
setupController(controller, model) { setupController(controller, model) {
super.setupController(controller, model); this._super(controller, model);
controller.set( controller.set(
"allLlms", "allLlms",
this.modelFor("adminPlugins.show.discourse-ai-llms") this.modelFor("adminPlugins.show.discourse-ai-llms")
); );
controller.set( },
"llmTemplate", });
this.paramsFor(this.routeName).llmTemplate || null
);
}
}
@@ -1,19 +1,17 @@
import DiscourseRoute from "discourse/routes/discourse"; import DiscourseRoute from "discourse/routes/discourse";
export default class AdminPluginsShowDiscourseAiLlmsShow extends DiscourseRoute { export default DiscourseRoute.extend({
async model(params) { async model(params) {
const allLlms = this.modelFor("adminPlugins.show.discourse-ai-llms"); const allLlms = this.modelFor("adminPlugins.show.discourse-ai-llms");
const id = parseInt(params.id, 10); const id = parseInt(params.id, 10);
const record = allLlms.findBy("id", id); return allLlms.findBy("id", id);
record.provider_params = record.provider_params || {}; },
return record;
}
setupController(controller, model) { setupController(controller, model) {
super.setupController(controller, model); this._super(controller, model);
controller.set( controller.set(
"allLlms", "allLlms",
this.modelFor("adminPlugins.show.discourse-ai-llms") this.modelFor("adminPlugins.show.discourse-ai-llms")
); );
} },
} });
@@ -1,7 +1,7 @@
import { AUTO_GROUPS } from "discourse/lib/constants"; import { AUTO_GROUPS } from "discourse/lib/constants";
import DiscourseRoute from "discourse/routes/discourse"; import DiscourseRoute from "discourse/routes/discourse";
export default class AdminPluginsShowDiscourseAiPersonasNew extends DiscourseRoute { export default DiscourseRoute.extend({
async model() { async model() {
const record = this.store.createRecord("ai-persona"); const record = this.store.createRecord("ai-persona");
record.set("allowed_group_ids", [AUTO_GROUPS.trust_level_0.id]); record.set("allowed_group_ids", [AUTO_GROUPS.trust_level_0.id]);
@@ -10,16 +10,14 @@ export default class AdminPluginsShowDiscourseAiPersonasNew extends DiscourseRou
record.set("rag_chunk_tokens", 374); record.set("rag_chunk_tokens", 374);
record.set("rag_chunk_overlap_tokens", 10); record.set("rag_chunk_overlap_tokens", 10);
record.set("rag_conversation_chunks", 10); record.set("rag_conversation_chunks", 10);
record.set("allow_personal_messages", true);
record.set("tool_details", false);
return record; return record;
} },
setupController(controller, model) { setupController(controller, model) {
super.setupController(controller, model); this._super(controller, model);
controller.set( controller.set(
"allPersonas", "allPersonas",
this.modelFor("adminPlugins.show.discourse-ai-personas") this.modelFor("adminPlugins.show.discourse-ai-personas")
); );
} },
} });
@@ -1,19 +1,19 @@
import DiscourseRoute from "discourse/routes/discourse"; import DiscourseRoute from "discourse/routes/discourse";
export default class AdminPluginsShowDiscourseAiPersonasShow extends DiscourseRoute { export default DiscourseRoute.extend({
async model(params) { async model(params) {
const allPersonas = this.modelFor( const allPersonas = this.modelFor(
"adminPlugins.show.discourse-ai-personas" "adminPlugins.show.discourse-ai-personas"
); );
const id = parseInt(params.id, 10); const id = parseInt(params.id, 10);
return allPersonas.findBy("id", id); return allPersonas.findBy("id", id);
} },
setupController(controller, model) { setupController(controller, model) {
super.setupController(controller, model); this._super(controller, model);
controller.set( controller.set(
"allPersonas", "allPersonas",
this.modelFor("adminPlugins.show.discourse-ai-personas") this.modelFor("adminPlugins.show.discourse-ai-personas")
); );
} },
} });
@@ -1,11 +0,0 @@
import { service } from "@ember/service";
import { ajax } from "discourse/lib/ajax";
import DiscourseRoute from "discourse/routes/discourse";
export default class DiscourseAiUsageRoute extends DiscourseRoute {
@service store;
model() {
return ajax("/admin/plugins/discourse-ai/ai-usage.json");
}
}
@@ -1,5 +1 @@
<AiLlmsListEditor <AiLlmsListEditor @llms={{this.allLlms}} @currentLlm={{this.model}} />
@llms={{this.allLlms}}
@currentLlm={{this.model}}
@llmTemplate={{this.llmTemplate}}
/>
@@ -1,7 +1,5 @@
<section class="ai-persona-tool-editor__current admin-detail pull-left"> <AiToolEditor
<AiToolEditor @tools={{this.allTools}}
@tools={{this.allTools}} @model={{this.model}}
@model={{this.model}} @presets={{this.presets}}
@presets={{this.presets}} />
/>
</section>
@@ -1,7 +1,5 @@
<section class="ai-persona-tool-editor__current admin-detail pull-left"> <AiToolEditor
<AiToolEditor @tools={{this.allTools}}
@tools={{this.allTools}} @model={{this.model}}
@model={{this.model}} @presets={{this.presets}}
@presets={{this.presets}} />
/>
</section>
@@ -1 +0,0 @@
<AiUsage @model={{this.model}} />
@@ -14,9 +14,6 @@ module DiscourseAi
llms, llms,
each_serializer: LlmModelSerializer, each_serializer: LlmModelSerializer,
root: false, root: false,
scope: {
llm_usage: DiscourseAi::Configuration::LlmEnumerator.global_usage,
},
).as_json, ).as_json,
meta: { meta: {
provider_params: LlmModel.provider_params, provider_params: LlmModel.provider_params,
@@ -39,34 +36,26 @@ module DiscourseAi
llm_model = LlmModel.new(ai_llm_params) llm_model = LlmModel.new(ai_llm_params)
if llm_model.save if llm_model.save
llm_model.toggle_companion_user llm_model.toggle_companion_user
render json: LlmModelSerializer.new(llm_model), status: :created render json: { ai_persona: LlmModelSerializer.new(llm_model) }, status: :created
else else
render_json_error llm_model render_json_error LlmModelSerializer.new(llm_model)
end end
end end
def update def update
llm_model = LlmModel.find(params[:id]) llm_model = LlmModel.find(params[:id])
if llm_model.seeded?
return render_json_error(I18n.t("discourse_ai.llm.cannot_edit_builtin"), status: 403)
end
if llm_model.update(ai_llm_params(updating: llm_model)) if llm_model.update(ai_llm_params(updating: llm_model))
llm_model.toggle_companion_user llm_model.toggle_companion_user
render json: LlmModelSerializer.new(llm_model) render json: LlmModelSerializer.new(llm_model)
else else
render_json_error llm_model render_json_error LlmModelSerializer.new(llm_model)
end end
end end
def destroy def destroy
llm_model = LlmModel.find(params[:id]) llm_model = LlmModel.find(params[:id])
if llm_model.seeded?
return render_json_error(I18n.t("discourse_ai.llm.cannot_delete_builtin"), status: 403)
end
in_use_by = DiscourseAi::Configuration::LlmValidator.new.modules_using(llm_model) in_use_by = DiscourseAi::Configuration::LlmValidator.new.modules_using(llm_model)
if !in_use_by.empty? if !in_use_by.empty?
@@ -108,8 +97,6 @@ module DiscourseAi
private private
def ai_llm_params(updating: nil) def ai_llm_params(updating: nil)
return {} if params[:ai_llm].blank?
permitted = permitted =
params.require(:ai_llm).permit( params.require(:ai_llm).permit(
:display_name, :display_name,
@@ -119,30 +106,20 @@ module DiscourseAi
:max_prompt_tokens, :max_prompt_tokens,
:api_key, :api_key,
:enabled_chat_bot, :enabled_chat_bot,
:vision_enabled,
) )
provider = updating ? updating.provider : permitted[:provider] provider = updating ? updating.provider : permitted[:provider]
permit_url = provider != LlmModel::BEDROCK_PROVIDER_NAME permit_url =
(updating && updating.url != LlmModel::RESERVED_VLLM_SRV_URL) ||
provider != LlmModel::BEDROCK_PROVIDER_NAME
new_url = params.dig(:ai_llm, :url) permitted[:url] = params.dig(:ai_llm, :url) if permit_url
permitted[:url] = new_url if permit_url && new_url
extra_field_names = LlmModel.provider_params.dig(provider&.to_sym) extra_field_names = LlmModel.provider_params.dig(provider&.to_sym, :fields).to_a
if extra_field_names.present? received_prov_params = params.dig(:ai_llm, :provider_params)
received_prov_params = permitted[:provider_params] = received_prov_params.slice(
params.dig(:ai_llm, :provider_params)&.slice(*extra_field_names.keys) *extra_field_names,
).permit! if !extra_field_names.empty? && received_prov_params.present?
if received_prov_params.present?
received_prov_params.each do |pname, value|
if extra_field_names[pname.to_sym] == :checkbox
received_prov_params[pname] = ActiveModel::Type::Boolean.new.cast(value)
end
end
permitted[:provider_params] = received_prov_params.permit!
end
end
permitted permitted
end end
@@ -5,7 +5,8 @@ module DiscourseAi
class AiPersonasController < ::Admin::AdminController class AiPersonasController < ::Admin::AdminController
requires_plugin ::DiscourseAi::PLUGIN_NAME requires_plugin ::DiscourseAi::PLUGIN_NAME
before_action :find_ai_persona, only: %i[show update destroy create_user] before_action :find_ai_persona,
only: %i[show update destroy create_user indexing_status_check]
def index def index
ai_personas = ai_personas =
@@ -40,7 +41,7 @@ module DiscourseAi
def create def create
ai_persona = AiPersona.new(ai_persona_params.except(:rag_uploads)) ai_persona = AiPersona.new(ai_persona_params.except(:rag_uploads))
if ai_persona.save if ai_persona.save
RagDocumentFragment.link_target_and_uploads(ai_persona, attached_upload_ids) RagDocumentFragment.link_persona_and_uploads(ai_persona, attached_upload_ids)
render json: { render json: {
ai_persona: LocalizedAiPersonaSerializer.new(ai_persona, root: false), ai_persona: LocalizedAiPersonaSerializer.new(ai_persona, root: false),
@@ -58,11 +59,11 @@ module DiscourseAi
def update def update
if @ai_persona.update(ai_persona_params.except(:rag_uploads)) if @ai_persona.update(ai_persona_params.except(:rag_uploads))
RagDocumentFragment.update_target_uploads(@ai_persona, attached_upload_ids) RagDocumentFragment.update_persona_uploads(@ai_persona, attached_upload_ids)
render json: LocalizedAiPersonaSerializer.new(@ai_persona, root: false) render json: LocalizedAiPersonaSerializer.new(@ai_persona, root: false)
else else
render_json_error @ai_persona render_json_error LocalizedAiPersonaSerializer.new(@ai_persona, root: false)
end end
end end
@@ -70,97 +71,43 @@ module DiscourseAi
if @ai_persona.destroy if @ai_persona.destroy
head :no_content head :no_content
else else
render_json_error @ai_persona render_json_error LocalizedAiPersonaSerializer.new(@ai_persona, root: false)
end end
end end
def stream_reply def upload_file
persona = file = params[:file] || params[:files].first
AiPersona.find_by(name: params[:persona_name]) ||
AiPersona.find_by(id: params[:persona_id])
return render_json_error(I18n.t("discourse_ai.errors.persona_not_found")) if persona.nil?
return render_json_error(I18n.t("discourse_ai.errors.persona_disabled")) if !persona.enabled if !SiteSetting.ai_embeddings_enabled?
raise Discourse::InvalidAccess.new("Embeddings not enabled")
if persona.default_llm.blank?
return render_json_error(I18n.t("discourse_ai.errors.no_default_llm"))
end end
if params[:query].blank? validate_extension!(file.original_filename)
return render_json_error(I18n.t("discourse_ai.errors.no_query_specified")) validate_file_size!(file.tempfile.size)
end
if !persona.user_id hijack do
return render_json_error(I18n.t("discourse_ai.errors.no_user_for_persona")) upload =
end UploadCreator.new(
file.tempfile,
file.original_filename,
type: "discourse_ai_rag_upload",
skip_validations: true,
).create_for(current_user.id)
if !params[:username] && !params[:user_unique_id] if upload.persisted?
return render_json_error(I18n.t("discourse_ai.errors.no_user_specified")) render json: UploadSerializer.new(upload)
end else
render json: failed_json.merge(errors: upload.errors.full_messages), status: 422
user = nil
if params[:username]
user = User.find_by_username(params[:username])
return render_json_error(I18n.t("discourse_ai.errors.user_not_found")) if user.nil?
elsif params[:user_unique_id]
user = stage_user
end
raise Discourse::NotFound if user.nil?
topic_id = params[:topic_id].to_i
topic = nil
if topic_id > 0
topic = Topic.find(topic_id)
if topic.topic_allowed_users.where(user_id: user.id).empty?
return render_json_error(I18n.t("discourse_ai.errors.user_not_allowed"))
end end
end end
end
hijack = request.env["rack.hijack"] def indexing_status_check
io = hijack.call render json: RagDocumentFragment.indexing_status(@ai_persona, @ai_persona.uploads)
DiscourseAi::AiBot::ResponseHttpStreamer.queue_streamed_reply(
io: io,
persona: persona,
user: user,
topic: topic,
query: params[:query].to_s,
custom_instructions: params[:custom_instructions].to_s,
current_user: current_user,
)
end end
private private
AI_STREAM_CONVERSATION_UNIQUE_ID = "ai-stream-conversation-unique-id"
def stage_user
unique_id = params[:user_unique_id].to_s
field = UserCustomField.find_by(name: AI_STREAM_CONVERSATION_UNIQUE_ID, value: unique_id)
if field
field.user
else
preferred_username = params[:preferred_username]
username = UserNameSuggester.suggest(preferred_username || unique_id)
user =
User.new(
username: username,
email: "#{SecureRandom.hex}@invalid.com",
staged: true,
active: false,
)
user.custom_fields[AI_STREAM_CONVERSATION_UNIQUE_ID] = unique_id
user.save!
user
end
end
def find_ai_persona def find_ai_persona
@ai_persona = AiPersona.find(params[:id]) @ai_persona = AiPersona.find(params[:id])
end end
@@ -181,6 +128,7 @@ module DiscourseAi
:temperature, :temperature,
:default_llm, :default_llm,
:user_id, :user_id,
:mentionable,
:max_context_posts, :max_context_posts,
:vision_enabled, :vision_enabled,
:vision_max_pixels, :vision_max_pixels,
@@ -188,13 +136,8 @@ module DiscourseAi
:rag_chunk_overlap_tokens, :rag_chunk_overlap_tokens,
:rag_conversation_chunks, :rag_conversation_chunks,
:question_consolidator_llm, :question_consolidator_llm,
:allow_chat_channel_mentions, :allow_chat,
:allow_chat_direct_messages,
:allow_topic_mentions,
:allow_personal_messages,
:tool_details, :tool_details,
:forced_tool_count,
:force_default_llm,
allowed_group_ids: [], allowed_group_ids: [],
rag_uploads: [:id], rag_uploads: [:id],
) )
@@ -209,12 +152,40 @@ module DiscourseAi
def permit_tools(tools) def permit_tools(tools)
return [] if !tools.is_a?(Array) return [] if !tools.is_a?(Array)
tools.filter_map do |tool, options, force_tool| tools.filter_map do |tool, options|
break nil if !tool.is_a?(String) break nil if !tool.is_a?(String)
options&.permit! if options && options.is_a?(ActionController::Parameters) options&.permit! if options && options.is_a?(ActionController::Parameters)
# this is simpler from a storage perspective, 1 way to store tools if options
[tool, options, !!force_tool] [tool, options]
else
tool
end
end
end
def validate_extension!(filename)
extension = File.extname(filename)[1..-1] || ""
authorized_extensions = %w[txt md]
if !authorized_extensions.include?(extension)
raise Discourse::InvalidParameters.new(
I18n.t(
"upload.unauthorized",
authorized_extensions: authorized_extensions.join(" "),
),
)
end
end
def validate_file_size!(filesize)
max_size_bytes = 20.megabytes
if filesize > max_size_bytes
raise Discourse::InvalidParameters.new(
I18n.t(
"upload.attachments.too_large_humanized",
max_size: ActiveSupport::NumberHelper.number_to_human_size(max_size_bytes),
),
)
end end
end end
end end
@@ -5,7 +5,7 @@ module DiscourseAi
class AiToolsController < ::Admin::AdminController class AiToolsController < ::Admin::AdminController
requires_plugin ::DiscourseAi::PLUGIN_NAME requires_plugin ::DiscourseAi::PLUGIN_NAME
before_action :find_ai_tool, only: %i[test show update destroy] before_action :find_ai_tool, only: %i[show update destroy]
def index def index
ai_tools = AiTool.all ai_tools = AiTool.all
@@ -21,7 +21,6 @@ module DiscourseAi
ai_tool.created_by_id = current_user.id ai_tool.created_by_id = current_user.id
if ai_tool.save if ai_tool.save
RagDocumentFragment.link_target_and_uploads(ai_tool, attached_upload_ids)
render_serialized(ai_tool, AiCustomToolSerializer, status: :created) render_serialized(ai_tool, AiCustomToolSerializer, status: :created)
else else
render_json_error ai_tool render_json_error ai_tool
@@ -30,7 +29,6 @@ module DiscourseAi
def update def update
if @ai_tool.update(ai_tool_params) if @ai_tool.update(ai_tool_params)
RagDocumentFragment.update_target_uploads(@ai_tool, attached_upload_ids)
render_serialized(@ai_tool, AiCustomToolSerializer) render_serialized(@ai_tool, AiCustomToolSerializer)
else else
render_json_error @ai_tool render_json_error @ai_tool
@@ -46,13 +44,18 @@ module DiscourseAi
end end
def test def test
@ai_tool.assign_attributes(ai_tool_params) if params[:ai_tool] if params[:id].present?
ai_tool = AiTool.find(params[:id])
else
ai_tool = AiTool.new(ai_tool_params)
end
parameters = params[:parameters].to_unsafe_h parameters = params[:parameters].to_unsafe_h
# we need an llm so we have a tokenizer # we need an llm so we have a tokenizer
# but will do without if none is available # but will do without if none is available
llm = LlmModel.first&.to_llm llm = LlmModel.first&.to_llm
runner = @ai_tool.runner(parameters, llm: llm, bot_user: current_user, context: {}) runner = ai_tool.runner(parameters, llm: llm, bot_user: current_user, context: {})
result = runner.invoke result = runner.invoke
if result.is_a?(Hash) && result[:error] if result.is_a?(Hash) && result[:error]
@@ -68,28 +71,18 @@ module DiscourseAi
private private
def attached_upload_ids
params[:ai_tool][:rag_uploads].to_a.map { |h| h[:id] }
end
def find_ai_tool def find_ai_tool
@ai_tool = AiTool.find(params[:id].to_i) @ai_tool = AiTool.find(params[:id])
end end
def ai_tool_params def ai_tool_params
params params.require(:ai_tool).permit(
.require(:ai_tool) :name,
.permit( :description,
:name, :script,
:description, :summary,
:script, parameters: [:name, :type, :description, :required, :enum, enum_values: []],
:summary, )
:rag_chunk_tokens,
:rag_chunk_overlap_tokens,
rag_uploads: [:id],
parameters: [:name, :type, :description, :required, enum: []],
)
.except(:rag_uploads)
end end
end end
end end
@@ -1,27 +0,0 @@
# frozen_string_literal: true
module DiscourseAi
module Admin
class AiUsageController < ::Admin::AdminController
requires_plugin "discourse-ai"
def show
render json: AiUsageSerializer.new(create_report, root: false)
end
private
def create_report
report =
DiscourseAi::Completions::Report.new(
start_date: params[:start_date]&.to_date || 30.days.ago,
end_date: params[:end_date]&.to_date || Time.current,
)
report = report.filter_by_feature(params[:feature]) if params[:feature].present?
report = report.filter_by_model(params[:model]) if params[:model].present?
report
end
end
end
end
@@ -1,75 +0,0 @@
# frozen_string_literal: true
module DiscourseAi
module Admin
class RagDocumentFragmentsController < ::Admin::AdminController
requires_plugin ::DiscourseAi::PLUGIN_NAME
def indexing_status_check
if params[:target_type] == "AiPersona"
@target = AiPersona.find(params[:target_id])
elsif params[:target_type] == "AiTool"
@target = AiTool.find(params[:target_id])
else
raise Discourse::InvalidParameters.new("Invalid target type")
end
render json: RagDocumentFragment.indexing_status(@target, @target.uploads)
end
def upload_file
file = params[:file] || params[:files].first
if !SiteSetting.ai_embeddings_enabled?
raise Discourse::InvalidAccess.new("Embeddings not enabled")
end
validate_extension!(file.original_filename)
validate_file_size!(file.tempfile.size)
hijack do
upload =
UploadCreator.new(
file.tempfile,
file.original_filename,
type: "discourse_ai_rag_upload",
skip_validations: true,
).create_for(current_user.id)
if upload.persisted?
render json: UploadSerializer.new(upload)
else
render json: failed_json.merge(errors: upload.errors.full_messages), status: 422
end
end
end
private
def validate_extension!(filename)
extension = File.extname(filename)[1..-1] || ""
authorized_extensions = %w[txt md]
if !authorized_extensions.include?(extension)
raise Discourse::InvalidParameters.new(
I18n.t(
"upload.unauthorized",
authorized_extensions: authorized_extensions.join(" "),
),
)
end
end
def validate_file_size!(filesize)
max_size_bytes = 20.megabytes
if filesize > max_size_bytes
raise Discourse::InvalidParameters.new(
I18n.t(
"upload.attachments.too_large_humanized",
max_size: ActiveSupport::NumberHelper.number_to_human_size(max_size_bytes),
),
)
end
end
end
end
end
@@ -1,87 +0,0 @@
# frozen_string_literal: true
module DiscourseAi
module AiBot
class ArtifactsController < ApplicationController
requires_plugin DiscourseAi::PLUGIN_NAME
before_action :require_site_settings!
skip_before_action :preload_json, :check_xhr, only: %i[show]
def show
artifact = AiArtifact.find(params[:id])
post = Post.find_by(id: artifact.post_id)
if artifact.metadata&.dig("public")
# no guardian needed
else
raise Discourse::NotFound if !post&.topic&.private_message?
raise Discourse::NotFound if !guardian.can_see?(post)
end
# Prepare the inner (untrusted) HTML document
untrusted_html = <<~HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>#{ERB::Util.html_escape(artifact.name)}</title>
<style>
#{artifact.css}
</style>
</head>
<body>
#{artifact.html}
<script>
#{artifact.js}
</script>
</body>
</html>
HTML
# Prepare the outer (trusted) HTML document
trusted_html = <<~HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>#{ERB::Util.html_escape(artifact.name)}</title>
<style>
html, body, iframe {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
border: 0;
overflow: hidden;
}
iframe {
overflow: auto;
}
</style>
</head>
<body>
<iframe sandbox="allow-scripts allow-forms" height="100%" width="100%" srcdoc="#{ERB::Util.html_escape(untrusted_html)}" frameborder="0"></iframe>
</body>
</html>
HTML
response.headers.delete("X-Frame-Options")
response.headers["Content-Security-Policy"] = "script-src 'unsafe-inline';"
response.headers["X-Robots-Tag"] = "noindex"
# Render the content
render html: trusted_html.html_safe, layout: false, content_type: "text/html"
end
private
def require_site_settings!
if !SiteSetting.discourse_ai_enabled ||
!SiteSetting.ai_artifact_security.in?(%w[lax strict])
raise Discourse::NotFound
end
end
end
end
end
@@ -6,14 +6,6 @@ module DiscourseAi
requires_plugin ::DiscourseAi::PLUGIN_NAME requires_plugin ::DiscourseAi::PLUGIN_NAME
requires_login requires_login
def show_debug_info_by_id
log = AiApiAuditLog.find(params[:id])
raise Discourse::NotFound if !log.topic
guardian.ensure_can_debug_ai_bot_conversation!(log.topic)
render json: AiApiAuditLogSerializer.new(log, root: false), status: 200
end
def show_debug_info def show_debug_info
post = Post.find(params[:post_id]) post = Post.find(params[:post_id])
guardian.ensure_can_debug_ai_bot_conversation!(post) guardian.ensure_can_debug_ai_bot_conversation!(post)
@@ -7,8 +7,7 @@ module DiscourseAi
requires_login only: %i[create update destroy] requires_login only: %i[create update destroy]
before_action :require_site_settings! before_action :require_site_settings!
skip_before_action :preload_json, :check_xhr, only: %i[show asset] skip_before_action :preload_json, :check_xhr, only: %i[show]
skip_before_action :verify_authenticity_token, only: ["asset"]
def create def create
ensure_allowed_create! ensure_allowed_create!
@@ -51,30 +50,6 @@ module DiscourseAi
end end
end end
def asset
no_cookies
name = params[:name]
path, content_type =
if name == "share"
%w[share.css text/css]
elsif name == "highlight"
%w[highlight.min.js application/javascript]
else
raise Discourse::NotFound
end
content = File.read(DiscourseAi.public_asset_path("ai-share/#{path}"))
# note, path contains a ":version" which automatically busts the cache
# based on file content, so this is safe
response.headers["Last-Modified"] = 10.years.ago.httpdate
response.headers["Content-Length"] = content.bytesize.to_s
immutable_for 1.year
render plain: content, disposition: :nil, content_type: content_type
end
def preview def preview
ensure_allowed_preview! ensure_allowed_preview!
data = SharedAiConversation.build_conversation_data(@topic, include_usernames: true) data = SharedAiConversation.build_conversation_data(@topic, include_usernames: true)
@@ -6,21 +6,10 @@ module DiscourseAi
requires_plugin ::DiscourseAi::PLUGIN_NAME requires_plugin ::DiscourseAi::PLUGIN_NAME
requires_login requires_login
before_action :ensure_can_request_suggestions before_action :ensure_can_request_suggestions
before_action :rate_limiter_performed! before_action :rate_limiter_performed!, except: %i[prompts]
include SecureUploadEndpointHelpers include SecureUploadEndpointHelpers
RATE_LIMITS = {
"default" => {
amount: 6,
interval: 3.minutes,
},
"caption_image" => {
amount: 20,
interval: 1.minute,
},
}.freeze
def suggest def suggest
input = get_text_param! input = get_text_param!
force_default_locale = params[:force_default_locale] || false force_default_locale = params[:force_default_locale] || false
@@ -35,7 +24,7 @@ module DiscourseAi
prompt.custom_instruction = params[:custom_prompt] prompt.custom_instruction = params[:custom_prompt]
end end
return suggest_thumbnails(input) if prompt.id == CompletionPrompt::ILLUSTRATE_POST suggest_thumbnails(input) if prompt.id == CompletionPrompt::ILLUSTRATE_POST
hijack do hijack do
render json: render json:
@@ -100,26 +89,18 @@ module DiscourseAi
end end
end end
def stream_suggestion def explain
post_id = get_post_param! post_id = get_post_param!
text = get_text_param! term_to_explain = get_text_param!
post = Post.includes(:topic).find_by(id: post_id) post = Post.includes(:topic).find_by(id: post_id)
prompt = CompletionPrompt.find_by(id: params[:mode])
raise Discourse::InvalidParameters.new(:mode) if !prompt || !prompt.enabled?
raise Discourse::InvalidParameters.new(:post_id) unless post raise Discourse::InvalidParameters.new(:post_id) unless post
if prompt.id == CompletionPrompt::CUSTOM_PROMPT
raise Discourse::InvalidParameters.new(:custom_prompt) if params[:custom_prompt].blank?
end
Jobs.enqueue( Jobs.enqueue(
:stream_post_helper, :stream_post_helper,
post_id: post.id, post_id: post.id,
user_id: current_user.id, user_id: current_user.id,
text: text, term_to_explain: term_to_explain,
prompt: prompt.name,
custom_prompt: params[:custom_prompt],
) )
render json: { success: true }, status: 200 render json: { success: true }, status: 200
@@ -172,23 +153,13 @@ module DiscourseAi
end end
def rate_limiter_performed! def rate_limiter_performed!
action_rate_limit = RATE_LIMITS[action_name] || RATE_LIMITS["default"] RateLimiter.new(current_user, "ai_assistant", 6, 3.minutes).performed!
RateLimiter.new(
current_user,
"ai_assistant",
action_rate_limit[:amount],
action_rate_limit[:interval],
).performed!
end end
def ensure_can_request_suggestions def ensure_can_request_suggestions
allowed_groups = if !current_user.in_any_groups?(SiteSetting.ai_helper_allowed_groups_map)
( raise Discourse::InvalidAccess
SiteSetting.composer_ai_helper_allowed_groups_map | end
SiteSetting.post_ai_helper_allowed_groups_map
)
raise Discourse::InvalidAccess if !current_user.in_any_groups?(allowed_groups)
end end
end end
end end
@@ -1,50 +0,0 @@
# frozen_string_literal: true
module DiscourseAi
module Discord
class BotController < ::ApplicationController
requires_plugin ::DiscourseAi::PLUGIN_NAME
skip_before_action :verify_authenticity_token
def interactions
# Request signature verification
begin
verify_request!
rescue Ed25519::VerifyError
return head :unauthorized
end
body = request.body.read
interaction = JSON.parse(body, object_class: OpenStruct)
if interaction.type == 1
# Respond to Discord PING request
render json: { type: 1 }
else
if !SiteSetting.ai_discord_allowed_guilds_map.include?(interaction.guild_id)
return head :forbidden
end
response = { type: 5, data: { content: "Searching..." } }
hijack { render json: response }
# Respond to Discord command
Jobs.enqueue(:stream_discord_reply, interaction: body)
end
end
private
def verify_request!
signature = request.headers["X-Signature-Ed25519"]
timestamp = request.headers["X-Signature-Timestamp"]
verify_key.verify([signature].pack("H*"), "#{timestamp}#{request.raw_post}")
end
def verify_key
Ed25519::VerifyKey.new([SiteSetting.ai_discord_app_public_key].pack("H*")).freeze
end
end
end
end
@@ -7,12 +7,8 @@ module DiscourseAi
SEMANTIC_SEARCH_TYPE = "semantic_search" SEMANTIC_SEARCH_TYPE = "semantic_search"
MAX_HYDE_SEARCHES_PER_MINUTE = 4
MAX_SEARCHES_PER_MINUTE = 100
def search def search
query = params[:q].to_s query = params[:q].to_s
skip_hyde = params[:hyde].to_s.downcase == "false" || params[:hyde].to_s == "0"
if query.length < SiteSetting.min_search_term_length if query.length < SiteSetting.min_search_term_length
raise Discourse::InvalidParameters.new(:q) raise Discourse::InvalidParameters.new(:q)
@@ -29,25 +25,13 @@ module DiscourseAi
semantic_search = DiscourseAi::Embeddings::SemanticSearch.new(guardian) semantic_search = DiscourseAi::Embeddings::SemanticSearch.new(guardian)
if !skip_hyde && !semantic_search.cached_query?(query) if !semantic_search.cached_query?(query)
RateLimiter.new( RateLimiter.new(current_user, "semantic-search", 4, 1.minutes).performed!
current_user,
"semantic-search",
MAX_HYDE_SEARCHES_PER_MINUTE,
1.minutes,
).performed!
else
RateLimiter.new(
current_user,
"semantic-search-non-hyde",
MAX_SEARCHES_PER_MINUTE,
1.minutes,
).performed!
end end
hijack do hijack do
semantic_search semantic_search
.search_for_topics(query, _page = 1, hyde: !skip_hyde) .search_for_topics(query)
.each { |topic_post| grouped_results.add(topic_post) } .each { |topic_post| grouped_results.add(topic_post) }
render_serialized(grouped_results, GroupedSearchResultSerializer, result: grouped_results) render_serialized(grouped_results, GroupedSearchResultSerializer, result: grouped_results)
@@ -55,9 +39,6 @@ module DiscourseAi
end end
def quick_search def quick_search
# this search function searches posts (vs: topics)
# it requires post embeddings and a reranker
# it will not perform a hyde expantion
query = params[:q].to_s query = params[:q].to_s
if query.length < SiteSetting.min_search_term_length if query.length < SiteSetting.min_search_term_length
@@ -15,21 +15,29 @@ module DiscourseAi
channel = ::Chat::Channel.find(params[:channel_id]) channel = ::Chat::Channel.find(params[:channel_id])
guardian.ensure_can_join_chat_channel!(channel) guardian.ensure_can_join_chat_channel!(channel)
summarizer = DiscourseAi::Summarization.chat_channel_summary(channel, since) strategy = DiscourseAi::Summarization.default_strategy
raise Discourse::NotFound.new unless summarizer raise Discourse::NotFound.new unless strategy
guardian.ensure_can_request_summary! guardian.ensure_can_request_summary!
RateLimiter.new(current_user, "channel_summary", 6, 5.minutes).performed! RateLimiter.new(current_user, "channel_summary", 6, 5.minutes).performed!
hijack do hijack do
strategy = DiscourseAi::Summarization::Strategies::ChatMessages.new(channel, since) content = { content_title: channel.name }
content[:contents] = channel
.chat_messages
.where("chat_messages.created_at > ?", since.hours.ago)
.includes(:user)
.order(created_at: :asc)
.pluck(:id, :username_lower, :message)
.map { { id: _1, poster: _2, text: _3 } }
summarized_text = summarized_text =
if strategy.targets_data.empty? if content[:contents].empty?
I18n.t("discourse_ai.summarization.chat.no_targets") I18n.t("discourse_ai.summarization.chat.no_targets")
else else
summarizer.summarize(current_user)&.summarized_text strategy.summarize(content, current_user).dig(:summary)
end end
render json: { summary: summarized_text } render json: { summary: summarized_text }
@@ -14,29 +14,19 @@ module DiscourseAi
RateLimiter.new(current_user, "summary", 6, 5.minutes).performed! if current_user RateLimiter.new(current_user, "summary", 6, 5.minutes).performed! if current_user
opts = params.permit(:skip_age_check) opts = params.permit(:skip_age_check)
skip_age_check = opts[:skip_age_check] == "true"
summarization_service = DiscourseAi::TopicSummarization.for(topic, current_user)
if params[:stream] && current_user if params[:stream] && current_user
cached_summary = summarization_service.cached_summary
if cached_summary && !skip_age_check
render_serialized(cached_summary, AiTopicSummarySerializer)
return
end
Jobs.enqueue( Jobs.enqueue(
:stream_topic_ai_summary, :stream_topic_ai_summary,
topic_id: topic.id, topic_id: topic.id,
user_id: current_user.id, user_id: current_user.id,
skip_age_check: skip_age_check, opts: opts.as_json,
) )
render json: success_json render json: success_json
else else
hijack do hijack do
summary = summarization_service.summarize(skip_age_check: skip_age_check) summary = DiscourseAi::TopicSummarization.summarize(topic, current_user, opts)
render_serialized(summary, AiTopicSummarySerializer) render_serialized(summary, AiTopicSummarySerializer)
end end
end end
@@ -2,29 +2,13 @@
module DiscourseAi module DiscourseAi
module AiBot module AiBot
module SharedAiConversationsHelper module SharedAiConversationsHelper
# keeping it here for caching # bump up version when assets change
def self.share_asset_url(asset_name) # long term we may want to change this cause it is hard to remember
if !%w[share.css highlight.js].include?(asset_name) # to bump versions, but for now this does the job
raise StandardError, "unknown asset type #{asset_name}" VERSION = "1"
end
@urls ||= {} def share_asset_url(short_path)
url = @urls[asset_name] ::UrlHelper.absolute("/plugins/discourse-ai/ai-share/#{short_path}?#{VERSION}")
return url if url
path = asset_name
path = "highlight.min.js" if asset_name == "highlight.js"
content = File.read(DiscourseAi.public_asset_path("ai-share/#{path}"))
sha1 = Digest::SHA1.hexdigest(content)
url = "/discourse-ai/ai-bot/shared-ai-conversations/asset/#{sha1}/#{asset_name}"
@urls[asset_name] = GlobalPath.cdn_path(url)
end
def share_asset_url(asset_name)
DiscourseAi::AiBot::SharedAiConversationsHelper.share_asset_url(asset_name)
end end
end end
end end
+7 -16
View File
@@ -9,24 +9,17 @@ module ::Jobs
# TODO(roman): Add a way to automatically recover from errors, resulting in unindexed uploads. # TODO(roman): Add a way to automatically recover from errors, resulting in unindexed uploads.
def execute(args) def execute(args)
return if (upload = Upload.find_by(id: args[:upload_id])).nil? return if (upload = Upload.find_by(id: args[:upload_id])).nil?
return if (ai_persona = AiPersona.find_by(id: args[:ai_persona_id])).nil?
target_type = args[:target_type]
target_id = args[:target_id]
return if !target_type || !target_id
target = target_type.constantize.find_by(id: target_id)
return if !target
truncation = DiscourseAi::Embeddings::Strategies::Truncation.new truncation = DiscourseAi::Embeddings::Strategies::Truncation.new
vector_rep = vector_rep =
DiscourseAi::Embeddings::VectorRepresentations::Base.current_representation(truncation) DiscourseAi::Embeddings::VectorRepresentations::Base.current_representation(truncation)
tokenizer = vector_rep.tokenizer tokenizer = vector_rep.tokenizer
chunk_tokens = target.rag_chunk_tokens chunk_tokens = ai_persona.rag_chunk_tokens
overlap_tokens = target.rag_chunk_overlap_tokens overlap_tokens = ai_persona.rag_chunk_overlap_tokens
fragment_ids = RagDocumentFragment.where(target: target, upload: upload).pluck(:id) fragment_ids = RagDocumentFragment.where(ai_persona: ai_persona, upload: upload).pluck(:id)
# Check if this is the first time we process this upload. # Check if this is the first time we process this upload.
if fragment_ids.empty? if fragment_ids.empty?
@@ -46,7 +39,7 @@ module ::Jobs
overlap_tokens: overlap_tokens, overlap_tokens: overlap_tokens,
) do |chunk, metadata| ) do |chunk, metadata|
fragment_ids << RagDocumentFragment.create!( fragment_ids << RagDocumentFragment.create!(
target: target, ai_persona: ai_persona,
fragment: chunk, fragment: chunk,
fragment_number: idx + 1, fragment_number: idx + 1,
upload: upload, upload: upload,
@@ -126,9 +119,7 @@ module ::Jobs
while overlap_token_ids.present? while overlap_token_ids.present?
begin begin
padding = split_char overlap = tokenizer.decode(overlap_token_ids) + split_char
padding = " " if padding.empty?
overlap = tokenizer.decode(overlap_token_ids) + padding
break if overlap.encoding == Encoding::UTF_8 break if overlap.encoding == Encoding::UTF_8
rescue StandardError rescue StandardError
# it is possible that we truncated mid char # it is possible that we truncated mid char
@@ -137,7 +128,7 @@ module ::Jobs
end end
# remove first word it is probably truncated # remove first word it is probably truncated
overlap = overlap.split(/\s/, 2).last.to_s.lstrip overlap = overlap.split(" ", 2).last
end end
end end
-22
View File
@@ -1,22 +0,0 @@
# frozen_string_literal: true
module ::Jobs
class FastTrackTopicGist < ::Jobs::Base
sidekiq_options retry: false
def execute(args)
return if !SiteSetting.discourse_ai_enabled
return if !SiteSetting.ai_summarization_enabled
return if !SiteSetting.ai_summary_gists_enabled
topic = Topic.find_by(id: args[:topic_id])
return if topic.blank?
summarizer = DiscourseAi::Summarization.topic_gist(topic)
gist = summarizer.existing_summary
return if gist.present? && !gist.outdated
summarizer.force_summarize(Discourse.system_user)
end
end
end

Some files were not shown because too many files have changed in this diff Show More