Class: ApplicationPrompt

Inherits:
Object
  • Object
show all
Defined in:
app/prompts/application_prompt.rb

Overview

Base class for LLM prompt templates.
Treat prompts like View templates - don't hardcode massive strings in Ruby files.

Examples:

Create a prompt class

class AnswerQuestionPrompt < ApplicationPrompt
  def self.render(context:, question:)
    new(context: context, question: question).to_s
  end

  def initialize(context:, question:)
    @context = context
    @question = question
  end

  def to_s
    <<~PROMPT
      You are a helpful assistant. Use the context below to answer.

      CONTEXT:
      #{@context}

      QUESTION:
      #{@question}
    PROMPT
  end
end

Use a prompt

prompt = AnswerQuestionPrompt.render(context: docs, question: user_query)
RubyLLM.chat.ask(prompt)

Direct Known Subclasses

ImageAnalysisPrompt

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.renderObject

Override in subclasses to define required parameters



37
38
39
# File 'app/prompts/application_prompt.rb', line 37

def render(**)
  new(**).to_s
end

Instance Method Details

#format_list(items, prefix: '- ') ⇒ Object (protected)

Format a list of items for inclusion in a prompt



56
57
58
# File 'app/prompts/application_prompt.rb', line 56

def format_list(items, prefix: '- ')
  Array(items).map { |item| "#{prefix}#{item}" }.join("\n")
end

#to_sObject

Raises:

  • (NotImplementedError)


42
43
44
# File 'app/prompts/application_prompt.rb', line 42

def to_s
  raise NotImplementedError, "#{self.class} must implement #to_s"
end

#truncate(text, max_length: 4000) ⇒ Object (protected)

Truncate text to a maximum length (for context windows)



49
50
51
52
53
# File 'app/prompts/application_prompt.rb', line 49

def truncate(text, max_length: 4000)
  return text if text.to_s.length <= max_length

  text.to_s[0...max_length] + '...[truncated]'
end