ruby-advanced-openai 4.1.0 → 4.1.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ebf6f6a2c422f1842883062ffe4e6dcc3315ed79323f126ebf1c759d005d68f4
4
- data.tar.gz: fc2be4ce29643e0f38a67adda1488364f2f280a139e66b8a484548f4ac97c5ac
3
+ metadata.gz: 524aac2fb147784d0a663a665b620de29a1e76359976d60be2697c08766c4ca1
4
+ data.tar.gz: 59056a07679f7669e735776aa5abb37bbd87dd74cdfc0178543e180272fb0ba1
5
5
  SHA512:
6
- metadata.gz: '06879b030e8f7b254101db3e1b11ca024471dc3491ee853552a167e4768529045761860c8d177fb7075e66af52c4a87b6816a193e1fd8abaf04b73ca64d945c1'
7
- data.tar.gz: '0028141fb741a851be88708ffa2c4eaffa0fd91470d45995f6b99a1297c411d16a387543f11849ee78602599746f63691b8aa003c43e78dde9c6aa5a8ba0784e'
6
+ metadata.gz: 7b596f1b5e887d8156b0a26ec96b2da76db8116894cc3bbb5b5bfb606f92ff62c02fc74cae64df1cad9674e2ce2149ecd79d6af644388f376ffa03f15b5bddd7
7
+ data.tar.gz: 7d339f816a2c3cbef65ed48eb8ca9d5a477725c51c45e8ccd8a33460df12095f89bc7bf26cd72def432224a05e63cf1bb3872658357e937958fe13f5e76bf6e9
data/README.md CHANGED
@@ -1,2 +1,394 @@
1
- # Ruby Advanced OpenAI
2
- I will be creating an advanced gem for utilizing OpenAI, based on https://github.com/alexrudall/ruby-openai.
1
+ # Ruby OpenAI
2
+ Use the [OpenAI API](https://openai.com/blog/openai-api/) with Ruby.
3
+ ruby-advanced-openai is a customized of https://github.com/alexrudall/ruby-openai.
4
+
5
+ ### Bundler
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem "ruby-advanced-openai"
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ ### Gem install
18
+
19
+ Or install with:
20
+
21
+ $ gem install ruby-advanced-openai
22
+
23
+ and require with:
24
+
25
+ ```ruby
26
+ require "openai"
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ - Get your API key from [https://platform.openai.com/account/api-keys](https://platform.openai.com/account/api-keys)
32
+ - If you belong to multiple organizations, you can get your Organization ID from [https://platform.openai.com/account/org-settings](https://platform.openai.com/account/org-settings)
33
+
34
+ ### Quickstart
35
+
36
+ For a quick test you can pass your token directly to a new client:
37
+
38
+ ```ruby
39
+ client = OpenAI::Client.new(access_token: "access_token_goes_here")
40
+ ```
41
+
42
+ ### With Config
43
+
44
+ For a more robust setup, you can configure the gem with your API keys, for example in an `openai.rb` initializer file. Never hardcode secrets into your codebase - instead use something like [dotenv](https://github.com/motdotla/dotenv) to pass the keys safely into your environments.
45
+
46
+ ```ruby
47
+ OpenAI.configure do |config|
48
+ config.access_token = ENV.fetch("OPENAI_ACCESS_TOKEN")
49
+ config.organization_id = ENV.fetch("OPENAI_ORGANIZATION_ID") # Optional.
50
+ end
51
+ ```
52
+
53
+ Then you can create a client like this:
54
+
55
+ ```ruby
56
+ client = OpenAI::Client.new
57
+ ```
58
+
59
+ #### Custom timeout or base URI
60
+
61
+ The default timeout for any request using this library is 120 seconds. You can change that by passing a number of seconds to the `request_timeout` when initializing the client. You can also change the base URI used for all requests, eg. to use observability tools like [Helicone](https://docs.helicone.ai/quickstart/integrate-in-one-line-of-code):
62
+
63
+ ```ruby
64
+ client = OpenAI::Client.new(
65
+ access_token: "access_token_goes_here",
66
+ uri_base: "https://oai.hconeai.com/",
67
+ request_timeout: 240
68
+ )
69
+ ```
70
+
71
+ or when configuring the gem:
72
+
73
+ ```ruby
74
+ OpenAI.configure do |config|
75
+ config.access_token = ENV.fetch("OPENAI_ACCESS_TOKEN")
76
+ config.organization_id = ENV.fetch("OPENAI_ORGANIZATION_ID") # Optional
77
+ config.uri_base = "https://oai.hconeai.com/" # Optional
78
+ config.request_timeout = 240 # Optional
79
+ end
80
+ ```
81
+
82
+ ### Models
83
+
84
+ There are different models that can be used to generate text. For a full list and to retrieve information about a single model:
85
+
86
+ ```ruby
87
+ client.models.list
88
+ client.models.retrieve(id: "text-ada-001")
89
+ ```
90
+
91
+ #### Examples
92
+
93
+ - [GPT-4 (limited beta)](https://platform.openai.com/docs/models/gpt-4)
94
+ - gpt-4
95
+ - gpt-4-0314
96
+ - gpt-4-32k
97
+ - [GPT-3.5](https://platform.openai.com/docs/models/gpt-3-5)
98
+ - gpt-3.5-turbo
99
+ - gpt-3.5-turbo-0301
100
+ - text-davinci-003
101
+ - [GPT-3](https://platform.openai.com/docs/models/gpt-3)
102
+ - text-ada-001
103
+ - text-babbage-001
104
+ - text-curie-001
105
+
106
+ ### ChatGPT
107
+
108
+ ChatGPT is a model that can be used to generate text in a conversational style. You can use it to [generate a response](https://platform.openai.com/docs/api-reference/chat/create) to a sequence of [messages](https://platform.openai.com/docs/guides/chat/introduction):
109
+
110
+ ```ruby
111
+ response = client.chat(
112
+ parameters: {
113
+ model: "gpt-3.5-turbo", # Required.
114
+ messages: [{ role: "user", content: "Hello!"}], # Required.
115
+ temperature: 0.7,
116
+ })
117
+ puts response.dig("choices", 0, "message", "content")
118
+ # => "Hello! How may I assist you today?"
119
+ ```
120
+
121
+ ### ChatGPT for reply mail or ...
122
+
123
+ ```ruby
124
+ incoming_mail = <<~MESSAGE
125
+ 拝啓、Hoge様
126
+
127
+ お世話になっております。私たちの会社は、〇〇に関する新規プロジェクトの立ち上げを検討しております。このたび、貴社に対して提案書の作成を依頼させていただきたく、ご連絡差し上げました。
128
+
129
+ ご承知の通り、弊社は〇〇分野での豊富な経験と実績を持つ企業です。今回のプロジェクトにおいても、貴社の専門知識と技術力に大変興味を持っており、提案書を通じて具体的な提案をいただければと考えています。
130
+
131
+ 提案書の内容には、以下の要素を含めていただけると幸いです:
132
+
133
+ 1. プロジェクトの目的と背景
134
+ 2. 提案するソリューションやアプローチ
135
+ 3. 予算と納期の見積もり
136
+ 4. 弊社と貴社の連携方法やプロジェクトの進行管理について
137
+
138
+ なお、提案書の作成にあたり、詳細な要件や資料を別途提供させていただきます。また、提案書の提出期限は〇〇月〇〇日までとさせていただきますので、お時間の許す範囲でご検討いただければ幸いです。
139
+
140
+ お忙しい中恐縮ですが、貴社のご協力とご検討をお願い申し上げます。何卒、ご返信をいただけますようお願い申し上げます。
141
+
142
+ 敬具
143
+ fuga株式会社
144
+ MESSAGE
145
+ response = client.suggested_reply(model: "gpt-4", incoming_mail: incoming_mail, reply_summary: "承知しました。")
146
+ puts response.dig("choices", 0, "message", "content")
147
+ # => {Email reply text}
148
+ ```
149
+
150
+ ### Streaming ChatGPT
151
+
152
+ [Quick guide to streaming ChatGPT with Rails 7 and Hotwire](https://gist.github.com/alexrudall/cb5ee1e109353ef358adb4e66631799d)
153
+
154
+ You can stream from the API in realtime, which can be much faster and used to create a more engaging user experience. Pass a [Proc](https://ruby-doc.org/core-2.6/Proc.html) (or any object with a `#call` method) to the `stream` parameter to receive the stream of text chunks as they are generated. Each time one or more chunks is received, the proc will be called once with each chunk, parsed as a Hash. If OpenAI returns an error, `ruby-openai` will pass that to your proc as a Hash.
155
+
156
+ ```ruby
157
+ client.chat(
158
+ parameters: {
159
+ model: "gpt-3.5-turbo", # Required.
160
+ messages: [{ role: "user", content: "Describe a character called Anna!"}], # Required.
161
+ temperature: 0.7,
162
+ stream: proc do |chunk, _bytesize|
163
+ print chunk.dig("choices", 0, "delta", "content")
164
+ end
165
+ })
166
+ # => "Anna is a young woman in her mid-twenties, with wavy chestnut hair that falls to her shoulders..."
167
+ ```
168
+
169
+ ### Completions
170
+
171
+ Hit the OpenAI API for a completion using other GPT-3 models:
172
+
173
+ ```ruby
174
+ response = client.completions(
175
+ parameters: {
176
+ model: "text-davinci-001",
177
+ prompt: "Once upon a time",
178
+ max_tokens: 5
179
+ })
180
+ puts response["choices"].map { |c| c["text"] }
181
+ # => [", there lived a great"]
182
+ ```
183
+
184
+ ### Edits
185
+
186
+ Send a string and some instructions for what to do to the string:
187
+
188
+ ```ruby
189
+ response = client.edits(
190
+ parameters: {
191
+ model: "text-davinci-edit-001",
192
+ input: "What day of the wek is it?",
193
+ instruction: "Fix the spelling mistakes"
194
+ }
195
+ )
196
+ puts response.dig("choices", 0, "text")
197
+ # => What day of the week is it?
198
+ ```
199
+
200
+ ### Embeddings
201
+
202
+ You can use the embeddings endpoint to get a vector of numbers representing an input. You can then compare these vectors for different inputs to efficiently check how similar the inputs are.
203
+
204
+ ```ruby
205
+ client.embeddings(
206
+ parameters: {
207
+ model: "babbage-similarity",
208
+ input: "The food was delicious and the waiter..."
209
+ }
210
+ )
211
+ ```
212
+
213
+ ### Files
214
+
215
+ Put your data in a `.jsonl` file like this:
216
+
217
+ ```json
218
+ {"prompt":"Overjoyed with my new phone! ->", "completion":" positive"}
219
+ {"prompt":"@lakers disappoint for a third straight night ->", "completion":" negative"}
220
+ ```
221
+
222
+ and pass the path to `client.files.upload` to upload it to OpenAI, and then interact with it:
223
+
224
+ ```ruby
225
+ client.files.upload(parameters: { file: "path/to/sentiment.jsonl", purpose: "fine-tune" })
226
+ client.files.list
227
+ client.files.retrieve(id: "file-123")
228
+ client.files.content(id: "file-123")
229
+ client.files.delete(id: "file-123")
230
+ ```
231
+
232
+ ### Fine-tunes
233
+
234
+ Upload your fine-tuning data in a `.jsonl` file as above and get its ID:
235
+
236
+ ```ruby
237
+ response = client.files.upload(parameters: { file: "path/to/sentiment.jsonl", purpose: "fine-tune" })
238
+ file_id = JSON.parse(response.body)["id"]
239
+ ```
240
+
241
+ You can then use this file ID to create a fine-tune model:
242
+
243
+ ```ruby
244
+ response = client.finetunes.create(
245
+ parameters: {
246
+ training_file: file_id,
247
+ model: "ada"
248
+ })
249
+ fine_tune_id = response["id"]
250
+ ```
251
+
252
+ That will give you the fine-tune ID. If you made a mistake you can cancel the fine-tune model before it is processed:
253
+
254
+ ```ruby
255
+ client.finetunes.cancel(id: fine_tune_id)
256
+ ```
257
+
258
+ You may need to wait a short time for processing to complete. Once processed, you can use list or retrieve to get the name of the fine-tuned model:
259
+
260
+ ```ruby
261
+ client.finetunes.list
262
+ response = client.finetunes.retrieve(id: fine_tune_id)
263
+ fine_tuned_model = response["fine_tuned_model"]
264
+ ```
265
+
266
+ This fine-tuned model name can then be used in completions:
267
+
268
+ ```ruby
269
+ response = client.completions(
270
+ parameters: {
271
+ model: fine_tuned_model,
272
+ prompt: "I love Mondays!"
273
+ }
274
+ )
275
+ response.dig("choices", 0, "text")
276
+ ```
277
+
278
+ You can delete the fine-tuned model when you are done with it:
279
+
280
+ ```ruby
281
+ client.finetunes.delete(fine_tuned_model: fine_tuned_model)
282
+ ```
283
+
284
+ ### Image Generation
285
+
286
+ Generate an image using DALL·E! The size of any generated images must be one of `256x256`, `512x512` or `1024x1024` -
287
+ if not specified the image will default to `1024x1024`.
288
+
289
+ ```ruby
290
+ response = client.images.generate(parameters: { prompt: "A baby sea otter cooking pasta wearing a hat of some sort", size: "256x256" })
291
+ puts response.dig("data", 0, "url")
292
+ # => "https://oaidalleapiprodscus.blob.core.windows.net/private/org-Rf437IxKhh..."
293
+ ```
294
+
295
+ ![Ruby](https://i.ibb.co/6y4HJFx/img-d-Tx-Rf-RHj-SO5-Gho-Cbd8o-LJvw3.png)
296
+
297
+ ### Image Edit
298
+
299
+ Fill in the transparent part of an image, or upload a mask with transparent sections to indicate the parts of an image that can be changed according to your prompt...
300
+
301
+ ```ruby
302
+ response = client.images.edit(parameters: { prompt: "A solid red Ruby on a blue background", image: "image.png", mask: "mask.png" })
303
+ puts response.dig("data", 0, "url")
304
+ # => "https://oaidalleapiprodscus.blob.core.windows.net/private/org-Rf437IxKhh..."
305
+ ```
306
+
307
+ ![Ruby](https://i.ibb.co/sWVh3BX/dalle-ruby.png)
308
+
309
+ ### Image Variations
310
+
311
+ Create n variations of an image.
312
+
313
+ ```ruby
314
+ response = client.images.variations(parameters: { image: "image.png", n: 2 })
315
+ puts response.dig("data", 0, "url")
316
+ # => "https://oaidalleapiprodscus.blob.core.windows.net/private/org-Rf437IxKhh..."
317
+ ```
318
+
319
+ ![Ruby](https://i.ibb.co/TWJLP2y/img-miu-Wk-Nl0-QNy-Xtj-Lerc3c0l-NW.png)
320
+ ![Ruby](https://i.ibb.co/ScBhDGB/img-a9-Be-Rz-Au-Xwd-AV0-ERLUTSTGdi.png)
321
+
322
+ ### Moderations
323
+
324
+ Pass a string to check if it violates OpenAI's Content Policy:
325
+
326
+ ```ruby
327
+ response = client.moderations(parameters: { input: "I'm worried about that." })
328
+ puts response.dig("results", 0, "category_scores", "hate")
329
+ # => 5.505014632944949e-05
330
+ ```
331
+
332
+ ### Whisper
333
+
334
+ Whisper is a speech to text model that can be used to generate text based on audio files:
335
+
336
+ #### Translate
337
+
338
+ The translations API takes as input the audio file in any of the supported languages and transcribes the audio into English.
339
+
340
+ ```ruby
341
+ response = client.translate(
342
+ parameters: {
343
+ model: "whisper-1",
344
+ file: File.open("path_to_file", "rb"),
345
+ })
346
+ puts response["text"]
347
+ # => "Translation of the text"
348
+ ```
349
+
350
+ #### Transcribe
351
+
352
+ The transcriptions API takes as input the audio file you want to transcribe and returns the text in the desired output file format.
353
+
354
+ ```ruby
355
+ response = client.transcribe(
356
+ parameters: {
357
+ model: "whisper-1",
358
+ file: File.open("path_to_file", "rb"),
359
+ })
360
+ puts response["text"]
361
+ # => "Transcription of the text"
362
+ ```
363
+
364
+ ## Development
365
+
366
+ After checking out the repo, run `bin/setup` to install dependencies. You can run `bin/console` for an interactive prompt that will allow you to experiment.
367
+
368
+ To install this gem onto your local machine, run `bundle exec rake install`.
369
+
370
+ ### Warning
371
+
372
+ If you have an `OPENAI_ACCESS_TOKEN` in your `ENV`, running the specs will use this to run the specs against the actual API, which will be slow and cost you money - 2 cents or more! Remove it from your environment with `unset` or similar if you just want to run the specs against the stored VCR responses.
373
+
374
+ ## Release
375
+
376
+ First run the specs without VCR so they actually hit the API. This will cost 2 cents or more. Set OPENAI_ACCESS_TOKEN in your environment or pass it in like this:
377
+
378
+ ```
379
+ OPENAI_ACCESS_TOKEN=123abc bundle exec rspec
380
+ ```
381
+
382
+ Then update the version number in `version.rb`, update `CHANGELOG.md`, run `bundle install` to update Gemfile.lock, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
383
+
384
+ ## Contributing
385
+
386
+ Bug reports and pull requests are welcome on GitHub at <https://github.com/alexrudall/ruby-openai>. 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/alexrudall/ruby-openai/blob/main/CODE_OF_CONDUCT.md).
387
+
388
+ ## License
389
+
390
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
391
+
392
+ ## Code of Conduct
393
+
394
+ Everyone interacting in the Ruby OpenAI project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/alexrudall/ruby-openai/blob/main/CODE_OF_CONDUCT.md).
@@ -0,0 +1,58 @@
1
+ module OpenAI
2
+ module Assistant
3
+ class Replyer
4
+ def initialize(model: "gpt-3.5-turbo", incoming_mail: "", reply_summary: "", situation: 'formal', other_request: "")
5
+ return if incoming_mail.empty? || reply_summary.empty?
6
+
7
+ @prompt_data = prompt_data(model:model, incoming_mail: incoming_mail, reply_summary: reply_summary, situation: situation, other_request: other_request)
8
+ end
9
+
10
+ def prompt_data(model:, incoming_mail:, reply_summary:, situation:, other_request:)
11
+ {
12
+ model: model,
13
+ incoming_mail: incoming_mail,
14
+ reply_summary: reply_summary,
15
+ situation: situation,
16
+ other_request: other_request
17
+ }
18
+ end
19
+
20
+ def get_prompt_data(model:, incoming_mail:, reply_summary:, situation:, other_request:)
21
+ @prompt_data
22
+ end
23
+
24
+ def set_prompt_data(model:, incoming_mail:, reply_summary:, situation:, other_request:)
25
+ @prompt_data[:incoming_mail] = incoming_mail if !incoming_mail.empty?
26
+ @prompt_data[:reply_summary] = reply_summary if !reply_summary.empty?
27
+ @prompt_data[:situation] = situation if !situation.empty?
28
+ @prompt_data[:other_request] = other_request if !other_request.empty?
29
+ end
30
+
31
+ def parameters
32
+ {
33
+ model: @prompt_data[:model],
34
+ messages: [
35
+ { role: "system", content: system_prompt },
36
+ # { role: "user", content: user_prompt }
37
+ ],
38
+ temperature: 0.7,
39
+ }
40
+ end
41
+
42
+ private
43
+
44
+ def system_prompt
45
+ system_prompt = []
46
+ system_prompt << "状況:" + @prompt_data[:situation]
47
+ system_prompt << "返信したい内容:" + @prompt_data[:reply_summary]
48
+ system_prompt << "受信したメール:" + @prompt_data[:incoming_mail]
49
+ system_prompt << "その他要望:" + @prompt_data[:other_request] if @prompt_data[:other_request].empty?
50
+ system_prompt << "USER: メールの返信を作成してください。\nASSISTANT:"
51
+ system_prompt.join(',')
52
+ end
53
+
54
+ def user_prompt
55
+ end
56
+ end
57
+ end
58
+ end
data/lib/openai/client.rb CHANGED
@@ -1,3 +1,5 @@
1
+ require_relative "assistant/replyer"
2
+
1
3
  module OpenAI
2
4
  class Client
3
5
  extend OpenAI::HTTP
@@ -13,6 +15,20 @@ module OpenAI
13
15
  OpenAI::Client.json_post(path: "/chat/completions", parameters: parameters)
14
16
  end
15
17
 
18
+ def suggested_reply(model: nil, incoming_mail: "", reply_summary: "", situation: nil, other_request: nil, assistant: nil)
19
+ response = if !assistant.nil?
20
+ self.chat(parameters: assistant.parameters)
21
+ else
22
+ return if incoming_mail.empty? || reply_summary.empty?
23
+
24
+ self.chat(
25
+ OpenAI::Assistant::Replyer.new(model: model, incoming_mail: incoming_mail, reply_summary: reply_summary, situation: situation, other_request: other_request)
26
+ )
27
+ end
28
+ response
29
+ # TODO: erorrs
30
+ end
31
+
16
32
  def completions(parameters: {})
17
33
  OpenAI::Client.json_post(path: "/completions", parameters: parameters)
18
34
  end
@@ -1,3 +1,3 @@
1
1
  module OpenAI
2
- VERSION = "4.1.0".freeze
2
+ VERSION = "4.1.1".freeze
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ruby-advanced-openai
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.1.0
4
+ version: 4.1.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Yudai-hub
@@ -63,6 +63,7 @@ files:
63
63
  - bin/console
64
64
  - bin/setup
65
65
  - lib/openai.rb
66
+ - lib/openai/assistant/replyer.rb
66
67
  - lib/openai/client.rb
67
68
  - lib/openai/compatibility.rb
68
69
  - lib/openai/files.rb