Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chunk documents ✨ #11

Merged
merged 1 commit into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ group :test do
end

# Nosia dependencies
gem "baran"
gem "commonmarker"
gem "faraday"
gem "langchainrb", github: "cbldev/langchainrb", branch: "main"
Expand Down
1 change: 1 addition & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@ PLATFORMS
x86_64-linux

DEPENDENCIES
baran
bootsnap
brakeman
capybara
Expand Down
2 changes: 1 addition & 1 deletion app/jobs/add_document_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ def perform(document_id)
document = Document.find(document_id)
document.titlize!
document.parse!
document.vectorize! if document.content.present?
document.chunkify! if document.content.present?
end
end
16 changes: 15 additions & 1 deletion app/jobs/get_ai_response_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,21 @@ def create_message(chat:)

def call_ollama(chat:)
message = create_message(chat:)
Document.ask(chat.last_question, k: 4) do |stream|

search_results = Chunk.similarity_search(chat.last_question, k: 4)
message.update(similar_document_ids: search_results.pluck(:document_id).uniq)

question = chat.last_question
context = search_results.map(&:content).join("\n---\n")

prompt = [
["Contexte :", context].join("\n"),
["Question :", question].join("\n"),
["Réponse :"]
].join("\n---\n")

llm = LangchainrbRails.config.vectorsearch.llm
llm.chat(messages: [{role: "user", content: prompt}]) do |stream|
new_content = stream.raw_response.dig("message", "content")
message.update(content: message.content + new_content) if new_content
end
Expand Down
5 changes: 5 additions & 0 deletions app/models/chunk.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class Chunk < ApplicationRecord
include Vectorizable

belongs_to :document
end
15 changes: 15 additions & 0 deletions app/models/chunk/vectorizable.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module Chunk::Vectorizable
extend ActiveSupport::Concern

included do
vectorsearch
end

def as_vector
self.content
end

def vectorize!
upsert_to_vectorsearch
end
end
2 changes: 1 addition & 1 deletion app/models/document.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class Document < ApplicationRecord
include Parsable, Vectorizable
include Chunkable, Parsable, Vectorizable

has_one_attached :file

Expand Down
24 changes: 24 additions & 0 deletions app/models/document/chunkable.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module Document::Chunkable
extend ActiveSupport::Concern

included do
has_many :chunks, dependent: :destroy
end

def chunkify!
splitter = ::Baran::CharacterTextSplitter.new(
chunk_size: 1024,
chunk_overlap: 64,
separator: "\n\n"
)

new_chunks = splitter.chunks(self.content)

self.chunks.destroy_all

new_chunks.each do |new_chunk|
chunk = self.chunks.create!(content: new_chunk.dig(:text))
chunk.vectorize!
end
end
end
4 changes: 4 additions & 0 deletions app/models/message.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ def broadcast_updated
)
end

def similar_documents
Document.where(id: similar_document_ids)
end

def to_html
Commonmarker.to_html(content)
end
Expand Down
23 changes: 23 additions & 0 deletions app/views/messages/_message.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,29 @@
</div>
</div>
<% else %>
<% if message.similar_document_ids.any? %>
<div class="px-2 py-4 sm:px-4">
<h2 class="text-lg font-semibold text-slate-900 dark:text-slate-200">Documents similaires</h2>
<ul role="list" class="grid grid-cols-1 gap-6 text-slate-900 dark:text-slate-200 sm:grid-cols-2 lg:grid-cols-3">
<% message.similar_documents.each do |document| %>
<li class="group col-span-1 rounded-lg bg-slate-50 shadow transition-colors duration-300 hover:bg-blue-600 dark:bg-slate-900 dark:hover:bg-blue-600">
<%= link_to document_path(document), class: "flex cursor-pointer items-center justify-between space-x-6 truncate p-6" do %>
<div class="flex-1 truncate">
<div class="flex items-center space-x-3">
<h3 class="text-sm font-medium text-slate-900 transition-colors duration-300 group-hover:text-slate-50 dark:text-slate-200">
<%= document.title %>
</h3>
</div>
<p class="mt-1 truncate text-sm text-slate-500 transition-colors duration-300 group-hover:text-slate-300">
<%= document.content.first(50) %>
</p>
</div>
<% end %>
</li>
<% end %>
</ul>
</div>
<% end %>
<div class="mb-4 flex rounded-xl bg-slate-50 px-2 py-6 dark:bg-slate-900 sm:px-4">
<div class="flex max-w-3xl items-center rounded-xl">
<div>
Expand Down
11 changes: 11 additions & 0 deletions db/migrate/20240628203936_create_chunks.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class CreateChunks < ActiveRecord::Migration[8.0]
def change
create_table :chunks do |t|
t.belongs_to :document, null: false, foreign_key: true
t.text :content
t.vector :embedding, limit: 768

t.timestamps
end
end
end
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class AddSimilarDocumentIdsToMessages < ActiveRecord::Migration[8.0]
def change
add_column :messages, :similar_document_ids, :string, array: true, default: []
end
end
13 changes: 12 additions & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.