2023-03-15 16:02:20 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module DiscourseAi
|
|
|
|
module AiHelper
|
|
|
|
class AssistantController < ::ApplicationController
|
|
|
|
requires_plugin ::DiscourseAi::PLUGIN_NAME
|
|
|
|
requires_login
|
|
|
|
before_action :ensure_can_request_suggestions
|
|
|
|
|
2023-03-17 14:14:19 -04:00
|
|
|
def prompts
|
|
|
|
render json:
|
|
|
|
ActiveModel::ArraySerializer.new(
|
|
|
|
DiscourseAi::AiHelper::OpenAiPrompt.new.available_prompts,
|
|
|
|
root: false,
|
|
|
|
),
|
|
|
|
status: 200
|
|
|
|
end
|
|
|
|
|
2023-03-15 16:02:20 -04:00
|
|
|
def suggest
|
|
|
|
raise Discourse::InvalidParameters.new(:text) if params[:text].blank?
|
|
|
|
|
2023-03-17 14:14:19 -04:00
|
|
|
prompt = CompletionPrompt.find_by(name: params[:mode])
|
|
|
|
raise Discourse::InvalidParameters.new(:mode) if !prompt || !prompt.enabled?
|
2023-03-15 16:02:20 -04:00
|
|
|
|
|
|
|
RateLimiter.new(current_user, "ai_assistant", 6, 3.minutes).performed!
|
|
|
|
|
|
|
|
hijack do
|
|
|
|
render json:
|
|
|
|
DiscourseAi::AiHelper::OpenAiPrompt.new.generate_and_send_prompt(
|
2023-03-17 14:14:19 -04:00
|
|
|
prompt,
|
2023-03-15 16:02:20 -04:00
|
|
|
params[:text],
|
|
|
|
),
|
|
|
|
status: 200
|
|
|
|
end
|
2023-03-22 15:00:28 -04:00
|
|
|
rescue DiscourseAi::Inference::OpenAiCompletions::CompletionFailed
|
|
|
|
render_json_error I18n.t("discourse_ai.ai_helper.errors.completion_request_failed"),
|
|
|
|
status: 502
|
2023-03-15 16:02:20 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def ensure_can_request_suggestions
|
|
|
|
user_group_ids = current_user.group_ids
|
|
|
|
|
|
|
|
allowed =
|
|
|
|
SiteSetting.ai_helper_allowed_groups_map.any? do |group_id|
|
|
|
|
user_group_ids.include?(group_id)
|
|
|
|
end
|
|
|
|
|
|
|
|
raise Discourse::InvalidAccess if !allowed
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|