intelligent 0.0.1

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: d6f01b278dcd2e68e01190a26a071c26efa6bde5d908bf92cdcccc374d877f27
4
+ data.tar.gz: 66965f55b534c1ff58d2acc3f7fa4d0ea56cfeff259ae6e13c83f69e5eff2030
5
+ SHA512:
6
+ metadata.gz: d8e1c319d236eb519e1b3e477f26a1eb682e49f940184d07ea987c10e7cec7b661d6cc8e4461a38ed8ba00fa29a800236292936630255f5c3bfee4e63ef42e62
7
+ data.tar.gz: 6bd03565495182c6c0702d890b3ba0aab2b1554015eed89c564f7c26a844dc7713066669fbb19f63b328ed1929033f4c9650d26405efbf9dc4140f7846c252e1
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --require spec_helper
2
+ --color
3
+ --format documentation
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.2.6
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-07-18
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at uysimty@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Uysim
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,212 @@
1
+ # Intelligent
2
+
3
+ A Ruby gem that provides intelligent text generation using LLMs (Large Language Models) with support for prompt templating, file attachments, and sequential thinking.
4
+
5
+ ## Features
6
+
7
+ - **Prompt Templating**: Use `{{variable}}` syntax to create dynamic prompts
8
+ - **Multiple LLM Models**: Support for various Claude models (Sonnet, Opus, Haiku)
9
+ - **File Attachments**: Attach images, text files, and PDFs to your prompts
10
+ - **Sequential Thinking**: Enable step-by-step reasoning for complex problems
11
+ - **Error Handling**: Robust error handling with detailed feedback
12
+ - **Variable Validation**: Automatic validation of required prompt variables
13
+
14
+ ## Installation
15
+
16
+ Add this line to your application's Gemfile:
17
+
18
+ ```ruby
19
+ gem 'intelligent'
20
+ ```
21
+
22
+ And then execute:
23
+
24
+ ```bash
25
+ $ bundle install
26
+ ```
27
+
28
+ Or install it yourself as:
29
+
30
+ ```bash
31
+ $ gem install intelligent
32
+ ```
33
+
34
+ ## Configuration
35
+
36
+ Set your Anthropic API key as an environment variable:
37
+
38
+ ```bash
39
+ export ANTHROPIC_API_KEY="your-api-key-here"
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ ### Basic Usage
45
+
46
+ ```ruby
47
+ require 'intelligent'
48
+
49
+ # Simple text generation
50
+ result = Intelligent.generate(
51
+ prompt: "Write a short story about {{character}} who {{action}}",
52
+ variables: {
53
+ character: "a brave knight",
54
+ action: "discovers a magical sword"
55
+ },
56
+ llm_model: "claude-sonnet-4-20250514"
57
+ )
58
+
59
+ if result[:success]
60
+ puts result[:generated_text]
61
+ else
62
+ puts "Error: #{result[:error]}"
63
+ end
64
+ ```
65
+
66
+ ### With File Attachments
67
+
68
+ ```ruby
69
+ # Attach files to your prompt
70
+ files = [
71
+ File.open("document.pdf"),
72
+ File.open("image.png")
73
+ ]
74
+
75
+ result = Intelligent.generate(
76
+ prompt: "Analyze this {{document_type}} and summarize the key points",
77
+ variables: { document_type: "financial report" },
78
+ llm_model: "claude-opus-4-20250514",
79
+ files: files
80
+ )
81
+ ```
82
+
83
+ ### Sequential Thinking
84
+
85
+ For complex problems that require step-by-step reasoning:
86
+
87
+ ```ruby
88
+ result = Intelligent.generate(
89
+ prompt: "Solve this math problem: {{problem}}",
90
+ variables: { problem: "If a train travels 120 km in 2 hours, what is its speed?" },
91
+ llm_model: "claude-sonnet-4-20250514",
92
+ use_sequential_thinking: true
93
+ )
94
+
95
+ if result[:success]
96
+ puts "Final Answer: #{result[:generated_text]}"
97
+ puts "\nThinking Process:"
98
+ result[:thoughts].each do |thought|
99
+ puts "Step #{thought[:number]}: #{thought[:content]}"
100
+ end
101
+ end
102
+ ```
103
+
104
+ ### Available Models
105
+
106
+ ```ruby
107
+ # Get available models
108
+ models = Intelligent::Llm::Anthropic.available_models
109
+ models.each do |model_id, description|
110
+ puts "#{model_id}: #{description}"
111
+ end
112
+
113
+ # Available models:
114
+ # "claude-sonnet-4-20250514": "Claude Sonnet 4 (Recommended)"
115
+ # "claude-opus-4-20250514": "Claude Opus 4 (Most Capable)"
116
+ # "claude-3-7-sonnet-20250219": "Claude Sonnet 3.7 (Fast)"
117
+ # "claude-3-5-haiku-20241022": "Claude Haiku 3.5 (Fastest)"
118
+ ```
119
+
120
+ ### Advanced Prompt Templates
121
+
122
+ ```ruby
123
+ # Complex prompt with multiple variables
124
+ prompt = <<~PROMPT
125
+ You are a {{role}} expert.
126
+
127
+ Task: {{task}}
128
+
129
+ Context: {{context}}
130
+
131
+ Requirements:
132
+ - {{requirement1}}
133
+ - {{requirement2}}
134
+
135
+ Please provide a detailed response.
136
+ PROMPT
137
+
138
+ variables = {
139
+ role: "software architect",
140
+ task: "design a microservices architecture",
141
+ context: "e-commerce platform with 10,000 daily users",
142
+ requirement1: "high availability",
143
+ requirement2: "scalable design"
144
+ }
145
+
146
+ result = Intelligent.generate(
147
+ prompt: prompt,
148
+ variables: variables,
149
+ llm_model: "claude-opus-4-20250514"
150
+ )
151
+ ```
152
+
153
+ ## API Reference
154
+
155
+ ### `Intelligent.generate`
156
+
157
+ Main method for generating text with LLMs.
158
+
159
+ **Parameters:**
160
+ - `prompt` (String): The prompt template with optional `{{variable}}` placeholders
161
+ - `variables` (Hash): Variables to substitute in the prompt template
162
+ - `llm_model` (String): The LLM model to use (see available models above)
163
+ - `use_sequential_thinking` (Boolean, optional): Enable step-by-step reasoning (default: false)
164
+ - `files` (Array, optional): Array of File objects to attach to the prompt
165
+
166
+ **Returns:**
167
+ - Hash with the following structure:
168
+ - `success` (Boolean): Whether the generation was successful
169
+ - `generated_text` (String): The generated text (if successful)
170
+ - `thoughts` (Array): Array of thinking steps (if sequential thinking was used)
171
+ - `error` (String): Error message (if failed)
172
+
173
+ ## Supported File Types
174
+
175
+ - **Images**: JPG, JPEG, PNG, GIF, WebP
176
+ - **Text Files**: TXT, MD, RB, PY, JS, HTML, CSS, JSON, XML, YAML, YML
177
+ - **Documents**: PDF
178
+
179
+ ## Error Handling
180
+
181
+ The gem provides comprehensive error handling:
182
+
183
+ ```ruby
184
+ result = Intelligent.generate(
185
+ prompt: "Hello {{name}}",
186
+ variables: {}, # Missing required variable
187
+ llm_model: "claude-sonnet-4-20250514"
188
+ )
189
+
190
+ if !result[:success]
191
+ puts "Error: #{result[:error]}"
192
+ # Output: Error: Missing required variables: name
193
+ end
194
+ ```
195
+
196
+ ## Development
197
+
198
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
199
+
200
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
201
+
202
+ ## Contributing
203
+
204
+ Bug reports and pull requests are welcome on GitHub at https://github.com/uysim/intelligent. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/uysim/intelligent/blob/main/CODE_OF_CONDUCT.md).
205
+
206
+ ## License
207
+
208
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
209
+
210
+ ## Code of Conduct
211
+
212
+ Everyone interacting in the Intelligent project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/uysim/intelligent/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ task default: %i[]
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/intelligent/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "intelligent"
7
+ spec.version = Intelligent::VERSION
8
+ spec.authors = ["Uysim"]
9
+ spec.email = ["uysimty@gmail.com"]
10
+
11
+ spec.summary = "Add intelligent to your Ruby engine"
12
+ spec.description = "Add intelligent to your Ruby engine"
13
+ spec.homepage = "https://github.com/uysim/intelligent"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.2.0"
16
+
17
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = "https://github.com/uysim/intelligent"
21
+ spec.metadata["changelog_uri"] = "https://github.com/uysim/intelligent/blob/main/CHANGELOG.md"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(__dir__) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (File.expand_path(f) == __FILE__) ||
28
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor Gemfile])
29
+ end
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+ # Uncomment to register a new dependency of your gem
36
+ # spec.add_dependency "example-gem", "~> 1.0"
37
+
38
+ # For more information and examples about making a new gem, check out our
39
+ # guide at: https://bundler.io/guides/creating_gem.html
40
+
41
+ spec.add_dependency "anthropic", ">= 1.1"
42
+ spec.add_dependency "pry", "~> 0.14.1"
43
+ spec.add_development_dependency "rspec", "~> 3.12"
44
+
45
+ end
@@ -0,0 +1,59 @@
1
+ require_relative "prompt"
2
+ require_relative "sequential_thinking"
3
+ require_relative "llm/anthropic"
4
+
5
+ module Intelligent
6
+ class Generation
7
+ attr_reader :prompt, :input_variables, :model, :use_sequential_thinking, :files
8
+
9
+ def initialize(prompt, input_variables, llm_model, use_sequential_thinking = false, files = nil)
10
+ @prompt = Prompt.new(prompt)
11
+ @input_variables = input_variables
12
+ @prompt.validate_variables!(@input_variables)
13
+
14
+ @model = llm_model
15
+ @use_sequential_thinking = use_sequential_thinking
16
+ @files = files
17
+ end
18
+
19
+ def call
20
+ @generated_prompt = @prompt.process_content(@input_variables)
21
+
22
+ begin
23
+ return generate_with_sequential_thinking(@generated_prompt, files) if @use_sequential_thinking
24
+
25
+ generate_with_llm(@generated_prompt, files)
26
+ rescue => e
27
+ { success: false, error: e.message, generated_prompt: @generated_prompt }
28
+ end
29
+ end
30
+
31
+ private
32
+
33
+ def use_sequential_thinking?
34
+ @use_sequential_thinking
35
+ end
36
+
37
+ def generate_with_sequential_thinking(processed_content, all_files)
38
+ thinking_service = SequentialThinking.new(model: @model)
39
+ result = thinking_service.think_through_problem(processed_content, all_files)
40
+
41
+ if result[:success]
42
+ { success: true, generated_text: result[:final_text], thoughts: result[:thoughts] }
43
+ else
44
+ { success: false, error: result[:error], generated_prompt: @generated_prompt }
45
+ end
46
+ end
47
+
48
+ def generate_with_llm(processed_content, all_files)
49
+ llm_service = Llm::Anthropic.new(model: @model)
50
+ result = llm_service.generate(processed_content, all_files)
51
+
52
+ if result[:success]
53
+ { success: true, generated_text: result[:text] }
54
+ else
55
+ { success: false, error: result[:error], generation: @generation }
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,126 @@
1
+ require "anthropic"
2
+ require_relative "base"
3
+
4
+ module Intelligent
5
+ module Llm
6
+ class Anthropic < Base
7
+ def self.available_models
8
+ {
9
+ "claude-sonnet-4-20250514" => "Claude Sonnet 4 (Recommended)",
10
+ "claude-opus-4-20250514" => "Claude Opus 4 (Most Capable)",
11
+ "claude-3-7-sonnet-20250219" => "Claude Sonnet 3.7 (Fast)",
12
+ "claude-3-5-haiku-20241022" => "Claude Haiku 3.5 (Fastest)"
13
+ }
14
+ end
15
+
16
+ def self.default_model
17
+ "claude-sonnet-4-20250514"
18
+ end
19
+
20
+ def initialize(model: self.class.default_model)
21
+ super(provider: "anthropic", model: model)
22
+ @client = ::Anthropic::Client.new(api_key: api_key)
23
+ end
24
+
25
+ def generate(prompt_content, files = [])
26
+ raise ArgumentError, "API key not configured" unless api_key_present?
27
+
28
+ # Prepare message content
29
+ content = [ { type: "text", text: prompt_content } ]
30
+
31
+ # Add files to content if provided
32
+ if files && !files.empty?
33
+ files.each do |file|
34
+ file_content = prepare_file_content(file)
35
+ content << file_content if file_content
36
+ end
37
+ end
38
+
39
+ begin
40
+
41
+
42
+ response = @client.messages.create(
43
+ model: model,
44
+ max_tokens: 4000,
45
+ messages: [
46
+ {
47
+ role: "user",
48
+ content: content
49
+ }
50
+ ]
51
+ )
52
+
53
+ {
54
+ success: true,
55
+ text: response.content.first.text,
56
+ usage: response.usage&.to_h
57
+ }
58
+ rescue ::Anthropic::Errors::APIError => e
59
+ {
60
+ error: "API request failed: #{e.message}",
61
+ status: e.status
62
+ }
63
+ rescue => e
64
+ { error: "Request failed: #{e.message}" }
65
+ end
66
+ end
67
+
68
+ private
69
+
70
+ def prepare_file_content(file)
71
+ # Determine content type from file extension
72
+ content_type = determine_content_type(file.path)
73
+
74
+ case content_type
75
+ when /^image\//
76
+ # For images, we need to encode as base64
77
+ {
78
+ type: "image",
79
+ source: {
80
+ type: "base64",
81
+ media_type: content_type,
82
+ data: Base64.strict_encode64(file.read)
83
+ }
84
+ }
85
+ when /^text\//
86
+ # For text files, we can include the content directly
87
+ {
88
+ type: "text",
89
+ text: file.read.dup.force_encoding("UTF-8")
90
+ }
91
+ when "application/pdf"
92
+ # For PDFs, use the document content type with base64 encoding
93
+ {
94
+ type: "document",
95
+ source: {
96
+ type: "base64",
97
+ media_type: "application/pdf",
98
+ data: Base64.strict_encode64(file.read)
99
+ }
100
+ }
101
+ else
102
+ raise "Unsupported file type: #{content_type} for file: #{file.path}"
103
+ end
104
+ end
105
+
106
+ def determine_content_type(file_path)
107
+ case File.extname(file_path).downcase
108
+ when '.jpg', '.jpeg'
109
+ 'image/jpeg'
110
+ when '.png'
111
+ 'image/png'
112
+ when '.gif'
113
+ 'image/gif'
114
+ when '.webp'
115
+ 'image/webp'
116
+ when '.txt', '.md', '.rb', '.py', '.js', '.html', '.css', '.json', '.xml', '.yaml', '.yml'
117
+ 'text/plain'
118
+ when '.pdf'
119
+ 'application/pdf'
120
+ else
121
+ 'application/octet-stream'
122
+ end
123
+ end
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,31 @@
1
+ module Intelligent
2
+ module Llm
3
+ class Base
4
+ attr_reader :provider, :model
5
+
6
+ def initialize(provider: "anthropic", model: "claude-sonnet-4-20250514")
7
+ @provider = provider
8
+ @model = model
9
+ end
10
+
11
+ def generate(prompt_content, files = [])
12
+ raise NotImplementedError, "Subclasses must implement generate method"
13
+ end
14
+
15
+ protected
16
+
17
+ def api_key
18
+ case provider
19
+ when "anthropic"
20
+ ENV["ANTHROPIC_API_KEY"]
21
+ else
22
+ raise ArgumentError, "Unsupported provider: #{provider}"
23
+ end
24
+ end
25
+
26
+ def api_key_present?
27
+ !api_key.nil? && !api_key.empty?
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,29 @@
1
+ module Intelligent
2
+ class Prompt
3
+ attr_reader :content
4
+
5
+ def initialize(content)
6
+ @content = content
7
+ end
8
+
9
+
10
+ def extract_variables
11
+ @content.scan(/\{\{(\w+)\}\}/).flatten.uniq
12
+ end
13
+
14
+ def process_content(input_variables = {})
15
+ processed_content = content.dup
16
+ input_variables.each do |key, value|
17
+ processed_content.gsub!("{{#{key}}}", value.to_s)
18
+ end
19
+ processed_content
20
+ end
21
+
22
+ def validate_variables!(input_variables)
23
+ missing_vars = extract_variables - input_variables.keys
24
+ if missing_vars.any?
25
+ raise "Missing required variables: #{missing_vars.join(', ')}"
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,112 @@
1
+ module Intelligent
2
+ class SequentialThinking
3
+ def initialize(model: "claude-sonnet-4-20250514")
4
+ @model = model
5
+ @anthropic_service = Llm::Anthropic.new(model: model)
6
+ end
7
+
8
+ def think_through_problem(problem_description, files = [], max_thoughts = 5)
9
+ thoughts = []
10
+ current_thought = 1
11
+ total_thoughts = max_thoughts
12
+
13
+ loop do
14
+ # Build the thinking prompt
15
+ thinking_prompt = build_thinking_prompt(problem_description, thoughts, current_thought, total_thoughts)
16
+
17
+ # Generate the next thought with files
18
+ result = @anthropic_service.generate(thinking_prompt, files)
19
+
20
+ if result[:success]
21
+ thought_content = result[:text]
22
+ thoughts << {
23
+ number: current_thought,
24
+ content: thought_content,
25
+ timestamp: Time.now
26
+ }
27
+
28
+ # Check if we need more thoughts
29
+ needs_more = analyze_thought_completeness(thought_content, current_thought, total_thoughts)
30
+
31
+ break if !needs_more || current_thought >= total_thoughts
32
+ current_thought += 1
33
+ else
34
+ return { success: false, error: result[:error] }
35
+ end
36
+ end
37
+
38
+ # Generate final answer directly from thinking process
39
+ final_answer = generate_final_answer(problem_description, thoughts, files)
40
+
41
+ if final_answer[:success]
42
+ {
43
+ success: true,
44
+ thoughts: thoughts,
45
+ final_text: final_answer[:text]
46
+ }
47
+ else
48
+ { success: false, error: final_answer[:error] }
49
+ end
50
+ end
51
+
52
+ private
53
+
54
+ def build_thinking_prompt(problem, thoughts, current_thought, total_thoughts)
55
+ previous_thoughts = thoughts.map { |t| "Thought #{t[:number]}: #{t[:content]}" }.join("\n")
56
+
57
+ <<~PROMPT
58
+ You are using a sequential thinking process to solve a complex problem.
59
+ Think through this step by step, one thought at a time.
60
+
61
+ Problem: #{problem}
62
+
63
+ #{previous_thoughts.empty? ? '' : "Previous thoughts:\n#{previous_thoughts}\n"}
64
+
65
+ You are currently on Thought #{current_thought} of #{total_thoughts}.
66
+
67
+ Instructions:
68
+ 1. Provide your next logical thought step
69
+ 2. Be specific and actionable
70
+ 3. Build upon previous thoughts
71
+ 4. If this is your final thought, clearly state your conclusion
72
+ 5. If you need more thoughts, indicate what still needs to be addressed
73
+
74
+ Thought #{current_thought}:
75
+ PROMPT
76
+ end
77
+
78
+ def analyze_thought_completeness(thought_content, current_thought, total_thoughts)
79
+ # Simple heuristic: if the thought mentions conclusion, final answer, or summary
80
+ conclusion_indicators = [ "conclusion", "final answer", "summary", "therefore", "thus", "in conclusion" ]
81
+
82
+ has_conclusion = conclusion_indicators.any? { |indicator| thought_content.downcase.include?(indicator) }
83
+
84
+ # Continue if no conclusion and we haven't reached max thoughts
85
+ !has_conclusion && current_thought < total_thoughts
86
+ end
87
+
88
+ def generate_final_answer(problem_description, thoughts, files)
89
+ thinking_summary = thoughts.map { |t| "Step #{t[:number]}: #{t[:content]}" }.join("\n")
90
+
91
+ final_prompt = <<~PROMPT
92
+ Based on your step-by-step thinking process below, provide ONLY the final answer to the original problem. Do not include any thinking process, explanations, or meta-commentary.
93
+
94
+ Original Problem: #{problem_description}
95
+
96
+ Your Thinking Process:
97
+ #{thinking_summary}
98
+
99
+ Instructions:
100
+ 1. Provide ONLY the final answer
101
+ 2. Do not include phrases like "Based on my analysis" or "Therefore"
102
+ 3. Do not explain your reasoning
103
+ 4. Give a direct, actionable response
104
+ 5. Be concise and to the point
105
+
106
+ Final Answer:
107
+ PROMPT
108
+
109
+ @anthropic_service.generate(final_prompt, files)
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Intelligent
4
+ VERSION = "0.0.1"
5
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "intelligent/version"
4
+ require_relative "intelligent/generation"
5
+
6
+ module Intelligent
7
+ class Error < StandardError; end
8
+
9
+ def self.generate(
10
+ prompt:,
11
+ variables:,
12
+ llm_model:,
13
+ use_sequential_thinking: false,
14
+ files: nil
15
+ )
16
+ generation = Generation.new(prompt, variables, llm_model, use_sequential_thinking, files)
17
+ generation.call
18
+ end
19
+ end
@@ -0,0 +1,4 @@
1
+ module Intelligent
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,105 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: intelligent
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Uysim
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-07-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: anthropic
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '1.1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '1.1'
27
+ - !ruby/object:Gem::Dependency
28
+ name: pry
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 0.14.1
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 0.14.1
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.12'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.12'
55
+ description: Add intelligent to your Ruby engine
56
+ email:
57
+ - uysimty@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".rspec"
63
+ - ".ruby-version"
64
+ - CHANGELOG.md
65
+ - CODE_OF_CONDUCT.md
66
+ - LICENSE.txt
67
+ - README.md
68
+ - Rakefile
69
+ - intelligent.gemspec
70
+ - lib/intelligent.rb
71
+ - lib/intelligent/generation.rb
72
+ - lib/intelligent/llm/anthropic.rb
73
+ - lib/intelligent/llm/base.rb
74
+ - lib/intelligent/prompt.rb
75
+ - lib/intelligent/sequential_thinking.rb
76
+ - lib/intelligent/version.rb
77
+ - sig/intelligent.rbs
78
+ homepage: https://github.com/uysim/intelligent
79
+ licenses:
80
+ - MIT
81
+ metadata:
82
+ allowed_push_host: https://rubygems.org
83
+ homepage_uri: https://github.com/uysim/intelligent
84
+ source_code_uri: https://github.com/uysim/intelligent
85
+ changelog_uri: https://github.com/uysim/intelligent/blob/main/CHANGELOG.md
86
+ post_install_message:
87
+ rdoc_options: []
88
+ require_paths:
89
+ - lib
90
+ required_ruby_version: !ruby/object:Gem::Requirement
91
+ requirements:
92
+ - - ">="
93
+ - !ruby/object:Gem::Version
94
+ version: 3.2.0
95
+ required_rubygems_version: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: '0'
100
+ requirements: []
101
+ rubygems_version: 3.4.19
102
+ signing_key:
103
+ specification_version: 4
104
+ summary: Add intelligent to your Ruby engine
105
+ test_files: []