Class: OllamaChat::Chat
- Inherits:
-
Object
- Object
- OllamaChat::Chat
- Includes:
- Clipboard, Commands, 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, 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 ThinkControl
ThinkControl::THINK_MODE_STATES
Constants included from Parsing
Parsing::DOCUMENT_POLICY_STATES
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.
-
#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 SessionManagement
Attributes included from ToolCalling
Attributes included from StateSelectors
#context_format, #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
-
#debug ⇒ TrueClass, FalseClass
The debug method accesses the debug configuration setting.
-
#generate(system: raw_system_prompt, prompt:) ⇒ String
Sends a structured chat request to the Ollama model and returns the response content.
-
#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.
-
#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::UTF8Converter
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, #duplicate_prompt, #export_prompt, #import_prompt, #info_prompt, #list_prompts, #prepare_conversation_history, #reset_prompt_to_default, #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, #set_current_system_prompt, #setup_system_prompt
Methods included from PromptHandling
#delete_prompt, #each_prompt, #load_prompt_from_file, #prompt, #store_prompt, #write_prompt
Methods included from SessionManagement
#load_links_from_session, #store_links_in_session, #store_messages_in_session
Methods included from PersonaeManagement
#assistant, #default_persona_profile, #initial_persona_name
Methods included from ConfigHandling
Methods included from ToolCalling
#configured_tools, #default_enabled_tools, #disable_tool, #enable_tool, #enabled_tools, #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 InputContent
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, send_to_server_socket
Methods included from 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
#perform_copy_to_clipboard, #perform_paste_from_clipboard
Methods included from MessageOutput
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, #print_welcome, #server_url, #server_version, #static_runtime_information, #static_runtime_information_values, #usage, #user, #user_name, #version
Methods included from ThinkControl
Methods included from Dialog
Methods included from WebSearching
#manage_links, #search_web, #web
Methods included from SourceFetching
#add_image, #embed, #embed_source, #fetch_source, #import, #import_source, #summarize, #summarize_source
Methods included from Parsing
#epub_read, #parse_atom, #parse_content, #parse_png, #parse_rss, #parse_source, #pdf_read, #personalize_character_profile, #ps_read, #reverse_markdown
Methods included from Utils::AnalyzeDirectory
Methods included from ModelHandling
Methods included from StateSelectors
Methods included from Switches
Methods included from Logging
Methods included from Commands
#collection, #compose, #config, #copy, #list, #pipe, #reconnect, #session
Methods included from HTTPHandling
#get_url, #http_options, #links
Methods included from TokenEstimator
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.
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 128 129 130 131 |
# File 'lib/ollama_chat/chat.rb', line 103 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 repair_group_uuids .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 ⇒ OllamaChat::RedisCache? (readonly)
Provides read-only access to the cache instance used by the object.
167 168 169 |
# File 'lib/ollama_chat/chat.rb', line 167 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.
147 148 149 |
# File 'lib/ollama_chat/chat.rb', line 147 def documents @documents end |
#images ⇒ Array (readonly)
Returns the list of images currently queued for the next message.
162 163 164 |
# File 'lib/ollama_chat/chat.rb', line 162 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.
157 158 159 |
# File 'lib/ollama_chat/chat.rb', line 157 def @messages end |
#ollama ⇒ Ollama::Client (readonly)
The ollama reader returns the Ollama API client instance.
136 137 138 |
# File 'lib/ollama_chat/chat.rb', line 136 def ollama @ollama end |
Instance Method Details
#debug ⇒ TrueClass, FalseClass
The debug method accesses the debug configuration setting.
198 199 200 |
# File 'lib/ollama_chat/chat.rb', line 198 def debug OC::OLLAMA::CHAT::DEBUG end |
#generate(system: raw_system_prompt, prompt:) ⇒ 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.
(defaults to current raw_system_prompt)
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 |
# File 'lib/ollama_chat/chat.rb', line 247 def generate(system: raw_system_prompt, prompt:) = [ OllamaChat::Message.new( role: 'system', content: system, ), OllamaChat::Message.new( role: 'user', content: prompt ), ] content = call_ollama_chat( model: @model, messages: , options: , stream: false, think: false, tools: )&.&.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 |
#initial_collection ⇒ Symbol
The initial_collection method determines the collection name to be used for embeddings in the RAG system.
218 219 220 221 222 223 224 225 |
# File 'lib/ollama_chat/chat.rb', line 218 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.
210 211 212 |
# File 'lib/ollama_chat/chat.rb', line 210 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.
231 232 233 |
# File 'lib/ollama_chat/chat.rb', line 231 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.
282 283 284 |
# File 'lib/ollama_chat/chat.rb', line 282 def inspect "#<#{self.class}: #{base_url.to_s}>" 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.
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
# File 'lib/ollama_chat/chat.rb', line 171 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 print_welcome info_session STDOUT.puts "\nType /help to display the chat help." interact_with_user end |