minds_sdk 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7c7f832efbb02c672f51644db5065474eb0795f5a34da8f97b1dcd345d43cd02
4
+ data.tar.gz: 6f0518f9fb72275fe165e1ef5ce47433f38eadfcf755c7dc0716d85cb488505f
5
+ SHA512:
6
+ metadata.gz: 1c0b304a9f92c73c61e9d96d9e9ef33e726dffd39740e92185ae6543eec606e2a3ea8b4dcdfcb3eb1e775f20ffbff445a1fb26e44e175c347d78d4432da41c93
7
+ data.tar.gz: 822c1f3baa51a8f9385787c0f984f9241b68e5b13df67c1d281cdf626c6937c68c0c49bbae493948f8a6e811c140378e23e092a923a69a0bae7e322c89e963d2
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,3 @@
1
+ # Omakase Ruby styling for Rails
2
+ inherit_gem:
3
+ rubocop-rails-omakase: rubocop.yml
data/CHANGELOG.md ADDED
@@ -0,0 +1,40 @@
1
+ ## [Unreleased]
2
+
3
+ ## [1.0.0] - 2024-10-14
4
+
5
+ ### Added
6
+ - Initial release of the Minds Ruby SDK
7
+ - Implemented `Minds::Client` for configuring and initializing the SDK
8
+ - Added `Minds::Resources::Datasources` for managing data sources:
9
+ - `create`: Create a new datasource
10
+ - `all`: List all datasources
11
+ - `find`: Get a datasource by name
12
+ - `destroy`: Delete a datasource
13
+ - Added `Minds::Resources::Minds` for managing minds:
14
+ - `all`: List all minds
15
+ - `find`: Get a mind by name
16
+ - `create`: Create a new mind
17
+ - `destroy`: Delete a mind
18
+ - Implemented `Minds::Resources::Mind` class with methods:
19
+ - `update`: Update mind properties
20
+ - `add_datasources`: Add a datasource to a mind
21
+ - `destroy_datasources`: Remove a datasource from a mind
22
+ - `completion`: Call mind completion (with streaming support)
23
+ - Added support for various datasource types through `DatabaseConfig` class
24
+ - Implemented error handling with custom error classes
25
+ - Added YARD-style documentation for all public methods
26
+
27
+ ### Changed
28
+ - N/A
29
+
30
+ ### Deprecated
31
+ - N/A
32
+
33
+ ### Removed
34
+ - N/A
35
+
36
+ ### Fixed
37
+ - N/A
38
+
39
+ ### Security
40
+ - N/A
@@ -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) 2024 tms-tungnt
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,206 @@
1
+ # Minds Ruby SDK
2
+
3
+ Minds Ruby SDK provides an interface to interact with the Minds AI system API. It allows you to create and manage "minds" (artificial intelligences), create chat completions, and manage data sources.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'minds_sdk'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ ```bash
16
+ $ bundle install
17
+ ```
18
+
19
+ Or install it yourself as:
20
+
21
+ ```bash
22
+ $ gem install minds_sdk
23
+ ```
24
+
25
+ ## Getting Started
26
+
27
+ ### Configuration
28
+
29
+ There are two ways to configure the Minds client:
30
+
31
+ 1. Global Configuration:
32
+
33
+ You can set up a global configuration that will be used by default for all client instances:
34
+
35
+ ```ruby
36
+ Minds::Client.configure do |config|
37
+ config.base_url = "https://mdb.ai" # Optional: defaults to https://mdb.ai
38
+ config.api_key = "YOUR_API_KEY"
39
+ end
40
+ ```
41
+
42
+ 2. Instance Configuration:
43
+
44
+ Alternatively, you can configure each client instance individually:
45
+
46
+ ```ruby
47
+ client = Minds::Client.new("YOUR_API_KEY", "https://mdb.ai")
48
+ ```
49
+
50
+ ### Initialize the Client
51
+
52
+ After configuration, you can initialize the client:
53
+
54
+ ```ruby
55
+ # Using global configuration
56
+ client = Minds::Client.new
57
+
58
+ # Or with instance-specific configuration
59
+ client = Minds::Client.new("YOUR_API_KEY", "https://mdb.ai")
60
+
61
+ # For a self-hosted Minds Cloud instance
62
+ client = Minds::Client.new("YOUR_API_KEY", "https://<custom_cloud>.mdb.ai")
63
+ ```
64
+
65
+ ## Resources
66
+ ### Creating a Data Source
67
+
68
+ You can connect to various databases, such as PostgreSQL, by configuring your data source. Use the DatabaseConfig to define the connection details for your data source.
69
+
70
+ ```ruby
71
+ postgres_config = Minds::Resources::DatabaseConfig.new(
72
+ name: 'my_datasource',
73
+ description: '<DESCRIPTION-OF-YOUR-DATA>',
74
+ engine: 'postgres',
75
+ connection_data: {
76
+ user: 'demo_user',
77
+ password: 'demo_password',
78
+ host: 'samples.mindsdb.com',
79
+ port: 5432,
80
+ database: 'demo',
81
+ schema: 'demo_data'
82
+ },
83
+ tables: ['<TABLE-1>', '<TABLE-2>']
84
+ )
85
+
86
+ See supported [Data Sources](https://docs.mdb.ai/docs/data_sources)
87
+ ```
88
+
89
+ ### Creating a Mind
90
+
91
+ You can create a mind and associate it with a data source.
92
+
93
+ ```ruby
94
+ # Create a mind with a data source
95
+ mind = client.minds.create(name: 'mind_name', datasources: [postgres_config])
96
+
97
+ # Alternatively, create a data source separately and add it to a mind later
98
+ datasource = client.datasources.create(postgres_config)
99
+ mind2 = client.minds.create(name: 'mind_name', datasources: [datasource])
100
+ ```
101
+
102
+ You can also add a data source to an existing mind:
103
+
104
+ ```ruby
105
+ # Create a mind without a data source
106
+ mind3 = client.minds.create(name: 'mind_name')
107
+
108
+ # Add a data source to the mind
109
+ mind3.add_datasources(postgres_config) # Using the config
110
+ mind3.add_datasources(datasource) # Using the data source object
111
+ ```
112
+
113
+ ### Managing Minds
114
+
115
+ You can create a mind or replace an existing one with the same name.
116
+
117
+ ```ruby
118
+ mind = client.minds.create(name: 'mind_name', replace: true, datasources: [postgres_config])
119
+ ```
120
+
121
+ To update a mind, specify the new attributes:
122
+
123
+ ```ruby
124
+ mind.update(
125
+ name: 'new_mind_name',
126
+ datasources: [postgres_config]
127
+ )
128
+ ```
129
+
130
+ ### List Minds
131
+
132
+ You can list all the minds you've created:
133
+
134
+ ```ruby
135
+ puts client.minds.all
136
+ ```
137
+
138
+ ### Get a Mind by Name
139
+
140
+ You can fetch details of a mind by its name:
141
+
142
+ ```ruby
143
+ mind = client.minds.find('mind_name')
144
+ ```
145
+
146
+ ### Remove a Mind
147
+
148
+ To delete a mind, use the following command:
149
+
150
+ ```ruby
151
+ client.minds.destroy('mind_name')
152
+ ```
153
+
154
+ ### Managing Data Sources
155
+
156
+ To view all data sources:
157
+
158
+ ```ruby
159
+ puts client.datasources.all
160
+ ```
161
+
162
+ ### Get a Data Source by Name
163
+
164
+ You can fetch details of a specific data source by its name:
165
+
166
+ ```ruby
167
+ datasource = client.datasources.find('my_datasource')
168
+ ```
169
+
170
+ ### Remove a Data Source
171
+
172
+ To delete a data source, use the following command:
173
+
174
+ ```ruby
175
+ client.datasources.destroy('my_datasource')
176
+ ```
177
+
178
+ Note: The SDK currently does not support automatically removing a data source if it is no longer connected to any mind.
179
+
180
+ ## Chat Completion
181
+
182
+ You can use a mind to generate chat completions:
183
+
184
+ ```ruby
185
+ response = mind.completion(message: "Hello, how are you?")
186
+ puts response
187
+
188
+ # For streaming responses
189
+ mind.completion(message: "Tell me a story", stream: true)
190
+ ```
191
+
192
+ ## Development
193
+
194
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
195
+
196
+ ## Contributing
197
+
198
+ Bug reports and pull requests are welcome on GitHub at [here](https://github.com/your_github_username/minds_ruby_sdk).
199
+
200
+ ## Acknowledgments
201
+
202
+ This SDK is built for integration with Minds, AI layer for existing databases. We would like to express our gratitude to the MindsDB team for their innovative work in making AI more accessible.
203
+ For more information about MindsDB, please visit their official website: [https://mindsdb.com/](https://mindsdb.com/)
204
+ ## License
205
+
206
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
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]
@@ -0,0 +1,42 @@
1
+ require "faraday"
2
+ require "json"
3
+ require_relative "config/base"
4
+ require_relative "resources/base"
5
+ require_relative "resources/minds"
6
+ require_relative "resources/datasources"
7
+
8
+ module Minds
9
+ class Client
10
+ class << self
11
+ def config
12
+ @config ||= Config::Base.new
13
+ end
14
+
15
+ def configure
16
+ yield(config) if block_given?
17
+ end
18
+ end
19
+
20
+ attr_accessor :base_url, :api_key
21
+ DEFAULT_HOST = "https://mdb.ai"
22
+
23
+ def initialize(api_key = nil, base_url = nil)
24
+ # if api_key & base_url not present. Fall back to global config
25
+ @base_url =
26
+ if base_url.nil?
27
+ Minds::Client.config.send(:base_url).nil? ? DEFAULT_HOST : Minds::Client.config.send(:base_url)
28
+ else
29
+ base_url
30
+ end
31
+ @api_key = api_key.nil? ? Minds::Client.config.send(:api_key) : api_key
32
+ end
33
+
34
+ def datasources
35
+ @datasources ||= Minds::Resources::Datasources.new(self)
36
+ end
37
+
38
+ def minds
39
+ @minds ||= Minds::Resources::Minds.new(self)
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,12 @@
1
+ module Minds
2
+ module Config
3
+ class Base
4
+ attr_accessor :base_url, :api_key
5
+
6
+ def initialize
7
+ @base_url = nil
8
+ @api_key = nil
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,5 @@
1
+ class Error < StandardError; end
2
+
3
+ class ValidationError < Error; end
4
+ class ObjectNotFound < Error; end
5
+ class ObjectNotSupported < Error; end
@@ -0,0 +1,26 @@
1
+ module Minds
2
+ module Resources
3
+ class Base
4
+ attr_accessor :api_key, :base_url, :api
5
+
6
+ def initialize(client)
7
+ @base_url = client.base_url
8
+ @api_key = client.api_key
9
+ @api = conn
10
+ end
11
+
12
+ private
13
+
14
+ def conn
15
+ Faraday.new(url: @base_url) do |builder|
16
+ builder.request :json
17
+ builder.response :json
18
+ builder.response :raise_error
19
+ builder.adapter Faraday.default_adapter
20
+ builder.headers["Authorization"] = "Bearer #{@api_key}"
21
+ builder.headers["Content-Type"] = "application/json"
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,95 @@
1
+ module Minds
2
+ module Resources
3
+ class DatabaseConfig
4
+ attr_reader :name, :engine, :description, :connection_data, :tables, :created_at
5
+
6
+ def initialize(name:, engine:, description:, connection_data: {}, tables: [], created_at: nil)
7
+ @name = name
8
+ @engine = engine
9
+ @description = description
10
+ @connection_data = connection_data
11
+ @tables = tables
12
+ @created_at = created_at
13
+ end
14
+
15
+ def to_h
16
+ {
17
+ name: @name,
18
+ engine: @engine,
19
+ description: @description,
20
+ connection_data: @connection_data,
21
+ tables: @tables
22
+ }
23
+ end
24
+ end
25
+
26
+ class Datasource < DatabaseConfig; end
27
+
28
+ class Datasources < Base
29
+ # Create a new datasource and return it
30
+ #
31
+ # @param ds_config [DatabaseConfig] datasource configuration
32
+ # @option ds_config [String] :name Name of the datasource
33
+ # @option ds_config [String] :engine Type of database handler (e.g., 'postgres', 'mysql')
34
+ # @option ds_config [String] :description Description of the database. Used by mind to understand what data can be retrieved from it.
35
+ # @option ds_config [Hash] :connection_data (optional) Credentials to connect to the database
36
+ # @option ds_config [Array<String>] :tables (optional) List of allowed tables
37
+ # @param replace [Boolean] If true, replaces an existing datasource with the same name
38
+ # @return [Datasource] The created datasource object
39
+ # @raise [ObjectNotFound] If the datasource to be replaced doesn't exist
40
+ def create(ds_config, replace = false)
41
+ name = ds_config.name
42
+
43
+ if replace
44
+ begin
45
+ find(name)
46
+ destroy(name)
47
+ rescue ObjectNotFound
48
+ # Do nothing
49
+ end
50
+ end
51
+ self.api.post("/api/datasources") do |req|
52
+ req.body = ds_config.to_h.to_json
53
+ end
54
+ find(name)
55
+ end
56
+
57
+ # Returns a list of all datasources
58
+ #
59
+ # @return [Array<Datasource>] An array of Datasource objects
60
+ def all
61
+ data = self.api.get("/api/datasources").body
62
+ data.each_with_object([]) do |item, ds_list|
63
+ next if item["engine"].nil?
64
+ ds_list << Datasource.new(**item.transform_keys(&:to_sym))
65
+ end
66
+ end
67
+
68
+ # Get a datasource by name
69
+ #
70
+ # @param name [String] The name of the datasource to find
71
+ # @return [Datasource] The found datasource object
72
+ # @raise [ObjectNotSupported] If the datasource type is not supported
73
+ def find(name)
74
+ data =self.api.get("api/datasources/#{name}").body
75
+
76
+ if data["engine"].nil?
77
+ raise ObjectNotSupported, "Wrong type of datasource: #{name}"
78
+ end
79
+
80
+ Datasource.new(**data.transform_keys(&:to_sym))
81
+ end
82
+
83
+ # Drop (delete) a datasource by name
84
+ #
85
+ # @param name [String] The name of the datasource to delete
86
+ # @return [void]
87
+ # @raise [Faraday::ResourceNotFound] If the datasource doesn't exist
88
+ # @raise [Faraday::ClientError] If there's a client-side error
89
+ # @raise [Faraday::ServerError] If there's a server-side error
90
+ def destroy(name)
91
+ self.api.delete("api/datasources/#{name}")
92
+ end
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,247 @@
1
+ require "openai"
2
+ require "uri"
3
+ module Minds
4
+ module Resources
5
+ DEFAULT_PROMPT_TEMPLATE = "Use your database tools to answer the user's question: {{question}}"
6
+
7
+ class Mind < Base
8
+ attr_accessor :name, :model_name, :provider, :parameters, :created_at, :updated_at, :datasources
9
+
10
+ def initialize(client, attributes = {})
11
+ super(client)
12
+ @project = "mindsdb"
13
+ @name = attributes["name"]
14
+ @model_name = attributes["model_name"]
15
+ @provider = attributes["provider"]
16
+ @parameters = attributes["parameters"] || {}
17
+ @prompt_template = @parameters.delete("prompt_template")
18
+ @created_at = attributes["created_at"]
19
+ @updated_at = attributes["updated_at"]
20
+ @datasources = attributes["datasources"]
21
+ end
22
+
23
+ # Update the mind with new parameters
24
+ #
25
+ # @param name [String, nil] New name of the mind (optional)
26
+ # @param model_name [String, nil] New LLM model name (optional)
27
+ # @param provider [String, nil] New LLM provider (optional)
28
+ # @param prompt_template [String, nil] New prompt template (optional)
29
+ # @param datasources [Array<String, Datasource, DatabaseConfig>, nil] Alter list of datasources used by mind (optional)
30
+ # Datasource can be passed as:
31
+ # - String: name of the datasource
32
+ # - Datasource object (Minds::Resources::Datasource)
33
+ # - DatabaseConfig object (Minds::Resources::DatabaseConfig), in this case datasource will be created
34
+ # @param parameters [Hash, nil] Alter other parameters of the mind (optional)
35
+ # @return [void]
36
+ def update(name: nil, model_name: nil, provider: nil, prompt_template: nil, datasources: nil, parameters: nil)
37
+ data = {}
38
+
39
+ ds_names = []
40
+ datasources.each do |ds|
41
+ minds = Minds.new(self)
42
+ ds_name = minds.check_datasource(ds)
43
+ ds_names << ds_name
44
+ data["datasources"] = ds_names
45
+ end if datasources
46
+
47
+ data["name"] = name if name
48
+ data["model_name"] = model_name if model_name
49
+ data["provider"] = provider if provider
50
+ data["parameters"] = parameters.nil? ? {} : parameters
51
+ data["parameters"]["prompt_template"] = prompt_template if prompt_template
52
+
53
+ self.api.patch("/api/projects/#{@project}/minds/#{@name}") do |req|
54
+ req.body = data.to_json
55
+ end
56
+
57
+ @name = name if name && name != @name
58
+ end
59
+
60
+ # Add a datasource to the mind
61
+ #
62
+ # @param datasource [String, Datasource, DatabaseConfig] The datasource to add
63
+ # Can be passed as:
64
+ # - String: name of the datasource
65
+ # - Datasource object (Minds::Resources::Datasource)
66
+ # - DatabaseConfig object (Minds::Resources::DatabaseConfig), in this case datasource will be created
67
+ # @return [void]
68
+ def add_datasources(datasource)
69
+ minds = Minds.new(self)
70
+ ds_name = minds.check_datasource(datasource)
71
+ self.api.post("/api/projects/#{project}/minds/#{@name}/datasources") do |req|
72
+ req.body = { name: ds_name }.to_json
73
+ end
74
+
75
+ mind = minds.find(@name)
76
+
77
+ @datasources = mind.datasources
78
+ end
79
+
80
+ # Delete a datasource from the mind
81
+ #
82
+ # @param datasource [String, Datasource] The datasource to delete
83
+ # Can be passed as:
84
+ # - String: name of the datasource
85
+ # - Datasource object (Minds::Resources::Datasource)
86
+ # @return [void]
87
+ def destroy_datasources(datasource)
88
+ if datasource.is_a?(Datasource)
89
+ datasource = datasource.name
90
+ elsif !datasource.is_a?(String)
91
+ raise ArgumentError, "Unknown type of datasource: #{datasource}"
92
+ end
93
+ self.api.delete("/api/projects/#{@project}/minds/#{@name}/datasources/#{datasource}")
94
+
95
+ minds = Minds.new(self)
96
+ mind = minds.find(@name)
97
+ @datasources = mind.datasources
98
+ end
99
+
100
+ # Call mind completion
101
+ #
102
+ # @param message [String] The input question or prompt
103
+ # @param stream [Boolean] Whether to enable stream mode (default: false)
104
+ # @return [String, Enumerator] If stream mode is off, returns a String.
105
+ # If stream mode is on, returns an Enumerator of ChoiceDelta objects (as defined by OpenAI)
106
+ def completion(message:, stream: false)
107
+ parsed = URI.parse(self.api.base_url)
108
+ host = parsed.host
109
+ if host == "mdb.ai"
110
+ llm_host = "llm.mdb.ai"
111
+ else
112
+ llm_host = "ai.#{host}"
113
+ end
114
+ parsed.host = llm_host
115
+ parsed.path = ""
116
+ parsed.query = nil
117
+ uri_base = parsed
118
+ openai_client = OpenAI::Client.new(access_token: self.api_key, uri_base: uri_base)
119
+ if stream
120
+ openai_client.chat(
121
+ parameters: {
122
+ model: @model_name,
123
+ messages: [ { role: "user", content: message } ], # Required.
124
+ temperature: 0,
125
+ stream: proc do |chunk, _bytesize|
126
+ print chunk.dig("choices", 0, "delta")
127
+ end
128
+ }
129
+ )
130
+ else
131
+ response = openai_client.chat(
132
+ parameters: {
133
+ model: @model_name,
134
+ messages: [ { role: "user", content: message } ],
135
+ temperature: 0
136
+ }
137
+ )
138
+ response.dig("choices", 0, "message", "content")
139
+ end
140
+ end
141
+ end
142
+
143
+ class Minds < Base
144
+ def initialize(client)
145
+ super
146
+ @project = "mindsdb"
147
+ end
148
+
149
+ # Returns a list of all minds
150
+ #
151
+ # @return [Array<Mind>] An array of Mind objects
152
+ def all
153
+ resp = self.api.get("/api/projects/#{@project}/minds")
154
+ resp.body
155
+ resp.body.map { |item| Mind.new(self, item) }
156
+ end
157
+
158
+ # Get a mind by name
159
+ #
160
+ # @param name [String] The name of the mind to find
161
+ # @return [Mind] The found mind object
162
+ def find(name)
163
+ resp = self.api.get("/api/projects/#{@project}/minds/#{name}")
164
+ Mind.new(self, resp.body)
165
+ end
166
+
167
+ # Drop (delete) a mind by name
168
+ #
169
+ # @param name [String] The name of the mind to delete
170
+ # @return [void]
171
+ def destroy(name)
172
+ self.api.delete("/api/projects/#{@project}/minds/#{name}")
173
+ end
174
+
175
+ # Create a new mind and return it
176
+ #
177
+ # @param name [String] The name of the mind
178
+ # @param model_name [String, nil] The LLM model name (optional)
179
+ # @param provider [String, nil] The LLM provider (optional)
180
+ # @param prompt_template [String, nil] Instructions to LLM (optional)
181
+ # @param datasources [Array<String, Datasource, DatabaseConfig>, nil] List of datasources used by mind (optional)
182
+ # Datasource can be passed as:
183
+ # - String: name of the datasource
184
+ # - Datasource object (Minds::Resources::Datasource)
185
+ # - DatabaseConfig object (Minds::Resources::DatabaseConfig), in this case datasource will be created
186
+ # @param parameters [Hash, nil] Other parameters of the mind (optional)
187
+ # @param replace [Boolean] If true, remove existing mind with the same name (default: false)
188
+ # @return [Mind] The created mind object
189
+ def create(name:, model_name: nil, provider: nil, prompt_template: nil, datasources: nil, parameters: nil, replace: false)
190
+ if replace
191
+ begin
192
+ find(name)
193
+ destroy(name)
194
+ rescue Faraday::ResourceNotFound
195
+ end
196
+ end
197
+
198
+ ds_names = []
199
+ datasources.each do |ds|
200
+ ds_name = check_datasource(ds)
201
+ ds_names << ds_name
202
+ end if datasources
203
+
204
+ parameters = {} if parameters.nil?
205
+
206
+ parameters["prompt_template"] = prompt_template if prompt_template
207
+ parameters["prompt_template"] ||= DEFAULT_PROMPT_TEMPLATE
208
+ self.api.post("api/projects/#{@project}/minds") do |req|
209
+ req.body = {
210
+ name: name,
211
+ model_name: model_name,
212
+ provider: provider,
213
+ parameters: parameters,
214
+ datasources: ds_names
215
+ }.to_json
216
+
217
+ find(name)
218
+ end
219
+ end
220
+
221
+ def check_datasource(ds)
222
+ ds_name = extract_datasource_name(ds)
223
+ create_datasource_if_needed(ds)
224
+ ds_name
225
+ end
226
+
227
+ private
228
+
229
+ def extract_datasource_name(ds)
230
+ case ds
231
+ when Datasource, DatabaseConfig, String
232
+ ds.respond_to?(:name) ? ds.name : ds
233
+ else
234
+ raise ArgumentError, "Unknown type of datasource: #{ds.class}"
235
+ end
236
+ end
237
+
238
+ def create_datasource_if_needed(ds)
239
+ return unless ds.is_a?(DatabaseConfig)
240
+ datasources = Datasources.new(self)
241
+ datasources.find(ds.name)
242
+ rescue Faraday::ResourceNotFound
243
+ datasources.create(ds)
244
+ end
245
+ end
246
+ end
247
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Minds
4
+ VERSION = "0.1.0"
5
+ end
data/lib/minds.rb ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "minds/version"
4
+ require_relative "minds/client"
5
+ require_relative "minds/errors"
6
+ require_relative "minds/config/base"
7
+ require_relative "minds/resources/datasources"
8
+
9
+ module Minds; end
data/sig/minds.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Minds
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,93 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: minds_sdk
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - tungnt
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-10-13 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: faraday
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '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'
27
+ - !ruby/object:Gem::Dependency
28
+ name: ruby-openai
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: Official Ruby SDK for Minds
42
+ email:
43
+ - tungnguyen120301@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".rspec"
49
+ - ".rubocop.yml"
50
+ - CHANGELOG.md
51
+ - CODE_OF_CONDUCT.md
52
+ - LICENSE.txt
53
+ - README.md
54
+ - Rakefile
55
+ - lib/minds.rb
56
+ - lib/minds/client.rb
57
+ - lib/minds/config/base.rb
58
+ - lib/minds/errors.rb
59
+ - lib/minds/resources/base.rb
60
+ - lib/minds/resources/datasources.rb
61
+ - lib/minds/resources/minds.rb
62
+ - lib/minds/version.rb
63
+ - sig/minds.rbs
64
+ homepage: https://github.com/tungnt1203/minds_ruby_sdk
65
+ licenses:
66
+ - MIT
67
+ metadata:
68
+ allowed_push_host: https://rubygems.org
69
+ homepage_uri: https://github.com/tungnt1203/minds_ruby_sdk
70
+ source_code_uri: https://github.com/tungnt1203/minds_ruby_sdk
71
+ changelog_uri: https://github.com/tungnt1203/minds_ruby_sdk/blob/main/CHANGELOG.md
72
+ post_install_message:
73
+ rdoc_options: []
74
+ require_paths:
75
+ - lib
76
+ required_ruby_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: 3.0.0
81
+ required_rubygems_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ requirements: []
87
+ rubygems_version: 3.2.22
88
+ signing_key:
89
+ specification_version: 4
90
+ summary: Minds Ruby SDK provides an interface to interact with the Minds AI system
91
+ API. It allows you to create and manage "minds" (artificial intelligences), create
92
+ chat completions, and manage data sources.
93
+ test_files: []