|
| 1 | +require "rails/generators/active_record" |
| 2 | + |
| 3 | +module LangchainrbRails |
| 4 | + module Generators |
| 5 | + # |
| 6 | + # PineconeGenerator does the following: |
| 7 | + # 1. Creates the `langchainrb_rails.rb` initializer file |
| 8 | + # 2. Adds necessary code to the ActiveRecord model to enable vectorsearch |
| 9 | + # 3. Adds `pinecone` gem to the Gemfile |
| 10 | + # |
| 11 | + # Usage: |
| 12 | + # rails generate langchainrb_rails:pinecone --model=Product --llm=openai |
| 13 | + # |
| 14 | + class PineconeGenerator < Rails::Generators::Base |
| 15 | + desc "This generator adds Pinecone vectorsearch integration to your ActiveRecord model" |
| 16 | + |
| 17 | + include ::ActiveRecord::Generators::Migration |
| 18 | + source_root File.join(__dir__, "templates") |
| 19 | + |
| 20 | + class_option :model, type: :string, required: true, desc: "ActiveRecord Model to add vectorsearch to", aliases: "-m" |
| 21 | + class_option :llm, type: :string, required: true, desc: "LLM provider that will be used to generate embeddings and completions" |
| 22 | + |
| 23 | + # Available LLM providers to be passed in as --llm option |
| 24 | + LLMS = { |
| 25 | + "cohere" => "Langchain::LLM::Cohere", |
| 26 | + "google_palm" => "Langchain::LLM::GooglePalm", |
| 27 | + "hugging_face" => "Langchain::LLM::HuggingFace", |
| 28 | + "llama_cpp" => "Langchain::LLM::LlamaCpp", |
| 29 | + "ollama" => "Langchain::LLM::Ollama", |
| 30 | + "openai" => "Langchain::LLM::OpenAI", |
| 31 | + "replicate" => "Langchain::LLM::Replicate" |
| 32 | + } |
| 33 | + |
| 34 | + # Creates the `langchainrb_rails.rb` initializer file |
| 35 | + def create_initializer_file |
| 36 | + template "pinecone_initializer.rb", "config/initializers/langchainrb_rails.rb" |
| 37 | + end |
| 38 | + |
| 39 | + # Adds `vectorsearch` class method to the model and `after_save` callback that calls `upsert_to_vectorsearch()` |
| 40 | + def add_to_model |
| 41 | + inject_into_class "app/models/#{model_name.downcase}.rb", model_name do |
| 42 | + " vectorsearch\n\n after_save :upsert_to_vectorsearch\n\n" |
| 43 | + end |
| 44 | + end |
| 45 | + |
| 46 | + # Adds `pinecone` gem to the Gemfile |
| 47 | + # TODO: Can we automatically run `bundle install`? |
| 48 | + def add_to_gemfile |
| 49 | + gem "pinecone" |
| 50 | + end |
| 51 | + |
| 52 | + private |
| 53 | + |
| 54 | + # @return [String] Name of the model |
| 55 | + def model_name |
| 56 | + options["model"] |
| 57 | + end |
| 58 | + |
| 59 | + # @return [String] LLM provider to use |
| 60 | + def llm |
| 61 | + options["llm"] |
| 62 | + end |
| 63 | + |
| 64 | + # @return [Langchain::LLM::*] LLM class |
| 65 | + def llm_class |
| 66 | + Langchain::LLM.const_get(LLMS[llm]) |
| 67 | + end |
| 68 | + end |
| 69 | + end |
| 70 | +end |
0 commit comments