Class: OllamaChat::Chat
- Inherits:
-
Object
- Object
- OllamaChat::Chat
- Includes:
- Clipboard, Conversation, Dialog, DocumentCache, History, Information, InputContent, KramdownANSI, MessageEditing, MessageFormat, MessageOutput, ModelHandling, Parsing, ServerSocket, SourceFetching, StateSelectors, Switches, ThinkControl, WebSearching, Term::ANSIColor, Tins::GO
- Defined in:
- lib/ollama_chat/chat.rb
Overview
A chat client for interacting with Ollama models through a terminal interface.
The Chat class provides a complete command-line interface for chatting with language models via the Ollama API. It handles configuration management, message history, document processing, web searching, and various interactive features including voice output, markdown rendering, and embedding capabilities.
Constant Summary
Constants included from Parsing
Class Attribute Summary collapse
-
.config ⇒ Object
The config attribute accessor provides read and write access to the configuration object associated with this instance.
Instance Attribute Summary collapse
-
#document_policy ⇒ OllamaChat::StateSelector
readonly
The document_policy reader returns the document policy selector for the chat session.
-
#documents ⇒ Documentrix::Documents
readonly
Returns the documents set for this object, initializing it lazily if needed.
-
#messages ⇒ OllamaChat::MessageList
readonly
Returns the messages set for this object, initializing it lazily if needed.
-
#ollama ⇒ Ollama::Client
readonly
The ollama reader returns the Ollama API client instance.
-
#think_mode ⇒ OllamaChat::StateSelector
readonly
The think_mode reader returns the think mode selector for the chat session.
Attributes included from ServerSocket
Attributes included from Switches
#embedding, #embedding_enabled, #embedding_paused, #location, #markdown, #stream, #think_loud, #voice
Instance Method Summary collapse
-
#add_documents_from_argv(document_list) ⇒ Object
private
Adds documents from command line arguments to the document collection.
-
#base_url ⇒ String
private
The base_url method returns the Ollama server URL from command-line options or environment configuration.
-
#clean(what) ⇒ Object
private
The clean method clears various parts of the chat session based on the specified parameter.
-
#config ⇒ ComplexConfig::Settings
The config method returns the configuration object associated with the class.
-
#config=(config) ⇒ Object
The config= method assigns a new configuration object to the class.
-
#connect_ollama ⇒ Ollama::Client
private
The connect_ollama method creates and returns a new Ollama::Client instance configured with timeout settings, base URL, debug flag, and user agent.
-
#debug ⇒ TrueClass, FalseClass
The debug method accesses the debug configuration setting.
-
#display_config ⇒ Object
private
The display_config method renders the configuration and displays it using a pager.
-
#enable_command_completion(&block) ⇒ Object
private
Enables tab completion for chat commands within the interactive session.
-
#fix_config(exception) ⇒ Object
private
The fix_config method handles configuration file errors by informing the user about the exception and prompting them to fix it.
-
#handle_input(content) ⇒ Symbol, ...
private
Handles user input commands and processes chat interactions.
-
#initialize(argv: ARGV.dup) ⇒ Chat
constructor
Initializes a new OllamaChat::Chat instance with the given command-line arguments.
-
#interact_with_user ⇒ Object
private
The interact_with_user method manages the interactive loop for user input and chat processing.
-
#links ⇒ Set
Returns the links set for this object, initializing it lazily if needed.
-
#manage_links(command) ⇒ Object
private
The manage_links method handles operations on a collection of links, such as displaying them or clearing specific entries.
-
#setup_cache ⇒ OllamaChat::RedisCache?
private
The setup_cache method initializes and returns a Redis cache instance with expiring keys if a Redis URL is configured.
-
#setup_documents ⇒ Documentrix::Documents, NULL
private
The setup_documents method initializes the document processing pipeline by configuring the embedding model and database connection.
-
#start ⇒ Object
The start method initializes the chat session by displaying information and conversation history, then prompts the user for input to begin interacting with the chat.
-
#web(count, query) ⇒ String, Symbol
private
Performs a web search and processes the results based on document processing configuration.
Methods included from MessageEditing
Methods included from InputContent
#choose_filename, #compose, #context_spook, #input
Methods included from Conversation
#load_conversation, #save_conversation
Methods included from KramdownANSI
#configure_kramdown_ansi_styles, #kramdown_ansi_parse
Methods included from ServerSocket
create_socket_server, #init_server_socket, send_to_server_socket
Methods included from History
#chat_history_filename, #clear_history, #init_chat_history, #save_history
Methods included from MessageFormat
#message_type, #talk_annotate, #think_annotate
Methods included from Clipboard
#copy_to_clipboard, #paste_from_input
Methods included from MessageOutput
#attempt_to_write_file, #output, #pipe
Methods included from Information
#collection_stats, #display_chat_help, #display_chat_help_message, #info, #server_url, #server_version, #usage, #version
Methods included from ThinkControl
Methods included from Dialog
#ask?, #change_system_prompt, #change_voice, #choose_collection, #choose_model, #choose_prompt, #connect_message, #message_list, #model_with_size
Methods included from WebSearching
#search_engine, #search_web, #search_web_with_duckduckgo, #search_web_with_searxng
Methods included from SourceFetching
#add_image, #embed, #embed_source, #fetch_source, #fetch_source_as_filename, #http_options, #import, #import_source, #summarize, #summarize_source
Methods included from Parsing
#parse_atom, #parse_content, #parse_csv, #parse_rss, #parse_source, #pdf_read, #ps_read, #reverse_markdown
Methods included from ModelHandling
#model_present?, #pull_model_from_remote, #pull_model_unless_present
Methods included from StateSelectors
Methods included from Switches
Methods included from DocumentCache
#configure_cache, #document_cache_class
Constructor Details
#initialize(argv: ARGV.dup) ⇒ Chat
Initializes a new OllamaChat::Chat instance with the given command-line arguments.
Sets up the chat environment including configuration parsing, Ollama client initialization, model selection, system prompt handling, document processing setup, and history management. This method handles all the bootstrapping necessary to create a functional chat session that can communicate with an Ollama server and process various input types including text, documents, web content, and images.
The initialization process includes parsing command-line options using Tins::GO for robust argument handling, setting up the Ollama client with configurable timeouts (connect, read, write), validating Ollama API version compatibility (requires >= 0.9.0 for features used), configuring model selection based on command-line or configuration defaults, initializing system prompts from files or inline content, setting up document processing pipeline with embedding capabilities through Documentrix::Documents, creating message history management through OllamaChat::MessageList, initializing cache systems for document embeddings, setting up voice support and image handling for multimodal interactions, enabling optional server socket functionality for remote input, and handling configuration errors with interactive recovery mechanisms.
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
# File 'lib/ollama_chat/chat.rb', line 84 def initialize(argv: ARGV.dup) @opts = go 'f:u:m:s:c:C:D:MESVh', argv @opts[?h] and exit usage @opts[?V] and exit version @messages = OllamaChat::MessageList.new(self) @ollama_chat_config = OllamaChat::OllamaChatConfig.new(@opts[?f]) self.config = @ollama_chat_config.config setup_switches(config) setup_state_selectors(config) @ollama = connect_ollama if server_version.version < '0.9.0'.version raise ArgumentError, 'require ollama API version 0.9.0 or higher' end @model = choose_model(@opts[?m], config.model.name) @model_options = Ollama::Options[config.model.] model_system = pull_model_unless_present(@model, @model_options) .set(config..enabled && !@opts[?E]) if @opts[?c] .load_conversation(@opts[?c]) else default = config.system_prompts.default? || model_system if @opts[?s] =~ /\A\?/ change_system_prompt(default, system: @opts[?s]) else system = OllamaChat::Utils::FileArgument.get_file_argument(@opts[?s], default:) system.present? and .set_system_prompt(system) end end @documents = setup_documents @cache = setup_cache @images = [] @kramdown_ansi_styles = configure_kramdown_ansi_styles init_chat_history @opts[?S] and init_server_socket rescue ComplexConfig::AttributeMissing, ComplexConfig::ConfigurationSyntaxError => e fix_config(e) end |
Class Attribute Details
.config ⇒ Object
The config attribute accessor provides read and write access to the configuration object associated with this instance.
179 180 181 |
# File 'lib/ollama_chat/chat.rb', line 179 def config @config end |
Instance Attribute Details
#document_policy ⇒ OllamaChat::StateSelector (readonly)
The document_policy reader returns the document policy selector for the chat session.
126 127 128 |
# File 'lib/ollama_chat/chat.rb', line 126 def document_policy @document_policy end |
#documents ⇒ Documentrix::Documents (readonly)
Returns the documents set for this object, initializing it lazily if needed.
The documents set is memoized, meaning it will only be created once per object instance and subsequent calls will return the same Documentrix::Documents instance.
154 155 156 |
# File 'lib/ollama_chat/chat.rb', line 154 def documents @documents end |
#messages ⇒ OllamaChat::MessageList (readonly)
Returns the messages set for this object, initializing it lazily if needed.
The messages set is memoized, meaning it will only be created once per object instance and subsequent calls will return the same OllamaChat::MessageList instance.
164 165 166 |
# File 'lib/ollama_chat/chat.rb', line 164 def @messages end |
#ollama ⇒ Ollama::Client (readonly)
The ollama reader returns the Ollama API client instance.
144 145 146 |
# File 'lib/ollama_chat/chat.rb', line 144 def ollama @ollama end |
#think_mode ⇒ OllamaChat::StateSelector (readonly)
The think_mode reader returns the think mode selector for the chat session.
132 133 134 |
# File 'lib/ollama_chat/chat.rb', line 132 def think_mode @think_mode end |
Instance Method Details
#add_documents_from_argv(document_list) ⇒ Object (private)
Empty entries in the document list will trigger a collection clear operation
Documents are processed in batches of 25 to manage memory usage
Progress is reported to STDOUT during processing
Adds documents from command line arguments to the document collection
Processes a list of document paths or URLs, handling both local files and remote resources.
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 |
# File 'lib/ollama_chat/chat.rb', line 769 def add_documents_from_argv(document_list) if document_list.any?(&:empty?) STDOUT.puts "Clearing collection #{bold{documents.collection}}." documents.clear document_list.reject!(&:empty?) end unless document_list.empty? document_list.map! do |doc| if doc =~ %r(\Ahttps?://) doc else File.(doc) end end STDOUT.puts "Collection #{bold{documents.collection}}: Adding #{document_list.size} documents…" count = 1 document_list.each_slice(25) do |docs| docs.each do |doc| fetch_source(doc) do |doc_io| (doc_io, doc, count:) end count += 1 end end end end |
#base_url ⇒ String (private)
The base_url method returns the Ollama server URL from command-line options or environment configuration.
695 696 697 |
# File 'lib/ollama_chat/chat.rb', line 695 def base_url @opts[?u] || OllamaChat::EnvConfig::OLLAMA::URL end |
#clean(what) ⇒ Object (private)
The clean method clears various parts of the chat session based on the specified parameter.
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 |
# File 'lib/ollama_chat/chat.rb', line 508 def clean(what) case what when 'messages', nil .clear STDOUT.puts "Cleared messages." when 'links' links.clear STDOUT.puts "Cleared links." when 'history' clear_history STDOUT.puts "Cleared history." when 'tags' @documents.clear STDOUT.puts "Cleared all tags." when 'all' if ask?(prompt: 'Are you sure to clear messages and collection? (y/n) ') =~ /\Ay/i .clear @documents.clear links.clear clear_history STDOUT.puts "Cleared messages and collection #{bold{@documents.collection}}." else STDOUT.puts 'Cancelled.' end end end |
#config ⇒ ComplexConfig::Settings
The config method returns the configuration object associated with the class.
193 194 195 |
# File 'lib/ollama_chat/chat.rb', line 193 def config self.class.config end |
#config=(config) ⇒ Object
The config= method assigns a new configuration object to the class.
185 186 187 |
# File 'lib/ollama_chat/chat.rb', line 185 def config=(config) self.class.config = config end |
#connect_ollama ⇒ Ollama::Client (private)
The connect_ollama method creates and returns a new Ollama::Client instance configured with timeout settings, base URL, debug flag, and user agent
703 704 705 706 707 708 709 710 711 712 |
# File 'lib/ollama_chat/chat.rb', line 703 def connect_ollama Ollama::Client.new( connect_timeout: config.timeouts.connect_timeout?, read_timeout: config.timeouts.read_timeout?, write_timeout: config.timeouts.write_timeout?, base_url: base_url, debug: , user_agent: ) end |
#debug ⇒ TrueClass, FalseClass
The debug method accesses the debug configuration setting.
137 138 139 |
# File 'lib/ollama_chat/chat.rb', line 137 def debug OllamaChat::EnvConfig::OLLAMA::CHAT::DEBUG end |
#display_config ⇒ Object (private)
The display_config method renders the configuration and displays it using a pager. It determines an appropriate pager command based on environment variables and available system commands, then uses Kramdown::ANSI::Pager to show the formatted configuration output.
540 541 542 543 544 545 546 547 548 549 |
# File 'lib/ollama_chat/chat.rb', line 540 def display_config command = OllamaChat::EnvConfig::PAGER? rendered = config.to_s Kramdown::ANSI::Pager.pager( lines: rendered.count(?\n), command: ) do |output| output.puts rendered end end |
#enable_command_completion(&block) ⇒ Object (private)
Enables tab completion for chat commands within the interactive session
Temporarily replaces the current Reline completion procedure with a custom one that provides command completion based on the chat help message.
850 851 852 853 854 855 856 857 858 859 |
# File 'lib/ollama_chat/chat.rb', line 850 def enable_command_completion(&block) old = Reline.completion_proc commands = .scan(/^\s*(\S+)/).inject(&:concat) Reline.completion_proc = -> input { commands.grep Regexp.new('\A' + Regexp.quote(input)) } block.() ensure Reline.completion_proc = old end |
#fix_config(exception) ⇒ Object (private)
The fix_config method handles configuration file errors by informing the user about the exception and prompting them to fix it. It then executes a diff tool to compare the current config file with the default one. This method exits the program after handling the configuration error
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 |
# File 'lib/ollama_chat/chat.rb', line 820 def fix_config(exception) save_conversation('backup.json') STDOUT.puts "When reading the config file, a #{exception.class} "\ "exception was caught: #{exception..inspect}" unless diff_tool = OllamaChat::EnvConfig::DIFF_TOOL? exit 1 end if ask?(prompt: 'Do you want to fix the config? (y/n) ') =~ /\Ay/i system Shellwords.join([ diff_tool, @ollama_chat_config.filename, @ollama_chat_config.default_config_path, ]) exit 0 else exit 1 end end |
#handle_input(content) ⇒ Symbol, ... (private)
Handles user input commands and processes chat interactions.
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 253 254 255 256 257 258 259 260 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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 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 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 |
# File 'lib/ollama_chat/chat.rb', line 217 def handle_input(content) case content when %r(^/reconnect) STDERR.print green { "Reconnecting to ollama #{base_url.to_s.inspect}…" } @ollama = connect_ollama STDERR.puts green { " Done." } :next when %r(^/copy$) copy_to_clipboard :next when %r(^/paste$) paste_from_input when %r(^/markdown$) markdown.toggle :next when %r(^/stream$) stream.toggle :next when %r(^/location$) location.toggle :next when %r(^/voice(?:\s+(change))?$) if $1 == 'change' change_voice else voice.toggle end :next when %r(^/list(?:\s+(\d*))?$) n = 2 * $1.to_i if $1 .list_conversation(n) :next when %r(^/last(?:\s+(\d*))?$) n = $1.to_i if $1 .show_last(n) :next when %r(^/clear(?:\s+(messages|links|history|tags|all))?$) clean($1) :next when %r(^/clobber$) clean('all') :next when %r(^/drop(?:\s+(\d*))?$) .drop($1) .show_last :next when %r(^/model$) @model = choose_model('', @model) :next when %r(^/system(?:\s+(show))?$) if $1 != 'show' change_system_prompt(@system) end @messages.show_system_prompt :next when %r(^/prompt) @prefill_prompt = choose_prompt :next when %r(^/regenerate$) if content = .second_last&.content content.gsub!(/\nConsider these chunks for your answer.*\z/, '') .drop(1) else STDOUT.puts "Not enough messages in this conversation." return :redo end @parse_content = false content when %r(^/collection(?:\s+(clear|change))?$) case $1 || 'change' when 'clear' loop do = @documents..add('[EXIT]').add('[ALL]') tag = OllamaChat::Utils::Chooser.choose(, prompt: 'Clear? %s') case tag when nil, '[EXIT]' STDOUT.puts "Exiting chooser." break when '[ALL]' if ask?(prompt: 'Are you sure? (y/n) ') =~ /\Ay/i @documents.clear STDOUT.puts "Cleared collection #{bold{@documents.collection}}." break else STDOUT.puts 'Cancelled.' sleep 3 end when /./ @documents.clear(tags: [ tag ]) STDOUT.puts "Cleared tag #{tag} from collection #{bold{@documents.collection}}." sleep 3 end end when 'change' choose_collection(@documents.collection) end :next when %r(^/info$) info :next when %r(^/document_policy$) document_policy.choose :next when %r(^/think$) think_mode.choose :next when %r(^/think_loud$) think_loud.toggle :next when %r(^/import\s+(.+)) @parse_content = false import($1) or :next when %r(^/summarize\s+(?:(\d+)\s+)?(.+)) @parse_content = false summarize($2, words: $1) or :next when %r(^/embedding$) .toggle(show: false) .show :next when %r(^/embed\s+(.+)) @parse_content = false ($1) or :next when %r(^/web\s+(?:(\d+)\s+)?(.+)) @parse_content = false web($1, $2) when %r(^/input(?:\s+(.+))?$) @parse_content = false input($1) or :next when %r(^/context(?:\s+(.+))?$) arg = $1 arg and patterns = arg.scan(/(\S+)/).flatten @parse_content = false context_spook(patterns) or :next when %r(^/compose$) compose or :next when %r(^/revise_last$) revise_last :next when %r(^/save\s+(.+)$) save_conversation($1) :next when %r(^/links(?:\s+(clear))?$) manage_links($1) :next when %r(^/load\s+(.+)$) load_conversation($1) :next when %r(^/pipe\s+(.+)$) pipe($1) :next when %r(^/output\s+(.+)$) output($1) :next when %r(^/vim(?:\s+(.+))?$) if = .last clientserver = config.vim?&.clientserver OllamaChat::Vim.new($1, clientserver:).insert .content else STDERR.puts "Warning: No message found to insert into Vim" end :next when %r(^/config$) display_config :next when %r(^/quit$), nil STDOUT.puts "Goodbye." :return when %r(^/) display_chat_help :next when /\A\s*\z/ STDOUT.puts "Type /quit to quit." :next end end |
#interact_with_user ⇒ Object (private)
The interact_with_user method manages the interactive loop for user input and chat processing. It handles reading user input, processing commands, managing messages, and communicating with the Ollama server. The method supports command completion, prefilling prompts, socket input handling, and various chat features including embedding context and voice support. It processes user input through command handling, content parsing, and message formatting before sending requests to the Ollama server. The method also handles server socket messages, manages chat history, and ensures proper cleanup and configuration handling throughout the interaction.
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 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 |
# File 'lib/ollama_chat/chat.rb', line 563 def interact_with_user loop do @parse_content = true type = :terminal_input input_prompt = bold { color(172) { (@images) + " user" } } + bold { "> " } begin content = enable_command_completion do if prefill_prompt = @prefill_prompt.full? Reline.pre_input_hook = -> { Reline.insert_text prefill_prompt.gsub(/\n*\z/, '') @prefill_prompt = nil } else Reline.pre_input_hook = nil end Reline.readline(input_prompt, true)&.chomp end rescue Interrupt if = type = .type.full?(:to_sym) || :socket_input content = .content @parse_content = .parse STDOUT.puts color(112) { "Received a server socket message. Processing now…" } else raise end end if type == :terminal_input case next_action = handle_input(content) when :next next when :redo redo when :return return when String content = next_action end end content = content.encode(invalid: :replace) content, = if @parse_content parse_content(content, @images) else [ content, Documentrix::Utils::Tags.new(valid_tag: /\A#*([\w\]\[]+)/) ] end if .on? && content records = @documents.find_where( content.downcase, tags:, prompt: config..model.prompt?, text_size: config..found_texts_size?, text_count: config..found_texts_count?, ) unless records.empty? content += "\nConsider these chunks for your answer:\n\n"\ "#{records.map { [ _1.text, _1. ] * ?\n }.join("\n\n---\n\n")}" end end << Ollama::Message.new(role: 'user', content:, images: @images.dup) @images.clear handler = OllamaChat::FollowChat.new( chat: self, messages:, voice: (@voices.selected if voice.on?) ) begin retried = false ollama.chat( model: @model, messages: , options: @model_options, stream: stream.on?, think: , &handler ) rescue Ollama::Errors::BadRequestError if think? && !retried STDOUT.puts "#{bold('Error')}: in think mode, switch thinking off and retry." sleep 1 think_mode.selected = 'disabled' retried = true retry else raise end end if .on? && !records.empty? STDOUT.puts "", records.map { |record| link = if record.source =~ %r(\Ahttps?://) record.source else 'file://%s' % File.(record.source) end [ link, ?# + record..first ] }.uniq.map { |l, t| hyperlink(l, t) }.join(' ') debug and jj .to_ary end case type when :socket_input &.disconnect when :socket_input_with_response if = handler..last .respond({ role: .role, content: .content }) end &.disconnect end rescue Ollama::Errors::TimeoutError STDOUT.puts "#{bold('Error')}: Currently lost connection to ollama server and cannot send command." rescue Interrupt STDOUT.puts "Type /quit to quit." ensure self. = nil end 0 rescue ComplexConfig::AttributeMissing, ComplexConfig::ConfigurationSyntaxError => e fix_config(e) ensure save_history end |
#links ⇒ Set
Returns the links set for this object, initializing it lazily if needed.
The links set is memoized, meaning it will only be created once per object instance and subsequent calls will return the same Set instance.
172 173 174 |
# File 'lib/ollama_chat/chat.rb', line 172 def links @links ||= Set.new end |
#manage_links(command) ⇒ Object (private)
The manage_links method handles operations on a collection of links, such as displaying them or clearing specific entries.
It supports two main commands: ‘clear’ and nil (default). When the command is ‘clear’, it presents an interactive menu to either clear all links or individual links. When the command is nil, it displays the current list of links with hyperlinks.
466 467 468 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 |
# File 'lib/ollama_chat/chat.rb', line 466 def manage_links(command) case command when 'clear' loop do = links.dup.add('[EXIT]').add('[ALL]') link = OllamaChat::Utils::Chooser.choose(, prompt: 'Clear? %s') case link when nil, '[EXIT]' STDOUT.puts "Exiting chooser." break when '[ALL]' if ask?(prompt: 'Are you sure? (y/n) ') =~ /\Ay/i links.clear STDOUT.puts "Cleared all links in list." break else STDOUT.puts 'Cancelled.' sleep 3 end when /./ links.delete(link) STDOUT.puts "Cleared link from links in list." sleep 3 end end when nil if links.empty? STDOUT.puts "List is empty." else Math.log10(links.size).ceil format = "% #{}s. %s" connect = -> link { hyperlink(link) { link } } STDOUT.puts links.each_with_index.map { |x, i| format % [ i + 1, connect.(x) ] } end end end |
#setup_cache ⇒ OllamaChat::RedisCache? (private)
The setup_cache method initializes and returns a Redis cache instance with expiring keys if a Redis URL is configured.
801 802 803 804 805 806 807 808 809 810 |
# File 'lib/ollama_chat/chat.rb', line 801 def setup_cache if url = config.redis.expiring.url? ex = config.redis.expiring.ex?.to_i OllamaChat::RedisCache.new( prefix: 'Expiring-', url:, ex: ) end end |
#setup_documents ⇒ Documentrix::Documents, NULL (private)
The setup_documents method initializes the document processing pipeline by configuring the embedding model and database connection. It then loads specified documents into the system and returns the configured document collection.
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 |
# File 'lib/ollama_chat/chat.rb', line 721 def setup_documents if .on? @embedding_model = config..model.name @embedding_model_options = Ollama::Options[config..model.] pull_model_unless_present(@embedding_model, @embedding_model_options) collection = @opts[?C] || config..collection @documents = Documentrix::Documents.new( ollama:, model: @embedding_model, model_options: config..model., embedding_length: config..model., database_filename: config..database_filename || @ollama_chat_config.database_path, collection: , cache: configure_cache, redis_url: config.redis.documents.url?, debug: ) document_list = @opts[?D].to_a add_documents_from_argv(document_list) @documents else NULL end end |
#start ⇒ Object
The start method initializes the chat session by displaying information and conversation history, then prompts the user for input to begin interacting with the chat.
200 201 202 203 204 205 206 207 208 |
# File 'lib/ollama_chat/chat.rb', line 200 def start info if .size > 1 .list_conversation(2) end STDOUT.puts "\nType /help to display the chat help." interact_with_user end |
#web(count, query) ⇒ String, Symbol (private)
Performs a web search and processes the results based on document processing configuration.
Searches for the given query using the configured search engine and processes up to the specified number of URLs. The processing approach varies based on the current document policy and embedding status:
-
**Embedding mode**: When ‘document_policy.selected == ’embedding’‘ AND `@embedding.on?` is true, each result is embedded and the query is interpolated into the
web_embedprompt. -
**Summarizing mode**: When ‘document_policy.selected == ’summarizing’‘, each result is summarized and both query and results are interpolated into the
web_summarizeprompt. -
**Importing mode**: For all other cases, each result is imported and both query and results are interpolated into the
web_importprompt.
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/chat.rb', line 429 def web(count, query) urls = search_web(query, count.to_i) or return :next if document_policy.selected == 'embedding' && @embedding.on? prompt = config.prompts. urls.each do |url| fetch_source(url) { |url_io| (url_io, url) } end prompt.named_placeholders_interpolate({query:}) elsif document_policy.selected == 'summarizing' prompt = config.prompts.web_import results = urls.each_with_object('') do |url, content| summarize(url).full? do |c| content << c.ask_and_send_or_self(:read) end end prompt.named_placeholders_interpolate({query:, results:}) else prompt = config.prompts.web_summarize results = urls.each_with_object('') do |url, content| import(url).full? do |c| content << c.ask_and_send_or_self(:read) end end prompt.named_placeholders_interpolate({query:, results:}) end end |