gigachat 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: bb38802873e44d6e1d9aad8940df6400c6a16f3a2814d3a8948e3ac130f9707c
4
+ data.tar.gz: c3300767d479e780969bf1dd2c406279cf39f48f4e48a6d6e68b718e342001fc
5
+ SHA512:
6
+ metadata.gz: 6a33cc2b0f65be98a5604b133dd43590acfd892feaa894ed4253b1a6b56561e35e126a1f24fca5040261492a1f5722b72abde10cde6b44549bbc86d136120b11
7
+ data.tar.gz: 2b55ed7b6f95fff6ea0b412904e0b0e7a81f05757b5708bf2c09a3b9c731da6590a7b66e3532b1610f9071bca588c533a2e308ab0cb9c2398f34d54675bba2f7
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.3.5
data/CHANGELOG.md ADDED
@@ -0,0 +1,4 @@
1
+
2
+ ## [0.1.0] - 2024-09-12
3
+
4
+ - 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 smolev@me.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 neonix20b
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,284 @@
1
+ # Ruby GigaChat
2
+
3
+ [![Gem Version](https://img.shields.io/gem/v/gigachat.svg)](https://rubygems.org/gems/gigachat)
4
+ [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/neonix20b/gigachat/blob/main/LICENSE.txt)
5
+
6
+ ## Installation
7
+
8
+ ### Bundler
9
+
10
+ Add this line to your application's Gemfile:
11
+
12
+ ```ruby
13
+ gem "gigachat"
14
+ ```
15
+
16
+ And then execute:
17
+
18
+ ```bash
19
+ $ bundle install
20
+ ```
21
+
22
+ ### Gem install
23
+
24
+ Or install with:
25
+
26
+ ```bash
27
+ $ gem install gigachat
28
+ ```
29
+
30
+ and require with:
31
+
32
+ ```ruby
33
+ require "gigachat"
34
+ ```
35
+
36
+ ## Usage
37
+
38
+ Get your API key from [developers.sber.ru](https://developers.sber.ru/)
39
+
40
+ ### Quickstart
41
+
42
+ For a quick test you can pass your token directly to a new client:
43
+
44
+ ```ruby
45
+ client = GigaChat::Client.new(
46
+ api_type: "GIGACHAT_API_CORP", # or GIGACHAT_API_PERS, GIGACHAT_API_B2B
47
+ client_base64: "Yjgy...VhYw==" # your authorization data
48
+ )
49
+ ```
50
+
51
+ ### With Config
52
+
53
+ For a more robust setup, you can configure the gem with your API keys, for example in an `gigachat.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.
54
+
55
+ ```ruby
56
+ GigaChat.configure do |config|
57
+ config.api_type = "GIGACHAT_API_CORP" # or GIGACHAT_API_PERS, GIGACHAT_API_B2B
58
+ config.client_base64 = ENV.fetch("GIGACHAT_CLIENT_KEY")
59
+ end
60
+ ```
61
+
62
+ Then you can create a client like this:
63
+
64
+ ```ruby
65
+ client = GigaChat::Client.new
66
+ ```
67
+
68
+ You can still override the config defaults when making new clients; any options not included will fall back to any global config set with GigaChat.configure. e.g. in this example the api_type, etc. will fallback to any set globally using GigaChat.configure, with only the client_base64 overridden:
69
+
70
+ ```ruby
71
+ client = GigaChat::Client.new(client_base64: "secret_token_goes_here")
72
+ ```
73
+
74
+ #### Custom timeout or base URI
75
+
76
+ 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), and add arbitrary other headers:
77
+
78
+ ```ruby
79
+ client = GigaChat::Client.new(
80
+ client_base64: "secret_token_goes_here",
81
+ uri_base: "https://oai.hconeai.com/",
82
+ uri_auth: "https://localhost:5362/",
83
+ request_timeout: 240,
84
+ extra_headers: {
85
+ "X-Proxy-TTL" => "43200",
86
+ "X-Proxy-Refresh": "true",
87
+ }
88
+ )
89
+ ```
90
+
91
+ or when configuring the gem:
92
+
93
+ ```ruby
94
+ GigaChat.configure do |config|
95
+ config.client_base64 = ENV.fetch("GIGACHAT_CLIENT_KEY")
96
+ config.log_errors = true # Optional
97
+ config.uri_base = "https://oai.hconeai.com/" # Optional
98
+ config.request_timeout = 240 # Optional
99
+ config.extra_headers = {
100
+ "X-Proxy-TTL" => "43200",
101
+ "X-Proxy-Refresh": "true"
102
+ } # Optional
103
+ end
104
+ ```
105
+
106
+ #### Extra Headers per Client
107
+
108
+ You can dynamically pass headers per client object, which will be merged with any headers set globally with GigaChat.configure:
109
+
110
+ ```ruby
111
+ client = GigaChat::Client.new(client_base64: "secret_token_goes_here")
112
+ client.add_headers("X-Proxy-TTL" => "43200")
113
+ ```
114
+
115
+ #### Logging
116
+
117
+ ##### Errors
118
+
119
+ By default, `gigachat` does not log any `Faraday::Error`s encountered while executing a network request to avoid leaking data (e.g. 400s, 500s, SSL errors and more - see [here](https://www.rubydoc.info/github/lostisland/faraday/Faraday/Error) for a complete list of subclasses of `Faraday::Error` and what can cause them).
120
+
121
+ If you would like to enable this functionality, you can set `log_errors` to `true` when configuring the client:
122
+
123
+ ```ruby
124
+ client = GigaChat::Client.new(log_errors: true)
125
+ ```
126
+
127
+ ##### Faraday middleware
128
+
129
+ You can pass [Faraday middleware](https://lostisland.github.io/faraday/#/middleware/index) to the client in a block, eg. to enable verbose logging with Ruby's [Logger](https://ruby-doc.org/3.2.2/stdlibs/logger/Logger.html):
130
+
131
+ ```ruby
132
+ client = GigaChat::Client.new do |f|
133
+ f.response :logger, Logger.new($stdout), bodies: true
134
+ end
135
+ ```
136
+
137
+ ### Counting Tokens
138
+
139
+ GigaChat parses prompt text into [tokens](https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them), which are words or portions of words. (These tokens are unrelated to your API access_token.) Counting tokens can help you estimate your [costs](https://openai.com/pricing). It can also help you ensure your prompt text size is within the max-token limits of your model's context window, and choose an appropriate [`max_tokens`](https://platform.openai.com/docs/api-reference/chat/create#chat/create-max_tokens) completion parameter so your response will fit as well.
140
+
141
+ To estimate the token-count of your text:
142
+
143
+ ```ruby
144
+ GigaChat.rough_token_count("Your text")
145
+ ```
146
+
147
+ If you need a more accurate count, try [tiktoken_ruby](https://github.com/IAPark/tiktoken_ruby).
148
+
149
+ ### Models
150
+
151
+ There are different models that can be used to generate text. For a full list and to retrieve information about a single model:
152
+
153
+ ```ruby
154
+ client.models.list
155
+ client.models.retrieve(id: "GigaChat-Pro")
156
+ ```
157
+
158
+ ### Chat
159
+
160
+ GPT is a model that can be used to generate text in a conversational style. You can use it to [generate a response](https://developers.sber.ru/docs/ru/gigachat/api/reference/rest/post-chat) to a sequence of messages:
161
+
162
+ ```ruby
163
+ response = client.chat(
164
+ parameters: {
165
+ model: "GigaChat-Pro", # Required.
166
+ messages: [{ role: "user", content: "Hello!"}], # Required.
167
+ temperature: 0.7,
168
+ })
169
+ puts response.dig("choices", 0, "message", "content")
170
+ # => "Hello! How may I assist you today?"
171
+ ```
172
+
173
+ #### Streaming Chat
174
+
175
+ 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 completion 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 raise a Faraday error.
176
+
177
+ ```ruby
178
+ client.chat(
179
+ parameters: {
180
+ model: "GigaChat-Pro", # Required.
181
+ messages: [{ role: "user", content: "Describe a character called Anna!"}], # Required.
182
+ temperature: 0.7,
183
+ update_interval: 1,
184
+ stream: proc do |chunk, _bytesize|
185
+ print chunk.dig("choices", 0, "delta", "content")
186
+ end
187
+ })
188
+ # => "Anna is a young woman in her mid-twenties, with wavy chestnut hair that falls to her shoulders..."
189
+ ```
190
+
191
+ ### Functions
192
+
193
+ You can describe and pass in functions and the model will intelligently choose to output a JSON object containing arguments to call them - eg., to use your method `get_current_weather` to get the weather in a given location. Note that tool_choice is optional, but if you exclude it, the model will choose whether to use the function or not ([see here](https://developers.sber.ru/docs/ru/gigachat/api/reference/rest/post-chat)).
194
+
195
+ ```ruby
196
+
197
+ def get_current_weather(location:, unit: "fahrenheit")
198
+ # Here you could use a weather api to fetch the weather.
199
+ "The weather in #{location} is nice 🌞 #{unit}"
200
+ end
201
+
202
+ messages = [
203
+ {
204
+ "role": "user",
205
+ "content": "What is the weather like in San Francisco?",
206
+ },
207
+ ]
208
+
209
+ response =
210
+ client.chat(
211
+ parameters: {
212
+ model: "GigaChat-Pro",
213
+ messages: messages, # Defined above because we'll use it again
214
+ tools: [
215
+ {
216
+ type: "function",
217
+ function: {
218
+ name: "get_current_weather",
219
+ description: "Get the current weather in a given location",
220
+ parameters: { # Format: https://json-schema.org/understanding-json-schema
221
+ type: :object,
222
+ properties: {
223
+ location: {
224
+ type: :string,
225
+ description: "The city and state, e.g. San Francisco, CA",
226
+ },
227
+ unit: {
228
+ type: "string",
229
+ enum: %w[celsius fahrenheit],
230
+ },
231
+ },
232
+ required: ["location"],
233
+ },
234
+ },
235
+ }
236
+ ],
237
+ function_call: "none" # Optional, defaults to "auto"
238
+ # Can also put "none" or specific functions, see docs
239
+ },
240
+ )
241
+ ```
242
+
243
+ ### Embeddings
244
+
245
+ 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.
246
+
247
+ ```ruby
248
+ response = client.embeddings(
249
+ parameters: {
250
+ model: "GigaChat",
251
+ input: "The food was delicious and the waiter..."
252
+ }
253
+ )
254
+
255
+ puts response.dig("data", 0, "embedding")
256
+ # => Vector representation of your embedding
257
+ ```
258
+
259
+ ### Image Generation
260
+
261
+
262
+ ### Errors
263
+
264
+ HTTP errors can be caught like this:
265
+
266
+ ```
267
+ begin
268
+ GigaChat::Client.new.models.retrieve(id: "GigaChat")
269
+ rescue Faraday::Error => e
270
+ raise "Got a Faraday error: #{e}"
271
+ end
272
+ ```
273
+
274
+ ## Contributing
275
+
276
+ 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/neonix20b/gigachat/blob/main/CODE_OF_CONDUCT.md).
277
+
278
+ ## License
279
+
280
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
281
+
282
+ ## Code of Conduct
283
+
284
+ 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/neonix20b/gigachat/blob/main/CODE_OF_CONDUCT.md).
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
+ module GigaChat
2
+ class Client
3
+ include GigaChat::HTTP
4
+
5
+ CONFIG_KEYS = %i[
6
+ api_type
7
+ api_version
8
+ client_base64
9
+ log_errors
10
+ uri_base
11
+ uri_auth
12
+ request_timeout
13
+ extra_headers
14
+ ].freeze
15
+ attr_reader *CONFIG_KEYS, :faraday_middleware
16
+
17
+ def initialize(config = {}, &faraday_middleware)
18
+ CONFIG_KEYS.each do |key|
19
+ # Set instance variables like client_id. Fall back to global config
20
+ # if not present.
21
+ instance_variable_set(
22
+ "@#{key}",
23
+ config[key].nil? ? GigaChat.configuration.send(key) : config[key]
24
+ )
25
+ end
26
+ @faraday_middleware = faraday_middleware
27
+ end
28
+
29
+ def models
30
+ @models ||= GigaChat::Models.new(client: self)
31
+ end
32
+
33
+ def chat(parameters: {})
34
+ json_post(path: "/chat/completions", parameters: parameters)
35
+ end
36
+
37
+ def embeddings(parameters: {})
38
+ json_post(path: "/embeddings", parameters: parameters)
39
+ end
40
+
41
+ end
42
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ruby
4
+ module Gigachat
5
+ VERSION = ::Gigachat::VERSION
6
+
7
+ Error = ::Gigachat::Error
8
+ ConfigurationError = ::Gigachat::ConfigurationError
9
+ Configuration = ::Gigachat::Configuration
10
+ end
11
+ end
@@ -0,0 +1,131 @@
1
+ require "event_stream_parser"
2
+
3
+ require_relative "http_headers"
4
+
5
+ module GigaChat
6
+ module HTTP
7
+ include HTTPHeaders
8
+
9
+ def get(path:, parameters: nil)
10
+ parse_jsonl(conn.get(uri(path: path), parameters) do |req|
11
+ req.headers = headers
12
+ end&.body)
13
+ end
14
+
15
+ def post(path:)
16
+ parse_jsonl(conn.post(uri(path: path)) do |req|
17
+ req.headers = headers
18
+ end&.body)
19
+ end
20
+
21
+ def json_post(path:, parameters:)
22
+ conn.post(uri(path: path)) do |req|
23
+ configure_json_post_request(req, parameters)
24
+ end&.body
25
+ end
26
+
27
+ def multipart_post(path:, parameters: nil)
28
+ conn(multipart: true).post(uri(path: path)) do |req|
29
+ req.headers = headers.merge({ "Content-Type" => "multipart/form-data" })
30
+ req.body = multipart_parameters(parameters)
31
+ end&.body
32
+ end
33
+
34
+ def delete(path:)
35
+ conn.delete(uri(path: path)) do |req|
36
+ req.headers = headers
37
+ end&.body
38
+ end
39
+
40
+ private
41
+
42
+ def parse_jsonl(response)
43
+ return unless response
44
+ return response unless response.is_a?(String)
45
+
46
+ # Convert a multiline string of JSON objects to a JSON array.
47
+ response = response.gsub("}\n{", "},{").prepend("[").concat("]")
48
+
49
+ JSON.parse(response)
50
+ end
51
+
52
+ # Given a proc, returns an outer proc that can be used to iterate over a JSON stream of chunks.
53
+ # For each chunk, the inner user_proc is called giving it the JSON object. The JSON object could
54
+ # be a data object or an error object as described in the OpenAI API documentation.
55
+ #
56
+ # @param user_proc [Proc] The inner proc to call for each JSON object in the chunk.
57
+ # @return [Proc] An outer proc that iterates over a raw stream, converting it to JSON.
58
+ def to_json_stream(user_proc:)
59
+ parser = EventStreamParser::Parser.new
60
+
61
+ proc do |chunk, _bytes, env|
62
+ if env && env.status != 200
63
+ raise_error = Faraday::Response::RaiseError.new
64
+ raise_error.on_complete(env.merge(body: try_parse_json(chunk)))
65
+ end
66
+
67
+ parser.feed(chunk) do |_type, data|
68
+ user_proc.call(JSON.parse(data)) unless data == "[DONE]"
69
+ end
70
+ end
71
+ end
72
+
73
+ def conn(multipart: false)
74
+ connection = Faraday.new do |f|
75
+ f.options[:timeout] = @request_timeout
76
+ f.request(:multipart) if multipart
77
+ f.use MiddlewareErrors if @log_errors
78
+ f.response :raise_error
79
+ f.response :json
80
+ f.ssl.verify = false
81
+ end
82
+
83
+ @faraday_middleware&.call(connection)
84
+
85
+ connection
86
+ end
87
+
88
+ def uri(path:)
89
+ if @uri_base.include?(@api_version)
90
+ File.join(@uri_base, path)
91
+ else
92
+ File.join(@uri_base, @api_version, path)
93
+ end
94
+ end
95
+
96
+ def multipart_parameters(parameters)
97
+ parameters&.transform_values do |value|
98
+ next value unless value.respond_to?(:close) # File or IO object.
99
+
100
+ # Faraday::UploadIO does not require a path, so we will pass it
101
+ # only if it is available. This allows StringIO objects to be
102
+ # passed in as well.
103
+ path = value.respond_to?(:path) ? value.path : nil
104
+ # Doesn't seem like OpenAI needs mime_type yet, so not worth
105
+ # the library to figure this out. Hence the empty string
106
+ # as the second argument.
107
+ Faraday::UploadIO.new(value, "", path)
108
+ end
109
+ end
110
+
111
+ def configure_json_post_request(req, parameters)
112
+ req_parameters = parameters.dup
113
+
114
+ if parameters[:stream].respond_to?(:call)
115
+ req.options.on_data = to_json_stream(user_proc: parameters[:stream])
116
+ req_parameters[:stream] = true # Necessary to tell OpenAI to stream.
117
+ elsif parameters[:stream]
118
+ raise ArgumentError, "The stream parameter must be a Proc or have a #call method"
119
+ end
120
+
121
+ req.headers = headers
122
+ req.body = req_parameters.to_json
123
+ end
124
+
125
+ def try_parse_json(maybe_json)
126
+ JSON.parse(maybe_json)
127
+ rescue JSON::ParserError
128
+ maybe_json
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,44 @@
1
+ module GigaChat
2
+ module HTTPHeaders
3
+ def add_headers(headers)
4
+ @extra_headers = extra_headers.merge(headers.transform_keys(&:to_s))
5
+ end
6
+
7
+ private
8
+
9
+ def headers
10
+ {
11
+ "Content-Type" => "application/json",
12
+ "Accept" => "application/json",
13
+ "Authorization" => "Bearer #{access_token}"
14
+ }.merge(extra_headers)
15
+ end
16
+
17
+ def extra_headers
18
+ @extra_headers ||= {}
19
+ end
20
+
21
+ def access_token
22
+ if @access_token.nil? || (@expires_in.to_i - Time.now.to_i).negative?
23
+ url = URI(@uri_auth)
24
+
25
+ https = Net::HTTP.new(url.host, url.port)
26
+ https.use_ssl = true
27
+ https.verify_mode = OpenSSL::SSL::VERIFY_NONE
28
+
29
+ request = Net::HTTP::Post.new(url)
30
+ request["Content-Type"] = "application/x-www-form-urlencoded"
31
+ request["Accept"] = "application/json"
32
+ request["RqUID"] = SecureRandom.uuid
33
+ request["Authorization"] = "Basic #{@client_base64}"
34
+ request.body = "scope=#{@api_type}"
35
+
36
+ resp = https.request(request).body
37
+ json = JSON.parse(resp)
38
+ @expires_in = json['expires_at']
39
+ @access_token = json['access_token']
40
+ end
41
+ @access_token
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,15 @@
1
+ module GigaChat
2
+ class Models
3
+ def initialize(client:)
4
+ @client = client
5
+ end
6
+
7
+ def list
8
+ @client.get(path: "/models")
9
+ end
10
+
11
+ def retrieve(id:)
12
+ @client.get(path: "/models/#{id}")
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GigaChat
4
+ VERSION = '0.1.0'
5
+ end
data/lib/gigachat.rb ADDED
@@ -0,0 +1,77 @@
1
+ require "faraday"
2
+ require "faraday/multipart"
3
+
4
+ require_relative "gigachat/http"
5
+ require_relative "gigachat/models"
6
+ require_relative "gigachat/client"
7
+ require_relative "gigachat/version"
8
+
9
+ module GigaChat
10
+ class Error < StandardError; end
11
+ class ConfigurationError < Error; end
12
+
13
+ class MiddlewareErrors < Faraday::Middleware
14
+ def call(env)
15
+ @app.call(env)
16
+ rescue Faraday::Error => e
17
+ raise e unless e.response.is_a?(Hash)
18
+
19
+ logger = Logger.new($stdout)
20
+ logger.error(e.response[:body])
21
+
22
+ raise e
23
+ end
24
+ end
25
+
26
+ class Configuration
27
+ attr_accessor :api_type,
28
+ :api_version,
29
+ :log_errors,
30
+ :client_base64,
31
+ :uri_base,
32
+ :uri_auth,
33
+ :request_timeout,
34
+ :extra_headers
35
+
36
+ DEFAULT_API_VERSION = "v1".freeze
37
+ DEFAULT_URI_BASE = "https://gigachat.devices.sberbank.ru/api/".freeze
38
+ DEFAULT_AUTH_UURL = "https://ngw.devices.sberbank.ru:9443/api/v2/oauth".freeze
39
+ DEFAULT_REQUEST_TIMEOUT = 120
40
+ DEFAULT_LOG_ERRORS = false
41
+
42
+ def initialize
43
+ @api_type = nil # GIGACHAT_API_PERS, GIGACHAT_API_B2B, GIGACHAT_API_CORP
44
+ @api_version = DEFAULT_API_VERSION
45
+ @log_errors = DEFAULT_LOG_ERRORS
46
+ @client_base64 = nil
47
+ @uri_base = DEFAULT_URI_BASE
48
+ @uri_auth = DEFAULT_AUTH_UURL
49
+ @request_timeout = DEFAULT_REQUEST_TIMEOUT
50
+ @extra_headers = {}
51
+ end
52
+ end
53
+
54
+ class << self
55
+ attr_writer :configuration
56
+ end
57
+
58
+ def self.configuration
59
+ @configuration ||= GigaChat::Configuration.new
60
+ end
61
+
62
+ def self.configure
63
+ yield(configuration)
64
+ end
65
+
66
+ # Estimate the number of tokens in a string, using the rules of thumb from OpenAI:
67
+ # https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them
68
+ def self.rough_token_count(content = "")
69
+ raise ArgumentError, "rough_token_count requires a string" unless content.is_a? String
70
+ return 0 if content.empty?
71
+
72
+ count_by_chars = content.size / 4.0
73
+ count_by_words = content.split.size * 4.0 / 3
74
+ estimate = ((count_by_chars + count_by_words) / 2.0).round
75
+ [1, estimate].max
76
+ end
77
+ end
@@ -0,0 +1,2 @@
1
+ require_relative "../oxaiworkers"
2
+ require_relative "../oxaiworkers/compatibility"
metadata ADDED
@@ -0,0 +1,88 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: gigachat
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Denis Smolev
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-09-12 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: '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'
27
+ - !ruby/object:Gem::Dependency
28
+ name: faraday-multipart
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '1'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '1'
41
+ description: " GigaChat\n"
42
+ email:
43
+ - smolev@me.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".ruby-version"
49
+ - CHANGELOG.md
50
+ - CODE_OF_CONDUCT.md
51
+ - LICENSE
52
+ - README.md
53
+ - Rakefile
54
+ - lib/gigachat.rb
55
+ - lib/gigachat/client.rb
56
+ - lib/gigachat/compatibility.rb
57
+ - lib/gigachat/http.rb
58
+ - lib/gigachat/http_headers.rb
59
+ - lib/gigachat/models.rb
60
+ - lib/gigachat/version.rb
61
+ - lib/ruby/gigachat.rb
62
+ homepage: https://ai.oxteam.me
63
+ licenses:
64
+ - MIT
65
+ metadata:
66
+ homepage_uri: https://ai.oxteam.me
67
+ source_code_uri: https://github.com/neonix20b/gigachat
68
+ changelog_uri: https://github.com/neonix20b/gigachat/blob/main/CHANGELOG.md
69
+ post_install_message:
70
+ rdoc_options: []
71
+ require_paths:
72
+ - lib
73
+ required_ruby_version: !ruby/object:Gem::Requirement
74
+ requirements:
75
+ - - ">="
76
+ - !ruby/object:Gem::Version
77
+ version: 3.2.0
78
+ required_rubygems_version: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ requirements: []
84
+ rubygems_version: 3.5.18
85
+ signing_key:
86
+ specification_version: 4
87
+ summary: ruby client for GigaChat from Sberbank
88
+ test_files: []