friday_gemini_ai 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.
Files changed (6) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +215 -0
  4. data/gemini_ai.gemspec +37 -0
  5. data/lib/gemini_ai.rb +185 -0
  6. metadata +121 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: aaac0eba90ceab2439b7f713c1a78cd649fb7419e80fb079baa25ac9e788e79f
4
+ data.tar.gz: 5045e0fcca735aae909c2e52c316ffab8023f72e0aa982f53e255b31d38dcf4a
5
+ SHA512:
6
+ metadata.gz: 6371fe6b7dcb90b6a83d0865f3dfd9ce2467ac465f8946f356a4cbfc82e851b44d5a4954959e495d94336a9c8751c5778ca8ed567e826943ec39c5d0afdec038
7
+ data.tar.gz: d6283f58a22cac64c5e0c2bb4f8101c15d7f102ee84262b735f3eb4ae797afd051013c0ac9c5dd91630ec13e6bb7698d4591b49f13a9c1e1a087dc93d46231ff
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Niladri Das
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,215 @@
1
+ # Gemini AI Ruby Gem
2
+
3
+ ## Overview
4
+ A powerful Ruby gem for interacting with Google's Gemini AI models, providing easy text generation capabilities.
5
+
6
+ ## Features
7
+ - Support for multiple Gemini AI models
8
+ - Flexible text generation
9
+ - Comprehensive error handling
10
+ - Configurable generation parameters
11
+ - Advanced security and logging
12
+
13
+ ## Security
14
+
15
+ ### 🔒 API Key Protection
16
+
17
+ #### Key Management
18
+ 1. **Never Hardcode API Keys**
19
+ - Do NOT include your API key directly in your code
20
+ - Use environment variables or secure key management systems
21
+
22
+ 2. **Environment Variable Setup**
23
+ ```bash
24
+ # Set in your shell profile (.bashrc, .zshrc, etc.)
25
+ export GEMINI_API_KEY='your_actual_api_key'
26
+ ```
27
+
28
+ 3. **Secure Key Passing**
29
+ ```ruby
30
+ # Recommended: Use environment variable
31
+ client = GeminiAI::Client.new
32
+
33
+ # Alternative: Pass key securely
34
+ client = GeminiAI::Client.new(ENV['GEMINI_API_KEY'])
35
+ ```
36
+
37
+ #### Advanced Security Features
38
+ - API key format validation
39
+ - Automatic key masking in logs
40
+ - Strict input validation
41
+ - Request timeout protection
42
+
43
+ ### 🕵️ Logging and Monitoring
44
+
45
+ #### Logging Configuration
46
+ ```ruby
47
+ # Configure logging level
48
+ GeminiAI::Client.logger.level = Logger::WARN # Default
49
+ GeminiAI::Client.logger.level = Logger::DEBUG # More verbose
50
+ ```
51
+
52
+ #### Log Masking
53
+ - API keys are automatically masked in logs
54
+ - Sensitive information is redacted
55
+ - Prevents accidental key exposure
56
+
57
+ ### 🛡️ Best Practices
58
+ - Restrict API key permissions
59
+ - Use the principle of least privilege
60
+ - Keep your API key confidential
61
+ - Monitor API usage and set up alerts
62
+ - Implement rate limiting
63
+ - Regularly rotate API keys
64
+
65
+ ## Installation
66
+
67
+ ### Local Installation
68
+ 1. Clone the repository
69
+ ```bash
70
+ git clone https://github.com/bniladridas/gemini_ai.git
71
+ cd gemini_ai
72
+ ```
73
+
74
+ 2. Build the gem
75
+ ```bash
76
+ gem build gemini_ai.gemspec
77
+ ```
78
+
79
+ 3. Install the gem locally
80
+ ```bash
81
+ gem install gemini_ai-0.1.0.gem
82
+ ```
83
+
84
+ ### Using Bundler
85
+ Add to your Gemfile:
86
+ ```ruby
87
+ gem 'gemini_ai', path: '/path/to/gemini_ai'
88
+ ```
89
+
90
+ ### From RubyGems
91
+ ```bash
92
+ gem install friday_gemini_ai
93
+ ```
94
+
95
+ Or add to your Gemfile:
96
+ ```ruby
97
+ gem 'friday_gemini_ai', '~> 0.1.0'
98
+ ```
99
+
100
+ ## Quick Start
101
+
102
+ 1. Get your API key from [Google AI Studio](https://aistudio.google.com/app/apikey)
103
+
104
+ 2. Set your API key:
105
+ ```bash
106
+ export GEMINI_API_KEY='your_api_key_here'
107
+ ```
108
+
109
+ 3. Start using the gem:
110
+ ```ruby
111
+ require 'gemini_ai'
112
+
113
+ # Initialize client
114
+ client = GeminiAI::Client.new
115
+
116
+ # Generate text
117
+ response = client.generate_text('Tell me a joke')
118
+ puts response
119
+
120
+ # Use different model
121
+ client_lite = GeminiAI::Client.new(model: :flash_lite)
122
+ response = client_lite.generate_text('What is AI?')
123
+ puts response
124
+
125
+ # Use custom parameters
126
+ response = client.generate_text('Write a haiku',
127
+ temperature: 0.3,
128
+ max_tokens: 30,
129
+ top_p: 0.8,
130
+ top_k: 20
131
+ )
132
+ puts response
133
+ ```
134
+
135
+ ## Configuration
136
+
137
+ ## Testing and Verification
138
+
139
+ ### Running the Test Suite
140
+ To run the comprehensive test suite:
141
+ ```bash
142
+ ruby comprehensive_test.rb
143
+ ```
144
+
145
+ ### Quick Verification
146
+ First, ensure your API key is set:
147
+ ```bash
148
+ export GEMINI_API_KEY='your_api_key_here'
149
+ ```
150
+
151
+ Then run the verification script:
152
+ ```bash
153
+ ruby verify_api.rb
154
+ ```
155
+
156
+ This will run a series of quick tests:
157
+ - Basic text generation with the default model
158
+ - Text generation with the flash_lite model
159
+ - Text generation with custom parameters
160
+
161
+ ## Usage
162
+
163
+ ### Basic Text Generation
164
+ ```ruby
165
+ require 'gemini_ai'
166
+
167
+ # Initialize client with default model
168
+ client = GeminiAI::Client.new(ENV['GEMINI_API_KEY'])
169
+
170
+ # Generate text
171
+ response = client.generate_text('Tell me a joke about programming')
172
+ puts response
173
+ ```
174
+
175
+ ### Specifying a Model
176
+ ```ruby
177
+ # Use Flash Lite model
178
+ client_lite = GeminiAI::Client.new(ENV['GEMINI_API_KEY'], model: :flash_lite)
179
+ response = client_lite.generate_text('Explain AI in simple terms')
180
+ ```
181
+
182
+ ### Custom Generation Options
183
+ ```ruby
184
+ options = {
185
+ temperature: 0.7,
186
+ max_tokens: 100,
187
+ top_p: 0.9,
188
+ top_k: 40
189
+ }
190
+
191
+ response = client.generate_text('Write a short story', options)
192
+ ```
193
+
194
+ ## Error Handling
195
+ The gem provides robust error handling:
196
+ ```ruby
197
+ begin
198
+ client.generate_text('') # Raises an error
199
+ rescue GeminiAI::Error => e
200
+ puts "An error occurred: #{e.message}"
201
+ end
202
+ ```
203
+
204
+ ## Contributing
205
+ 1. Fork the repository
206
+ 2. Create your feature branch
207
+ 3. Commit your changes
208
+ 4. Push to the branch
209
+ 5. Create a new Pull Request
210
+
211
+ ## License
212
+ MIT License
213
+
214
+ ## Support
215
+ For issues, please file a GitHub issue in the repository.
data/gemini_ai.gemspec ADDED
@@ -0,0 +1,37 @@
1
+ Gem::Specification.new do |spec|
2
+ spec.name = 'friday_gemini_ai'
3
+ spec.version = '0.1.0'
4
+ spec.date = '2025-03-01'
5
+ spec.summary = 'Ruby interface for Google Gemini AI models'
6
+ spec.description = 'A flexible Ruby gem for generating text using Google Gemini AI models with comprehensive error handling and multiple model support.'
7
+ spec.authors = ['bniladridas']
8
+ spec.email = ['bniladridas@gmail.com']
9
+ spec.homepage = 'https://github.com/bniladridas/gemini_ai'
10
+ spec.license = 'MIT'
11
+
12
+ spec.files = [
13
+ 'lib/gemini_ai.rb',
14
+ 'README.md',
15
+ 'LICENSE',
16
+ 'gemini_ai.gemspec'
17
+ ]
18
+
19
+ spec.require_paths = ['lib']
20
+
21
+ spec.required_ruby_version = '>= 3.0.0'
22
+
23
+ # Runtime dependencies
24
+ spec.add_runtime_dependency 'httparty', '~> 0.21.0'
25
+ spec.add_runtime_dependency 'json', '~> 2.6.3'
26
+
27
+ # Development dependencies
28
+ spec.add_development_dependency 'minitest', '~> 5.25.4'
29
+ spec.add_development_dependency 'dotenv', '~> 2.8'
30
+ spec.add_development_dependency 'rake', '~> 13.0'
31
+
32
+ spec.metadata = {
33
+ 'source_code_uri' => 'https://github.com/bniladridas/gemini_ai',
34
+ 'documentation_uri' => 'https://github.com/bniladridas/gemini_ai/blob/main/README.md',
35
+ 'bug_tracker_uri' => 'https://github.com/bniladridas/gemini_ai/issues'
36
+ }
37
+ end
data/lib/gemini_ai.rb ADDED
@@ -0,0 +1,185 @@
1
+ require 'httparty'
2
+ require 'json'
3
+ require 'base64'
4
+ require 'logger'
5
+
6
+ module GeminiAI
7
+ class Error < StandardError; end
8
+
9
+ class Client
10
+ BASE_URL = 'https://generativelanguage.googleapis.com/v1/models'
11
+ MODELS = {
12
+ pro: 'gemini-2.0-flash',
13
+ flash: 'gemini-2.0-flash',
14
+ flash_lite: 'gemini-2.0-flash-lite'
15
+ }
16
+
17
+ # Configure logging
18
+ def self.logger
19
+ @logger ||= Logger.new(STDOUT).tap do |log|
20
+ log.level = Logger::DEBUG # Changed to DEBUG for more information
21
+ log.formatter = proc do |severity, datetime, progname, msg|
22
+ # Mask any potential API key in logs
23
+ masked_msg = msg.to_s.gsub(/AIza[a-zA-Z0-9_-]{35,}/, '[REDACTED]')
24
+ "#{datetime}: #{severity} -- #{masked_msg}\n"
25
+ end
26
+ end
27
+ end
28
+
29
+ def initialize(api_key = nil, model: :pro)
30
+ # Prioritize passed API key, then environment variable
31
+ @api_key = api_key || ENV['GEMINI_API_KEY']
32
+
33
+ # Extensive logging for debugging
34
+ self.class.logger.debug("Initializing Client")
35
+ self.class.logger.debug("API Key present: #{!@api_key.nil?}")
36
+ self.class.logger.debug("API Key length: #{@api_key&.length}")
37
+
38
+ # Validate API key
39
+ validate_api_key!
40
+
41
+ @model = MODELS.fetch(model) {
42
+ self.class.logger.warn("Invalid model: #{model}, defaulting to pro")
43
+ MODELS[:pro]
44
+ }
45
+
46
+ self.class.logger.debug("Selected model: #{@model}")
47
+ end
48
+
49
+ def generate_text(prompt, options = {})
50
+ validate_prompt!(prompt)
51
+
52
+ request_body = {
53
+ contents: [{ parts: [{ text: prompt }] }],
54
+ generationConfig: build_generation_config(options)
55
+ }
56
+
57
+ send_request(request_body)
58
+ end
59
+
60
+ def generate_image_text(image_base64, prompt, options = {})
61
+ raise Error, "Image is required" if image_base64.nil? || image_base64.empty?
62
+
63
+ request_body = {
64
+ contents: [
65
+ { parts: [
66
+ { inline_data: { mime_type: 'image/jpeg', data: image_base64 } },
67
+ { text: prompt }
68
+ ]}
69
+ ],
70
+ generationConfig: build_generation_config(options)
71
+ }
72
+
73
+ send_request(request_body, model: :pro_vision)
74
+ end
75
+
76
+ def chat(messages, options = {})
77
+ request_body = {
78
+ contents: messages.map { |msg| { role: msg[:role], parts: [{ text: msg[:content] }] } },
79
+ generationConfig: build_generation_config(options)
80
+ }
81
+
82
+ send_request(request_body)
83
+ end
84
+
85
+ private
86
+
87
+ def validate_api_key!
88
+ if @api_key.nil? || @api_key.strip.empty?
89
+ self.class.logger.error("API key is missing")
90
+ raise Error, "API key is required. Set GEMINI_API_KEY environment variable or pass key directly."
91
+ end
92
+
93
+ # Optional: Add basic API key format validation
94
+ unless valid_api_key_format?(@api_key)
95
+ self.class.logger.error("Invalid API key format")
96
+ raise Error, "Invalid API key format. Please check your key."
97
+ end
98
+
99
+ # Optional: Check key length and complexity
100
+ if @api_key.length < 40
101
+ self.class.logger.warn("Potentially weak API key detected")
102
+ end
103
+ end
104
+
105
+ def valid_api_key_format?(key)
106
+ # Strict format check: starts with 'AIza', reasonable length
107
+ key =~ /^AIza[a-zA-Z0-9_-]{35,}$/
108
+ end
109
+
110
+ def validate_prompt!(prompt)
111
+ if prompt.nil? || prompt.strip.empty?
112
+ self.class.logger.error("Empty prompt provided")
113
+ raise Error, "Prompt cannot be empty"
114
+ end
115
+
116
+ if prompt.length > 8192
117
+ self.class.logger.error("Prompt exceeds maximum length")
118
+ raise Error, "Prompt too long (max 8192 tokens)"
119
+ end
120
+ end
121
+
122
+ def build_generation_config(options)
123
+ {
124
+ temperature: options[:temperature] || 0.7,
125
+ maxOutputTokens: options[:max_tokens] || 1024,
126
+ topP: options[:top_p] || 0.9,
127
+ topK: options[:top_k] || 40
128
+ }
129
+ end
130
+
131
+ def send_request(body, model: nil)
132
+ current_model = model ? MODELS.fetch(model) { MODELS[:pro] } : @model
133
+ url = "#{BASE_URL}/#{current_model}:generateContent?key=#{@api_key}"
134
+
135
+ # Log URL with masked API key for security
136
+ masked_url = "#{BASE_URL}/#{current_model}:generateContent?key=#{mask_api_key(@api_key)}"
137
+ self.class.logger.debug("Request URL: #{masked_url}")
138
+ self.class.logger.debug("Request Body: #{body.to_json}")
139
+
140
+ begin
141
+ response = HTTParty.post(
142
+ url,
143
+ body: body.to_json,
144
+ headers: {
145
+ 'Content-Type' => 'application/json',
146
+ 'x-goog-api-client' => 'gemini_ai_ruby_gem/0.1.0'
147
+ },
148
+ # Add timeout to prevent hanging
149
+ timeout: 30
150
+ )
151
+
152
+ self.class.logger.debug("Response Code: #{response.code}")
153
+ self.class.logger.debug("Response Body: #{response.body}")
154
+
155
+ parse_response(response)
156
+ rescue HTTParty::Error, Net::OpenTimeout => e
157
+ self.class.logger.error("API request failed: #{e.message}")
158
+ raise Error, "API request failed: #{e.message}"
159
+ end
160
+ end
161
+
162
+ def parse_response(response)
163
+ case response.code
164
+ when 200
165
+ text = response.parsed_response
166
+ .dig('candidates', 0, 'content', 'parts', 0, 'text')
167
+ text || 'No response generated'
168
+ else
169
+ error_message = response.parsed_response['error']&.dig('message') || response.body
170
+ self.class.logger.error("API Error: #{error_message}")
171
+ raise Error, "API Error: #{error_message}"
172
+ end
173
+ end
174
+
175
+ # Mask API key for logging and error reporting
176
+ def mask_api_key(key)
177
+ return '[REDACTED]' if key.nil?
178
+
179
+ # Keep first 4 and last 4 characters, replace middle with asterisks
180
+ return key if key.length <= 8
181
+
182
+ "#{key[0,4]}#{'*' * (key.length - 8)}#{key[-4,4]}"
183
+ end
184
+ end
185
+ end
metadata ADDED
@@ -0,0 +1,121 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: friday_gemini_ai
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - bniladridas
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2025-03-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: httparty
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.21.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.21.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: json
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 2.6.3
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 2.6.3
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 5.25.4
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 5.25.4
55
+ - !ruby/object:Gem::Dependency
56
+ name: dotenv
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '2.8'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '2.8'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rake
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '13.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '13.0'
83
+ description: A flexible Ruby gem for generating text using Google Gemini AI models
84
+ with comprehensive error handling and multiple model support.
85
+ email:
86
+ - bniladridas@gmail.com
87
+ executables: []
88
+ extensions: []
89
+ extra_rdoc_files: []
90
+ files:
91
+ - LICENSE
92
+ - README.md
93
+ - gemini_ai.gemspec
94
+ - lib/gemini_ai.rb
95
+ homepage: https://github.com/bniladridas/gemini_ai
96
+ licenses:
97
+ - MIT
98
+ metadata:
99
+ source_code_uri: https://github.com/bniladridas/gemini_ai
100
+ documentation_uri: https://github.com/bniladridas/gemini_ai/blob/main/README.md
101
+ bug_tracker_uri: https://github.com/bniladridas/gemini_ai/issues
102
+ post_install_message:
103
+ rdoc_options: []
104
+ require_paths:
105
+ - lib
106
+ required_ruby_version: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: 3.0.0
111
+ required_rubygems_version: !ruby/object:Gem::Requirement
112
+ requirements:
113
+ - - ">="
114
+ - !ruby/object:Gem::Version
115
+ version: '0'
116
+ requirements: []
117
+ rubygems_version: 3.4.10
118
+ signing_key:
119
+ specification_version: 4
120
+ summary: Ruby interface for Google Gemini AI models
121
+ test_files: []