|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "rails/generators" |
| 4 | +require "rails/generators/active_record" |
| 5 | + |
| 6 | +module LangchainrbRails |
| 7 | + module Generators |
| 8 | + # |
| 9 | + # Usage: |
| 10 | + # rails generate langchainrb_rails:assistant --llm=openai |
| 11 | + # |
| 12 | + class AssistantGenerator < Rails::Generators::Base |
| 13 | + include ::ActiveRecord::Generators::Migration |
| 14 | + |
| 15 | + # TODO: Move constant this to a shared place |
| 16 | + LLMS = { |
| 17 | + "anthropic" => "Langchain::LLM::Anthropic", |
| 18 | + "cohere" => "Langchain::LLM::Cohere", |
| 19 | + "google_palm" => "Langchain::LLM::GooglePalm", |
| 20 | + "google_gemini" => "Langchain::LLM::GoogleGemini", |
| 21 | + "google_vertex_ai" => "Langchain::LLM::GoogleVertexAI", |
| 22 | + "hugging_face" => "Langchain::LLM::HuggingFace", |
| 23 | + "llama_cpp" => "Langchain::LLM::LlamaCpp", |
| 24 | + "mistral_ai" => "Langchain::LLM::MistralAI", |
| 25 | + "ollama" => "Langchain::LLM::Ollama", |
| 26 | + "openai" => "Langchain::LLM::OpenAI", |
| 27 | + "replicate" => "Langchain::LLM::Replicate" |
| 28 | + }.freeze |
| 29 | + |
| 30 | + class_option :llm, |
| 31 | + type: :string, |
| 32 | + required: true, |
| 33 | + default: "openai", |
| 34 | + desc: "LLM provider that will be used to generate embeddings and completions", |
| 35 | + enum: LLMS.keys |
| 36 | + |
| 37 | + desc "This generator adds Assistant and Message models and tables to your Rails app" |
| 38 | + source_root File.join(__dir__, "templates") |
| 39 | + |
| 40 | + def copy_migration |
| 41 | + migration_template "assistant/migrations/create_assistants.rb", "db/migrate/create_assistants.rb", migration_version: migration_version |
| 42 | + migration_template "assistant/migrations/create_messages.rb", "db/migrate/create_messages.rb", migration_version: migration_version |
| 43 | + end |
| 44 | + |
| 45 | + def create_model_file |
| 46 | + template "assistant/models/assistant.rb", "app/models/assistant.rb" |
| 47 | + template "assistant/models/message.rb", "app/models/message.rb" |
| 48 | + end |
| 49 | + |
| 50 | + def migration_version |
| 51 | + "[#{::ActiveRecord::VERSION::MAJOR}.#{::ActiveRecord::VERSION::MINOR}]" |
| 52 | + end |
| 53 | + |
| 54 | + # TODO: Depending on the LLM provider, we may need to add additional gems |
| 55 | + # def add_to_gemfile |
| 56 | + # end |
| 57 | + |
| 58 | + private |
| 59 | + |
| 60 | + # @return [String] LLM provider to use |
| 61 | + def llm |
| 62 | + options["llm"] |
| 63 | + end |
| 64 | + |
| 65 | + # @return [Langchain::LLM::*] LLM class |
| 66 | + def llm_class |
| 67 | + Langchain::LLM.const_get(LLMS[llm]) |
| 68 | + end |
| 69 | + end |
| 70 | + end |
| 71 | +end |
0 commit comments