Class: OllamaChat::Chat
- Inherits:
-
Object
- Object
- OllamaChat::Chat
- Includes:
- Clipboard, CollectionSearch, Commands, Compaction, ConfigHandling, Conversation, Dialog, DocumentCache, FavouritesManagement, Feedback, FileEditing, HTTPHandling, History, Information, InputContent, KramdownANSI, LocationHandling, Logging, MessageEditing, MessageFormat, MessageOutput, ModelHandling, Pager, Parsing, PersonaeManagement, PromptHandling, PromptManagement, RAGHandling, ServerSocket, SessionManagement, SourceFetching, StateSelectors, Switches, SystemPromptManagement, ThinkControl, TokenEstimator, ToolCalling, Utils::Chooser, Utils::UTF8Converter, Utils::ValueFormatter, 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
Parsing::CONTENT_REGEXP, Parsing::DOCUMENT_POLICY_STATES, Parsing::HAS_AUDIO
Constants included from Feedback
Instance Attribute Summary collapse
-
#cache ⇒ OllamaChat::RedisCache?
readonly
Provides read-only access to the cache instance used by the object.
-
#documents ⇒ Documentrix::Documents
readonly
Returns the documents set for this object, initializing it lazily if needed.
-
#images ⇒ Array
readonly
Returns the list of images currently queued for the next message.
-
#messages ⇒ OllamaChat::MessageList
readonly
Returns the messages set for this object, initializing it lazily if needed.
-
#model_cache ⇒ ModelCache
readonly
The model_cache method provides read-only access to the model cache.
-
#ollama ⇒ Ollama::Client
readonly
The ollama reader returns the Ollama API client instance.
-
#prefill_prompt ⇒ String, NilClass
private
Returns the prefill prompt string if one exists and is not empty, or nil otherwise.
-
#prefill_prompt== ⇒ String, NilClass
writeonly
private
Sets the content to be prefilled into the next user input prompt.
-
#tool_call_processor ⇒ OllamaChat::ToolCallProcessor
readonly
Returns the tool call processor instance.
Attributes included from Utils::Chooser
#current_search_state Stores the
Attributes included from SessionManagement
Attributes included from PersonaeManagement
Attributes included from ServerSocket
Attributes included from StateSelectors
#context_format, #document_policy, #think_mode, #voices
Attributes included from Switches
#context_manifest, #embedding, #embedding_enabled, #embedding_paused, #location, #markdown, #memory_trigger, #runtime_info, #stream, #think_loud, #think_strip, #tools_support, #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.
-
#call_ollama_chat(**opts, &block) ⇒ Object
private
Wrapper for ollama.chat to provide consistent logging of all arguments.
-
#connect_embedding_ollama ⇒ Ollama::Client?
private
Establishes a dedicated Ollama connection for embedding operations.
-
#connect_ollama ⇒ Ollama::Client
private
The connect_ollama method establishes a connection to the Ollama API server.
-
#debug ⇒ TrueClass, FalseClass
The debug method accesses the debug configuration setting.
-
#disable_content_parsing ⇒ self
private
The disable_content_parsing method turns off content parsing by setting
@parse_contentto false. -
#embedding_ollama ⇒ Ollama::Client
Returns the Ollama client to use for embedding operations.
-
#enable_command_completion(&block) ⇒ Object
private
Enables tab completion for chat commands within the interactive session.
-
#enable_content_parsing ⇒ self
private
The enable_content_parsing method enables content parsing for the chat session.
-
#generate(system: raw_system_prompt, prompt:, stream: false, think: false) ⇒ String
Sends a structured chat request to the Ollama model and returns the response content.
-
#handle_input(content) ⇒ Symbol, ...
private
Handles user input commands and processes chat interactions.
-
#initial_collection ⇒ Symbol
The initial_collection method determines the collection name to be used for embeddings in the RAG system.
-
#initial_model ⇒ String
Returns the model name to be used for the chat session.
-
#initial_system_prompt ⇒ String
The initial_system_prompt method returns the system prompt for the initial message.
-
#initialize(argv: ARGV.dup) ⇒ Chat
constructor
Initializes a new OllamaChat::Chat instance with the given command-line arguments.
-
#inspect ⇒ String
Returns a human-readable string representation of the Chat object, including the class name and the base URL.
-
#interact_with_user ⇒ Integer
private
The interact_with_user method manages the interactive loop for user input and chat processing.
-
#models ⇒ Module
private
The module containing the database models.
-
#parse_content? ⇒ TrueClass, FalseClass
private
The parse_content? method returns the boolean value of the @parse_content instance variable.
-
#quit_app ⇒ Object
private
Signals a graceful shutdown of the application.
-
#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.
-
#speak(text, background: true) ⇒ OllamaChat::TTS, ...
Synthesizes and plays a short voice notification using the session's current voice.
-
#start ⇒ Object
The start method initializes the chat session by displaying information, then prompts the user for input to begin interacting with the chat.
-
#truncate_logs ⇒ Object
private
Truncates chat.log and database.log to the configured tail line count before any new logging begins for this session.
-
#voice_handler ⇒ Class, NilClass
Returns the voice handler class based on the configuration.
Methods included from Utils::UTF8Converter
Methods included from Utils::ValueFormatter
Methods included from Utils::Chooser
#choose_entry, #choose_with_state
Methods included from Compaction
#assemble_summary, #build_tool_entries, #call_summarizer, #compact_min_tokens, #compact_ratio, #compact_ratio_tokens, #compact_with_retry, #extract_narrative, #extract_old_tool_calls, #format_summary_line, #report_compaction, #serialize_groups, #show_compaction_summary, #summarize_for_compaction, tool_summary_line
Methods included from PromptManagement
#add_new_prompt, #all_prompts, #choose_and_delete_prompt, #choose_and_edit_prompt, #choose_and_reset_count, #choose_prompt, #choose_prompt_context, #determine_valid_new_name_for_prompt, #duplicate_prompt, #export_prompt, #import_prompt, #info_prompt, #list_prompts, #prepare_conversation_history, #prompt_sync, #prompt_with_favourite, #rename_prompt, #reset_prompt_count, #reset_prompt_to_default, #show_prompt_diff, #suggest_prompts
Methods included from SystemPromptManagement
#all_system_prompts, #change_system_prompt, #current_system_prompt, #current_system_prompt_name, #model_default_system_prompt, #raw_system_prompt, #refresh_system_prompt, #set_current_system_prompt, #setup_system_prompt, #system_prompt_with_favourite
Methods included from PromptHandling
#delete_prompt, #each_prompt, #load_prompt_from_file, #prompt, #store_prompt, #write_prompt
Methods included from FavouritesManagement
#add_favourite, #all_favourited, #delete_favourite, #favourite_all_things, #prefix_favourite
Methods included from RAGHandling
#all_collections, #choose_collection, #clear_collection_sources, #clear_collection_tags, #clear_tag_records, #clear_whole_collection, #collection, #collection_descriptions, #create_collection, #create_memory_collection, #database_collection?, #delete_collection, #edit_collection, #extract_patterns, #list_collections, #memory_dump, #memory_restore, #query_collection, #rename_collection, #set_documents_collection, #switch_collection, #update_collection, #view_tag_records
Methods included from CollectionSearch
#find_document_records, #rerank_records, #trigger_inject
Methods included from SessionManagement
#change_session, #choose_session, #delete_session, #derive_session_name, #determine_valid_new_name_for_session, #duplicate_session, #edit_session_trigger, #generate_conversation_report, #list_sessions, #load_links_from_session, #new_random_session_name, #new_session, #preferred_session, #previous_session, #rename_session, #repair_group_uuids, #report_conversation, #session_apply, #session_close, #session_sync, #set_new_session, #set_previous_session_on_change, #setup_session, #show_session, #store_links_in_session, #store_messages_in_session, #summarize_conversation, #summarize_session
Methods included from PersonaeManagement
#add_persona, #ask_to_set_default_persona_name, #assistant, #available_personae, #available_personae_names, #backup_persona, #choose_persona, #convert_json_character_to_markdown, #default_persona, #default_persona_profile, #delete_persona, #determine_valid_new_name_for_persona, #duplicate_persona, #edit_persona, #export_persona, #import_persona, #import_persona_from_json, #info_persona, #initial_persona_name, #list_personae, #load_persona_file, #load_personae, #pathname_to_persona_name, #persona_backup_pathname, #persona_description, #persona_exist?, #persona_name_to_pathname, #persona_name_with_favourite, #personae_backup_directory, #personae_directory, #personae_result, #play_persona, #select_persona_path, #set_default_persona, #set_default_persona_name, #setup_persona_from_session, #setup_personae_directory, #substitute_variables, #sync_trigger
Methods included from ConfigHandling
#config, #config=, #diff_config, #display_config, #edit_config, #fix_config, #fix_session, #reload_config, #run_syntax_check, #syntax_checker_for
Methods included from ToolCalling
#configured_tools, #default_enabled_tools, #disable_tool, #enable_tool, #enabled_tools, #list_tools, #tool_configured?, #tool_enabled?, #tool_function, #tool_registered?, #tools
Methods included from LocationHandling
#location_data, #location_description, #location_description?
Methods included from MessageEditing
Methods included from InputContent
#all_file_set, #choose_filename, #context_spook, #file_set_each, #input, #provide_file_set_content
Methods included from Conversation
#conversation_clean, #load_conversation, #save_conversation
Methods included from FileEditing
#determine_valid_output_filename, #edit_file, #edit_text, #edit_text_block, #perform_insert, #vim
Methods included from KramdownANSI
#configure_kramdown_ansi_styles, #kramdown_ansi_parse, #kramdown_markdown_remove, #table_column_budgets, #wrap_table_rows
Methods included from ServerSocket
create_socket_server, #init_server_socket, send_to_server_socket
Methods included from History
#clear_history, #current_history, #current_history=, #histories, #init_history, #save_history, #switch_history
Methods included from Pager
#determine_pager_command, #use_pager
Methods included from MessageFormat
#chat, #display_sender, #message_type, #role_color, #role_template, #sender_name_displayed, #talk_annotate, #think_annotate
Methods included from Clipboard
#copy_to_clipboard, #last_message_content, #paste_from_clipboard, #paste_from_stdin, #perform_copy_to_clipboard, #perform_paste_from_clipboard
Methods included from MessageOutput
#attempt_to_write_file, #output, #pipe
Methods included from Information
#client, #collection_stats, #context_filled, #context_usage, #context_usage_colored, #context_usage_plain, #conversation_length, #current_context_length, #display_chat_help, #dynamic_runtime_information, #dynamic_runtime_information_values, #info, #info_model, #info_rag, #info_runtime, #info_session, #infobar_message, #machine_profile, #print_welcome, #runtime_information_inject, #server_url, #server_version, #static_runtime_information, #static_runtime_information_values, #usage, #user, #user_name, #version
Methods included from Utils::Redact
#redact_password, redact_password
Methods included from ThinkControl
#normalize_think_state, #think, #think?, #think_loud?, #think_mode_states
Methods included from Dialog
#ask?, #ask_for_filename?, #change_voice, #choose_file_set, #confirm?, #connect_message, #connect_message_done, #go_command, #message_list, #should_overwrite?
Methods included from WebSearching
#manage_links, #search_engine, #search_web, #search_web_with_duckduckgo, #search_web_with_searxng, #web
Methods included from SourceFetching
#add_image, #bulk_embed_sources, #embed, #embed_source, #fetch_source, #fetch_source_as_filename, #import, #import_source, #summarize, #summarize_source
Methods included from Parsing
#epub_read, #parse_atom, #parse_audio, #parse_content, #parse_png, #parse_rss, #parse_source, #pdf_read, #personalize_character_profile, #process_document, #ps_read, #reverse_markdown
Methods included from Utils::AnalyzeDirectory
#generate_structure, #recurse_generate_structure, #structure_each_entry
Methods included from ModelHandling
#all_models, #choose_model, #choose_profile_for_model, #copy_model_options_from_session, #copy_model_options_profile, #copy_model_options_to_session, #delete_model_options_profile, #edit_model_options, #edit_session_model_options, #export_model_options, #fill_up_model_options, #get_default_model_options, #get_session_model_options, #get_stored_model_options, #import_model_options, #model_options, #model_present?, #model_with_size, #prepare_model, #pull_model_from_remote, #pull_model_unless_present, #reconfigure_model_options, #store_model_options, #stored_model_options_exist?, #use_model
Methods included from StateSelectors
Methods included from Switches
Methods included from DocumentCache
#configure_cache, #document_cache_class
Methods included from Logging
Methods included from HTTPHandling
#get_url, #http_options, #links, #request_url_response
Methods included from TokenEstimator
Methods included from Feedback
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.
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 |
# File 'lib/ollama_chat/chat.rb', line 107 def initialize(argv: ARGV.dup) @opts = go 'f:u:m:l:nSVh', argv @opts[?h] and exit usage @opts[?V] and exit version @ollama_chat_config = OllamaChat::OllamaChatConfig.new(@opts[?f]) self.config = @ollama_chat_config.config truncate_logs @messages = OllamaChat::MessageList.new(self) OllamaChat::Database.setup_models.each { _1.ask_and_send(:seed, self) } setup_switches setup_session setup_state_selectors(config) @model_cache = ModelCache.new connect_ollama @documents = setup_documents models::Collection.sync(self) @cache = setup_cache @images = [] @kramdown_ansi_styles = configure_kramdown_ansi_styles @tool_call_processor = OllamaChat::ToolCallProcessor.new(chat: self) setup_personae_directory @opts[?S] and init_server_socket rescue ComplexConfig::AttributeMissing, ComplexConfig::ConfigurationSyntaxError => e fix_config(e) end |
Instance Attribute Details
#cache ⇒ OllamaChat::RedisCache? (readonly)
Provides read-only access to the cache instance used by the object.
168 169 170 |
# File 'lib/ollama_chat/chat.rb', line 168 def cache @cache 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.
148 149 150 |
# File 'lib/ollama_chat/chat.rb', line 148 def documents @documents end |
#images ⇒ Array (readonly)
Returns the list of images currently queued for the next message.
163 164 165 |
# File 'lib/ollama_chat/chat.rb', line 163 def images @images 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.
158 159 160 |
# File 'lib/ollama_chat/chat.rb', line 158 def @messages end |
#model_cache ⇒ ModelCache (readonly)
The model_cache method provides read-only access to the model cache.
173 174 175 |
# File 'lib/ollama_chat/chat.rb', line 173 def model_cache @model_cache end |
#ollama ⇒ Ollama::Client (readonly)
The ollama reader returns the Ollama API client instance.
137 138 139 |
# File 'lib/ollama_chat/chat.rb', line 137 def ollama @ollama end |
#prefill_prompt ⇒ String, NilClass (private)
Returns the prefill prompt string if one exists and is not empty, or nil otherwise.
424 425 426 |
# File 'lib/ollama_chat/chat.rb', line 424 def prefill_prompt @prefill_prompt.full? end |
#prefill_prompt==(value) ⇒ String, NilClass (writeonly, private)
Sets the content to be prefilled into the next user input prompt.
431 |
# File 'lib/ollama_chat/chat.rb', line 431 attr_writer :prefill_prompt |
#tool_call_processor ⇒ OllamaChat::ToolCallProcessor (readonly)
Returns the tool call processor instance.
354 355 356 |
# File 'lib/ollama_chat/chat.rb', line 354 def tool_call_processor @tool_call_processor 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.
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 |
# File 'lib/ollama_chat/chat.rb', line 725 def add_documents_from_argv(document_list) if document_list.any?(&:empty?) feedback("Clearing collection #{bold{collection}}.", type: :info) 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 feedback("Collection #{bold{collection}}: Adding #{document_list.size} documents…", type: :info) 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.
617 618 619 |
# File 'lib/ollama_chat/chat.rb', line 617 def base_url @opts[?u] || OC::OLLAMA::URL end |
#call_ollama_chat(**opts, &block) ⇒ Object (private)
Wrapper for ollama.chat to provide consistent logging of all arguments.
362 363 364 365 366 367 368 369 370 371 |
# File 'lib/ollama_chat/chat.rb', line 362 def call_ollama_chat(**opts, &block) if debug log(:debug, "Ollama chat request sent", data: opts) else clean_opts = opts.dup clean_opts = clean_opts.slice!(:messages, :tools) log(:info, "Ollama chat request sent", data: clean_opts) end ollama.chat(**opts, &block) end |
#connect_embedding_ollama ⇒ Ollama::Client? (private)
Establishes a dedicated Ollama connection for embedding operations.
When OC::OLLAMA::EMBEDDING_URL is configured, creates a separate Ollama::Client targeting that host so the embedding model can run on a different machine (e.g. a GPU box running audio.cpp alongside the embedding model) while the chat model stays on the primary Ollama server.
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 |
# File 'lib/ollama_chat/chat.rb', line 689 def if base_url = OC::OLLAMA::EMBEDDING_URL? (base_url:, prefix: 'embedding ') @embedding_ollama = Ollama::Client.new( connect_timeout: config.timeouts.connect_timeout?, read_timeout: config.timeouts.read_timeout?, write_timeout: config.timeouts.write_timeout?, base_url: , debug: , user_agent: ) log(:info, "Embedding connection established", data: { base_url: }) @embedding_ollama end end |
#connect_ollama ⇒ Ollama::Client (private)
The connect_ollama method establishes a connection to the Ollama API server.
This method initializes a new Ollama::Client instance with configured timeouts and connection parameters, then verifies that the connected server meets the minimum required API version (0.9.0). It sets the @ollama instance variable to the configured client and stores the version in @server_version.
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 |
# File 'lib/ollama_chat/chat.rb', line 631 def connect_ollama (base_url:) @server_version = nil @ollama = Ollama::Client.new( connect_timeout: config.timeouts.connect_timeout?, read_timeout: config.timeouts.read_timeout?, write_timeout: config.timeouts.write_timeout?, base_url: , debug: , user_agent: ) if server_version.version < '0.9.0'.version raise 'require ollama API version 0.9.0 or higher' end log(:info, "Connection established", data: { base_url: }) @ollama end |
#debug ⇒ TrueClass, FalseClass
The debug method accesses the debug configuration setting.
224 225 226 |
# File 'lib/ollama_chat/chat.rb', line 224 def debug OC::OLLAMA::CHAT::DEBUG end |
#disable_content_parsing ⇒ self (private)
The disable_content_parsing method turns off content parsing by setting
@parse_content to false.
This prevents automatic parsing of user input content during chat processing.
397 398 399 400 |
# File 'lib/ollama_chat/chat.rb', line 397 def disable_content_parsing @parse_content = false self end |
#embedding_ollama ⇒ Ollama::Client
Returns the Ollama client to use for embedding operations.
Falls back to the primary chat client when no dedicated embedding URL has been configured.
338 339 340 |
# File 'lib/ollama_chat/chat.rb', line 338 def @embedding_ollama || ollama 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.
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 |
# File 'lib/ollama_chat/chat.rb', line 777 def enable_command_completion(&block) old = Reline.completion_proc Reline.autocompletion = true Reline.completion_proc = -> input, pre { before = [ pre, input ].join case before when %r(^/) start = [ pre, input ].join(' ').strip.gsub(/\s+/, ' ') command_completions.select { _1.start_with?(start) } when %r((./\S*)) OllamaChat::Utils::PathCompleter.new(pre, input).complete end } block.() ensure Reline.completion_proc = old end |
#enable_content_parsing ⇒ self (private)
The enable_content_parsing method enables content parsing for the chat session.
406 407 408 409 |
# File 'lib/ollama_chat/chat.rb', line 406 def enable_content_parsing @parse_content = true self end |
#generate(system: raw_system_prompt, prompt:, stream: false, think: false) ⇒ String
Sends a structured chat request to the Ollama model and returns the response content.
This method creates a minimal conversation consisting of a system message and a user message, executing it as a one-shot chat interaction.
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 |
# File 'lib/ollama_chat/chat.rb', line 277 def generate(system: raw_system_prompt, prompt:, stream: false, think: false) = [ OllamaChat::Message.new( role: 'system', content: system, ), OllamaChat::Message.new( role: 'user', content: prompt ), ] content = call_ollama_chat( model: @model, messages: , options: , stream: , think: )&.&.content.to_s if content.empty? log(:warn, "LLM generation returned empty content", data: { prompt: }) else log(:info, "LLM generation successful", data: { prompt:, content: }) end content end |
#handle_input(content) ⇒ Symbol, ... (private)
Handles user input commands and processes chat interactions.
446 447 448 449 450 451 452 |
# File 'lib/ollama_chat/chat.rb', line 446 def handle_input(content) commands.each do |_name, command| action = command.execute_if_match?(content) {} action and return action end content end |
#initial_collection ⇒ Symbol
The initial_collection method determines the collection name to be used for embeddings in the RAG system.
244 245 246 247 248 249 250 251 252 253 |
# File 'lib/ollama_chat/chat.rb', line 244 def initial_collection c = session&.current_collection.full? || config..collection.full? || 'default' if c =~ /\A#{OllamaChat::COLLECTION_NAME_REGEXP.source}\z/ c else 'default' end.to_sym end |
#initial_model ⇒ String
Returns the model name to be used for the chat session.
The resolution priority is:
- The current session's model (if present).
- The model specified via the command line option
-m. - The default model name defined in the configuration.
236 237 238 |
# File 'lib/ollama_chat/chat.rb', line 236 def initial_model session&.current_model.full? || @opts[?m].full? || config.model.name end |
#initial_system_prompt ⇒ String
The initial_system_prompt method returns the system prompt for the initial message.
259 260 261 |
# File 'lib/ollama_chat/chat.rb', line 259 def initial_system_prompt @messages.system_name end |
#inspect ⇒ String
Returns a human-readable string representation of the Chat object, including the class name and the base URL.
346 347 348 |
# File 'lib/ollama_chat/chat.rb', line 346 def inspect "#<#{self.class}: #{redact_password(base_url)}>" end |
#interact_with_user ⇒ Integer (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.
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 502 503 504 505 506 507 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 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 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 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 |
# File 'lib/ollama_chat/chat.rb', line 468 def interact_with_user loop do content = nil group_uuid = OllamaChat::UUIDV7.generate tools_were_called = false enable_content_parsing type = :terminal_input input_prompt = bold { color(172) { (@images) + " user" } } + bold { "> " } begin tools_were_called = tool_call_processor.drain { |index, tool_name, content| << OllamaChat::Message.new( role: 'user', # XXX this should be 'tool' but it doesn't currently seem to work in Ollama API sender_name: tool_name, tool_name: , content: , images: @images.dup, group_uuid: ) } tools_were_called and type = :tool_input unless tools_were_called content = enable_command_completion do if prefill_prompt Reline.pre_input_hook = -> { Reline.insert_text prefill_prompt.gsub(/\n*\z/, '') self.prefill_prompt = nil } else Reline.pre_input_hook = nil end Reline.readline(input_prompt, true)&.chomp end end rescue Interrupt if = type = .type.full?(:to_sym) || :socket_input content = .content @parse_content = .parse feedback color(112) { "Received a server socket message. Processing now…" }, type: :info else raise end end content = content.strip if content =~ %r(\A/[^/]) if type == :terminal_input case next_action = handle_input(content) when :next next when :redo redo when String content = next_action end end unless type == :tool_input content = content.encode(invalid: :replace) content.present? or next parse_content? and content = parse_content(content, @images) << OllamaChat::Message.new( role: 'user', sender_name: user_name, content: , images: @images.dup, group_uuid: ) runtime_information_inject(group_uuid:) trigger_inject(content, group_uuid:) end @images.clear handler = OllamaChat::FollowChat.new( chat: self, messages:, voice: (voices.selected if voice.on?), group_uuid: ) begin retried = false = . = .map { _1.dup.tap { || .sender_name = nil .group_uuid = nil .tool_calls = nil .thinking = nil if think_strip.on? } } prepare_model(@model) call_ollama_chat( model: @model, messages: , options: , stream: stream.on?, think: , tools: , &handler ) rescue Ollama::Errors::BadRequestError if (think? || tools_support.on?) && !retried msg = "Error in think mode/with tool support, switch both off and retry." log(:warn, msg, warn: true) sleep 1 think_mode.selected = 'disabled' tools_support.set false retried = true retry else raise end 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 msg = "Currently lost connection to ollama server and cannot send command." log(:warn, msg, warn: true) rescue Interrupt feedback("Type /quit to quit.") ensure self. = nil end 0 rescue OllamaChat::OllamaChatQuitError feedback("Goodbye.") rescue ComplexConfig::AttributeMissing, ComplexConfig::ConfigurationSyntaxError => e log(:error, e) fix_config(e) ensure session_close end |
#models ⇒ Module (private)
Returns The module containing the database models.
386 387 388 |
# File 'lib/ollama_chat/chat.rb', line 386 def models OllamaChat::Database::Models end |
#parse_content? ⇒ TrueClass, FalseClass (private)
The parse_content? method returns the boolean value of the @parse_content instance variable.
416 417 418 |
# File 'lib/ollama_chat/chat.rb', line 416 def parse_content? !!@parse_content end |
#quit_app ⇒ Object (private)
Signals a graceful shutdown of the application.
Raises OllamaChatQuitError which is caught by the main interaction loop to terminate the session cleanly.
437 438 439 |
# File 'lib/ollama_chat/chat.rb', line 437 def quit_app raise OllamaChat::OllamaChatQuitError 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.
757 758 759 760 761 762 763 764 765 766 |
# File 'lib/ollama_chat/chat.rb', line 757 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.
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 |
# File 'lib/ollama_chat/chat.rb', line 657 def setup_documents if .on? @embedding_model = config..model.name @embedding_model_options = Ollama::Options[config..model.] pull_model_unless_present(@embedding_model, ollama: ) collection = initial_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: ) else NULL end end |
#speak(text, background: true) ⇒ OllamaChat::TTS, ...
Synthesizes and plays a short voice notification using the session's current voice.
This is the chat-level facade for one-shot speech: it resolves the
active voice, instantiates the configured voice handler, and delegates
to its #speak method. It is a no-op when the voice switch is off,
no voice is selected, or the handler lacks #speak.
324 325 326 327 328 329 330 |
# File 'lib/ollama_chat/chat.rb', line 324 def speak(text, background: true) session or return voice.on? or return current_voice = session.current_voice.full? or return voice_handler.method_defined?(:speak) or return voice_handler.new(chat: self, voice: current_voice).speak(text, background:) end |
#start ⇒ Object
The start method initializes the chat session by displaying information, then prompts the user for input to begin interacting with the chat.
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
# File 'lib/ollama_chat/chat.rb', line 193 def start log(:info, 'Starting chat client', data: { client:, server: { version: server_version, url: server_url }, user:, config: @ollama_chat_config.filename, }) begin if model = session.current_model.full? use_model(model, keep_options: true) else use_model(initial_model) end rescue OllamaChat::UnknownModelError => e abort "Failed to use to model: #{e}" end feedback ?\n setup_persona_from_session setup_system_prompt print_welcome info_session feedback("\nType /help to display the chat help.") interact_with_user end |
#truncate_logs ⇒ Object (private)
Truncates chat.log and database.log to the configured tail line count before any new logging begins for this session.
375 376 377 378 379 380 381 382 383 |
# File 'lib/ollama_chat/chat.rb', line 375 def truncate_logs keep = OC::OLLAMA::CHAT::LOG::TAIL_LINES OllamaChat::Utils::LogRotation.truncate_tail( OC::OLLAMA::CHAT::LOG::CHAT, keep_lines: keep ) OllamaChat::Utils::LogRotation.truncate_tail( OC::OLLAMA::CHAT::LOG::DATABASE, keep_lines: keep ) end |
#voice_handler ⇒ Class, NilClass
Returns the voice handler class based on the configuration.
This method resolves the voice handler class specified in the config. If running within RSpec, it returns nil to avoid side effects.
181 182 183 184 185 186 187 188 189 |
# File 'lib/ollama_chat/chat.rb', line 181 def voice_handler defined?(RSpec) and return nil case config.voice.handler when 'OllamaChat::TTS' OllamaChat::TTS when 'OllamaChat::Say' OllamaChat::Say end end |