orbai 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: 5c90da28fcf62b76b25bee920a7d76c218ea9bc863a37bdaf0890b68d873d064
4
+ data.tar.gz: 8732e8319d49c793fc79a14d8d2fd36596e037f6ab90867b3dd4329784c4935a
5
+ SHA512:
6
+ metadata.gz: 4aff74febd95ea6e0d7515b0a8411a641169fe62307ac020bd212a177172556f28c94cc32d0c8046f6042fc166c295a3d805a482c523f4155f09ef5e69bf6519
7
+ data.tar.gz: 22d6aed2f31a6c9f85d3d485909dac450f9dd3d14eafbe331712b622d47ea0f689b702e0068d810189cdbeb79a7750c4fc3c3d627b6a2b19fb6ff56b5a9a136e
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/testdouble/standard
3
+ ruby_version: 2.6
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.0.1] - 2023-10-22
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 TODO: Write your email address. 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/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in orbai.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "standard", "~> 1.3"
data/README.md ADDED
@@ -0,0 +1,253 @@
1
+ # `orbai`: A Ruby DSL for OpenAI
2
+
3
+ Welcome to `orbai`, an idiomatic Ruby DSL for OpenAI's powerful API. With the
4
+ combination of Ruby's natural language processing strengths and OpenAI's
5
+ advanced capabilities, your applications are set to take a massive leap forward.
6
+
7
+ ## Disclaimer
8
+
9
+ Please be aware that `orbai` is in its early stages and is not maintained
10
+ regularly. While we aim to provide the best, there might be bugs or
11
+ unimplemented features. Your patience and contributions are highly appreciated.
12
+
13
+ ## Quick Start (For Rubyists)
14
+
15
+ 1. Install the orbai gem:
16
+
17
+ ```sh
18
+ gem install orbai
19
+ ```
20
+
21
+ 1. [Have an OpenAI API key](https://beta.openai.com/account/api-keys) in your
22
+ environment. By default, `orbai` will look for `OPENAI_API_KEY`..
23
+
24
+ 1. Use `orbai` to query OpenAI:
25
+
26
+ ```ruby
27
+ require "orbai"
28
+
29
+ Orbai.query("What's the capital of France?")
30
+
31
+ # => "The capital of France is Paris."
32
+ ```
33
+
34
+ ## Rationale
35
+
36
+ 1. **Ruby is the Best Language for DSLs**: Ruby's expressiveness has made it the
37
+ go-to language for Domain Specific Languages, finding its use in a myriad of
38
+ practical domains.
39
+ 2. **OpenAI & Ruby**: OpenAI offers transformative capabilities to the domains
40
+ where Ruby DSLs excel.
41
+ 3. **orbai**: Born out of the need for an expressive, easy-to-integrate tool
42
+ that merges the power of OpenAI and the elegance of Ruby.
43
+
44
+ ## Getting Started (For Newbies)
45
+
46
+ 1. Installing Ruby: If you're a technical person, we recommend using
47
+ [asdf-vm](https://github.com/asdf-vm/asdf) for version management.
48
+ 1. Learning Ruby: If you're new to Ruby... `TODO`
49
+ 1. Follow the "Quick Start" guide above to get up and running.
50
+
51
+ ## Development
52
+
53
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run
54
+ `rake spec` to run the tests. You can also run `bin/console` for an interactive
55
+ prompt that will allow you to experiment.
56
+
57
+ To install this gem onto your local machine, run `bundle exec rake install`. To
58
+ release a new version, update the version number in `version.rb`, and then run
59
+ `bundle exec rake release`, which will create a git tag for the version, push
60
+ git commits and the created tag, and push the `.gem` file to
61
+ [rubygems.org](https://rubygems.org).
62
+
63
+ ## Contributing
64
+
65
+ We welcome contributions to `orbai`! If you stumble upon issues or have features
66
+ you'd like to suggest, please:
67
+
68
+ - [Submit an issue](https://github.com/skotchpine/orbai/issues)
69
+ - For direct contributions,
70
+ [submit a pull request](https://github.com/skotchpine/orbai/pulls).
71
+
72
+ ## Help Wanted!
73
+
74
+ - 🔲 Feedback
75
+ - 🔲 Docs
76
+ - 🔲 Tests
77
+ - 🔲 Triage
78
+ - 🔲 Imagination
79
+
80
+ ## `Orbai::DSL`
81
+
82
+ ### Simple Query API
83
+
84
+ ```ruby
85
+ require "orbai"
86
+ Orbai.query("What is your favorite color?")
87
+ #=> "My favorite color is blue."
88
+ ```
89
+
90
+ ### Wishlist
91
+
92
+ - 🔲 Config DX
93
+ - 🔲 Roles Builder DX
94
+ - 🔲 Context Params DX
95
+ - 🔲 Extract structured data
96
+ - 🔲 Functions DX
97
+ - 🔲 Images DX
98
+ - 🔲 Audio DX
99
+ - 🔲 Files DX
100
+ - 🔲 Embeddings DX
101
+ - 🔲 Fine-tuning DX
102
+
103
+ ## `Orbai` Module / `HttpClient` HTTP Methods
104
+
105
+ The `Orbai` module is just a container for everything else.
106
+
107
+ For ease of use, it includes http getters through an `HttpClient` singleton.
108
+
109
+ The HTTP getters throw an `Orbai::HTTPClient::Error` if the request fails. The
110
+ OpenAI API `type` field from the error response is assigned to
111
+ `Orbai::HTTPClient::Error#type`.
112
+
113
+ ### Example
114
+
115
+ ```ruby
116
+ Orbai.get("/chat/completions", model: 'gpt-3.5-turbo', messages: [
117
+ {role:'system',content:'Act as a helpful prompt.'},
118
+ {role:'user',content:'What is the capital of France?'},
119
+ ])
120
+
121
+ # Returns
122
+ {"id"=>"chatcmpl-XXXXXXXX",
123
+ "object"=>"chat.completion",
124
+ "created"=>1697444538,
125
+ "model"=>"gpt-3.5-turbo-0613",
126
+ "choices"=>
127
+ [{"index"=>0,
128
+ "message"=>
129
+ {"role"=>"assistant", "content"=>"The capital of France is Paris."},
130
+ "finish_reason"=>"stop"}],
131
+ "usage"=>{"prompt_tokens"=>24, "completion_tokens"=>7, "total_tokens"=>31}}
132
+ ```
133
+
134
+ ### `Orbai` Shortcuts / `HttpClient` HTTP Methods
135
+
136
+ ```ruby
137
+ c = Orbai::HttpClient.new
138
+
139
+ # HttpClient singleton
140
+ c.http_client #=> #<Orbai::HttpClient>
141
+
142
+ # HTTP Methods
143
+ c.get(path, **params) #=> Returns JSON result as a ruby hash.
144
+ c.post(path, **params)
145
+ c.put(path, **params)
146
+ c.patch(path, **params)
147
+ c.delete(path, **params)
148
+ c.http_request(method, path, **params)
149
+ ```
150
+
151
+ ## `Orbai::HttpClient`
152
+
153
+ The `HttpClient` class is used to make requests to the OpenAI API. It returns
154
+ the JSON response from the API as a ruby hash.
155
+
156
+ ### Example:
157
+
158
+ ```ruby
159
+ c = Orbai::HttpClient.new
160
+
161
+ c.chat_completions(
162
+ model: 'gpt-3.5-turbo',
163
+ messages: [
164
+ {role:'system',content:'Act as a helpful prompt.'},
165
+ {role:'user',content:'What is the capital of France?'},
166
+ ],
167
+ )
168
+
169
+ # Returns
170
+ {"id"=>"chatcmpl-XXXXXXXX",
171
+ "object"=>"chat.completion",
172
+ "created"=>1697983333,
173
+ "model"=>"gpt-3.5-turbo-0613",
174
+ "choices"=>
175
+ [{"index"=>0,
176
+ "message"=>
177
+ {"role"=>"assistant", "content"=>"The capital of France is Paris."},
178
+ "finish_reason"=>"stop"}],
179
+ "usage"=>{"prompt_tokens"=>24, "completion_tokens"=>7, "total_tokens"=>31}}
180
+ ```
181
+
182
+ ### API Methods Cheatsheet
183
+
184
+ ```ruby
185
+ c = Orbai::HttpClient.new
186
+
187
+ # Chat
188
+ # POST /chat/completions
189
+ c.chat_completions(**params)
190
+
191
+ # Completions
192
+ # POST /completions
193
+ c.completions(**params)
194
+
195
+ # Edits
196
+ # POST /edits
197
+ c.edits(**params)
198
+
199
+ # Images
200
+ # POST /images/generations
201
+ c.create_image(**params)
202
+ # POST /images/edits
203
+ c.create_image_edit(**params)
204
+ # POST /images/variations
205
+ c.create_image_variation(**params)
206
+
207
+ # Embeddings
208
+ # POST /embeddings
209
+ c.create_embedding(**params)
210
+
211
+ # Fine_tuning
212
+ #
213
+ # POST /fine_tuning/jobs
214
+ c.create_fine_tuning_jobs(**params)
215
+ # GET /fine_tuning/jobs
216
+ c.list_fine_tuning_jobs(**params)
217
+ # GET /fine_tuning/jobs/{fine_tuning_job_id}
218
+ c.retrieve_fine_tuning_job(id, **params)
219
+ # POST /fine_tuning/jobs/{fine_tuning_job_id}/cancel
220
+ c.cancel_fine_tuning_job(id, **params)
221
+ # GET /fine_tuning/jobs/{fine_tuning_job_id}/events
222
+ c.list_fine_tuning_events(id, **params)
223
+
224
+ # Audio
225
+ # POST /audio/transcriptions
226
+ c.create_transcription(**params)
227
+ # POST /audio/translations
228
+ c.create_translation(**params)
229
+
230
+ # Files
231
+ # GET /files
232
+ c.list_files(**params)
233
+ # POST /files
234
+ c.upload_file(**params)
235
+ # DELETE /files/{file_id}
236
+ c.delete_file(id, **params)
237
+ # GET /files/{file_id}
238
+ c.retrieve_file(id, **params)
239
+ # GET /files/{file_id}/content
240
+ c.file_content(id, **params)
241
+
242
+ # Models
243
+ # GET /models
244
+ c.list_models(**params)
245
+ # GET /models/{model}
246
+ c.retrieve_model(id, **params)
247
+ # DELETE /models/{model}
248
+ c.delete_model(id, **params)
249
+
250
+ # Moderations
251
+ # POST /moderations
252
+ c.create_moderation(**params)
253
+ ```
data/Rakefile ADDED
@@ -0,0 +1,10 @@
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 "standard/rake"
9
+
10
+ task default: %i[spec standard]
data/lib/orbai/dsl.rb ADDED
@@ -0,0 +1,3 @@
1
+ module Orbai::Dsl
2
+ # TODO
3
+ end
@@ -0,0 +1,51 @@
1
+ module Orbai
2
+ # Better experience for API interaction
3
+ class HttpClient
4
+ class Error < StandardError
5
+ attr_reader :type
6
+ def initialize(response)
7
+ @type = response['type']
8
+ super(response['message'])
9
+ end
10
+ end
11
+
12
+ DEFAULT_OPS = {
13
+ url: 'https://api.openai.com/v1',
14
+ token: ENV['OPENAI_API_KEY'],
15
+ default_prompt: 'Act as a ruby programmer introducing someone to the language.',
16
+ default_model: 'gpt-3.5-turbo'
17
+ }
18
+
19
+ def initialize(**ops)
20
+ @ops = DEFAULT_OPS.merge(ops)
21
+ end
22
+
23
+ # Send HTTP request to openAI's API
24
+ #
25
+ # NOTE: method must be lowercase
26
+ #
27
+ def http_request(method, path, multipart: false, **params)
28
+ url = "#{@ops[:url]}#{path}"
29
+ headers = {'Authorization' => "Bearer #{@ops[:token]}"}
30
+
31
+ response = if multipart
32
+ headers['Content-Type'] = 'multipart/form-data'
33
+ HTTParty.send(method, url, multipart:, headers:, body: params)
34
+ else
35
+ headers['Content-Type'] = 'application/json'
36
+ HTTParty.send(method, url, multipart:, headers:, body: params.to_json)
37
+ end
38
+
39
+ raise Error, response['error'] if response['error']
40
+
41
+ response
42
+ end
43
+
44
+ # HTTP method helpers: get, post, put, patch, delete
45
+ def get(path, **params) = http_request('get', path, **params)
46
+ def post(path, **params) = http_request('post', path, **params)
47
+ def put(path, **params) = http_request('put', path, **params)
48
+ def patch(path, **params) = http_request('patch', path, **params)
49
+ def delete(path, **params) = http_request('delete', path, **params)
50
+ end
51
+ end
@@ -0,0 +1,69 @@
1
+ # Complete public openai API: https://beta.openai.com/docs/api-reference
2
+ class Orbai::HttpClient
3
+ # Chat
4
+ # POST /chat/completions
5
+ def chat_completions(**params) = post("/chat/completions", **params)
6
+
7
+ # Completions
8
+ # POST /completions
9
+ def completions(**params) = post("/completions", **params)
10
+
11
+ # Edits
12
+ # POST /edits
13
+ def edits(**params) = post("/edits", **params)
14
+
15
+ # Images
16
+ # POST /images/generations
17
+ def create_image(**params) = post("/images/generations", **params)
18
+ # POST /images/edits
19
+ def create_image_edit(**params) = post("/images/edits", multipart: true, **params)
20
+ # POST /images/variations
21
+ def create_image_variation(**params) = post("/images/variations", multipart: true, **params)
22
+
23
+ # Embeddings
24
+ # POST /embeddings
25
+ def create_embedding(**params) = post("/embeddings", **params)
26
+
27
+ # Fine_tuning
28
+ #
29
+ # POST /fine_tuning/jobs
30
+ def create_fine_tuning_jobs(**params) = post("/fine_tuning/jobs", **params)
31
+ # GET /fine_tuning/jobs
32
+ def list_fine_tuning_jobs(**params) = get("/fine_tuning/jobs", **params)
33
+ # GET /fine_tuning/jobs/{fine_tuning_job_id}
34
+ def retrieve_fine_tuning_job(id, **params) = get("/fine_tuning/jobs/#{id}", **params)
35
+ # POST /fine_tuning/jobs/{fine_tuning_job_id}/cancel
36
+ def cancel_fine_tuning_job(id, **params) = post("/fine_tuning/jobs/#{id}/cancel", **params)
37
+ # GET /fine_tuning/jobs/{fine_tuning_job_id}/events
38
+ def list_fine_tuning_events(id, **params) = get("/fine_tuning/jobs/#{id}/events", **params)
39
+
40
+ # Audio
41
+ # POST /audio/transcriptions
42
+ def create_transcription(**params) = post("/audio/transcriptions", multipart: true, **params)
43
+ # POST /audio/translations
44
+ def create_translation(**params) = post("/audio/translations", multipart: true, **params)
45
+
46
+ # Files
47
+ # GET /files
48
+ def list_files(**params) = get("/files", **params)
49
+ # POST /files
50
+ def upload_file(**params) = post("/files", multipart: true, **params)
51
+ # DELETE /files/{file_id}
52
+ def delete_file(id, **params) = delete("/files/#{id}", **params)
53
+ # GET /files/{file_id}
54
+ def retrieve_file(id, **params) = get("/files/#{id}", **params)
55
+ # GET /files/{file_id}/content
56
+ def file_content(id, **params) = get("/files/#{id}/content", **params)
57
+
58
+ # Models
59
+ # GET /models
60
+ def list_models(**params) = get("/models", **params)
61
+ # GET /models/{model}
62
+ def retrieve_model(id, **params) = get("/models/#{id}", **params)
63
+ # DELETE /models/{model}
64
+ def delete_model(id, **params) = delete("/models/#{id}", **params)
65
+
66
+ # Moderations
67
+ # POST /moderations
68
+ def create_moderation(**params) = post("/moderations", **params)
69
+ end
@@ -0,0 +1,10 @@
1
+ class << Orbai
2
+ def query(prompt)
3
+ response = http_client.chat_completions(model: 'gpt-3.5-turbo', messages: [
4
+ {role:'system', content: 'Act as a helpful prompt.'},
5
+ {role:'user', content: prompt},
6
+ ])
7
+
8
+ response['choices'].first['message']['content']
9
+ end
10
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Orbai
4
+ VERSION = "0.0.1"
5
+ end
data/lib/orbai.rb ADDED
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'httparty'
4
+
5
+ require_relative "orbai/version"
6
+ require_relative "orbai/http_client"
7
+ require_relative "orbai/openai_methods"
8
+ require_relative "orbai/simple_methods"
9
+ require_relative "orbai/dsl"
10
+
11
+ module Orbai
12
+ # Better experience for API errors
13
+ class << self
14
+ extend Forwardable
15
+
16
+ # Singleton client for method delegation
17
+ def http_client = @http_client ||= HttpClient.new
18
+
19
+ def_delegators :http_client,
20
+ :get, :post, :put, :patch, :delete, :http_request
21
+ end
22
+ end