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
-
#add_new_prompt(context: nil) ⇒ self?
Interactively prompts the user for a name and content (optionally loading from a file) to create a new prompt template.
-
#all_prompts(default: nil, context: nil) ⇒ Array<SearchUI::Wrapper>
Retrieves all stored prompts, decorated with a heart if they are marked as favourites.
-
#choose_and_delete_prompt(context: nil, force: false) ⇒ Object
Interactively selects an existing non-default prompt and deletes it after confirmation.
-
#choose_and_edit_prompt(context: nil) ⇒ self?
Interactively selects an existing prompt and allows the user to edit its content via the integrated editor.
-
#choose_and_reset_count(context: nil) ⇒ Object
Interactively selects prompts and resets their usage counters.
-
#choose_prompt(default: nil, context: nil, count: false, prompt: "Select a #{context || 'prompt'} template: %s") ⇒ OllamaChat::Database::Models::Prompt?
The choose_prompt method presents a menu of available prompts for selection.
-
#choose_prompt_context ⇒ String?
The choose_prompt_context method presents a menu of available prompt contexts for selection.
-
#determine_valid_new_name_for_prompt(action, context: nil) ⇒ String?
private
Interactively determines a unique name for a new prompt, ensuring it does not conflict with existing prompts in the database.
-
#duplicate_prompt(context: nil) ⇒ self?
Duplicates an existing prompt.
-
#export_prompt(context: nil) ⇒ self?
Interactively exports a prompt to a specified file.
-
#import_prompt(filename, context: nil) ⇒ self?
Interactively imports a prompt from a file.
-
#info_prompt(context: nil) ⇒ self
Displays detailed information about a selected prompt template.
-
#list_prompts(context: nil) ⇒ Array
Lists all prompt templates in the database, indicating which are defaults and showing a truncated preview of their content.
-
#prepare_conversation_history ⇒ String
Aggregates the current conversation history into a single string for context-aware generation.
-
#prompt_sync(context: nil) ⇒ self?
Synchronizes database prompts with their shipped defaults from the configuration.
-
#prompt_with_favourite(name, favourited) ⇒ SearchUI::Wrapper
private
Helper to wrap a prompt name with its favourite status for the UI.
-
#rename_prompt(context: nil) ⇒ self?
Interactively selects an existing prompt and renames it.
-
#reset_prompt_count(name, context: nil) ⇒ Boolean?
Resets the usage counter (
metadata['use_count']) for a prompt to zero, removing its position boost in the #all_prompts sort. -
#reset_prompt_to_default(name, context: nil) ⇒ Boolean?
Resets a prompt's content to the default value defined in the configuration.
-
#show_prompt_diff(prompt, shipped, context:) ⇒ Object
private
Writes the database copy and the shipped default to temp files and displays a unified diff via
OC::DIFF_COMMAND. -
#suggest_prompts(edit: false) ⇒ String?
Interactively generates follow-up prompt suggestions based on the current session.
Instance Method Details
#add_new_prompt(context: nil) ⇒ self?
Interactively prompts the user for a name and content (optionally loading from a file) to create a new prompt template.
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
# File 'lib/ollama_chat/prompt_management.rb', line 106 def add_new_prompt(context: nil) context ||= 'prompt' switch_history(: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 = switch_history(:patterns) do ask?( prompt: "β Enter file patterns to load file, C-u β new, C-c β cancel: ", prefill: '**/*.{txt,md}' ) end 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: }) self 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.
18 19 20 21 22 23 24 25 26 |
# File 'lib/ollama_chat/prompt_management.rb', line 18 def all_prompts(default: nil, context: nil) context ||= 'prompt' favs = all_favourited(context) each_prompt(context:, default:).sort_by do |p| [ -p.['use_count'].to_i, p.name ] end.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.
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
# File 'lib/ollama_chat/prompt_management.rb', line 139 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 use_pager do |output| feedback(kramdown_ansi_parse(selected_prompt.to_s + "\n---"), output:) end 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.
161 162 163 164 165 166 167 168 |
# File 'lib/ollama_chat/prompt_management.rb', line 161 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_and_reset_count(context: nil) ⇒ Object
Interactively selects prompts and resets their usage counters.
Presents a looping chooser (similar to #disable_tool) that displays
each prompt's current use_count so the user can see which prompts
have been inflated by frequent selection.
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
# File 'lib/ollama_chat/prompt_management.rb', line 426 def choose_and_reset_count(context: nil) context ||= 'prompt' choose_with_state do loop do entries = each_prompt(context:).sort_by do |p| [ -p.['use_count'].to_i, p.name ] end.map do |p| count = p.['use_count'].to_i display = count > 0 ? "#{p.name} #{italic { "(#{count})" }}" : p.name SearchUI::Wrapper.new(p.name, display:) end entries.unshift('[EXIT]') chosen = choose_entry( entries, prompt: 'Which prompt count shall be reset? %s' ) case chosen when '[EXIT]', nil feedback("Exiting chooser.") return when SearchUI::Wrapper if reset_prompt_count(chosen.value, context:) feedback("Reset count for #{bold { chosen.value }}.", type: :info) end end end end end |
#choose_prompt(default: nil, context: nil, count: false, 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.
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/ollama_chat/prompt_management.rb', line 62 def choose_prompt(default: nil, context: nil, count: false, 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 feedback("Exiting chooser.") return when SearchUI::Wrapper if record = models::Prompt.where(context:, name: chosen.value).first if count record.['use_count'] = 1 + record.['use_count'].to_i record.save end end prompt(chosen.value, context:) end end |
#choose_prompt_context ⇒ String?
The choose_prompt_context method presents a menu of available prompt contexts for selection. It allows the user to choose between 'prompt', 'system', and 'suggest' contexts.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/ollama_chat/prompt_management.rb', line 34 def choose_prompt_context contexts = models::Prompt.group(:context).order(:context).pluck(:context) contexts.unshift('[EXIT]') case chosen = choose_entry( contexts, prompt: 'π Which prompt context shall we work in? %s' ) when '[EXIT]', nil feedback("Exiting chooser.") return else chosen end end |
#determine_valid_new_name_for_prompt(action, context: nil) ⇒ String? (private)
Interactively determines a unique name for a new prompt, ensuring it does not conflict with existing prompts in the database.
The method loops until the user either provides a name that is not currently in use or cancels the operation.
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
# File 'lib/ollama_chat/prompt_management.rb', line 607 def determine_valid_new_name_for_prompt(action, context: nil) context ||= 'prompt' switch_history(:prompt) do prompt_name = nil loop do prompt_name = ask?( prompt: "β Enter new prompt name #{action}, C-c β cancel: " ) if prompt_name.nil? feedback("Cancelled.", type: :cancel) return nil end if prompt(prompt_name, context:) feedback("Prompt named #{bold{prompt_name}} already exists.", type: :warn) else break end end prompt_name end end |
#duplicate_prompt(context: nil) ⇒ self?
Duplicates an existing prompt.
This method initiates an interactive workflow:
- Prompts the user to select a prompt to clone.
- Displays the content of the selected prompt for verification.
- Requests a new name for the duplicate, validating that it does not already exist in the database.
- Creates and saves the new prompt record using the Database::Duplicatable mixin.
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/ollama_chat/prompt_management.rb', line 181 def duplicate_prompt(context: nil) context ||= 'prompt' switch_history(:prompt) do selected_prompt = choose_prompt(context:, prompt: 'Which prompt shall be the basis for a new one? %s') or return use_pager do |output| feedback(kramdown_ansi_parse(selected_prompt.to_s + "\n---"), output:) end name = nil loop do name = ask?( prompt: "β Enter new prompt name to duplicate as, C-c β cancel: " ) if name.nil? feedback("Cancelled.", type: :cancel) return nil end if prompt(name, context:) feedback("Prompt named #{bold{name}} already exists.", type: :warn) 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 end |
#export_prompt(context: nil) ⇒ self?
Interactively exports a prompt to a specified file.
The process follows these steps:
- Prompts the user to select a prompt via
choose_prompt. - Displays the prompt's current content to the terminal.
- Prompts for a destination filename via
determine_valid_output_filename. - Writes the prompt content to the chosen file.
300 301 302 303 304 305 306 307 308 309 310 311 |
# File 'lib/ollama_chat/prompt_management.rb', line 300 def export_prompt(context: nil) context ||= 'prompt' selected_prompt = choose_prompt(context:, prompt: 'Which template are you exporting to disk? %s') or return use_pager do |output| feedback(kramdown_ansi_parse(selected_prompt.to_s + "\n---"), output:) end 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: }) feedback("Prompt #{selected_prompt.name.inspect} was exported as #{filename.to_path.inspect}?", type: :info) self end |
#import_prompt(filename, context: nil) ⇒ self?
Interactively imports a prompt from a file.
The process follows these steps:
- Resolves the source file path (either using the provided filename or prompting the user to choose one).
- Prompts for a unique name for the new prompt via
determine_valid_new_name_for_prompt. - Reads the file content and stores it in the database.
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
# File 'lib/ollama_chat/prompt_management.rb', line 266 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 feedback("Cancelled.", type: :cancel) 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: }) feedback("Imported prompt as #{prompt_name.inspect}.", type: :info) self end |
#info_prompt(context: nil) ⇒ self
Displays detailed information about a selected prompt template.
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/ollama_chat/prompt_management.rb', line 84 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.
376 377 378 379 380 381 382 383 384 385 386 387 388 389 |
# File 'lib/ollama_chat/prompt_management.rb', line 376 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 = truncate( content, length: 0.9 * (Tins::Terminal.columns - start.size) ) feedback '%s %s' % [ start, italic { content } ] end end |
#prepare_conversation_history ⇒ String
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.
320 321 322 323 324 325 326 |
# File 'lib/ollama_chat/prompt_management.rb', line 320 def prepare_conversation_history ..inject('') do |result, | = .content.full? or next result sender_name = sender_name_displayed(, template: false) result << "%s: %s" % [ sender_name, ] end end |
#prompt_sync(context: nil) ⇒ self?
Synchronizes database prompts with their shipped defaults from the configuration.
For each default prompt in the given context, compares the database copy
against the shipped default. Drifted prompts are displayed as a unified
diff (via OC::DIFF_COMMAND), and the user is offered an interactive
resolution via OC::DIFF_TOOL.
Orphaned default prompts (present in the database but no longer in the shipped config) are listed and offered for deletion.
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 |
# File 'lib/ollama_chat/prompt_management.rb', line 469 def prompt_sync(context: nil) context ||= 'prompt' shipped = config.prompts[context].to_h.stringify_keys_recursive db_prompts = each_prompt(context:, default: true).to_a drifted = db_prompts.select do |p| shipped.key?(p.name) && shipped[p.name].to_s != p.to_s end orphans = db_prompts.select { |p| !shipped.key?(p.name) } if drifted.empty? && orphans.empty? feedback("All prompts in context #{bold{context}} are in sync. β¨", type: :success) return self end if drifted.any? feedback(<<~EOT, type: :warn) #{drifted.count} drifted prompt(s) found: #{drifted.map { |p| " β’ #{bold{p.name}} in #{italic{p.context}}" }.join("\n")} EOT end confirm?(prompt: 'β Press any key to continue (%s). ', timeout: 5) drifted.each do |p| show_prompt_diff(p, shipped[p.name], context:) end if orphans.any? feedback(<<~EOT, type: :warn) #{orphans.count} orphaned prompt(s) (no longer in default config): #{orphans.map { |p| " β’ #{bold{p.name}} in #{italic{p.context}}" }.join("\n")} EOT end confirm?(prompt: 'β Press any key to continue (%s). ', timeout: 5) unless orphans.empty? feedback(?\n) if confirm?( prompt: "π§Ή Remove #{orphans.count} orphaned prompt(s)? (y/n) ", yes: /\Ay/i ) then orphans.each do |p| p.destroy feedback("Removed #{bold{p.name}}", type: :success) log(:info, "Orphan prompt cleaned up", data: { name: p.name, context: }) end end end models::AppState.acknowledge(self) self end |
#prompt_with_favourite(name, favourited) ⇒ SearchUI::Wrapper (private)
Helper to wrap a prompt name with its favourite status for the UI.
534 535 536 537 |
# File 'lib/ollama_chat/prompt_management.rb', line 534 def prompt_with_favourite(name, favourited) display = prefix_favourite(name, favourited) SearchUI::Wrapper.new(name, display:) end |
#rename_prompt(context: nil) ⇒ self?
Interactively selects an existing prompt and renames it.
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
# File 'lib/ollama_chat/prompt_management.rb', line 216 def rename_prompt(context: nil) context ||= 'prompt' switch_history(:prompt) do selected_prompt = choose_prompt( prompt: 'Which prompt would you like to rename? %s', context: ) or return use_pager do |output| feedback(kramdown_ansi_parse(selected_prompt.to_s + "\n---"), output:) end name = nil loop do name = ask?( prompt: "β Enter new prompt name, C-c β cancel: " ) if name.nil? feedback("Cancelled.", type: :cancel) return nil end if name == selected_prompt.name feedback("That is the current name.", type: :info) elsif prompt(name, context:) feedback("Prompt named #{bold{name}} already exists.", type: :warn) else break end end old_name = selected_prompt.name selected_prompt.name = name selected_prompt.save log(:info, "Prompt renamed", data: { old_name:, new_name: name, context: }) self end end |
#reset_prompt_count(name, context: nil) ⇒ Boolean?
Resets the usage counter (metadata['use_count']) for a prompt to zero,
removing its position boost in the #all_prompts sort.
410 411 412 413 414 415 416 417 |
# File 'lib/ollama_chat/prompt_management.rb', line 410 def reset_prompt_count(name, context: nil) context ||= 'prompt' if record = models::Prompt.where(context:, name:).first record.['use_count'] = 0 record.save true end end |
#reset_prompt_to_default(name, context: nil) ⇒ Boolean?
Resets a prompt's content to the default value defined in the configuration.
395 396 397 398 399 400 401 |
# File 'lib/ollama_chat/prompt_management.rb', line 395 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 |
#show_prompt_diff(prompt, shipped, context:) ⇒ Object (private)
Writes the database copy and the shipped default to temp files and
displays a unified diff via OC::DIFF_COMMAND.
If the user opts in, launches OC::DIFF_TOOL for interactive
resolution; the resolved content (file A) is then written back
to the database.
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 |
# File 'lib/ollama_chat/prompt_management.rb', line 549 def show_prompt_diff(prompt, shipped, context:) feedback(<<~EOT) #{'β' * 60} π #{bold{prompt.name}} #{'β' * 60} EOT Dir.mktmpdir('prompt_sync') do |dir| file_a = File.join(dir, "#{prompt.name}.local") file_b = File.join(dir, "#{prompt.name}.default") File.write(file_a, prompt.to_s) File.write(file_b, shipped.to_s) cmd = OC::DIFF_COMMAND.dup << file_a << file_b diff_output = IO.popen(cmd, &:read).chomp if diff_output.empty? use_pager do |output| feedback(" (no differences detected)", output:) end else feedback(diff_output) end feedback(?\n) if confirm?( prompt: "π§ Resolve differences for #{bold{prompt.name}}? (y/n) ", yes: /\Ay/i ) then unless diff_tool = OC::DIFF_TOOL? feedback('No DIFF_TOOL available.', type: :warn) return end system(*[diff_tool, file_a, file_b].map(&:to_s)) resolved = File.read(file_a) if resolved != prompt.to_s write_prompt(prompt.name, resolved, context:) feedback(" \u2713 Updated #{bold{prompt.name}}") log(:info, "Prompt synced via diff tool", data: { name: prompt.name, context: }) else feedback(" (no changes made)") end end 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.
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 |
# File 'lib/ollama_chat/prompt_management.rb', line 341 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 template = prompt('context_template_suggest', context: 'prompt').to_s full_prompt = template.named_placeholders_interpolate({ history:, instruction: }) # Execute a silent chat oneshot call (doesn't add to history) suggestions = Infobar.busy( label: 'Creating suggestionsβ¦', frames: :braille7, output: STDOUT, ) do generate(prompt: full_prompt) end # Pass the AI's suggestions through the editor for final refinement edit_text(suggestions) if suggestions.present? end |