A platform for community discussion. Free, open, simple.
FIX: Prevent RAG chunking from corrupting CJK text (#42389)
Natalie Tay13c03c9f9276
diff --git a/plugins/discourse-ai/app/jobs/regular/digest_rag_upload.rb b/plugins/discourse-ai/app/jobs/regular/digest_rag_upload.rbindex b579ba6bf3c..2574306767f 100644--- a/plugins/discourse-ai/app/jobs/regular/digest_rag_upload.rb+++ b/plugins/discourse-ai/app/jobs/regular/digest_rag_upload.rb@@ -73,18 +73,17 @@ module Jobs# generally this will be plentyread_size = chunk_tokens * 10+ document_chunks = each_utf8_text_chunk(file:, chunk_size: read_size)while buffer.present? || !done- if buffer.length < read_size- read = file.read(read_size)- done = true if read.nil?-- read = Encodings.to_utf8(read) if read-- buffer << (read || "")+ while buffer.length < read_size && !done+ begin+ buffer << document_chunks.next+ rescue StopIteration+ done = true+ endend- # at this point we unconditionally have 2x CHUNK_SIZE worth of data in the buffermetadata_regex = /\[\[metadata (.*?)\]\]/mbefore_metadata, new_metadata, after_metadata = buffer.split(metadata_regex)@@ -136,6 +135,35 @@ module Jobsendend+ def each_utf8_text_chunk(file:, chunk_size:)+ return enum_for(__method__, file:, chunk_size:) if !block_given?++ file.binmode if file.respond_to?(:binmode)+ file.set_encoding(Encoding::UTF_8) if file.respond_to?(:set_encoding)++ source_chunks =+ if file.respond_to?(:each_line)+ file.each_line(chunk_size)+ else+ Enumerator.new do |yielder|+ while (chunk = file.read(chunk_size))+ yielder << chunk+ end+ end+ end++ first_chunk = true++ source_chunks.each do |chunk|+ chunk.force_encoding(Encoding::UTF_8)+ chunk.scrub!("")+ Encodings.delete_bom!(chunk) if first_chunk+ first_chunk = false++ yield chunk if !chunk.empty?+ end+ end+def first_chunk(text, chunk_tokens:, tokenizer:, splitters: ["\n\n", "\n", ".", ""])return text, " " if tokenizer.tokenize(text).length <= chunk_tokensdiff --git a/plugins/discourse-ai/spec/fixtures/rag/2-page.pdf b/plugins/discourse-ai/spec/fixtures/rag/2-page.pdfindex e12bec20cc4..1df6c106e5b 100644Binary files a/plugins/discourse-ai/spec/fixtures/rag/2-page.pdf and b/plugins/discourse-ai/spec/fixtures/rag/2-page.pdf differdiff --git a/plugins/discourse-ai/spec/fixtures/rag/parsed_doc_with_metadata.txt b/plugins/discourse-ai/spec/fixtures/rag/parsed_doc_with_metadata.txtindex 331a51d04ba..52f36ad13d0 100644--- a/plugins/discourse-ai/spec/fixtures/rag/parsed_doc_with_metadata.txt+++ b/plugins/discourse-ai/spec/fixtures/rag/parsed_doc_with_metadata.txt@@ -79,7 +79,7 @@ metadata: Jane's storynumber: 13these tools, jane began her work.-As she typed away at her keyboard, Jane couldnât help but feel a sense of excitement bubbling up inside her. This was no ordinary project; this was a chance to create something truly extraordinary. She poured her heart and soul into every line of code, crafting algorithms that would make even the most advanced AI systems [[look]] like mere calculators.+As she typed away at her keyboard, Jane couldn’t help but feel a sense of excitement bubbling up inside her. This was no ordinary project; this was a chance to create something truly extraordinary. She poured her heart and soul into every line of code, crafting algorithms that would make even the most advanced AI systems [[look]] like mere calculators.metadata: Jane's storynumber: 14@@ -91,7 +91,7 @@ metadata: Jane's storynumber: 15jane left no stone unturned.-As the weeks turned into months, Janeâs creation began to take shape. It was a thing of beauty, a masterpiece of artificial intelligence that could engage in witty banter, offer sage advice, and even tell the occasional joke (though its sense of humor was admittedly a bit on the quirky side). Jane beamed with pride as she watched her AI converse with humans, marveling at its ability to understand and respond to even the most complex of queries.+As the weeks turned into months, Jane’s creation began to take shape. It was a thing of beauty, a masterpiece of artificial intelligence that could engage in witty banter, offer sage advice, and even tell the occasional joke (though its sense of humor was admittedly a bit on the quirky side). Jane beamed with pride as she watched her AI converse with humans, marveling at its ability to understand and respond to even the most complex of queries.metadata: Jane's storynumber: 16@@ -119,4 +119,4 @@ In the end, Jane’s discourse AI became the stuff of legend, a shining examplemetadata: blank2number: 20-abc\ No newline at end of file+abcdiff --git a/plugins/discourse-ai/spec/jobs/regular/digest_rag_upload_spec.rb b/plugins/discourse-ai/spec/jobs/regular/digest_rag_upload_spec.rbindex 9bad02e2ce0..facbef7ce8d 100644--- a/plugins/discourse-ai/spec/jobs/regular/digest_rag_upload_spec.rb+++ b/plugins/discourse-ai/spec/jobs/regular/digest_rag_upload_spec.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-RSpec.describe Jobs::DigestRagUpload do+describe Jobs::DigestRagUpload dosubject(:job) { described_class.new }fab!(:agent, :ai_agent)@@ -48,6 +48,27 @@ RSpec.describe Jobs::DigestRagUpload do}.to raise_error(Discourse::InvalidAccess)endend++ context "when processing a PDF upload" do+ let(:pdf) { plugin_file_from_fixtures("2-page.pdf", "rag") }++ it "indexes multilingual text extracted from the PDF" do+ SiteSetting.authorized_extensions = "txt|pdf"+ pdf_upload = UploadCreator.new(pdf, "2-page.pdf").create_for(Discourse.system_user.id)++ job.execute(upload_id: pdf_upload.id, target_id: agent.id, target_type: agent.class.to_s)++ indexed_content =+ RagDocumentFragment+ .where(upload: pdf_upload, target: agent)+ .order(:fragment_number)+ .pluck(:fragment)+ .join("\n")++ expect(indexed_content).to include("| 猫 | cat | 貓 |", "| 犬 | dog | 狗 |")+ end+ end+context "when processing an upload containing metadata" doit "correctly splits on metadata boundary" do# be explicit here about chunking strategy@@ -75,7 +96,7 @@ RSpec.describe Jobs::DigestRagUpload do# to rebuild parsed#File.write("/tmp/testing", parsed)- expect(parsed).to eq(parsed_document_with_metadata.read)+ expect(parsed).to eq(parsed_document_with_metadata.read.delete_suffix("\n"))endendcontext "when processing an upload for the first time" do@@ -96,6 +117,65 @@ RSpec.describe Jobs::DigestRagUpload dojob.execute(upload_id: upload.id, target_id: agent.id, target_type: agent.class.to_s)}.to change(Jobs::GenerateRagEmbeddings.jobs, :size).by(1)end++ context "when UTF-8 content crosses a read boundary" do+ let(:multilingual_row) { "| 雷顎大剣ドネルヘレヴ | Donnerzahn | 兵器雷顎大劍 |\n" }+ let(:document_file) do+ read_size = agent.rag_chunk_tokens * 10+ StringIO.new((("a" * (read_size - 1)) + "猫\n" + multilingual_row).b)+ end++ it "preserves multilingual content across read boundaries" do+ SiteSetting.authorized_extensions = "txt|md"+ markdown_upload = Fabricate(:upload, extension: "md", original_filename: "glossary.md")+ job.execute(+ upload_id: markdown_upload.id,+ target_id: agent.id,+ target_type: agent.class.to_s,+ )++ indexed_content =+ RagDocumentFragment+ .where(upload: markdown_upload, target: agent)+ .order(:fragment_number)+ .pluck(:fragment)+ .join("\n")++ expect(indexed_content).to include("猫", multilingual_row.strip)+ end+ end++ context "when the document contains a UTF-8 byte order mark" do+ let(:document_file) { StringIO.new("\xEF\xBB\xBF猫".b) }++ it "removes the byte order mark" do+ job.execute(upload_id: upload.id, target_id: agent.id, target_type: agent.class.to_s)++ indexed_content =+ RagDocumentFragment+ .where(upload:, target: agent)+ .order(:fragment_number)+ .pick(:fragment)++ expect(indexed_content).to eq("猫")+ end+ end++ context "when a UTF-8 text document contains an invalid byte" do+ let(:document_file) { StringIO.new("before 猫 \xFF after 犬\n".b) }++ it "removes the invalid byte and preserves the surrounding text" do+ job.execute(upload_id: upload.id, target_id: agent.id, target_type: agent.class.to_s)++ indexed_content =+ RagDocumentFragment+ .where(upload:, target: agent)+ .order(:fragment_number)+ .pick(:fragment)++ expect(indexed_content).to eq("before 猫 after 犬")+ end+ endendit "doesn't generate new fragments if we already processed the upload" dodiff --git a/plugins/discourse-ai/spec/lib/utils/pdf_to_text_spec.rb b/plugins/discourse-ai/spec/lib/utils/pdf_to_text_spec.rbindex 3375550d150..f956b9878b4 100644--- a/plugins/discourse-ai/spec/lib/utils/pdf_to_text_spec.rb+++ b/plugins/discourse-ai/spec/lib/utils/pdf_to_text_spec.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-RSpec.describe DiscourseAi::Utils::PdfToText do+describe DiscourseAi::Utils::PdfToText dolet(:pdf) { plugin_file_from_fixtures("2-page.pdf", "rag") }let(:upload) { UploadCreator.new(pdf, "2-page.pdf").create_for(Discourse.system_user.id) }@@ -15,7 +15,7 @@ RSpec.describe DiscourseAi::Utils::PdfToText dopages = []pdf_to_text.extract_text { |page| pages << page }- expect(pages).to eq(["Page 1", "Page 2"])+ expect(pages).to eq(["| 猫 | cat | 貓 |", "| 犬 | dog | 狗 |"])endendend