Class: OllamaChat::Chat
- Inherits:
-
Object
- Object
- OllamaChat::Chat
- Includes:
- Clipboard, CommandConcern, ConfigHandling, Conversation, Dialog, DocumentCache, FavouritesManagement, 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, ToolCalling, Utils::Chooser, 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 ThinkControl
ThinkControl::THINK_MODE_STATES
Constants included from Parsing
Parsing::CONTENT_REGEXP, Parsing::DOCUMENT_POLICY_STATES
Instance Attribute Summary collapse
-
#cache ⇒ Object
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.
-
#ollama ⇒ Ollama::Client
readonly
The ollama reader returns the Ollama API client instance.
Attributes included from Utils::Chooser
#current_search_state Stores the
Attributes included from PersonaeManagement
Attributes included from ToolCalling
Attributes included from ServerSocket
Attributes included from StateSelectors
#document_policy, #think_mode, #voices
Attributes included from Switches
#embedding, #embedding_enabled, #embedding_paused, #location, #markdown, #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.
-
#clean(what) ⇒ Object
private
The clean method clears various parts of the chat session based on the specified parameter.
-
#collection ⇒ Object
private
Collection.
-
#compose ⇒ Object
private
Input.
-
#config ⇒ Object
private
Settings.
-
#connect_ollama ⇒ Ollama::Client
private
The connect_ollama method establishes a connection to the Ollama API server.
-
#copy ⇒ Object
private
Clipboard.
-
#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. -
#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(prompt:) ⇒ Ollama::Response
private
The generate method sends a prompt to the Ollama model and returns the result.
-
#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.
-
#interact_with_user ⇒ Object
private
The interact_with_user method manages the interactive loop for user input and chat processing.
-
#list ⇒ Object
private
Conversation.
-
#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.
-
#reconnect ⇒ Object
private
Actions.
-
#session ⇒ Object
private
Session.
-
#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, then prompts the user for input to begin interacting with the chat.
Methods included from Utils::ValueFormatter
Methods included from Utils::Chooser
#choose_entry, #choose_with_state
Methods included from PromptManagement
#add_new_prompt, #all_prompts, #choose_and_delete_prompt, #choose_and_edit_prompt, #choose_prompt, #determine_valid_new_name_for_prompt, #duplicate_prompt, #export_prompt, #import_prompt, #info_prompt, #list_prompts, #prompt_with_favourite, #reset_prompt_to_default
Methods included from SystemPromptManagement
#add_new_system_prompt, #all_system_prompts, #ask_to_set_current_system_prompt, #change_system_prompt, #choose_and_delete_system_prompt, #choose_and_edit_system_prompt, #choose_system_prompt, #current_system_prompt, #current_system_prompt_name, #determine_valid_new_name_for_system_prompt, #duplicate_system_prompt, #export_system_prompt, #import_system_prompt, #info_system_prompt, #list_system_prompts, #model_default_system_prompt, #reset_system_prompt_to_default, #set_current_system_prompt, #setup_system_prompt, #system_prompt_with_favourite
Methods included from PromptHandling
#delete_prompt, #delete_system_prompt, #each_prompt, #each_system_prompt, #load_prompt_from_file, #prompt, #store_prompt, #store_system_prompt, #system_prompt, #write_prompt
Methods included from FavouritesManagement
#add_favourite, #all_favourited, #delete_favourite, #favourite_all_things, #prefix_favourite
Methods included from RAGHandling
#choose_collection, #clear_collection, #list_collections, #rename_collection, #set_current_collection, #switch_collection, #update_collection
Methods included from SessionManagement
#change_session, #choose_session, #delete_session, #derive_session_name, #determine_valid_new_name_for_session, #duplicate_session, #list_sessions, #load_links_from_session, #new_session, #preferred_session, #previous_session, #rename_session, #session_apply, #session_close, #set_new_session, #setup_session, #show_session, #store_links_in_session, #store_messages_in_session, #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, #info_persona, #initial_persona_name, #list_personae, #load_persona_file, #load_personae, #pathname_to_persona_name, #persona_backup_pathname, #persona_description, #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
Methods included from ConfigHandling
#config=, #display_config, #edit_config, #fix_config, #fix_session, #reload_config
Methods included from ToolCalling
#configured_tools, #default_enabled_tools, #disable_tool, #enable_tool, #enabled_tools, #handle_tool_call_results?, #list_tools, #tool_configured?, #tool_enabled?, #tool_function, #tool_paths_allowed, #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
#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
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, #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, #display_chat_help, #dynamic_runtime_information, #dynamic_runtime_information_values, #info, #info_model, #info_rag, #info_runtime, #info_session, #infobar_message, #server_url, #server_version, #static_runtime_information, #static_runtime_information_values, #usage, #user, #user_name, #version
Methods included from ThinkControl
Methods included from Dialog
#ask?, #change_voice, #choose_file_set, #confirm?, #connect_message, #go_command, #message_list
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, #embed, #embed_source, #fetch_source, #fetch_source_as_filename, #import, #import_source, #summarize, #summarize_source
Methods included from Parsing
#parse_atom, #parse_character_json, #parse_content, #parse_rss, #parse_source, #pdf_read, #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, #copy_model_options_from_session, #copy_model_options_to_session, #edit_model_options, #edit_session_model_options, #fill_up_model_options, #get_default_model_options, #get_session_model_options, #get_stored_model_options, #model_options, #model_present?, #model_with_size, #prepare_model, #pull_model_from_remote, #pull_model_unless_present, #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
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.
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/ollama_chat/chat.rb', line 100 def initialize(argv: ARGV.dup) @opts = go 'f:u:m:c:C:D:l:nMESVh', 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 @messages = OllamaChat::MessageList.new(self) OllamaChat::Database.setup_models.each { _1.ask_and_send(:seed, self) } setup_session setup_switches setup_state_selectors(config) connect_ollama if conversation_file = @opts[?c] .load_conversation(conversation_file) else .read_conversation_jsonl(session..to_s) end .set(config..enabled && !@opts[?E]) @documents = setup_documents @cache = setup_cache @images = [] @kramdown_ansi_styles = configure_kramdown_ansi_styles @tool_call_results = Hash.new { |h, name| h[name] = [] } setup_personae_directory @opts[?S] and init_server_socket rescue ComplexConfig::AttributeMissing, ComplexConfig::ConfigurationSyntaxError => e fix_config(e) end |
Instance Attribute Details
#cache ⇒ Object (readonly)
Provides read-only access to the cache instance used by the object
163 164 165 |
# File 'lib/ollama_chat/chat.rb', line 163 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.
143 144 145 |
# File 'lib/ollama_chat/chat.rb', line 143 def documents @documents end |
#images ⇒ Array (readonly)
Returns the list of images currently queued for the next message.
158 159 160 |
# File 'lib/ollama_chat/chat.rb', line 158 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.
153 154 155 |
# File 'lib/ollama_chat/chat.rb', line 153 def @messages end |
#ollama ⇒ Ollama::Client (readonly)
The ollama reader returns the Ollama API client instance.
132 133 134 |
# File 'lib/ollama_chat/chat.rb', line 132 def ollama @ollama 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.
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 |
# File 'lib/ollama_chat/chat.rb', line 1405 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.
1322 1323 1324 |
# File 'lib/ollama_chat/chat.rb', line 1322 def base_url @opts[?u] || OC::OLLAMA::URL end |
#clean(what) ⇒ Object (private)
The clean method clears various parts of the chat session based on the specified parameter.
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 |
# File 'lib/ollama_chat/chat.rb', line 1123 def clean(what) persona_profile = nil 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 'images' .clear_images STDOUT.puts "Cleared all images." when 'all' if confirm?( prompt: '🔔 Are you sure to clear messages and collection? (y/n) ', yes: /\Ay/i ) then .clear @documents.clear links.clear clear_history STDOUT.puts "Cleared messages and collection #{bold{collection}}." else STDOUT.puts 'Cancelled.' end end persona_profile end |
#collection ⇒ Object (private)
Collection
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 |
# File 'lib/ollama_chat/chat.rb', line 723 command( name: :collection, regexp: %r(^/collection(?:\s+(change|clear|list|rename|update))?$), complete: [ 'collection', %w[ change clear list rename update ] ], optional: true, help: <<~EOT Manage the current RAG document collection: change, clear, list, rename, update and show EOT ) do |subcommand| case subcommand when 'clear' clear_collection when 'change' choose_collection(collection) when 'list' list_collections when 'rename' rename_collection(collection) when 'update' update_collection when nil collection_stats end :next end |
#compose ⇒ Object (private)
Input
866 867 868 869 870 871 872 |
# File 'lib/ollama_chat/chat.rb', line 866 command( name: :compose, regexp: %r(^/compose$), help: 'Compose a message using the text editor' ) do edit_text.full? or :next end |
#config ⇒ Object (private)
Settings
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
# File 'lib/ollama_chat/chat.rb', line 312 command( name: :config, regexp: %r(^/config(?:\s+(edit|reload))?$), complete: [ 'config', %w[ edit reload ] ], optional: true, help: 'View, edit, or reload configuration' ) do |subcommand| case subcommand when 'edit' edit_config when 'reload' reload_config else display_config end :next 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.
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 |
# File 'lib/ollama_chat/chat.rb', line 1336 def connect_ollama @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: 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 to #{base_url} established.") @ollama end |
#copy ⇒ Object (private)
Clipboard
288 289 290 291 292 293 294 295 296 297 |
# File 'lib/ollama_chat/chat.rb', line 288 command( name: :copy, regexp: %r(^/copy(?:\s+(edit))?$), complete: [ 'copy', %w[ edit ] ], optional: true, help: 'Copy the last response to the clipboard (optionally edit it first)' ) do |subcommand| copy_to_clipboard(edit: subcommand == 'edit') :next end |
#debug ⇒ TrueClass, FalseClass
The debug method accesses the debug configuration setting.
193 194 195 |
# File 'lib/ollama_chat/chat.rb', line 193 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.
261 262 263 264 |
# File 'lib/ollama_chat/chat.rb', line 261 def disable_content_parsing @parse_content = false self 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.
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 |
# File 'lib/ollama_chat/chat.rb', line 1457 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.
270 271 272 273 |
# File 'lib/ollama_chat/chat.rb', line 270 def enable_content_parsing @parse_content = true self end |
#generate(prompt:) ⇒ Ollama::Response (private)
The generate method sends a prompt to the Ollama model and returns the result.
238 239 240 241 242 243 244 245 246 247 |
# File 'lib/ollama_chat/chat.rb', line 238 def generate(prompt:) prepare_model(@model) ollama.generate( model: @model, prompt:, options: , stream: false, think: false, ) end |
#handle_input(content) ⇒ Symbol, ... (private)
Handles user input commands and processes chat interactions.
1110 1111 1112 1113 1114 1115 1116 |
# File 'lib/ollama_chat/chat.rb', line 1110 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.
213 214 215 216 217 218 219 220 |
# File 'lib/ollama_chat/chat.rb', line 213 def initial_collection ( @opts[?C] || session&.current_collection.full? || config..collection.full? || :default ).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.
205 206 207 |
# File 'lib/ollama_chat/chat.rb', line 205 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.
226 227 228 |
# File 'lib/ollama_chat/chat.rb', line 226 def initial_system_prompt @messages.system_name 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.
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 |
# File 'lib/ollama_chat/chat.rb', line 1171 def interact_with_user loop do content = nil tools_were_called = false enable_content_parsing type = :terminal_input input_prompt = bold { color(172) { (@images) + " user" } } + bold { "> " } begin tools_were_called = handle_tool_call_results? { |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 ) } tools_were_called and type = :tool_input unless tools_were_called 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 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 content = content.strip if content =~ %r(\A/[^/]) 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 unless type == :tool_input content = content.encode(invalid: :replace) content.present? or next parse_content? and content = parse_content(content, @images) if runtime_info.on? tool_name = 'runtime_information' << OllamaChat::Message.new( role: 'user', tool_name: , sender_name: tool_name, content: dynamic_runtime_information, images: @images.dup ) end << OllamaChat::Message.new( role: 'user', sender_name: user_name, content: , images: @images.dup ) end @images.clear handler = OllamaChat::FollowChat.new( chat: self, messages:, voice: (voices.selected if voice.on?) ) begin retried = false = .to_ary if think_strip.on? = .map { _1.dup.tap { || .thinking = nil } } end prepare_model(@model) ollama.chat( model: @model, messages: , options: , stream: stream.on?, think: , tools: , &handler ) rescue Ollama::Errors::BadRequestError if (think? || tools_support.on?) && !retried STDOUT.puts "#{bold('Error')}: in think mode/with tool support, switch both off and retry." 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 STDOUT.puts "Type /quit to quit." ensure self. = nil end 0 rescue ComplexConfig::AttributeMissing, ComplexConfig::ConfigurationSyntaxError => e log(:error, e) fix_config(e) ensure session_close end |
#list ⇒ Object (private)
Conversation
569 570 571 572 573 574 575 576 577 578 |
# File 'lib/ollama_chat/chat.rb', line 569 command( name: :list, regexp: %r(^/list(?:\s+(\d*))?$), options: '[n=1]', help: 'List the last n or all conversation exchanges' ) do n = 2 * _1.to_i if _1 .list_conversation(n) :next end |
#models ⇒ Module (private)
Returns The module containing the database models.
250 251 252 |
# File 'lib/ollama_chat/chat.rb', line 250 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.
280 281 282 |
# File 'lib/ollama_chat/chat.rb', line 280 def parse_content? !!@parse_content end |
#reconnect ⇒ Object (private)
Actions
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 |
# File 'lib/ollama_chat/chat.rb', line 1023 command( name: :reconnect, regexp: %r(^/reconnect$), help: 'Reconnect to the Ollama server' ) do STDERR.print green { "Reconnecting to ollama #{base_url.to_s.inspect}…" } connect_ollama STDERR.puts green { " Done." } :next end |
#session ⇒ Object (private)
Session
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 |
# File 'lib/ollama_chat/chat.rb', line 493 command( name: :session, regexp: %r(^/session(?:\s+(change|previous|list|new|duplicate|rename|summarize|delete|model options))?((?:\s+-(?:[sf]))*)(?:\s+(.+))?$), complete: [ 'session', %w[ change previous list new duplicate rename summarize delete model\ options ] ], optional: true, options: '[-s|-f] [name]', help: <<~EOT Manage chat sessions (change, previous, list, new, duplicate, rename, summarize, delete, model options). For summarize: -s (single sentence), -f (output to markdown file) EOT ) do |subcommand, opts, name| case subcommand when nil show_session when 'list' list_sessions when 'new' set_new_session when 'duplicate' duplicate_session when 'delete' delete_session when 'rename' rename_session when 'summarize' opts = go_command('fs', opts) if opts[?f] and filename = ask?(prompt: "❓ Enter filename: ").full? { Pathname.new(_1) } then if filename.exist? && !confirm?( prompt: "🔔 File #{filename.to_s.inspect} already exists, overwrite? (y/n) ", yes: /\Ay/i ) then STDERR.puts "File not written!" next :next end summary = summarize_session(pretty: true, sentence: opts[?s]) do |content| .puts kramdown_ansi_parse(content) end if summary.full? filename.write(summary) STDOUT.puts "File successfully written." else STDERR.puts "Nothing to summarize!" next :next end end summary = summarize_session(pretty: true, sentence: opts[?s]) do |content| .puts kramdown_ansi_parse(content) << ?\n end if summary.full? use_pager do |output| output.puts kramdown_ansi_parse(summary) end else STDERR.puts "Nothing to summarize!" next :next end when 'change' change_session(name) when 'model options' when 'previous' if prev = previous_session change_session(prev.id) else STDOUT.puts "No previous session defined." end end :next 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.
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 |
# File 'lib/ollama_chat/chat.rb', line 1437 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.
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 |
# File 'lib/ollama_chat/chat.rb', line 1360 def setup_documents if .on? @embedding_model = config..model.name @embedding_model_options = Ollama::Options[config..model.] pull_model_unless_present(@embedding_model) 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: ) 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, then prompts the user for input to begin interacting with the chat.
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
# File 'lib/ollama_chat/chat.rb', line 167 def start 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 STDOUT.puts setup_persona_from_session setup_system_prompt info_session STDOUT.puts "\nType /help to display the chat help." interact_with_user end |