Module: OllamaChat::PromptManagement

Included in:
Chat
Defined in:
lib/ollama_chat/prompt_management.rb

Overview

Provides administrative and interactive management for prompt templates stored in the database.

This module handles the user-facing selection process for prompts, allowing users to interactively pick a prompt from the database.

Instance Method Summary collapse

Instance Method Details

#add_new_prompt(context: nil) ⇒ Boolean?

Interactively prompts the user for a name and content (optionally loading from a file) to create a new prompt template.

Returns:

  • (Boolean, nil)

    true if the prompt was added, nil if the process was cancelled



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/ollama_chat/prompt_management.rb', line 72

def add_new_prompt(context: nil)
  context ||= 'prompt'
  switch_history(:add_prompt) do
    name = determine_valid_new_name_for_prompt('to add', context:) or return

    sources       = %w[ [CLIPBOARD] [FILES] [EMPTY/MANUAL] ]
    chosen_source = choose_entry(sources, prompt: 'Where shall we source the prompt from? %s')
    chosen_source or return

    content = case chosen_source
              when '[CLIPBOARD]'
                perform_paste_from_clipboard(edit: false)
              when '[FILES]'
                patterns = ask?(
                  prompt: "❓ Enter file patterns to load file, C-u ⇒ new, C-c ⇒ cancel: ",
                  prefill: '**/*.{txt,md}'
                )
                patterns.nil? ? (return) : (patterns.present? ? load_prompt_from_file(patterns) : nil)
              else
                nil
              end

    prompt_content = edit_text(content)
    store_prompt(name, prompt_content, context:)
    log(:info, "Prompt added", data: { name:, context: })
    true
  end
end

#all_prompts(default: nil, context: nil) ⇒ Array<SearchUI::Wrapper>

Retrieves all stored prompts, decorated with a heart if they are marked as favourites.

Parameters:

  • default (Boolean, nil) (defaults to: nil)

    filter for default prompts (true: only defaults, false: only non-defaults)

Returns:

  • (Array<SearchUI::Wrapper>)

    the list of prompts for display in a chooser



16
17
18
19
20
21
22
# File 'lib/ollama_chat/prompt_management.rb', line 16

def all_prompts(default: nil, context: nil)
  context ||= 'prompt'
  favs = all_favourited(context)
  each_prompt(context:, default:).sort_by(&:name).map do |p|
    prompt_with_favourite(p.name, favs[p.name])
  end
end

#choose_and_delete_prompt(context: nil, force: false) ⇒ Object

Interactively selects an existing non-default prompt and deletes it after confirmation.



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/ollama_chat/prompt_management.rb', line 103

def choose_and_delete_prompt(context: nil, force: false)
  context ||= 'prompt'
  selected_prompt = choose_prompt(
    default:  force ? nil : false,
    context:,
    prompt:  'Which template has outlived its usefulness? %s'
  ) or return
  STDOUT.puts kramdown_ansi_parse(
    selected_prompt.to_s + "\n---"
  )
  confirm?(
    prompt: "🔔 Really delete the prompt #{bold{selected_prompt.name}}? (y/n) ",
    yes: /\Ay/i
  ) or return
  selected_prompt.destroy
  log(:info, "Prompt deleted", data: { name: selected_prompt.name, context: })
end

#choose_and_edit_prompt(context: nil) ⇒ self?

Interactively selects an existing prompt and allows the user to edit its content via the integrated editor.

Returns:

  • (self, nil)

    the current context on success, or nil if cancelled



125
126
127
128
129
130
131
132
# File 'lib/ollama_chat/prompt_management.rb', line 125

def choose_and_edit_prompt(context: nil)
  context ||= 'prompt'
  selected_prompt = choose_prompt(context:, prompt: 'Which spell needs some fine-tuning? %s') or return
  selected_prompt.['content'] = edit_text(selected_prompt.['content'].to_s)
  selected_prompt.save
  log(:info, "Prompt edited", data: { name: selected_prompt.name, context: })
  self
end

#choose_prompt(default: nil, context: nil, prompt: "Select a #{context || 'prompt'} template: %s") ⇒ OllamaChat::Database::Models::Prompt?

The choose_prompt method presents a menu of available prompts for selection. It retrieves the list of prompt names from the database, adds an '[EXIT]' option, and displays them via the Chooser utility.

Parameters:

  • default (Boolean, nil) (defaults to: nil)

    filter for default prompts (true: only defaults, false: only non-defaults)

  • prompt (String) (defaults to: "Select a #{context || 'prompt'} template: %s")

    the prompt message to display when asking for input

Returns:



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/ollama_chat/prompt_management.rb', line 34

def choose_prompt(default: nil, context: nil, prompt: "Select a #{context || 'prompt'} template: %s")
  context ||= 'prompt'
  prompts = all_prompts(default:, context:)
  prompts.unshift('[EXIT]')
  case chosen = choose_entry(prompts, prompt:)
  when '[EXIT]', nil
    STDOUT.puts "Exiting chooser."
    return
  when SearchUI::Wrapper
    prompt(chosen.value, context:)
  end
end

#duplicate_prompt(context: nil) ⇒ self?

Duplicates an existing prompt.

This method initiates an interactive workflow:

  1. Prompts the user to select a prompt to clone.
  2. Displays the content of the selected prompt for verification.
  3. Requests a new name for the duplicate, validating that it does not already exist in the database.
  4. Creates and saves the new prompt record using the Database::Duplicatable mixin.

Returns:

  • (self, nil)

    the current context on success, or nil if the user cancelled the operation or no prompt was selected.



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/ollama_chat/prompt_management.rb', line 145

def duplicate_prompt(context: nil)
  context ||= 'prompt'
  selected_prompt = choose_prompt(context:, prompt: 'Which prompt shall be the basis for a new one? %s') or return
  STDOUT.puts kramdown_ansi_parse(
    selected_prompt.to_s + "\n---"
  )
  name = nil
  loop do
    name = ask?(
      prompt: "❓ Enter new prompt name to duplicate as, C-c ⇒ cancel: "
    )
    if name.nil?
      STDOUT.puts "Cancelled."
      return nil
    end
    if prompt(name, context:)
      STDOUT.puts "Prompt named #{bold{name}} already exists."
    else
      break
    end
  end
  duplicated_prompt = selected_prompt.duplicate
  duplicated_prompt.name = name
  duplicated_prompt.['default'] = false
  duplicated_prompt.save
  log(:info, "Prompt duplicated", data: { name:, old_name: selected_prompt.name, context: })
  self
end

#export_prompt(context: nil) ⇒ self?

Interactively exports a prompt to a specified file.

The process follows these steps:

  1. Prompts the user to select a prompt via choose_prompt.
  2. Displays the prompt's current content to the terminal.
  3. Prompts for a destination filename via determine_valid_output_filename.
  4. Writes the prompt content to the chosen file.

Returns:

  • (self, nil)

    returns self if the export was successful, or nil if the process was cancelled during prompt selection or filename entry.



220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/ollama_chat/prompt_management.rb', line 220

def export_prompt(context: nil)
  context ||= 'prompt'
  selected_prompt = choose_prompt(context:, prompt: 'Which template are you exporting to disk? %s') or return
  STDOUT.puts kramdown_ansi_parse(
    selected_prompt.to_s + "\n---"
  )
  filename = determine_valid_output_filename('to write to') or return
  filename.write(selected_prompt.to_s)
  log(:info, "Prompt exported", data: { name: selected_prompt.name, dest: filename.to_s, context: })
  STDOUT.puts "Prompt #{selected_prompt.name.inspect} was exported as #{filename.to_path.inspect}?"
  self
end

#import_prompt(filename, context: nil) ⇒ self?

Interactively imports a prompt from a file.

The process follows these steps:

  1. Resolves the source file path (either using the provided filename or prompting the user to choose one).
  2. Prompts for a unique name for the new prompt via determine_valid_new_name_for_prompt.
  3. Reads the file content and stores it in the database.

Parameters:

  • filename (String, Pathname, nil)

    the path to the file to import, or nil to trigger interactive file selection.

Returns:

  • (self, nil)

    the current context on success, or nil if the import was cancelled.



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/ollama_chat/prompt_management.rb', line 186

def import_prompt(filename, context: nil)
  context ||= 'prompt'
  if filename
    if File.exist?(filename)
      filename = Pathname.new(filename)
    else
      filename = choose_filename(filename)
    end
  else
    filename = choose_filename('**/*.md')
  end
  unless filename
    STDOUT.puts "Cancelled."
    return
  end
  prompt_name = determine_valid_new_name_for_prompt('to import', context:) or return
  prompt_content = filename.read
  store_prompt(prompt_name, prompt_content, context:)
  log(:info, "Prompt imported", data: { name: prompt_name, source: filename.to_s, context: })
  STDOUT.puts "Imported prompt as #{prompt_name.inspect}."
  self
end

#info_prompt(context: nil) ⇒ self?

Displays detailed information about a selected prompt template.

Returns:

  • (self, nil)

    the current context on success, or nil if cancelled



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/ollama_chat/prompt_management.rb', line 50

def info_prompt(context: nil)
  context ||= 'prompt'
  if selected_prompt = choose_prompt(context:, prompt: 'Which blueprint would you like to inspect? %s')
    use_pager do |output|
      output.puts kramdown_ansi_parse(<<~EOT)
        # Prompt #{selected_prompt.name}
        ---

        #{selected_prompt.to_s}

        ---
      EOT
    end
  end
  self
end

#list_prompts(context: nil) ⇒ Array

Lists all prompt templates in the database, indicating which are defaults and showing a truncated preview of their content.

Returns:

  • (Array)

    the result of the prompt mapping



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/ollama_chat/prompt_management.rb', line 295

def list_prompts(context: nil)
  context ||= 'prompt'
  favs = all_favourited(context)
  each_prompt(context:).sort_by(&:name).map do |p|
    default = p.['default'] ? '' : ''
    start   = '%s %s' % [ default, bold { p.name } ]
    start   = prefix_favourite(start, favs[p.name])
    content = p.to_s.inspect[1..-2]
    content = Kramdown::ANSI::Width.truncate(
      content, length: 0.9 * (Tins::Terminal.columns - start.size)
    )
    STDOUT.print start
    STDOUT.puts ' %s' % italic { content }
  end
end

#prepare_conversation_historyString

Aggregates the current conversation history into a single string for context-aware generation.

Each message is formatted as "Sender Name: Message Content", skipping messages that contain no content.

Returns:

  • (String)

    The flattened conversation history.



240
241
242
243
244
245
246
# File 'lib/ollama_chat/prompt_management.rb', line 240

def prepare_conversation_history
  messages.each_message.inject('') do |result, message|
    message_content = message.content.full? or next result
    sender_name     = sender_name_displayed(message, template: false)
    result << "%s: %s" % [ sender_name, message_content ]
  end
end

#reset_prompt_to_default(name, context: nil) ⇒ Boolean?

Resets a prompt's content to the default value defined in the configuration.

Parameters:

  • name (String, Symbol)

    the name of the prompt to reset

Returns:

  • (Boolean, nil)

    true if the prompt was reset, false if no default was found



315
316
317
318
319
320
321
# File 'lib/ollama_chat/prompt_management.rb', line 315

def reset_prompt_to_default(name, context: nil)
  context ||= 'prompt'
  if content = config.prompts.prompt[name.to_s]
    store_prompt(name, content, context:)
    true
  end
end

#suggest_prompts(edit: false) ⇒ String?

Interactively generates follow-up prompt suggestions based on the current session.

This method constructs a prompt containing the conversation history and an instruction (either selected from a template or provided manually) and requests a generation from the AI model. The resulting suggestions are then opened in the editor for final refinement before being returned.

Parameters:

  • edit (Boolean) (defaults to: false)

    If true, allows the user to write a custom suggestion instruction on the fly; otherwise, prompts the user to pick a template.

Returns:

  • (String, nil)

    The refined suggestion text, or nil if the process was cancelled.



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/ollama_chat/prompt_management.rb', line 261

def suggest_prompts(edit: false)
  instruction = nil
  if edit
    # Let the user write a suggestion instruction on the fly
    instruction = edit_text('').full? or return
  else
    # Let the user pick a prompt template (e.g., suggest_coding, suggest_roleplaying)
    instruction = choose_prompt(
      prompt: 'Which suggestion strategy shall we employ? %s',
      context: 'suggest'
    ) or return
  end

  # Build the context by gathering all current conversation messages
  history     = prepare_conversation_history
  full_prompt = <<~EOT
    Conversation History:
    #{history}

    Instruction:
    #{instruction}
  EOT

  # Execute a silent chat oneshot call (doesn't add to history)
  suggestions  = generate(prompt: full_prompt).full? or return

  # Pass the AI's suggestions through the editor for final refinement
  edit_text(suggestions)
end