blackman_client 0.0.5

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.
@@ -0,0 +1,251 @@
1
+ =begin
2
+ #Blackman AI API
3
+
4
+ #A transparent AI API proxy that optimizes token usage to reduce costs. ## Authentication Blackman AI supports two authentication methods: ### 1. API Key (Recommended for integrations) Use the API key created from your dashboard: ```bash curl -X POST https://ap.useblackman.ai/v1/completions \\ -H \"Authorization: Bearer sk_your_api_key_here\" \\ -H \"Content-Type: application/json\" \\ -d '{\"provider\": \"OpenAI\", \"model\": \"gpt-4\", \"messages\": [{\"role\": \"user\", \"content\": \"Hello!\"}]}' ``` ### 2. JWT Token (For web UI) Obtain a JWT token by logging in: ```bash curl -X POST https://ap.useblackman.ai/v1/auth/login \\ -H \"Content-Type: application/json\" \\ -d '{\"email\": \"user@example.com\", \"password\": \"yourpassword\"}' ``` Then use the token: ```bash curl -X POST https://ap.useblackman.ai/v1/completions \\ -H \"Authorization: Bearer your_jwt_token\" \\ -H \"Content-Type: application/json\" \\ -d '{...}' ``` ### Provider API Keys (Optional) You can optionally provide your own LLM provider API key via the `X-Provider-Api-Key` header, or store it in your account settings. ## Client SDKs Auto-generated SDKs are available for 10 languages: - **TypeScript**: [View Docs](/v1/sdks/typescript) - **Python**: [View Docs](/v1/sdks/python) - **Go**: [View Docs](/v1/sdks/go) - **Java**: [View Docs](/v1/sdks/java) - **Ruby**: [View Docs](/v1/sdks/ruby) - **PHP**: [View Docs](/v1/sdks/php) - **C#**: [View Docs](/v1/sdks/csharp) - **Rust**: [View Docs](/v1/sdks/rust) - **Swift**: [View Docs](/v1/sdks/swift) - **Kotlin**: [View Docs](/v1/sdks/kotlin) All SDKs are generated from this OpenAPI spec using [openapi-generator](https://openapi-generator.tech). ## Quick Start ```python # Python example with API key import blackman_client from blackman_client import CompletionRequest configuration = blackman_client.Configuration( host=\"http://localhost:8080\", access_token=\"sk_your_api_key_here\" # Your Blackman API key ) with blackman_client.ApiClient(configuration) as api_client: api = blackman_client.CompletionsApi(api_client) response = api.completions( CompletionRequest( provider=\"OpenAI\", model=\"gpt-4o\", messages=[{\"role\": \"user\", \"content\": \"Hello!\"}] ) ) ```
5
+
6
+ The version of the OpenAPI document: 0.1.0
7
+
8
+ Generated by: https://openapi-generator.tech
9
+ Generator version: 7.14.0
10
+
11
+ =end
12
+
13
+ require 'cgi'
14
+
15
+ module BlackmanClient
16
+ class SemanticCacheApi
17
+ attr_accessor :api_client
18
+
19
+ def initialize(api_client = ApiClient.default)
20
+ @api_client = api_client
21
+ end
22
+ # Get semantic cache configuration for the current account
23
+ # @param [Hash] opts the optional parameters
24
+ # @return [SemanticCacheConfig]
25
+ def get_config(opts = {})
26
+ data, _status_code, _headers = get_config_with_http_info(opts)
27
+ data
28
+ end
29
+
30
+ # Get semantic cache configuration for the current account
31
+ # @param [Hash] opts the optional parameters
32
+ # @return [Array<(SemanticCacheConfig, Integer, Hash)>] SemanticCacheConfig data, response status code and response headers
33
+ def get_config_with_http_info(opts = {})
34
+ if @api_client.config.debugging
35
+ @api_client.config.logger.debug 'Calling API: SemanticCacheApi.get_config ...'
36
+ end
37
+ # resource path
38
+ local_var_path = '/v1/semantic-cache/config'
39
+
40
+ # query parameters
41
+ query_params = opts[:query_params] || {}
42
+
43
+ # header parameters
44
+ header_params = opts[:header_params] || {}
45
+ # HTTP header 'Accept' (if needed)
46
+ header_params['Accept'] = @api_client.select_header_accept(['application/json']) unless header_params['Accept']
47
+
48
+ # form parameters
49
+ form_params = opts[:form_params] || {}
50
+
51
+ # http body (model)
52
+ post_body = opts[:debug_body]
53
+
54
+ # return_type
55
+ return_type = opts[:debug_return_type] || 'SemanticCacheConfig'
56
+
57
+ # auth_names
58
+ auth_names = opts[:debug_auth_names] || ['BearerAuth']
59
+
60
+ new_options = opts.merge(
61
+ :operation => :"SemanticCacheApi.get_config",
62
+ :header_params => header_params,
63
+ :query_params => query_params,
64
+ :form_params => form_params,
65
+ :body => post_body,
66
+ :auth_names => auth_names,
67
+ :return_type => return_type
68
+ )
69
+
70
+ data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
71
+ if @api_client.config.debugging
72
+ @api_client.config.logger.debug "API called: SemanticCacheApi#get_config\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
73
+ end
74
+ return data, status_code, headers
75
+ end
76
+
77
+ # Get semantic cache statistics including hit rate and savings
78
+ # @param [Hash] opts the optional parameters
79
+ # @return [SemanticCacheStats]
80
+ def get_stats(opts = {})
81
+ data, _status_code, _headers = get_stats_with_http_info(opts)
82
+ data
83
+ end
84
+
85
+ # Get semantic cache statistics including hit rate and savings
86
+ # @param [Hash] opts the optional parameters
87
+ # @return [Array<(SemanticCacheStats, Integer, Hash)>] SemanticCacheStats data, response status code and response headers
88
+ def get_stats_with_http_info(opts = {})
89
+ if @api_client.config.debugging
90
+ @api_client.config.logger.debug 'Calling API: SemanticCacheApi.get_stats ...'
91
+ end
92
+ # resource path
93
+ local_var_path = '/v1/semantic-cache/stats'
94
+
95
+ # query parameters
96
+ query_params = opts[:query_params] || {}
97
+
98
+ # header parameters
99
+ header_params = opts[:header_params] || {}
100
+ # HTTP header 'Accept' (if needed)
101
+ header_params['Accept'] = @api_client.select_header_accept(['application/json']) unless header_params['Accept']
102
+
103
+ # form parameters
104
+ form_params = opts[:form_params] || {}
105
+
106
+ # http body (model)
107
+ post_body = opts[:debug_body]
108
+
109
+ # return_type
110
+ return_type = opts[:debug_return_type] || 'SemanticCacheStats'
111
+
112
+ # auth_names
113
+ auth_names = opts[:debug_auth_names] || ['BearerAuth']
114
+
115
+ new_options = opts.merge(
116
+ :operation => :"SemanticCacheApi.get_stats",
117
+ :header_params => header_params,
118
+ :query_params => query_params,
119
+ :form_params => form_params,
120
+ :body => post_body,
121
+ :auth_names => auth_names,
122
+ :return_type => return_type
123
+ )
124
+
125
+ data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
126
+ if @api_client.config.debugging
127
+ @api_client.config.logger.debug "API called: SemanticCacheApi#get_stats\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
128
+ end
129
+ return data, status_code, headers
130
+ end
131
+
132
+ # Invalidate all cache entries for the current account
133
+ # @param [Hash] opts the optional parameters
134
+ # @return [InvalidateResponse]
135
+ def invalidate_all(opts = {})
136
+ data, _status_code, _headers = invalidate_all_with_http_info(opts)
137
+ data
138
+ end
139
+
140
+ # Invalidate all cache entries for the current account
141
+ # @param [Hash] opts the optional parameters
142
+ # @return [Array<(InvalidateResponse, Integer, Hash)>] InvalidateResponse data, response status code and response headers
143
+ def invalidate_all_with_http_info(opts = {})
144
+ if @api_client.config.debugging
145
+ @api_client.config.logger.debug 'Calling API: SemanticCacheApi.invalidate_all ...'
146
+ end
147
+ # resource path
148
+ local_var_path = '/v1/semantic-cache/invalidate'
149
+
150
+ # query parameters
151
+ query_params = opts[:query_params] || {}
152
+
153
+ # header parameters
154
+ header_params = opts[:header_params] || {}
155
+ # HTTP header 'Accept' (if needed)
156
+ header_params['Accept'] = @api_client.select_header_accept(['application/json']) unless header_params['Accept']
157
+
158
+ # form parameters
159
+ form_params = opts[:form_params] || {}
160
+
161
+ # http body (model)
162
+ post_body = opts[:debug_body]
163
+
164
+ # return_type
165
+ return_type = opts[:debug_return_type] || 'InvalidateResponse'
166
+
167
+ # auth_names
168
+ auth_names = opts[:debug_auth_names] || ['BearerAuth']
169
+
170
+ new_options = opts.merge(
171
+ :operation => :"SemanticCacheApi.invalidate_all",
172
+ :header_params => header_params,
173
+ :query_params => query_params,
174
+ :form_params => form_params,
175
+ :body => post_body,
176
+ :auth_names => auth_names,
177
+ :return_type => return_type
178
+ )
179
+
180
+ data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, new_options)
181
+ if @api_client.config.debugging
182
+ @api_client.config.logger.debug "API called: SemanticCacheApi#invalidate_all\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
183
+ end
184
+ return data, status_code, headers
185
+ end
186
+
187
+ # Update semantic cache configuration for the current account
188
+ # @param semantic_cache_config [SemanticCacheConfig]
189
+ # @param [Hash] opts the optional parameters
190
+ # @return [nil]
191
+ def update_config(semantic_cache_config, opts = {})
192
+ update_config_with_http_info(semantic_cache_config, opts)
193
+ nil
194
+ end
195
+
196
+ # Update semantic cache configuration for the current account
197
+ # @param semantic_cache_config [SemanticCacheConfig]
198
+ # @param [Hash] opts the optional parameters
199
+ # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers
200
+ def update_config_with_http_info(semantic_cache_config, opts = {})
201
+ if @api_client.config.debugging
202
+ @api_client.config.logger.debug 'Calling API: SemanticCacheApi.update_config ...'
203
+ end
204
+ # verify the required parameter 'semantic_cache_config' is set
205
+ if @api_client.config.client_side_validation && semantic_cache_config.nil?
206
+ fail ArgumentError, "Missing the required parameter 'semantic_cache_config' when calling SemanticCacheApi.update_config"
207
+ end
208
+ # resource path
209
+ local_var_path = '/v1/semantic-cache/config'
210
+
211
+ # query parameters
212
+ query_params = opts[:query_params] || {}
213
+
214
+ # header parameters
215
+ header_params = opts[:header_params] || {}
216
+ # HTTP header 'Content-Type'
217
+ content_type = @api_client.select_header_content_type(['application/json'])
218
+ if !content_type.nil?
219
+ header_params['Content-Type'] = content_type
220
+ end
221
+
222
+ # form parameters
223
+ form_params = opts[:form_params] || {}
224
+
225
+ # http body (model)
226
+ post_body = opts[:debug_body] || @api_client.object_to_http_body(semantic_cache_config)
227
+
228
+ # return_type
229
+ return_type = opts[:debug_return_type]
230
+
231
+ # auth_names
232
+ auth_names = opts[:debug_auth_names] || ['BearerAuth']
233
+
234
+ new_options = opts.merge(
235
+ :operation => :"SemanticCacheApi.update_config",
236
+ :header_params => header_params,
237
+ :query_params => query_params,
238
+ :form_params => form_params,
239
+ :body => post_body,
240
+ :auth_names => auth_names,
241
+ :return_type => return_type
242
+ )
243
+
244
+ data, status_code, headers = @api_client.call_api(:PUT, local_var_path, new_options)
245
+ if @api_client.config.debugging
246
+ @api_client.config.logger.debug "API called: SemanticCacheApi#update_config\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
247
+ end
248
+ return data, status_code, headers
249
+ end
250
+ end
251
+ end
@@ -0,0 +1,393 @@
1
+ =begin
2
+ #Blackman AI API
3
+
4
+ #A transparent AI API proxy that optimizes token usage to reduce costs. ## Authentication Blackman AI supports two authentication methods: ### 1. API Key (Recommended for integrations) Use the API key created from your dashboard: ```bash curl -X POST https://ap.useblackman.ai/v1/completions \\ -H \"Authorization: Bearer sk_your_api_key_here\" \\ -H \"Content-Type: application/json\" \\ -d '{\"provider\": \"OpenAI\", \"model\": \"gpt-4\", \"messages\": [{\"role\": \"user\", \"content\": \"Hello!\"}]}' ``` ### 2. JWT Token (For web UI) Obtain a JWT token by logging in: ```bash curl -X POST https://ap.useblackman.ai/v1/auth/login \\ -H \"Content-Type: application/json\" \\ -d '{\"email\": \"user@example.com\", \"password\": \"yourpassword\"}' ``` Then use the token: ```bash curl -X POST https://ap.useblackman.ai/v1/completions \\ -H \"Authorization: Bearer your_jwt_token\" \\ -H \"Content-Type: application/json\" \\ -d '{...}' ``` ### Provider API Keys (Optional) You can optionally provide your own LLM provider API key via the `X-Provider-Api-Key` header, or store it in your account settings. ## Client SDKs Auto-generated SDKs are available for 10 languages: - **TypeScript**: [View Docs](/v1/sdks/typescript) - **Python**: [View Docs](/v1/sdks/python) - **Go**: [View Docs](/v1/sdks/go) - **Java**: [View Docs](/v1/sdks/java) - **Ruby**: [View Docs](/v1/sdks/ruby) - **PHP**: [View Docs](/v1/sdks/php) - **C#**: [View Docs](/v1/sdks/csharp) - **Rust**: [View Docs](/v1/sdks/rust) - **Swift**: [View Docs](/v1/sdks/swift) - **Kotlin**: [View Docs](/v1/sdks/kotlin) All SDKs are generated from this OpenAPI spec using [openapi-generator](https://openapi-generator.tech). ## Quick Start ```python # Python example with API key import blackman_client from blackman_client import CompletionRequest configuration = blackman_client.Configuration( host=\"http://localhost:8080\", access_token=\"sk_your_api_key_here\" # Your Blackman API key ) with blackman_client.ApiClient(configuration) as api_client: api = blackman_client.CompletionsApi(api_client) response = api.completions( CompletionRequest( provider=\"OpenAI\", model=\"gpt-4o\", messages=[{\"role\": \"user\", \"content\": \"Hello!\"}] ) ) ```
5
+
6
+ The version of the OpenAPI document: 0.1.0
7
+
8
+ Generated by: https://openapi-generator.tech
9
+ Generator version: 7.14.0
10
+
11
+ =end
12
+
13
+ require 'date'
14
+ require 'json'
15
+ require 'logger'
16
+ require 'tempfile'
17
+ require 'time'
18
+ require 'typhoeus'
19
+
20
+
21
+ module BlackmanClient
22
+ class ApiClient
23
+ # The Configuration object holding settings to be used in the API client.
24
+ attr_accessor :config
25
+
26
+ # Defines the headers to be used in HTTP requests of all API calls by default.
27
+ #
28
+ # @return [Hash]
29
+ attr_accessor :default_headers
30
+
31
+ # Initializes the ApiClient
32
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
33
+ def initialize(config = Configuration.default)
34
+ @config = config
35
+ @user_agent = "OpenAPI-Generator/#{VERSION}/ruby"
36
+ @default_headers = {
37
+ 'Content-Type' => 'application/json',
38
+ 'User-Agent' => @user_agent
39
+ }
40
+ end
41
+
42
+ def self.default
43
+ @@default ||= ApiClient.new
44
+ end
45
+
46
+ # Call an API with given options.
47
+ #
48
+ # @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
49
+ # the data deserialized from response body (may be a Tempfile or nil), response status code and response headers.
50
+ def call_api(http_method, path, opts = {})
51
+ request = build_request(http_method, path, opts)
52
+ tempfile = nil
53
+ (download_file(request) { tempfile = _1 }) if opts[:return_type] == 'File'
54
+ response = request.run
55
+
56
+ if @config.debugging
57
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
58
+ end
59
+
60
+ unless response.success?
61
+ if response.timed_out?
62
+ fail ApiError.new('Connection timed out')
63
+ elsif response.code == 0
64
+ # Errors from libcurl will be made visible here
65
+ fail ApiError.new(:code => 0,
66
+ :message => response.return_message)
67
+ else
68
+ fail ApiError.new(:code => response.code,
69
+ :response_headers => response.headers,
70
+ :response_body => response.body),
71
+ response.status_message
72
+ end
73
+ end
74
+
75
+ if opts[:return_type] == 'File'
76
+ data = tempfile
77
+ elsif opts[:return_type]
78
+ data = deserialize(response, opts[:return_type])
79
+ else
80
+ data = nil
81
+ end
82
+ return data, response.code, response.headers
83
+ end
84
+
85
+ # Builds the HTTP request
86
+ #
87
+ # @param [String] http_method HTTP method/verb (e.g. POST)
88
+ # @param [String] path URL path (e.g. /account/new)
89
+ # @option opts [Hash] :header_params Header parameters
90
+ # @option opts [Hash] :query_params Query parameters
91
+ # @option opts [Hash] :form_params Query parameters
92
+ # @option opts [Object] :body HTTP body (JSON/XML)
93
+ # @return [Typhoeus::Request] A Typhoeus Request
94
+ def build_request(http_method, path, opts = {})
95
+ url = build_request_url(path, opts)
96
+ http_method = http_method.to_sym.downcase
97
+
98
+ header_params = @default_headers.merge(opts[:header_params] || {})
99
+ query_params = opts[:query_params] || {}
100
+ form_params = opts[:form_params] || {}
101
+ follow_location = opts[:follow_location] || true
102
+
103
+ update_params_for_auth! header_params, query_params, opts[:auth_names]
104
+
105
+ # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
106
+ _verify_ssl_host = @config.verify_ssl_host ? 2 : 0
107
+
108
+ req_opts = {
109
+ :method => http_method,
110
+ :headers => header_params,
111
+ :params => query_params,
112
+ :params_encoding => @config.params_encoding,
113
+ :timeout => @config.timeout,
114
+ :ssl_verifypeer => @config.verify_ssl,
115
+ :ssl_verifyhost => _verify_ssl_host,
116
+ :sslcert => @config.cert_file,
117
+ :sslkey => @config.key_file,
118
+ :verbose => @config.debugging,
119
+ :followlocation => follow_location
120
+ }
121
+
122
+ # set custom cert, if provided
123
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
124
+
125
+ if [:post, :patch, :put, :delete].include?(http_method)
126
+ req_body = build_request_body(header_params, form_params, opts[:body])
127
+ req_opts.update :body => req_body
128
+ if @config.debugging
129
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
130
+ end
131
+ end
132
+
133
+ Typhoeus::Request.new(url, req_opts)
134
+ end
135
+
136
+ # Builds the HTTP request body
137
+ #
138
+ # @param [Hash] header_params Header parameters
139
+ # @param [Hash] form_params Query parameters
140
+ # @param [Object] body HTTP body (JSON/XML)
141
+ # @return [String] HTTP body data in the form of string
142
+ def build_request_body(header_params, form_params, body)
143
+ # http form
144
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
145
+ header_params['Content-Type'] == 'multipart/form-data'
146
+ data = {}
147
+ form_params.each do |key, value|
148
+ case value
149
+ when ::File, ::Array, nil
150
+ # let typhoeus handle File, Array and nil parameters
151
+ data[key] = value
152
+ else
153
+ data[key] = value.to_s
154
+ end
155
+ end
156
+ elsif body
157
+ data = body.is_a?(String) ? body : body.to_json
158
+ else
159
+ data = nil
160
+ end
161
+ data
162
+ end
163
+
164
+ # Save response body into a file in (the defined) temporary folder, using the filename
165
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
166
+ # The response body is written to the file in chunks in order to handle files which
167
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
168
+ # process can use.
169
+ #
170
+ # @see Configuration#temp_folder_path
171
+ #
172
+ # @return [Tempfile] the tempfile generated
173
+ def download_file(request)
174
+ tempfile = nil
175
+ encoding = nil
176
+ request.on_headers do |response|
177
+ content_disposition = response.headers['Content-Disposition']
178
+ if content_disposition && content_disposition =~ /filename=/i
179
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
180
+ prefix = sanitize_filename(filename)
181
+ else
182
+ prefix = 'download-'
183
+ end
184
+ prefix = prefix + '-' unless prefix.end_with?('-')
185
+ encoding = response.body.encoding
186
+ tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
187
+ end
188
+ request.on_body do |chunk|
189
+ chunk.force_encoding(encoding)
190
+ tempfile.write(chunk)
191
+ end
192
+ request.on_complete do
193
+ if !tempfile
194
+ fail ApiError.new("Failed to create the tempfile based on the HTTP response from the server: #{request.inspect}")
195
+ end
196
+ tempfile.close
197
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
198
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
199
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
200
+ "explicitly with `tempfile.delete`"
201
+ yield tempfile if block_given?
202
+ end
203
+ end
204
+
205
+ # Check if the given MIME is a JSON MIME.
206
+ # JSON MIME examples:
207
+ # application/json
208
+ # application/json; charset=UTF8
209
+ # APPLICATION/JSON
210
+ # */*
211
+ # @param [String] mime MIME
212
+ # @return [Boolean] True if the MIME is application/json
213
+ def json_mime?(mime)
214
+ (mime == '*/*') || !(mime =~ /^Application\/.*json(?!p)(;.*)?/i).nil?
215
+ end
216
+
217
+ # Deserialize the response to the given return type.
218
+ #
219
+ # @param [Response] response HTTP response
220
+ # @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
221
+ def deserialize(response, return_type)
222
+ body = response.body
223
+ return nil if body.nil? || body.empty?
224
+
225
+ # return response body directly for String return type
226
+ return body.to_s if return_type == 'String'
227
+
228
+ # ensuring a default content type
229
+ content_type = response.headers['Content-Type'] || 'application/json'
230
+
231
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
232
+
233
+ begin
234
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
235
+ rescue JSON::ParserError => e
236
+ if %w(String Date Time).include?(return_type)
237
+ data = body
238
+ else
239
+ raise e
240
+ end
241
+ end
242
+
243
+ convert_to_type data, return_type
244
+ end
245
+
246
+ # Convert data to the given return type.
247
+ # @param [Object] data Data to be converted
248
+ # @param [String] return_type Return type
249
+ # @return [Mixed] Data in a particular type
250
+ def convert_to_type(data, return_type)
251
+ return nil if data.nil?
252
+ case return_type
253
+ when 'String'
254
+ data.to_s
255
+ when 'Integer'
256
+ data.to_i
257
+ when 'Float'
258
+ data.to_f
259
+ when 'Boolean'
260
+ data == true
261
+ when 'Time'
262
+ # parse date time (expecting ISO 8601 format)
263
+ Time.parse data
264
+ when 'Date'
265
+ # parse date time (expecting ISO 8601 format)
266
+ Date.parse data
267
+ when 'Object'
268
+ # generic object (usually a Hash), return directly
269
+ data
270
+ when /\AArray<(.+)>\z/
271
+ # e.g. Array<Pet>
272
+ sub_type = $1
273
+ data.map { |item| convert_to_type(item, sub_type) }
274
+ when /\AHash\<String, (.+)\>\z/
275
+ # e.g. Hash<String, Integer>
276
+ sub_type = $1
277
+ {}.tap do |hash|
278
+ data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
279
+ end
280
+ else
281
+ # models (e.g. Pet) or oneOf
282
+ klass = BlackmanClient.const_get(return_type)
283
+ klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data)
284
+ end
285
+ end
286
+
287
+ # Sanitize filename by removing path.
288
+ # e.g. ../../sun.gif becomes sun.gif
289
+ #
290
+ # @param [String] filename the filename to be sanitized
291
+ # @return [String] the sanitized filename
292
+ def sanitize_filename(filename)
293
+ filename.split(/[\/\\]/).last
294
+ end
295
+
296
+ def build_request_url(path, opts = {})
297
+ # Add leading and trailing slashes to path
298
+ path = "/#{path}".gsub(/\/+/, '/')
299
+ @config.base_url(opts[:operation]) + path
300
+ end
301
+
302
+ # Update header and query params based on authentication settings.
303
+ #
304
+ # @param [Hash] header_params Header parameters
305
+ # @param [Hash] query_params Query parameters
306
+ # @param [String] auth_names Authentication scheme name
307
+ def update_params_for_auth!(header_params, query_params, auth_names)
308
+ Array(auth_names).each do |auth_name|
309
+ auth_setting = @config.auth_settings[auth_name]
310
+ next unless auth_setting
311
+ case auth_setting[:in]
312
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
313
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
314
+ else fail ArgumentError, 'Authentication token must be in `query` or `header`'
315
+ end
316
+ end
317
+ end
318
+
319
+ # Sets user agent in HTTP header
320
+ #
321
+ # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
322
+ def user_agent=(user_agent)
323
+ @user_agent = user_agent
324
+ @default_headers['User-Agent'] = @user_agent
325
+ end
326
+
327
+ # Return Accept header based on an array of accepts provided.
328
+ # @param [Array] accepts array for Accept
329
+ # @return [String] the Accept header (e.g. application/json)
330
+ def select_header_accept(accepts)
331
+ return nil if accepts.nil? || accepts.empty?
332
+ # use JSON when present, otherwise use all of the provided
333
+ json_accept = accepts.find { |s| json_mime?(s) }
334
+ json_accept || accepts.join(',')
335
+ end
336
+
337
+ # Return Content-Type header based on an array of content types provided.
338
+ # @param [Array] content_types array for Content-Type
339
+ # @return [String] the Content-Type header (e.g. application/json)
340
+ def select_header_content_type(content_types)
341
+ # return nil by default
342
+ return if content_types.nil? || content_types.empty?
343
+ # use JSON when present, otherwise use the first one
344
+ json_content_type = content_types.find { |s| json_mime?(s) }
345
+ json_content_type || content_types.first
346
+ end
347
+
348
+ # Convert object (array, hash, object, etc) to JSON string.
349
+ # @param [Object] model object to be converted into JSON string
350
+ # @return [String] JSON string representation of the object
351
+ def object_to_http_body(model)
352
+ return model if model.nil? || model.is_a?(String)
353
+ local_body = nil
354
+ if model.is_a?(Array)
355
+ local_body = model.map { |m| object_to_hash(m) }
356
+ else
357
+ local_body = object_to_hash(model)
358
+ end
359
+ local_body.to_json
360
+ end
361
+
362
+ # Convert object(non-array) to hash.
363
+ # @param [Object] obj object to be converted into JSON string
364
+ # @return [String] JSON string representation of the object
365
+ def object_to_hash(obj)
366
+ if obj.respond_to?(:to_hash)
367
+ obj.to_hash
368
+ else
369
+ obj
370
+ end
371
+ end
372
+
373
+ # Build parameter value according to the given collection format.
374
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
375
+ def build_collection_param(param, collection_format)
376
+ case collection_format
377
+ when :csv
378
+ param.join(',')
379
+ when :ssv
380
+ param.join(' ')
381
+ when :tsv
382
+ param.join("\t")
383
+ when :pipes
384
+ param.join('|')
385
+ when :multi
386
+ # return the array directly as typhoeus will handle it as expected
387
+ param
388
+ else
389
+ fail "unknown collection format: #{collection_format.inspect}"
390
+ end
391
+ end
392
+ end
393
+ end