Class: RubyCanUseLLM::Prompt
- Inherits:
-
Object
- Object
- RubyCanUseLLM::Prompt
- Defined in:
- lib/rubycanusellm/prompt.rb
Constant Summary collapse
- VALID_ROLES =
%w[system user assistant].freeze
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(**roles) ⇒ Prompt
constructor
A new instance of Prompt.
- #render(**variables) ⇒ Object
Constructor Details
#initialize(**roles) ⇒ Prompt
Returns a new instance of Prompt.
10 11 12 13 14 15 16 |
# File 'lib/rubycanusellm/prompt.rb', line 10 def initialize(**roles) invalid = roles.keys.map(&:to_s) - VALID_ROLES raise Error, "Invalid role(s): #{invalid.join(", ")}. Valid roles: #{VALID_ROLES.join(", ")}" unless invalid.empty? raise Error, "Prompt requires at least a :user role" if !roles.key?(:user) && !roles.key?("user") @roles = roles.transform_keys(&:to_sym) end |
Class Method Details
.load(path, **variables) ⇒ Object
18 19 20 21 22 23 24 25 26 |
# File 'lib/rubycanusellm/prompt.rb', line 18 def self.load(path, **variables) raise Error, "Prompt file not found: #{path}" unless File.exist?(path) data = YAML.safe_load(File.read(path)) raise Error, "Prompt file must be a YAML hash with role keys (system, user, assistant)" unless data.is_a?(Hash) roles = data.transform_keys(&:to_sym).slice(*VALID_ROLES.map(&:to_sym)) new(**roles).render(**variables) end |
Instance Method Details
#render(**variables) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/rubycanusellm/prompt.rb', line 28 def render(**variables) binding_obj = build_binding(variables) @roles.filter_map do |role, template| next if template.nil? || template.strip.empty? content = ERB.new(template, trim_mode: "-").result(binding_obj) { role: role, content: content.strip } end rescue NameError => e raise Error, "Missing variable in prompt template: #{e.}" end |