ruby_llm-mongoid 0.1.0

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: faf4e9de8443c878f505ec2060a9eb6cb399f0137b6af8048c5071cf960d3f28
4
+ data.tar.gz: 34d9df17d8720aeda41fe9449c2f49d752a562a914898c22433f9683c2bb3e1e
5
+ SHA512:
6
+ metadata.gz: 5bcee2ff357b9420d83f37f2cb76afa35f03c5fa6efadae125e80011fe5ceebf2fb4e23a563cffd178db00b8f478a6fea9f08cf1f8781f74bcfa08db7d421402
7
+ data.tar.gz: ffe7ea01a5e0182ff3620861b86ab3d7e861104493762f72820740f58cb65bf8f16b76fd3e08d2c984c062eb71109150b382757b383c372ae8ce105e12849e9c
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,55 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.3
3
+ SuggestExtensions: false
4
+ NewCops: enable
5
+
6
+ Style/StringLiterals:
7
+ EnforcedStyle: double_quotes
8
+
9
+ Style/StringLiteralsInInterpolation:
10
+ EnforcedStyle: double_quotes
11
+
12
+ Style/Documentation:
13
+ Enabled: false
14
+
15
+ # Metrics are disabled for spec files (standard RuboCop convention).
16
+ Metrics/BlockLength:
17
+ Exclude:
18
+ - "spec/**/*"
19
+ - "lib/generators/**/*"
20
+ - "*.gemspec"
21
+
22
+ # The acts_as_* macros and the chat/model persistence methods are complex by
23
+ # design — they mirror the ruby_llm ActiveRecord integration and must handle
24
+ # many edge cases. Disable length/complexity metrics for these files.
25
+ Metrics/MethodLength:
26
+ Exclude:
27
+ - "lib/ruby_llm/mongoid/acts_as.rb"
28
+ - "lib/ruby_llm/mongoid/chat_methods.rb"
29
+ - "lib/ruby_llm/mongoid/grid_fs_attachment.rb"
30
+ - "lib/ruby_llm/mongoid/model_methods.rb"
31
+ - "lib/ruby_llm/mongoid/message_methods.rb"
32
+ - "spec/support/openai_stubs.rb"
33
+
34
+ Metrics/AbcSize:
35
+ Exclude:
36
+ - "lib/ruby_llm/mongoid/acts_as.rb"
37
+ - "lib/ruby_llm/mongoid/chat_methods.rb"
38
+ - "lib/ruby_llm/mongoid/grid_fs_attachment.rb"
39
+ - "lib/ruby_llm/mongoid/model_methods.rb"
40
+
41
+ Metrics/CyclomaticComplexity:
42
+ Exclude:
43
+ - "lib/ruby_llm/mongoid/chat_methods.rb"
44
+
45
+ Metrics/PerceivedComplexity:
46
+ Exclude:
47
+ - "lib/ruby_llm/mongoid/chat_methods.rb"
48
+
49
+ Metrics/ModuleLength:
50
+ Exclude:
51
+ - "lib/ruby_llm/mongoid/chat_methods.rb"
52
+
53
+ Metrics/ClassLength:
54
+ Exclude:
55
+ - "lib/ruby_llm/mongoid/acts_as.rb"
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.3.6
data/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-06-17
4
+
5
+ ### Added
6
+
7
+ - `acts_as_chat` macro — persists chat sessions to MongoDB with full parity to ruby_llm's ActiveRecord integration
8
+ - `acts_as_message` macro — persists messages with role, content, token counts, thinking fields, and tool-call associations
9
+ - `acts_as_tool_call` macro — persists provider-issued tool calls and links result messages via `parent_tool_call_id`
10
+ - `acts_as_model` macro — persists LLM model registry records; supports `refresh!` and `save_to_database`
11
+ - `RubyLLM::Mongoid::MongoidSource` — plugs into `RubyLLM.config.model_registry_source` for Mongoid-backed model registry
12
+ - `RubyLLM::Mongoid::Transaction` — wraps blocks in multi-document transactions with automatic fallback for standalone mongod
13
+ - `bin/rails g ruby_llm:mongoid:install` generator — creates model files with field declarations (no migrations needed)
14
+ - SimpleCov with ≥ 90% line and ≥ 50% branch coverage enforced on every CI run
15
+ - `RubyLLM::Mongoid::GridFsAttachment` concern — opt-in GridFS-backed file attachments with automatic cleanup on message/chat destroy
16
+ - Full RSpec suite against a real MongoDB 8.0 instance; spec_helper auto-starts a Docker container if none is reachable
17
+ - GitHub Actions `ci.yml` — tests on Ruby 3.2–3.4 with MongoDB 8.0, separate RuboCop lint job, coverage artifact upload
18
+ - GitHub Actions `release.yml` — automated gem publishing on `v*.*.*` tags
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 washu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,253 @@
1
+ # ruby_llm-mongoid
2
+
3
+ [![CI](https://github.com/washu/ruby_llm-mongoid/actions/workflows/ci.yml/badge.svg)](https://github.com/washu/ruby_llm-mongoid/actions/workflows/ci.yml)
4
+ [![Coverage Status](https://coveralls.io/repos/github/washu/ruby_llm-mongoid/badge.svg?branch=main)](https://coveralls.io/github/washu/ruby_llm-mongoid?branch=main)
5
+ [![Gem Version](https://img.shields.io/gem/v/ruby_llm-mongoid)](https://rubygems.org/gems/ruby_llm-mongoid)
6
+
7
+ Drop-in Mongoid persistence for [ruby_llm](https://github.com/crmne/ruby_llm). Use MongoDB as your Rails model layer instead of ActiveRecord — same `acts_as_chat` API, same feel.
8
+
9
+ ## Requirements
10
+
11
+ - Ruby >= 3.3
12
+ - Mongoid >= 8.0
13
+ - ruby_llm >= 1.16
14
+
15
+ ## Installation
16
+
17
+ Add to your Gemfile:
18
+
19
+ ```ruby
20
+ gem "ruby_llm-mongoid"
21
+ ```
22
+
23
+ ## Quick start
24
+
25
+ ### 1. Generate models
26
+
27
+ ```bash
28
+ bin/rails g ruby_llm:mongoid:install
29
+ ```
30
+
31
+ This creates four model files (`Chat`, `Message`, `ToolCall`, `LlmModel`) and `config/initializers/ruby_llm.rb`. No migrations — Mongoid is schemaless; fields are declared in the model files.
32
+
33
+ ### 2. Create indexes
34
+
35
+ ```bash
36
+ bin/rails db:mongoid:create_indexes
37
+ ```
38
+
39
+ ### 3. Configure API keys
40
+
41
+ Edit `config/initializers/ruby_llm.rb`:
42
+
43
+ ```ruby
44
+ RubyLLM.configure do |config|
45
+ config.openai_api_key = ENV["OPENAI_API_KEY"]
46
+ config.anthropic_api_key = ENV["ANTHROPIC_API_KEY"]
47
+ end
48
+ ```
49
+
50
+ ### 4. Seed the model registry
51
+
52
+ ```bash
53
+ bin/rails runner "LlmModel.save_to_database"
54
+ ```
55
+
56
+ This populates MongoDB with the bundled model list so `Chat.create!(model: "gpt-4o-mini")` can resolve the model record.
57
+
58
+ ### 5. Start chatting
59
+
60
+ ```ruby
61
+ chat = Chat.create!(model: "gpt-4o-mini")
62
+ chat.ask("What is the capital of France?")
63
+ # => saves user + assistant messages to MongoDB
64
+ ```
65
+
66
+ ## Model setup
67
+
68
+ ### Default (generated) layout
69
+
70
+ ```ruby
71
+ class Chat
72
+ include Mongoid::Document
73
+ include Mongoid::Timestamps
74
+
75
+ acts_as_chat model: :llm_model, model_class: "LlmModel"
76
+ end
77
+
78
+ class Message
79
+ include Mongoid::Document
80
+ include Mongoid::Timestamps
81
+
82
+ field :role, type: String
83
+ field :content, type: String
84
+ field :input_tokens, type: Integer
85
+ field :output_tokens, type: Integer
86
+ # ...additional token/thinking fields
87
+
88
+ acts_as_message model: :llm_model, model_class: "LlmModel"
89
+ end
90
+
91
+ class ToolCall
92
+ include Mongoid::Document
93
+ include Mongoid::Timestamps
94
+
95
+ field :tool_call_id, type: String
96
+ field :name, type: String
97
+ field :arguments, type: Hash, default: {}
98
+
99
+ acts_as_tool_call
100
+ end
101
+
102
+ class LlmModel
103
+ include Mongoid::Document
104
+ include Mongoid::Timestamps
105
+
106
+ field :model_id, type: String
107
+ field :name, type: String
108
+ field :provider, type: String
109
+ # ...pricing/capability fields
110
+
111
+ acts_as_model
112
+ end
113
+ ```
114
+
115
+ ### Custom class / association names
116
+
117
+ ```ruby
118
+ class Conversation
119
+ include Mongoid::Document
120
+
121
+ acts_as_chat messages: :turns,
122
+ message_class: "Turn",
123
+ model: :ai_model,
124
+ model_class: "AiModel"
125
+ end
126
+ ```
127
+
128
+ ## API reference
129
+
130
+ ### Chat
131
+
132
+ ```ruby
133
+ chat = Chat.create!(model: "gpt-4o-mini")
134
+ chat = Chat.create!(model: "claude-opus-4-7", provider: "anthropic")
135
+
136
+ chat.ask("Hello!")
137
+ chat.say("Hello!") # alias for ask
138
+
139
+ chat.with_instructions("You are a helpful assistant.")
140
+ chat.with_instructions("More context.", append: true)
141
+ chat.with_runtime_instructions("Only reply in French.") # not persisted to DB
142
+
143
+ chat.with_model("claude-opus-4-7")
144
+ chat.with_tool(MyTool)
145
+ chat.with_tools(ToolA, ToolB)
146
+ chat.with_temperature(0.7)
147
+ chat.with_thinking(budget: 5000)
148
+
149
+ chat.on_new_message { |msg| puts msg.content }
150
+ chat.on_end_message { |msg| broadcast(msg) }
151
+
152
+ chat.cost # => RubyLLM::Cost
153
+ ```
154
+
155
+ ### Message
156
+
157
+ ```ruby
158
+ msg = chat.messages_association.last
159
+ msg.to_llm # => RubyLLM::Message
160
+ msg.tokens # => RubyLLM::Tokens
161
+ msg.cost # => RubyLLM::Cost
162
+ msg.to_partial_path # => "messages/assistant"
163
+ ```
164
+
165
+ ### Model registry
166
+
167
+ `acts_as_model` automatically registers a `MongoidSource` with `RubyLLM.config.model_registry_source`, so `RubyLLM.models` reads from MongoDB on boot instead of the bundled JSON file.
168
+
169
+ ```ruby
170
+ LlmModel.save_to_database # seed MongoDB from the bundled model registry (run once after install)
171
+ LlmModel.refresh! # fetch the latest list from all providers, then persist to MongoDB
172
+ ```
173
+
174
+ Both methods are idempotent — `refresh!` is a good candidate for a periodic background job or a deploy hook.
175
+
176
+ ## Differences from ActiveRecord integration
177
+
178
+ | Concern | ActiveRecord | Mongoid (this gem) |
179
+ |---|---|---|
180
+ | Primary key type | integer | BSON::ObjectId |
181
+ | Tool-call result FK field | `tool_call_id` (integer) | `parent_tool_call_id` (ObjectId) |
182
+ | Transactions | native | requires replica set; auto no-op on standalone |
183
+ | File attachments | ActiveStorage | GridFS via `GridFsAttachment` concern |
184
+ | `has_many :through` | supported | replaced by direct queries |
185
+
186
+ ### `parent_tool_call_id` field name
187
+
188
+ In the ActiveRecord integration the FK column linking a tool-result message back to its ToolCall is named `tool_call_id` (integer). Mongoid uses `parent_tool_call_id` (BSON::ObjectId) to avoid a type collision with the string `tool_call_id` field that stores the provider-issued call ID. This is handled automatically — you don't need to think about it unless you are writing raw queries.
189
+
190
+ ## Transactions
191
+
192
+ Multi-document transactions require a MongoDB **replica set** or Atlas cluster. On a standalone `mongod` the transaction helper automatically falls back to running the block without a transaction — useful for development and testing.
193
+
194
+ For production, run at minimum a single-node replica set:
195
+
196
+ ```bash
197
+ # mongod.conf: add replication.replSetName: "rs0"
198
+ mongosh --eval "rs.initiate()"
199
+ ```
200
+
201
+ ## File attachments (GridFS)
202
+
203
+ Include `RubyLLM::Mongoid::GridFsAttachment` in your message model to store attachments in MongoDB's native GridFS bucket instead of ActiveStorage:
204
+
205
+ ```ruby
206
+ class Message
207
+ include Mongoid::Document
208
+ include Mongoid::Timestamps
209
+ include RubyLLM::Mongoid::GridFsAttachment
210
+
211
+ field :role, type: String
212
+ field :content, type: String
213
+ # ...other fields
214
+
215
+ acts_as_message model: :llm_model, model_class: "LlmModel"
216
+ end
217
+ ```
218
+
219
+ Then pass files to `ask` the same way you would with the ActiveRecord integration:
220
+
221
+ ```ruby
222
+ chat.ask("What's in this image?", with: [params[:file]])
223
+ chat.ask("Summarise this PDF.", with: ["/path/to/doc.pdf"])
224
+ ```
225
+
226
+ Files are stored in a GridFS bucket named `"attachments"` by default. Change it per model:
227
+
228
+ ```ruby
229
+ class Message
230
+ include RubyLLM::Mongoid::GridFsAttachment
231
+ use_gridfs_bucket :llm_files
232
+ end
233
+ ```
234
+
235
+ GridFS files are automatically deleted when the owning message or its parent chat is destroyed.
236
+
237
+ ## Testing
238
+
239
+ ```bash
240
+ bundle exec rspec
241
+ ```
242
+
243
+ The spec_helper checks whether MongoDB is reachable on `localhost:27017`. If nothing is listening it starts a `mongo:8.0` Docker container automatically and stops it when the suite exits. You don't need to start MongoDB manually.
244
+
245
+ The suite uses `database_cleaner-mongoid` for collection-level isolation between examples. LLM HTTP calls are stubbed with WebMock — no real API keys required.
246
+
247
+ ## Contributing
248
+
249
+ Bug reports and pull requests welcome at [github.com/SalScotto/ruby_llm-mongoid](https://github.com/SalScotto/ruby_llm-mongoid).
250
+
251
+ ## License
252
+
253
+ MIT — see [LICENSE.txt](LICENSE.txt).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/build_release.sh ADDED
@@ -0,0 +1,38 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+
4
+ # Maintainer release helper.
5
+ #
6
+ # Usage:
7
+ # SKIP_PUSH=1 ./build_release.sh # build and verify only
8
+ # ./build_release.sh # build, then let `gem push` prompt for MFA
9
+ # GEM_HOST_OTP=123456 ./build_release.sh # build and publish with explicit OTP
10
+
11
+ ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
12
+ cd "$ROOT_DIR"
13
+
14
+ VERSION="$(ruby -r ./lib/ruby_llm/mongoid/version.rb -e 'puts RubyLLM::Mongoid::VERSION')"
15
+ GEM_FILE="ruby_llm-mongoid-${VERSION}.gem"
16
+
17
+ echo "Building gem version ${VERSION}..."
18
+ rm -f "$GEM_FILE"
19
+ gem build ruby_llm-mongoid.gemspec
20
+
21
+ if [[ ! -f "$GEM_FILE" ]]; then
22
+ echo "Expected gem file not found: $GEM_FILE" >&2
23
+ exit 1
24
+ fi
25
+
26
+ if [[ "${SKIP_PUSH:-0}" == "1" ]]; then
27
+ echo "SKIP_PUSH=1 set; build verified, skipping publish."
28
+ exit 0
29
+ fi
30
+
31
+ echo "Pushing $GEM_FILE to RubyGems..."
32
+ if [[ -n "${GEM_HOST_OTP:-}" ]]; then
33
+ gem push "$GEM_FILE" --otp "$GEM_HOST_OTP"
34
+ else
35
+ gem push "$GEM_FILE"
36
+ fi
37
+
38
+ echo "Done!"
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ module RubyLLM
6
+ module Generators
7
+ module Mongoid
8
+ # Generator that scaffolds Mongoid model files for ruby_llm-mongoid.
9
+ # Unlike the ActiveRecord generator there are no migrations — Mongoid models
10
+ # declare their fields inline.
11
+ #
12
+ # Usage:
13
+ # bin/rails g ruby_llm:mongoid:install [chat:ChatName] [message:MessageName] ...
14
+ class InstallGenerator < Rails::Generators::Base
15
+ namespace "ruby_llm:mongoid:install"
16
+
17
+ source_root File.expand_path("templates", __dir__)
18
+
19
+ argument :model_mappings, type: :array, default: [],
20
+ banner: "chat:ChatName message:MessageName ..."
21
+
22
+ desc "Creates Mongoid model files for the ruby_llm-mongoid integration."
23
+
24
+ def create_model_files
25
+ template "chat_model.rb.tt", "app/models/#{chat_model_name.underscore}.rb"
26
+ template "message_model.rb.tt", "app/models/#{message_model_name.underscore}.rb"
27
+ template "tool_call_model.rb.tt", "app/models/#{tool_call_model_name.underscore}.rb"
28
+ template "model_model.rb.tt", "app/models/#{model_model_name.underscore}.rb"
29
+ end
30
+
31
+ def create_initializer
32
+ template "initializer.rb.tt", "config/initializers/ruby_llm.rb"
33
+ end
34
+
35
+ def create_convention_directories
36
+ %w[agents tools schemas prompts].each do |name|
37
+ empty_directory "app/#{name}"
38
+ end
39
+ end
40
+
41
+ def show_install_info
42
+ say "\n ruby_llm-mongoid installed!", :green
43
+ say "\n Next steps:", :yellow
44
+ say " 1. Ensure mongoid.yml is configured (bin/rails g mongoid:config)"
45
+ say " 2. Run: bin/rails ruby_llm:mongoid:create_indexes"
46
+ say " 3. Set your API keys in config/initializers/ruby_llm.rb"
47
+ say " 4. Start chatting: #{chat_model_name}.create!(model: 'gpt-4.1-nano').ask('Hello!')"
48
+ say "\n Documentation: https://github.com/SalScotto/ruby_llm-mongoid\n", :cyan
49
+ end
50
+
51
+ private
52
+
53
+ def mappings
54
+ @mappings ||= parse_mappings
55
+ end
56
+
57
+ def parse_mappings
58
+ result = { "chat" => "Chat", "message" => "Message",
59
+ "tool_call" => "ToolCall", "model" => "LlmModel" }
60
+ model_mappings.each do |pair|
61
+ key, value = pair.split(":")
62
+ result[key] = value if key && value
63
+ end
64
+ result
65
+ end
66
+
67
+ def chat_model_name
68
+ mappings.fetch("chat", "Chat")
69
+ end
70
+
71
+ def message_model_name
72
+ mappings.fetch("message", "Message")
73
+ end
74
+
75
+ def tool_call_model_name
76
+ mappings.fetch("tool_call", "ToolCall")
77
+ end
78
+
79
+ def model_model_name
80
+ mappings.fetch("model", "LlmModel")
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,6 @@
1
+ class <%= chat_model_name %>
2
+ include Mongoid::Document
3
+ include Mongoid::Timestamps
4
+
5
+ acts_as_chat
6
+ end
@@ -0,0 +1,6 @@
1
+ RubyLLM.configure do |config|
2
+ config.openai_api_key = ENV.fetch("OPENAI_API_KEY", nil)
3
+ config.anthropic_api_key = ENV.fetch("ANTHROPIC_API_KEY", nil)
4
+ # config.default_model = "gpt-4.1-nano"
5
+ # config.model_registry_class = "<%= model_model_name %>"
6
+ end
@@ -0,0 +1,21 @@
1
+ class <%= message_model_name %>
2
+ include Mongoid::Document
3
+ include Mongoid::Timestamps
4
+
5
+ field :role, type: String
6
+ field :content, type: String
7
+ field :content_raw, type: Hash
8
+ field :thinking_text, type: String
9
+ field :thinking_signature, type: String
10
+ field :thinking_tokens, type: Integer
11
+ field :input_tokens, type: Integer
12
+ field :output_tokens, type: Integer
13
+ field :cached_tokens, type: Integer
14
+ field :cache_creation_tokens, type: Integer
15
+
16
+ index({ role: 1 })
17
+ index({ created_at: 1 })
18
+ index({ parent_tool_call_id: 1 }, sparse: true)
19
+
20
+ acts_as_message
21
+ end