add openai pdf upload support

This commit is contained in:
Tanmay Deep Sharma
2025-08-04 18:47:16 +05:30
parent 51b9fd8eca
commit 634782ea65
13 changed files with 693 additions and 5 deletions
+31 -2
View File
@@ -26,10 +26,13 @@ class Captain::Document < ApplicationRecord
belongs_to :assistant, class_name: 'Captain::Assistant'
has_many :responses, class_name: 'Captain::AssistantResponse', dependent: :destroy, as: :documentable
belongs_to :account
has_one_attached :pdf_file
validates :external_link, presence: true
validates :external_link, uniqueness: { scope: :assistant_id }
validates :external_link, presence: true, unless: -> { pdf_file.attached? }
validates :external_link, uniqueness: { scope: :assistant_id }, allow_blank: true
validates :content, length: { maximum: 200_000 }
validates :pdf_file, presence: true, if: :pdf_document?
validate :validate_pdf_format, if: :pdf_document?
before_validation :ensure_account_id
enum status: {
@@ -47,6 +50,20 @@ class Captain::Document < ApplicationRecord
scope :for_account, ->(account_id) { where(account_id: account_id) }
scope :for_assistant, ->(assistant_id) { where(assistant_id: assistant_id) }
def pdf_document?
(external_link&.ends_with?('.pdf')) || (pdf_file.attached? && pdf_file.content_type == 'application/pdf')
end
def openai_file_id
metadata = self[:content].is_a?(Hash) ? self[:content] : {}
metadata['openai_file_id']
end
def store_openai_file_id(file_id)
current_metadata = self[:content].is_a?(Hash) ? self[:content] : {}
update!(content: current_metadata.merge('openai_file_id' => file_id).to_json)
end
private
def enqueue_crawl_job
@@ -73,4 +90,16 @@ class Captain::Document < ApplicationRecord
limits = account.usage_limits[:captain][:documents]
raise LimitExceededError, 'Document limit exceeded' unless limits[:current_available].positive?
end
def validate_pdf_format
return unless pdf_file.attached?
unless pdf_file.content_type == 'application/pdf'
errors.add(:pdf_file, 'must be a PDF file')
end
if pdf_file.byte_size > 512.megabytes
errors.add(:pdf_file, 'must be less than 512MB')
end
end
end