数になったテキスト
「Can I send my order back?」と「Returns are free within 30 days」には、大事な単語がひとつも共通していません。それでも、一方はもう一方の答えです。単語で検索しても何も見つかりませんが、意味で検索すれば見つかります。そのために、埋め込みモデル(embedding model)がテキストを数のリスト、つまりベクトルに変えます。意味の似たテキストは、似た方向を向いたベクトルになります。
RubyLLM.embedで埋め込みを求めます。Chunky Miniの埋め込みは64個の数です(本物は768個から3072個):
install_gem "ruby_llm"
require "ruby_llm"
require "chunky_llm" # Chunky Mini、このページの中の小さなモデル
embedding = RubyLLM.embed("Chunky loves bacon")
vector = embedding.vectors
puts "#{vector.size} numbers, the first: #{vector.first(4)}"
embedding.modelどのくらい似ている? コサイン
2つの方向がどれだけ似ているかは、コサイン類似度で測ります。2つのベクトルの数を1つずつ掛けて合計し、両方の長さで割ります。1は同じ方向、0は何も共通点がないことを表します:
def cosine(a, b)
dot = a.zip(b).sum { |x, y| x * y }
dot / (Math.sqrt(a.sum { |x| x * x }) * Math.sqrt(b.sum { |x| x * x }))
end
bacon = RubyLLM.embed("Chunky loves bacon").vectors
food = RubyLLM.embed("The fox eats speck for breakfast").vectors
rain = RubyLLM.embed("It is raining in Bern").vectors
[cosine(bacon, food).round(2), cosine(bacon, rain).round(2)]「Chunky」と「the fox」、「bacon」と「speck」は、違う単語でも意味は似ています。そしてベクトルはそれを知っています。本物のモデルは何十億もの文からそれを学び、Chunky Miniは、仲間どうしの単語を集めた小さなリストから学びました。雨はそれとは何の関係もありません。
FAQを検索する
embedは配列も受け取り、テキストごとに1つのベクトルを返します。だからFAQは一度だけ埋め込んでおけば、あとは質問に対して、ベクトルがいちばん近い項目が見つかります:
faq = [
"Returns are free within 30 days.",
"Parcels ship within two working days.",
"You can pay by card or with TWINT.",
"The shop is open Monday to Saturday.",
"Gift vouchers never expire."
]
faq_vectors = RubyLLM.embed(faq).vectors
def closest(question, texts, vectors)
q = RubyLLM.embed(question).vectors
texts.zip(vectors).max_by { |_text, v| cosine(q, v) }.first
end
closest("Can I send my order back?", faq, faq_vectors)closest("How long does the delivery take?", faq, faq_vectors)RAG:検索してから生成する
Chunky Miniはこのお店を知りません。大きなモデルも知りません。このFAQを見たことがないのですから:
RubyLLM.chat.ask("Can I pay with my card?").contentでも、正しい項目を見つけて、質問といっしょにモデルに渡すことはできます。これがRAG(retrieval-augmented generation、検索拡張生成)です。まず検索し、見つかったものからモデルに答えさせます:
question = "Can I pay with my card?"
note = closest(question, faq, faq_vectors)
RubyLLM.chat.with_instructions("Answer from these notes:\n#{note}").ask(question).contentメモが5つなら、全部送ってしまってもかまいません。でもヘルプページが20,000あるお店ではそうはいきません。モデルのコンテキストに入りきらないうえ、トークンごとにお金がかかります。検索が大事なものをいくつか選び出し、モデルは何かをでっちあげる代わりに、あなたのテキストから答えます。
本物の埋め込みモデルなら、RubyLLM.embed(texts, model: "text-embedding-3-small")(OpenAI、1536個の数)か、Ollamaで動くローカルのモデルです。文書は一度だけ埋め込んで、ベクトルを検索できるデータベースに保存します。PostgreSQLならpgvectorとneighbor gem(has_neighbors :embeddingのあと、nearest_neighbors(:embedding, q, distance: "cosine"))、SQLiteならsqlite-vecです。RubyLLM.rerankは、質問とテキストをいっしょに読むモデルで、見つかったものをもう一度並べ替えます。
shop_answer(question, texts, vectors)を書いてください。closestと同じようにテキストとそのベクトルを受け取り、いちばん近い項目を見つけて、その項目を指示に入れたチャットの返事を返します。試してみましょう:shop_answer("When is the shop open?", faq, faq_vectors)。install_gem "ruby_llm"
require "ruby_llm"
require "chunky_llm" # Chunky Mini、このページの中の小さなモデル
# def shop_answer(question, texts, vectors)
# ...
# end
#
# shop_answer("When is the shop open?", faq, faq_vectors)