ollama_chat 0.0.24 → 0.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. checksums.yaml +4 -4
  2. data/.contexts/code_comment.rb +25 -0
  3. data/.contexts/full.rb +31 -0
  4. data/.contexts/info.rb +17 -0
  5. data/.contexts/lib.rb +25 -0
  6. data/.contexts/yard.md +94 -0
  7. data/.gitignore +1 -0
  8. data/CHANGES.md +39 -0
  9. data/README.md +10 -1
  10. data/Rakefile +4 -3
  11. data/VERSION +1 -1
  12. data/bin/ollama_chat_send +9 -2
  13. data/lib/ollama_chat/chat.rb +42 -18
  14. data/lib/ollama_chat/clipboard.rb +12 -0
  15. data/lib/ollama_chat/dialog.rb +17 -0
  16. data/lib/ollama_chat/document_cache.rb +28 -10
  17. data/lib/ollama_chat/follow_chat.rb +26 -7
  18. data/lib/ollama_chat/history.rb +55 -7
  19. data/lib/ollama_chat/information.rb +32 -1
  20. data/lib/ollama_chat/kramdown_ansi.rb +15 -1
  21. data/lib/ollama_chat/message_format.rb +16 -0
  22. data/lib/ollama_chat/message_list.rb +52 -5
  23. data/lib/ollama_chat/message_output.rb +12 -0
  24. data/lib/ollama_chat/model_handling.rb +17 -0
  25. data/lib/ollama_chat/ollama_chat_config/default_config.yml +4 -2
  26. data/lib/ollama_chat/ollama_chat_config.rb +19 -0
  27. data/lib/ollama_chat/parsing.rb +13 -0
  28. data/lib/ollama_chat/server_socket.rb +34 -3
  29. data/lib/ollama_chat/source_fetching.rb +25 -2
  30. data/lib/ollama_chat/switches.rb +49 -0
  31. data/lib/ollama_chat/utils/cache_fetcher.rb +15 -0
  32. data/lib/ollama_chat/utils/chooser.rb +16 -0
  33. data/lib/ollama_chat/utils/fetcher.rb +41 -1
  34. data/lib/ollama_chat/utils/file_argument.rb +19 -0
  35. data/lib/ollama_chat/utils.rb +8 -0
  36. data/lib/ollama_chat/version.rb +1 -1
  37. data/lib/ollama_chat/vim.rb +6 -0
  38. data/lib/ollama_chat/web_searching.rb +11 -0
  39. data/lib/ollama_chat.rb +9 -0
  40. data/ollama_chat.gemspec +8 -7
  41. data/spec/ollama_chat/chat_spec.rb +11 -1
  42. data/spec/ollama_chat/kramdown_ansi_spec.rb +45 -0
  43. data/spec/ollama_chat/message_list_spec.rb +70 -9
  44. data/spec/ollama_chat/server_socket_spec.rb +68 -47
  45. data/spec/spec_helper.rb +120 -26
  46. metadata +28 -7
@@ -1,29 +1,77 @@
1
+ # A module that provides history management functionality for OllamaChat
2
+ # sessions.
3
+ #
4
+ # The History module encapsulates methods for initializing, saving, and
5
+ # clearing command-line history within the OllamaChat application. It handles
6
+ # persistence of user input history to a file and ensures that chat sessions
7
+ # can maintain state across invocations by loading previous command histories.
8
+ #
9
+ # @example Initializing chat history
10
+ # chat.init_chat_history
11
+ #
12
+ # @example Saving chat history
13
+ # chat.save_history
14
+ #
15
+ # @example Clearing chat history
16
+ # chat.clear_history
1
17
  module OllamaChat::History
2
- # Returns the full path of the chat history filename based on the
3
- # configuration.
18
+ # The chat_history_filename method constructs and returns the full file path
19
+ # for the chat history file.
20
+ #
21
+ # This method takes the configured chat history filename from the
22
+ # configuration and expands it to an absolute path using File.expand_path.
23
+ # This ensures that the returned path is fully qualified and can be used
24
+ # reliably for reading from or writing to the chat history file.
25
+ #
26
+ # @return [String] the absolute file path to the chat history file as
27
+ # specified in the configuration
4
28
  def chat_history_filename
5
29
  File.expand_path(config.chat_history_filename)
6
30
  end
7
31
 
8
- # Initializes the chat history by loading it from a file if it exists, and
9
- # then loads the history into Readline::HISTORY.
32
+ # The init_chat_history method initializes the chat session by loading
33
+ # previously saved command history from a file.
34
+ #
35
+ # This method checks for the existence of a chat history file and, if found,
36
+ # loads its contents into the Readline::HISTORY array. It clears the current
37
+ # history and replaces it with the saved history data. Any errors during the
38
+ # loading process are caught and logged as warnings, but do not interrupt the
39
+ # execution flow.
10
40
  def init_chat_history
11
41
  if File.exist?(chat_history_filename)
12
42
  File.open(chat_history_filename, ?r) do |history|
13
43
  history_data = JSON.load(history)
14
- clear_history
44
+ Readline::HISTORY.clear
15
45
  Readline::HISTORY.push(*history_data)
16
46
  end
17
47
  end
48
+ rescue => e
49
+ warn "Caught #{e.class} while loading #{chat_history_filename.inspect}: #{e}"
18
50
  end
19
51
 
20
- # Saves the current chat history to a file in JSON format.
52
+ # The save_history method persists the current command history to a file.
53
+ #
54
+ # This method serializes the Readline::HISTORY array into JSON format and
55
+ # writes it to the chat history filename. It handles potential errors during
56
+ # the write operation by catching exceptions and issuing a warning message.
21
57
  def save_history
22
58
  File.secure_write(chat_history_filename, JSON.dump(Readline::HISTORY))
59
+ rescue => e
60
+ warn "Caught #{e.class} while saving #{chat_history_filename.inspect}: #{e}"
23
61
  end
24
62
 
25
- # Clears all entries from Readline::HISTORY.
63
+ # The clear_history method clears the Readline history array and ensures that
64
+ # the chat history is saved afterwards.
65
+ #
66
+ # This method removes all entries from the Readline::HISTORY array,
67
+ # effectively clearing the command history maintained by the readline
68
+ # library. It then calls save_history to persist this cleared state to the
69
+ # configured history file. The method uses an ensure block to guarantee that
70
+ # save_history is called even if an exception occurs during the clearing
71
+ # process.
26
72
  def clear_history
27
73
  Readline::HISTORY.clear
74
+ ensure
75
+ save_history
28
76
  end
29
77
  end
@@ -1,3 +1,20 @@
1
+ # A module that provides information and user agent functionality for
2
+ # OllamaChat
3
+ #
4
+ # The Information module encapsulates methods for managing application
5
+ # identification, displaying version and configuration details, and handling
6
+ # command-line interface help messages. It includes user agent capabilities for
7
+ # HTTP requests and provides comprehensive information display features for
8
+ # chat sessions.
9
+ #
10
+ # @example Displaying application information
11
+ # chat.info
12
+ #
13
+ # @example Showing version details
14
+ # chat.version
15
+ #
16
+ # @example Displaying usage help
17
+ # chat.usage
1
18
  module OllamaChat::Information
2
19
  extend Tins::Concern
3
20
 
@@ -6,6 +23,20 @@ module OllamaChat::Information
6
23
  extend UserAgent
7
24
  end
8
25
 
26
+ # A module that provides user agent functionality for identifying the
27
+ # application.
28
+ #
29
+ # This module encapsulates methods for determining the application name and
30
+ # constructing a standardized user agent string that includes the application
31
+ # name and version. It is designed to be included in classes that need to
32
+ # provide identification information for HTTP requests or other
33
+ # communications.
34
+ #
35
+ # @example Accessing the program name
36
+ # UserAgent.progname # => "ollama_chat"
37
+ #
38
+ # @example Generating a user agent string
39
+ # UserAgent.user_agent # => "ollama_chat/0.0.25"
9
40
  module UserAgent
10
41
  # The progname method returns the name of the application.
11
42
  #
@@ -92,7 +123,7 @@ module OllamaChat::Information
92
123
  /stream toggle stream output
93
124
  /location toggle location submission
94
125
  /voice [change] toggle voice output or change the voice
95
- /last show the last system/assistant message
126
+ /last [n] show the last n / 1 system/assistant message
96
127
  /list [n] list the last n / all conversation exchanges
97
128
  /clear [what] clear what=messages|links|history|tags|all
98
129
  /clobber clear the conversation, links, and collection
@@ -1,3 +1,15 @@
1
+ # A module that provides Kramdown::ANSI styling configuration and parsing
2
+ # functionality for OllamaChat.
3
+ #
4
+ # This module handles the setup and application of ANSI styles for markdown
5
+ # rendering, allowing for customizable terminal output formatting. It manages
6
+ # the configuration of ANSI styles either from environment variables or falls
7
+ # back to default settings, and provides methods to parse content with the
8
+ # configured styling.
9
+ #
10
+ # @example Configuring custom ANSI styles via environment variable
11
+ # Set KRAMDOWN_ANSI_OLLAMA_CHAT_STYLES to a JSON object containing style
12
+ # definitions for customizing markdown output formatting in the terminal.
1
13
  module OllamaChat::KramdownANSI
2
14
  # The configure_kramdown_ansi_styles method sets up ANSI styling for
3
15
  # Kramdown::ANSI output by checking for specific environment variables and
@@ -21,11 +33,13 @@ module OllamaChat::KramdownANSI
21
33
  # content with appropriate terminal formatting based on the application's
22
34
  # styling configuration.
23
35
  #
24
- # @param content [ String ] the raw content to be parsed and formatted
36
+ # @param content [ String, nil ] the raw content to be parsed and formatted.
37
+ # If nil, returns an empty string.
25
38
  #
26
39
  # @return [ String ] the content formatted with ANSI escape sequences
27
40
  # according to the configured styles
28
41
  def kramdown_ansi_parse(content)
42
+ content.nil? and return ''
29
43
  Kramdown::ANSI.parse(content, ansi_styles: @kramdown_ansi_styles)
30
44
  end
31
45
  end
@@ -1,3 +1,19 @@
1
+ # A module that provides formatting functionality for chat messages.
2
+ #
3
+ # The MessageFormat module encapsulates methods for determining message icons
4
+ # based on whether images are present, and for conditionally annotating content
5
+ # with thinking or talk indicators. It supports customizable formatting of
6
+ # message text for display in terminal interfaces.
7
+ #
8
+ # @example Using message_type to determine icon based on images
9
+ # message_type([]) # => "📨"
10
+ # message_type(["image"]) # => "📸"
11
+ #
12
+ # @example Annotating content with thinking indicator
13
+ # think_annotate { "Thinking..." } # => "💭\nThinking...\n" (when think is enabled)
14
+ #
15
+ # @example Annotating content with talk indicator
16
+ # talk_annotate { "Speaking..." } # => "💬\nSpeaking...\n" (when think is enabled)
1
17
  module OllamaChat::MessageFormat
2
18
  # The message_type method determines the appropriate message icon based on
3
19
  # whether images are present.
@@ -1,3 +1,33 @@
1
+ # A collection class for managing chat messages with support for system
2
+ # prompts, paged output, and conversation history.
3
+
4
+ # This class provides functionality for storing, retrieving, and displaying
5
+ # chat messages in a structured manner. It handles system prompts separately
6
+ # from regular user and assistant messages, supports pagination for displaying
7
+ # conversations, and offers methods for manipulating message history including
8
+ # clearing, loading, saving, and dropping exchanges. The class integrates with
9
+ # Kramdown::ANSI for formatted output and supports location information in
10
+ # system messages.
11
+
12
+ # @example Creating a new message list
13
+ # chat = OllamaChat::Chat.new
14
+ # messages = OllamaChat::MessageList.new(chat)
15
+ #
16
+ # @example Adding messages to the list
17
+ # messages << Ollama::Message.new(role: 'user', content: 'Hello')
18
+ # messages << Ollama::Message.new(role: 'assistant', content: 'Hi there!')
19
+ #
20
+ # @example Displaying conversation history
21
+ # messages.list_conversation(5) # Shows last 5 exchanges
22
+ #
23
+ # @example Clearing messages
24
+ # messages.clear # Removes all non-system messages
25
+ #
26
+ # @example Loading a saved conversation
27
+ # messages.load_conversation('conversation.json')
28
+ #
29
+ # @example Saving current conversation
30
+ # messages.save_conversation('my_conversation.json')
1
31
  class OllamaChat::MessageList
2
32
  include Term::ANSIColor
3
33
  include OllamaChat::MessageFormat
@@ -11,8 +41,20 @@ class OllamaChat::MessageList
11
41
  @messages = []
12
42
  end
13
43
 
44
+ # The system attribute reader returns the system prompt for the chat session.
45
+ #
46
+ # @attr_reader [ String, nil ] the current system prompt content or nil if not set
14
47
  attr_reader :system
15
48
 
49
+ # The messages attribute reader returns the messages set for this object,
50
+ # initializing it lazily if needed.
51
+ #
52
+ # The messages set is memoized, meaning it will only be created once per
53
+ # object instance and subsequent calls will return the same
54
+ # OllamaChat::MessageList instance.
55
+ #
56
+ # @attr_reader [OllamaChat::MessageList] A MessageList object containing all
57
+ # messages associated with this instance
16
58
  attr_reader :messages
17
59
 
18
60
  # Returns the number of messages stored in the message list.
@@ -111,11 +153,15 @@ class OllamaChat::MessageList
111
153
  # from the user. It uses a pager for output and returns the instance itself.
112
154
  #
113
155
  # @return [ OllamaChat::MessageList ] returns the instance of the class
114
- def show_last
115
- message = last
116
- message&.role == 'user' and return
156
+ def show_last(n = nil)
157
+ n ||= 1
158
+ messages = @messages.reject { |message| message.role == 'user' }
159
+ n = n.clamp(0..messages.size)
160
+ n <= 0 and return
117
161
  use_pager do |output|
118
- output.puts message_text_for(message)
162
+ messages[-n..-1].to_a.each do |message|
163
+ output.puts message_text_for(message)
164
+ end
119
165
  end
120
166
  self
121
167
  end
@@ -277,7 +323,8 @@ class OllamaChat::MessageList
277
323
  # If the output would exceed the terminal's line capacity, it pipes the content
278
324
  # through an appropriate pager command (like 'less' or 'more').
279
325
  #
280
- # @param block [Proc] A block that yields an IO object to write output to
326
+ # @yield A block that yields an IO object to write output to
327
+ # @yieldparam [IO] the IO object to write to
281
328
  def use_pager
282
329
  command = determine_pager_command
283
330
  output_buffer = StringIO.new
@@ -1,3 +1,15 @@
1
+ # A module that provides output functionality for chat messages.
2
+ #
3
+ # This module encapsulates methods for piping assistant responses to command
4
+ # standard input and writing assistant responses to files. It handles the
5
+ # mechanics of sending output to external processes or saving content to disk
6
+ # while providing appropriate error handling and user feedback.
7
+ #
8
+ # @example Piping a response to a command
9
+ # chat.pipe('cat > output.txt')
10
+ #
11
+ # @example Writing a response to a file
12
+ # chat.output('response.txt')
1
13
  module OllamaChat::MessageOutput
2
14
  # The pipe method forwards the last assistant message to a command's standard
3
15
  # input.
@@ -1,3 +1,20 @@
1
+ # A module that provides functionality for managing Ollama models, including
2
+ # checking model availability, pulling models from remote servers, and handling
3
+ # model presence verification.
4
+ #
5
+ # This module encapsulates the logic for interacting with Ollama models,
6
+ # ensuring that required models are available locally before attempting to use
7
+ # them in chat sessions. It handles both local model verification and remote
8
+ # model retrieval when necessary.
9
+ #
10
+ # @example Checking if a model is present
11
+ # chat.model_present?('llama3.1')
12
+ #
13
+ # @example Pulling a model from a remote server
14
+ # chat.pull_model_from_remote('mistral')
15
+ #
16
+ # @example Ensuring a model is available locally
17
+ # chat.pull_model_unless_present('phi3', {})
1
18
  module OllamaChat::ModelHandling
2
19
  # The model_present? method checks if the specified Ollama model is available.
3
20
  #
@@ -21,8 +21,10 @@ prompts:
21
21
  %{words} words:
22
22
 
23
23
  %{source_content}
24
- web: |
25
- Answer the the query %{query} using these sources and summaries:
24
+ web_embed: |
25
+ Answer the the query %{query} using the provided chunks.
26
+ web_import: |
27
+ Answer the the query %{query} using these imported source:
26
28
 
27
29
  %{results}
28
30
  location: You are at %{location_name}, %{location_decimal_degrees}, on %{localtime}, preferring %{units}
@@ -1,12 +1,31 @@
1
1
  require 'pathname'
2
2
 
3
+ # A configuration class for managing OllamaChat settings and file paths.
4
+ #
5
+ # This class handles the initialization and management of configuration files
6
+ # for the OllamaChat application. It provides methods for setting up default
7
+ # configurations, determining appropriate file paths for config and cache
8
+ # directories, and managing the loading and creation of configuration files
9
+ # based on XDG standards.
10
+ #
11
+ # @example Initializing with a custom configuration file
12
+ # config = OllamaChat::OllamaChatConfig.new('/path/to/custom/config.yml')
13
+ #
14
+ # @example Accessing default configuration paths
15
+ # config = OllamaChat::OllamaChatConfig.new
16
+ # config.default_config_path # => Path to the default configuration file
17
+ # config.config_dir_path # => Path to the configuration directory
18
+ # config.cache_dir_path # => Path to the cache directory
19
+ # config.database_path # => Path to the documents database file
3
20
  class OllamaChat::OllamaChatConfig
4
21
  include ComplexConfig
5
22
  include FileUtils
6
23
 
24
+ # Path to the default config
7
25
  DEFAULT_CONFIG_PATH = Pathname.new(__FILE__).dirname.
8
26
  join('ollama_chat_config/default_config.yml')
9
27
 
28
+ # Content of the default config
10
29
  DEFAULT_CONFIG = File.read(DEFAULT_CONFIG_PATH)
11
30
 
12
31
  # The initialize method sets up the configuration file path and ensures the
@@ -1,3 +1,16 @@
1
+ # A module that provides content parsing functionality for OllamaChat.
2
+ #
3
+ # The Parsing module encapsulates methods for processing various types of input
4
+ # sources including HTML, XML, CSV, RSS, Atom, PDF, and Postscript documents.
5
+ # It handles content extraction and conversion into standardized text formats
6
+ # suitable for chat interactions. The module supports different document
7
+ # policies for handling imported or embedded content and provides utilities for
8
+ # parsing structured data from multiple source types.
9
+ #
10
+ # @example Processing different document types
11
+ # chat.parse_source(html_io) # Converts HTML to markdown
12
+ # chat.parse_source(pdf_io) # Extracts text from PDF files
13
+ # chat.parse_source(csv_io) # Formats CSV data into readable strings
1
14
  module OllamaChat::Parsing
2
15
  # The parse_source method processes different types of input sources and
3
16
  # converts them into a standardized text representation.
@@ -1,3 +1,25 @@
1
+ # A module that provides server socket functionality for OllamaChat
2
+ #
3
+ # The ServerSocket module encapsulates the logic for creating and managing Unix
4
+ # domain socket servers that enable external processes to send input to running
5
+ # ollama_chat sessions. It supports both simple message transmission and
6
+ # bidirectional communication with response handling, allowing for integration
7
+ # with tools like ollama_chat_send.
8
+ #
9
+ # @example Sending a message to a running chat session
10
+ # OllamaChat::ServerSocket.send_to_server_socket(
11
+ # "Hello from external process",
12
+ # config: chat_config,
13
+ # type: :socket_input
14
+ # )
15
+ #
16
+ # @example Sending a message and waiting for a response
17
+ # response = OllamaChat::ServerSocket.send_to_server_socket(
18
+ # "What is the answer?",
19
+ # config: chat_config,
20
+ # type: :socket_input_with_response,
21
+ # parse: true
22
+ # )
1
23
  module OllamaChat::ServerSocket
2
24
  class << self
3
25
  # The send_to_server_socket method transmits a message to a Unix domain
@@ -13,12 +35,13 @@ module OllamaChat::ServerSocket
13
35
  # @param content [ String ] the message content to be sent
14
36
  # @param config [ ComplexConfig::Settings ] the configuration object containing server settings
15
37
  # @param type [ Symbol ] the type of message transmission, defaults to :socket_input
38
+ # @param runtime_dir [ String ] pathname to runtime_dir of socket file
16
39
  # @param parse [ TrueClass, FalseClass ] whether to parse the response, defaults to false
17
40
  #
18
41
  # @return [ UnixSocks::Message, nil ] the response from transmit_with_response if type
19
42
  # is :socket_input_with_response, otherwise nil
20
- def send_to_server_socket(content, config:, type: :socket_input, parse: false)
21
- server = create_socket_server(config:)
43
+ def send_to_server_socket(content, config:, type: :socket_input, runtime_dir: nil, parse: false)
44
+ server = create_socket_server(config:, runtime_dir:)
22
45
  message = { content:, type:, parse: }
23
46
  if type.to_sym == :socket_input_with_response
24
47
  server.transmit_with_response(message)
@@ -43,7 +66,10 @@ module OllamaChat::ServerSocket
43
66
  #
44
67
  # @return [UnixSocks::Server] a configured Unix domain socket server
45
68
  # instance ready to receive messages
46
- def create_socket_server(config:)
69
+ def create_socket_server(config:, runtime_dir: nil)
70
+ if runtime_dir
71
+ return UnixSocks::Server.new(socket_name: 'ollama_chat.sock', runtime_dir:)
72
+ end
47
73
  if runtime_dir = config.server_socket_runtime_dir
48
74
  UnixSocks::Server.new(socket_name: 'ollama_chat.sock', runtime_dir:)
49
75
  else
@@ -52,6 +78,11 @@ module OllamaChat::ServerSocket
52
78
  end
53
79
  end
54
80
 
81
+ # The server_socket_message accessor method provides read and write access to
82
+ # the server socket message instance variable.
83
+ #
84
+ # @return [ Object, nil ] the current server socket message object or nil if
85
+ # not set
55
86
  attr_accessor :server_socket_message
56
87
 
57
88
  # Initializes the server socket to receive messages from the Ollama Chat
@@ -1,3 +1,28 @@
1
+ # A module that provides functionality for fetching and processing various
2
+ # types of content sources.
3
+ #
4
+ # The SourceFetching module encapsulates methods for retrieving content from
5
+ # different source types including URLs, file paths, and shell commands. It
6
+ # handles the logic for determining the appropriate fetching method based on
7
+ # the source identifier and processes the retrieved content through specialized
8
+ # parsers depending on the content type. The module also manages image
9
+ # handling, document importing, summarizing, and embedding operations while
10
+ # providing error handling and debugging capabilities.
11
+ #
12
+ # @example Fetching content from a URL
13
+ # chat.fetch_source('https://example.com/document.html') do |source_io|
14
+ # # Process the fetched content
15
+ # end
16
+ #
17
+ # @example Importing a local file
18
+ # chat.fetch_source('/path/to/local/file.txt') do |source_io|
19
+ # # Process the imported file content
20
+ # end
21
+ #
22
+ # @example Executing a shell command
23
+ # chat.fetch_source('!ls -la') do |source_io|
24
+ # # Process the command output
25
+ # end
1
26
  module OllamaChat::SourceFetching
2
27
  # The http_options method prepares HTTP options for requests based on
3
28
  # configuration settings.
@@ -110,7 +135,6 @@ module OllamaChat::SourceFetching
110
135
  end
111
136
  end
112
137
 
113
-
114
138
  # Summarizes content from the given source IO and source identifier.
115
139
  #
116
140
  # This method takes an IO object containing document content and generates a
@@ -146,7 +170,6 @@ module OllamaChat::SourceFetching
146
170
  end
147
171
  end
148
172
 
149
-
150
173
  # Embeds content from the given source IO and source identifier.
151
174
  #
152
175
  # This method processes document content by splitting it into chunks using
@@ -1,4 +1,28 @@
1
+ # A module that provides switch functionality for configuring application
2
+ # behavior.
3
+ #
4
+ # The Switches module encapsulates various toggle switches used throughout the
5
+ # OllamaChat application to control different features and settings such as
6
+ # streaming, thinking, markdown output, voice output, embedding, and location
7
+ # information. These switches allow users to dynamically enable or disable
8
+ # specific functionalities during a chat session.
9
+ #
10
+ # @example Toggling a switch on/off
11
+ # switch = OllamaChat::Switches::Switch.new(value: false, msg: { true => 'Enabled', false => 'Disabled' })
12
+ # switch.toggle # Turns the switch on
13
+ # switch.toggle # Turns the switch off
1
14
  module OllamaChat::Switches
15
+ # A module that provides switch state checking functionality.
16
+ #
17
+ # The CheckSwitch module adds methods for checking the boolean state of
18
+ # switches and displaying their current status. It's designed to be included
19
+ # in switch classes to provide consistent behavior for querying switch states
20
+ # and outputting status messages.
21
+ #
22
+ # @example Checking switch states
23
+ # switch = OllamaChat::Switches::Switch.new(value: true, msg: { true => 'On', false => 'Off' })
24
+ # switch.on? # Returns true
25
+ # switch.off? # Returns false
2
26
  module CheckSwitch
3
27
  extend Tins::Concern
4
28
 
@@ -23,6 +47,19 @@ module OllamaChat::Switches
23
47
  end
24
48
  end
25
49
 
50
+ # A switch class that manages boolean state with toggle and set
51
+ # functionality.
52
+ #
53
+ # The Switch class provides a simple way to manage boolean configuration
54
+ # options with methods to toggle, set, and query the current state. It
55
+ # includes messaging capabilities to provide feedback when the state changes.
56
+ #
57
+ # @example Creating and using a switch
58
+ # switch = Switch.new(value: false, msg: { true => 'Enabled', false => 'Disabled' })
59
+ # switch.toggle # Turns the switch on
60
+ # switch.value # Returns true
61
+ # switch.off? # Returns false
62
+ # switch.on? # Returns true
26
63
  class Switch
27
64
  # The initialize method sets up the switch with a default value and
28
65
  # message.
@@ -64,6 +101,18 @@ module OllamaChat::Switches
64
101
  include CheckSwitch
65
102
  end
66
103
 
104
+ # A switch class that manages a boolean state based on a proc value.
105
+ #
106
+ # The CombinedSwitch class provides a way to manage a boolean configuration
107
+ # option where the state is determined by evaluating a stored proc. This is
108
+ # useful for complex conditions that depend on multiple factors or dynamic
109
+ # values, such as combining multiple switch states into a single effective
110
+ # state.
111
+ #
112
+ # @example Checking if embedding is currently performed
113
+ # # When embedding_enabled is true and embedding_paused is false,
114
+ # # the combined switch will return true
115
+ # combined_switch.value # => true
67
116
  class CombinedSwitch
68
117
  # The initialize method sets up the switch with a value and message.
69
118
  #
@@ -1,5 +1,20 @@
1
1
  require 'digest/md5'
2
2
 
3
+ # A cache fetcher implementation that handles caching of HTTP responses with
4
+ # content type metadata.
5
+ #
6
+ # This class provides a mechanism to store and retrieve cached HTTP responses,
7
+ # including their content types, using a key-based system. It is designed to
8
+ # work with various cache backends and ensures that both the response body and
9
+ # metadata are properly cached and retrieved for efficient subsequent requests.
10
+ #
11
+ # @example Using the CacheFetcher to cache and retrieve HTTP responses
12
+ # cache = Redis.new
13
+ # fetcher = OllamaChat::Utils::CacheFetcher.new(cache)
14
+ # fetcher.put('https://example.com', io)
15
+ # fetcher.get('https://example.com') do |cached_io|
16
+ # # Process cached content
17
+ # end
3
18
  class OllamaChat::Utils::CacheFetcher
4
19
  # The initialize method sets up the cache instance variable for the object.
5
20
  #
@@ -2,6 +2,22 @@ require 'amatch'
2
2
  require 'search_ui'
3
3
  require 'term/ansicolor'
4
4
 
5
+ # A module that provides interactive selection functionality using fuzzy
6
+ # matching and search capabilities.
7
+ #
8
+ # The Chooser module enables users to interactively select items from a list
9
+ # using a search interface with fuzzy matching. It leverages the Amatch library
10
+ # for similarity matching and SearchUI for the interactive display and
11
+ # selection experience.
12
+ #
13
+ # @example Using the chooser in an interactive menu
14
+ # entries = ['apple', 'banana', 'cherry']
15
+ # selected = OllamaChat::Utils::Chooser.choose(entries, prompt: 'Choose a fruit:')
16
+ #
17
+ # @example Returning immediately if only one entry exists
18
+ # entries = ['single_option']
19
+ # result = OllamaChat::Utils::Chooser.choose(entries, return_immediately: true)
20
+ # # Returns 'single_option' directly without user interaction
5
21
  module OllamaChat::Utils::Chooser
6
22
  class << self
7
23
  include SearchUI
@@ -5,7 +5,34 @@ require 'mime-types'
5
5
  require 'stringio'
6
6
  require 'ollama_chat/utils/cache_fetcher'
7
7
 
8
+ # A fetcher implementation that handles retrieval and caching of HTTP
9
+ # resources.
10
+ #
11
+ # This class provides functionality to fetch content from URLs, with support
12
+ # for caching responses and their metadata. It handles various content types
13
+ # and integrates with different cache backends to improve performance by
14
+ # avoiding redundant network requests.
15
+ #
16
+ # @example Fetching content from a URL with caching
17
+ # fetcher = OllamaChat::Utils::Fetcher.new(cache: redis_cache)
18
+ # fetcher.get('https://example.com/data.json') do |tmp|
19
+ # # Process the fetched content
20
+ # end
8
21
  class OllamaChat::Utils::Fetcher
22
+ # A module that extends IO objects with content type metadata and expiration
23
+ # tracking.
24
+ #
25
+ # This module provides a way to attach MIME content type information and
26
+ # cache expiration details to IO objects, enabling them to carry metadata
27
+ # about their source and caching behavior. It is primarily used by fetcher
28
+ # implementations to decorate response objects with additional context for
29
+ # processing and caching decisions.
30
+ #
31
+ # @example Extending an IO object with header metadata
32
+ # io = StringIO.new("content")
33
+ # io.extend(OllamaChat::Utils::Fetcher::HeaderExtension)
34
+ # io.content_type = MIME::Types['text/plain'].first
35
+ # io.ex = 3600
9
36
  module HeaderExtension
10
37
  # The content_type method accesses the content type attribute of the object.
11
38
  #
@@ -30,6 +57,18 @@ class OllamaChat::Utils::Fetcher
30
57
  end
31
58
  end
32
59
 
60
+ # A custom error class raised when retrying HTTP requests without streaming.
61
+ #
62
+ # This exception is specifically used in the Fetcher class to indicate that
63
+ # an HTTP request should be retried using a non-streaming approach when a
64
+ # streaming attempt fails or is not supported.
65
+ #
66
+ # @example Handling the RetryWithoutStreaming error
67
+ # begin
68
+ # fetcher.get('https://example.com')
69
+ # rescue RetryWithoutStreaming
70
+ # # Handle retry with non-streaming method
71
+ # end
33
72
  class RetryWithoutStreaming < StandardError; end
34
73
 
35
74
  # The get method retrieves content from a URL, using caching when available.
@@ -51,8 +90,9 @@ class OllamaChat::Utils::Fetcher
51
90
  def self.get(url, headers: {}, **options, &block)
52
91
  cache = options.delete(:cache) and
53
92
  cache = OllamaChat::Utils::CacheFetcher.new(cache)
93
+ cache and infobar.puts "Getting #{url.to_s.inspect} via cache…"
54
94
  if result = cache&.get(url, &block)
55
- infobar.puts "Getting #{url.to_s.inspect} from cache."
95
+ infobar.puts "…hit, found#{result.content_type} content in cache."
56
96
  return result
57
97
  else
58
98
  new(**options).send(:get, url, headers:) do |tmp|