open_router 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.rspec +3 -0
- data/.rubocop.yml +13 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/Gemfile +12 -0
- data/Gemfile.lock +71 -0
- data/LICENSE.txt +21 -0
- data/README.md +119 -0
- data/Rakefile +12 -0
- data/lib/open_router/client.rb +45 -0
- data/lib/open_router/http.rb +94 -0
- data/lib/open_router/version.rb +5 -0
- data/lib/open_router.rb +56 -0
- data/open_router.gemspec +32 -0
- data/sig/open_router.rbs +20 -0
- metadata +89 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 3a93aba25cb96e636386ff6124b516fd580fd1535b215d0e5152dd02873f01f5
|
4
|
+
data.tar.gz: cb2aae6801e85efb8b2e1603797ca2186ed696a019e29839d7fa5509573958e5
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 8cbcf5b988d5a709d7de4289aa3dccd470af4975e8f9a37a826ff5df097f0fee04328a9fa3877a3299d1c5849370aeab3f3bada91617efcc10ab13a8116523d3
|
7
|
+
data.tar.gz: 91d41c29aee465880f59c1b6bcc121f559c929da2c7dec9be55ecc68f992031fa0c096655af0aa56942c9cd4076506e9dbf22d898c274d9fb653222269a871e0
|
data/.rspec
ADDED
data/.rubocop.yml
ADDED
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -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 obiefernandez@gmail.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/Gemfile
ADDED
data/Gemfile.lock
ADDED
@@ -0,0 +1,71 @@
|
|
1
|
+
PATH
|
2
|
+
remote: .
|
3
|
+
specs:
|
4
|
+
open_router (0.1.0)
|
5
|
+
faraday (>= 1)
|
6
|
+
faraday-multipart (>= 1)
|
7
|
+
|
8
|
+
GEM
|
9
|
+
remote: https://rubygems.org/
|
10
|
+
specs:
|
11
|
+
ast (2.4.2)
|
12
|
+
diff-lcs (1.5.0)
|
13
|
+
faraday (2.7.10)
|
14
|
+
faraday-net_http (>= 2.0, < 3.1)
|
15
|
+
ruby2_keywords (>= 0.0.4)
|
16
|
+
faraday-multipart (1.0.4)
|
17
|
+
multipart-post (~> 2)
|
18
|
+
faraday-net_http (3.0.2)
|
19
|
+
json (2.6.3)
|
20
|
+
language_server-protocol (3.17.0.3)
|
21
|
+
multipart-post (2.3.0)
|
22
|
+
parallel (1.23.0)
|
23
|
+
parser (3.2.2.3)
|
24
|
+
ast (~> 2.4.1)
|
25
|
+
racc
|
26
|
+
racc (1.7.1)
|
27
|
+
rainbow (3.1.1)
|
28
|
+
rake (13.0.6)
|
29
|
+
regexp_parser (2.8.1)
|
30
|
+
rexml (3.2.6)
|
31
|
+
rspec (3.12.0)
|
32
|
+
rspec-core (~> 3.12.0)
|
33
|
+
rspec-expectations (~> 3.12.0)
|
34
|
+
rspec-mocks (~> 3.12.0)
|
35
|
+
rspec-core (3.12.2)
|
36
|
+
rspec-support (~> 3.12.0)
|
37
|
+
rspec-expectations (3.12.3)
|
38
|
+
diff-lcs (>= 1.2.0, < 2.0)
|
39
|
+
rspec-support (~> 3.12.0)
|
40
|
+
rspec-mocks (3.12.6)
|
41
|
+
diff-lcs (>= 1.2.0, < 2.0)
|
42
|
+
rspec-support (~> 3.12.0)
|
43
|
+
rspec-support (3.12.1)
|
44
|
+
rubocop (1.55.1)
|
45
|
+
json (~> 2.3)
|
46
|
+
language_server-protocol (>= 3.17.0)
|
47
|
+
parallel (~> 1.10)
|
48
|
+
parser (>= 3.2.2.3)
|
49
|
+
rainbow (>= 2.2.2, < 4.0)
|
50
|
+
regexp_parser (>= 1.8, < 3.0)
|
51
|
+
rexml (>= 3.2.5, < 4.0)
|
52
|
+
rubocop-ast (>= 1.28.1, < 2.0)
|
53
|
+
ruby-progressbar (~> 1.7)
|
54
|
+
unicode-display_width (>= 2.4.0, < 3.0)
|
55
|
+
rubocop-ast (1.29.0)
|
56
|
+
parser (>= 3.2.1.0)
|
57
|
+
ruby-progressbar (1.13.0)
|
58
|
+
ruby2_keywords (0.0.5)
|
59
|
+
unicode-display_width (2.4.2)
|
60
|
+
|
61
|
+
PLATFORMS
|
62
|
+
arm64-darwin-21
|
63
|
+
|
64
|
+
DEPENDENCIES
|
65
|
+
open_router!
|
66
|
+
rake (~> 13.0)
|
67
|
+
rspec (~> 3.0)
|
68
|
+
rubocop (~> 1.21)
|
69
|
+
|
70
|
+
BUNDLED WITH
|
71
|
+
2.4.12
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2024 Obie Fernandez
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,119 @@
|
|
1
|
+
# OpenRouter
|
2
|
+
|
3
|
+
The future will bring us hundreds of language models and dozens of providers for each. How will you choose the best?
|
4
|
+
|
5
|
+
The [OpenRouter API](https://openrouter.ai/docs) is a single unified interface for all LLMs! And now you can easily use it with Ruby! 🤖🌌
|
6
|
+
|
7
|
+
## Features
|
8
|
+
|
9
|
+
- **Prioritize price or performance**: OpenRouter scouts for the lowest prices and best latencies/throughputs across dozens of providers, and lets you choose how to prioritize them.
|
10
|
+
- **Standardized API**: No need to change your code when switching between models or providers. You can even let users choose and pay for their own.
|
11
|
+
- **Easy integration**: This Ruby gem provides a simple and intuitive interface to interact with the OpenRouter API, making it effortless to integrate AI capabilities into your Ruby applications.
|
12
|
+
|
13
|
+
👬 This Ruby library was originally bootstrapped from the [🤖 OpenRouter](https://github.com/alexrudall/anthropic) gem by Alex Rudall, and subsequently extracted from the codebase of my fast-growing AI startup called [Olympia](https://olympia.chat?utm_source=open_router_gem&utm_medium=github) that lets you add AI-powered consultants to your startup!
|
14
|
+
|
15
|
+
🚢 Need someone to develop AI software for you using modern Ruby on Rails? My other company Magma Labs does exactly that: [magmalabs.io](https://www.magmalabs.io/?utm_source=open_router_gem&utm_medium=github). In fact, we also sell off-the-shelf solutions based on my early work on the field, via a platform called [MagmaChat](https://magmachat.ai?utm_source=open_router_gem&utm_medium=github)
|
16
|
+
|
17
|
+
|
18
|
+
[🐦 Olympia's Twitter](https://twitter.com/OlympiaChat) | [🐦 Obie's Twitter](https://twitter.com/OlympiaChat) | [🎮 Ruby AI Builders Discord](https://discord.gg/k4Uc224xVD)
|
19
|
+
|
20
|
+
### Bundler
|
21
|
+
|
22
|
+
Add this line to your application's Gemfile:
|
23
|
+
|
24
|
+
```ruby
|
25
|
+
gem "open_router"
|
26
|
+
```
|
27
|
+
|
28
|
+
And then execute:
|
29
|
+
|
30
|
+
$ bundle install
|
31
|
+
|
32
|
+
### Gem install
|
33
|
+
|
34
|
+
Or install with:
|
35
|
+
|
36
|
+
$ gem install open_router
|
37
|
+
|
38
|
+
and require with:
|
39
|
+
|
40
|
+
```ruby
|
41
|
+
require "open_router"
|
42
|
+
```
|
43
|
+
|
44
|
+
## Usage
|
45
|
+
|
46
|
+
- Get your API key from [https://openrouter.ai/keys](https://openrouter.ai/keys)
|
47
|
+
|
48
|
+
### Quickstart
|
49
|
+
|
50
|
+
Configure the gem with your API keys, for example in an `open_router.rb` initializer file. Never hardcode secrets into your codebase - instead use `Rails.application.credentials` or something like [dotenv](https://github.com/motdotla/dotenv) to pass the keys safely into your environments.
|
51
|
+
|
52
|
+
```ruby
|
53
|
+
OpenRouter.configure do |config|
|
54
|
+
config.access_token = Rails.application.credentials.open_router[:access_token]
|
55
|
+
config.site_name = 'Olympia'
|
56
|
+
config.site_url = 'https://olympia.chat'
|
57
|
+
end
|
58
|
+
```
|
59
|
+
|
60
|
+
Then you can create a client like this:
|
61
|
+
|
62
|
+
```ruby
|
63
|
+
client = OpenRouter::Client.new
|
64
|
+
```
|
65
|
+
|
66
|
+
#### Change version or timeout
|
67
|
+
|
68
|
+
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.
|
69
|
+
|
70
|
+
```ruby
|
71
|
+
client = OpenRouter::Client.new(
|
72
|
+
access_token: "access_token_goes_here",
|
73
|
+
request_timeout: 240 # Optional
|
74
|
+
)
|
75
|
+
```
|
76
|
+
|
77
|
+
### Completions
|
78
|
+
|
79
|
+
Hit the OpenRouter API for a completion:
|
80
|
+
|
81
|
+
```ruby
|
82
|
+
messages = [
|
83
|
+
{ role: "system", content: "You are a helpful assistant." },
|
84
|
+
{ role: "user", content: "What is the color of the sky?" }
|
85
|
+
]
|
86
|
+
|
87
|
+
response = client.complete(messages)
|
88
|
+
puts response["choices"][0]["message"]["content"]
|
89
|
+
# => "The sky is typically blue during the day due to a phenomenon called Rayleigh scattering. Sunlight..."
|
90
|
+
```
|
91
|
+
|
92
|
+
### Models
|
93
|
+
|
94
|
+
Fetch the list of available models from the OpenRouter API:
|
95
|
+
|
96
|
+
```ruby
|
97
|
+
models = client.models
|
98
|
+
puts models
|
99
|
+
# => [{"id"=>"openrouter/auto", "object"=>"model", "created"=>1684195200, "owned_by"=>"openrouter", "permission"=>[], "root"=>"openrouter", "parent"=>nil}, ...]
|
100
|
+
```
|
101
|
+
|
102
|
+
### Query Generation Stats
|
103
|
+
|
104
|
+
Query the generation stats for a given generation ID:
|
105
|
+
|
106
|
+
```ruby
|
107
|
+
generation_id = "generation-abcdefg"
|
108
|
+
stats = client.query_generation_stats(generation_id)
|
109
|
+
puts stats
|
110
|
+
# => {"id"=>"generation-abcdefg", "object"=>"generation", "created"=>1684195200, "model"=>"openrouter/auto", "usage"=>{"prompt_tokens"=>10, "completion_tokens"=>50, "total_tokens"=>60}, "cost"=>0.0006}
|
111
|
+
```
|
112
|
+
|
113
|
+
## Contributing
|
114
|
+
|
115
|
+
Bug reports and pull requests are welcome on GitHub at <https://github.com/OlympiaAI/open_router>. 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/OlympiaAI/open_router/blob/main/CODE_OF_CONDUCT.md).
|
116
|
+
|
117
|
+
## License
|
118
|
+
|
119
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
data/Rakefile
ADDED
@@ -0,0 +1,45 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative 'http'
|
4
|
+
|
5
|
+
module OpenRouter
|
6
|
+
class Client
|
7
|
+
include OpenRouter::HTTP
|
8
|
+
|
9
|
+
# Initializes the client with optional configurations.
|
10
|
+
def initialize
|
11
|
+
yield(OpenRouter.configuration) if block_given?
|
12
|
+
end
|
13
|
+
|
14
|
+
# Performs a chat completion request to the OpenRouter API.
|
15
|
+
# @param messages [Array<Hash>] Array of message hashes with role and content, like [{role: "user", content: "What is the meaning of life?"}]
|
16
|
+
# @param model [String] Model identifier, defaults to 'openrouter/auto'
|
17
|
+
# @param providers [Array<String>] Optional array of provider identifiers, ordered by priority
|
18
|
+
# @param transforms [Array<String>] Optional array of strings that tell OpenRouter to apply a series of transformations to the prompt before sending it to the model. Transformations are applied in-order
|
19
|
+
# @param extras [Hash] Optional hash of model-specific parameters to send to the OpenRouter API
|
20
|
+
# @param stream [Proc, nil] Optional callable object for streaming
|
21
|
+
# @return [Hash] The completion response.
|
22
|
+
def complete(messages, model: 'openrouter/auto', providers: [], transforms: [], extras: {}, stream: nil)
|
23
|
+
parameters = { model:, messages: }
|
24
|
+
parameters[:provider] = { provider: { order: providers } } if providers.any?
|
25
|
+
parameters[:transforms] = transforms if transforms.any?
|
26
|
+
parameters[:stream] = stream if stream
|
27
|
+
parameters.merge!(extras)
|
28
|
+
json_post(path: "/chat/completions", parameters:)
|
29
|
+
end
|
30
|
+
|
31
|
+
# Fetches the list of available models from the OpenRouter API.
|
32
|
+
# @return [Array<Hash>] The list of models.
|
33
|
+
def models
|
34
|
+
get(path: "/models")["data"]
|
35
|
+
end
|
36
|
+
|
37
|
+
# Queries the generation stats for a given id.
|
38
|
+
# @param generation_id [String] The generation id returned from a previous request.
|
39
|
+
# @return [Hash] The stats including token counts and cost.
|
40
|
+
def query_generation_stats(generation_id)
|
41
|
+
response = get(path: "/generation?id=#{generation_id}")
|
42
|
+
response["data"]
|
43
|
+
end
|
44
|
+
end
|
45
|
+
end
|
@@ -0,0 +1,94 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module OpenRouter
|
4
|
+
module HTTP
|
5
|
+
def get(path:)
|
6
|
+
to_json(conn.get(uri(path:)) do |req|
|
7
|
+
req.headers = headers
|
8
|
+
end&.body)
|
9
|
+
end
|
10
|
+
|
11
|
+
def json_post(path:, parameters:)
|
12
|
+
to_json(conn.post(uri(path:)) do |req|
|
13
|
+
if parameters[:stream].respond_to?(:call)
|
14
|
+
req.options.on_data = to_json_stream(user_proc: parameters[:stream])
|
15
|
+
parameters[:stream] = true # Necessary to tell OpenRouter to stream.
|
16
|
+
end
|
17
|
+
|
18
|
+
req.headers = headers
|
19
|
+
req.body = parameters.to_json
|
20
|
+
end&.body)
|
21
|
+
end
|
22
|
+
|
23
|
+
def multipart_post(path:, parameters: nil)
|
24
|
+
to_json(conn(multipart: true).post(uri(path:)) do |req|
|
25
|
+
req.headers = headers.merge({ "Content-Type" => "multipart/form-data" })
|
26
|
+
req.body = multipart_parameters(parameters)
|
27
|
+
end&.body)
|
28
|
+
end
|
29
|
+
|
30
|
+
def delete(path:)
|
31
|
+
to_json(conn.delete(uri(path:)) do |req|
|
32
|
+
req.headers = headers
|
33
|
+
end&.body)
|
34
|
+
end
|
35
|
+
|
36
|
+
private
|
37
|
+
|
38
|
+
def to_json(string)
|
39
|
+
return unless string
|
40
|
+
|
41
|
+
JSON.parse(string)
|
42
|
+
rescue JSON::ParserError
|
43
|
+
# Convert a multiline string of JSON objects to a JSON array.
|
44
|
+
JSON.parse(string.gsub("}\n{", "},{").prepend("[").concat("]"))
|
45
|
+
end
|
46
|
+
|
47
|
+
# Given a proc, returns an outer proc that can be used to iterate over a JSON stream of chunks.
|
48
|
+
# For each chunk, the inner user_proc is called giving it the JSON object. The JSON object could
|
49
|
+
# be a data object or an error object as described in the OpenRouter API documentation.
|
50
|
+
#
|
51
|
+
# If the JSON object for a given data or error message is invalid, it is ignored.
|
52
|
+
#
|
53
|
+
# @param user_proc [Proc] The inner proc to call for each JSON object in the chunk.
|
54
|
+
# @return [Proc] An outer proc that iterates over a raw stream, converting it to JSON.
|
55
|
+
def to_json_stream(user_proc:)
|
56
|
+
proc do |chunk, _|
|
57
|
+
chunk.scan(/(?:data|error): (\{.*\})/i).flatten.each do |data|
|
58
|
+
user_proc.call(JSON.parse(data))
|
59
|
+
rescue JSON::ParserError
|
60
|
+
# Ignore invalid JSON.
|
61
|
+
end
|
62
|
+
end
|
63
|
+
end
|
64
|
+
|
65
|
+
def conn(multipart: false)
|
66
|
+
Faraday.new do |f|
|
67
|
+
f.options[:timeout] = OpenRouter.configuration.request_timeout
|
68
|
+
f.request(:multipart) if multipart
|
69
|
+
end
|
70
|
+
end
|
71
|
+
|
72
|
+
def uri(path:)
|
73
|
+
File.join(OpenRouter.configuration.uri_base, OpenRouter.configuration.api_version, path)
|
74
|
+
end
|
75
|
+
|
76
|
+
def headers
|
77
|
+
{
|
78
|
+
"Authorization" => "Bearer #{OpenRouter.configuration.access_token}",
|
79
|
+
"Content-Type" => "application/json"
|
80
|
+
}.merge(OpenRouter.configuration.extra_headers)
|
81
|
+
end
|
82
|
+
|
83
|
+
def multipart_parameters(parameters)
|
84
|
+
parameters&.transform_values do |value|
|
85
|
+
next value unless value.is_a?(File)
|
86
|
+
|
87
|
+
# Doesn't seem like OpenRouter needs mime_type yet, so not worth
|
88
|
+
# the library to figure this out. Hence the empty string
|
89
|
+
# as the second argument.
|
90
|
+
Faraday::UploadIO.new(value, "", value.path)
|
91
|
+
end
|
92
|
+
end
|
93
|
+
end
|
94
|
+
end
|
data/lib/open_router.rb
ADDED
@@ -0,0 +1,56 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "faraday"
|
4
|
+
require "faraday/multipart"
|
5
|
+
|
6
|
+
require_relative "open_router/http"
|
7
|
+
require_relative "open_router/client"
|
8
|
+
require_relative "open_router/version"
|
9
|
+
|
10
|
+
module OpenRouter
|
11
|
+
class Error < StandardError; end
|
12
|
+
class ConfigurationError < Error; end
|
13
|
+
|
14
|
+
class Configuration
|
15
|
+
attr_writer :access_token
|
16
|
+
attr_accessor :api_version, :extra_headers, :request_timeout, :uri_base
|
17
|
+
|
18
|
+
DEFAULT_API_VERSION = "v1"
|
19
|
+
DEFAULT_REQUEST_TIMEOUT = 120
|
20
|
+
DEFAULT_URI_BASE = 'https://openrouter.ai/api'
|
21
|
+
|
22
|
+
def initialize
|
23
|
+
@access_token = nil
|
24
|
+
@uri_base = DEFAULT_URI_BASE
|
25
|
+
@api_version = DEFAULT_API_VERSION
|
26
|
+
@request_timeout = DEFAULT_REQUEST_TIMEOUT
|
27
|
+
@extra_headers = {}
|
28
|
+
end
|
29
|
+
|
30
|
+
def access_token
|
31
|
+
return @access_token if @access_token
|
32
|
+
|
33
|
+
raise ConfigurationError, "OpenRouter access token missing!"
|
34
|
+
end
|
35
|
+
|
36
|
+
def site_name=(value)
|
37
|
+
@extra_headers["X-Title"] = value
|
38
|
+
end
|
39
|
+
|
40
|
+
def site_url=(value)
|
41
|
+
@extra_headers["HTTP-Referer"] = value
|
42
|
+
end
|
43
|
+
end
|
44
|
+
|
45
|
+
class << self
|
46
|
+
attr_writer :configuration
|
47
|
+
end
|
48
|
+
|
49
|
+
def self.configuration
|
50
|
+
@configuration ||= OpenRouter::Configuration.new
|
51
|
+
end
|
52
|
+
|
53
|
+
def self.configure
|
54
|
+
yield(configuration)
|
55
|
+
end
|
56
|
+
end
|
data/open_router.gemspec
ADDED
@@ -0,0 +1,32 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "lib/open_router/version"
|
4
|
+
|
5
|
+
Gem::Specification.new do |spec|
|
6
|
+
spec.name = "open_router"
|
7
|
+
spec.version = OpenRouter::VERSION
|
8
|
+
spec.authors = ["Obie Fernandez"]
|
9
|
+
spec.email = ["obiefernandez@gmail.com"]
|
10
|
+
|
11
|
+
spec.summary = "Ruby library for OpenRouter API."
|
12
|
+
spec.homepage = "https://github.com/OlympiaAI/open_router"
|
13
|
+
spec.license = "MIT"
|
14
|
+
spec.required_ruby_version = ">= 3.2.1"
|
15
|
+
|
16
|
+
spec.metadata["homepage_uri"] = spec.homepage
|
17
|
+
spec.metadata["source_code_uri"] = "https://github.com/OlympiaAI/open_router"
|
18
|
+
spec.metadata["changelog_uri"] = "https://github.com/OlympiaAI/open_router/blob/main/CHANGELOG.md"
|
19
|
+
|
20
|
+
spec.files = Dir.chdir(__dir__) do
|
21
|
+
`git ls-files -z`.split("\x0").reject do |f|
|
22
|
+
(File.expand_path(f) == __FILE__) || f.end_with?('.gem') || f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor])
|
23
|
+
end
|
24
|
+
end
|
25
|
+
|
26
|
+
spec.bindir = "exe"
|
27
|
+
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
|
28
|
+
spec.require_paths = ["lib"]
|
29
|
+
|
30
|
+
spec.add_dependency "faraday", ">= 1"
|
31
|
+
spec.add_dependency "faraday-multipart", ">= 1"
|
32
|
+
end
|
data/sig/open_router.rbs
ADDED
@@ -0,0 +1,20 @@
|
|
1
|
+
module OpenRouter
|
2
|
+
class Client
|
3
|
+
include OpenRouter::HTTP
|
4
|
+
|
5
|
+
def initialize: () { (OpenRouter::Configuration) -> void } -> void
|
6
|
+
|
7
|
+
def complete: (
|
8
|
+
messages: Array[Hash[Symbol, String]],
|
9
|
+
?model: String,
|
10
|
+
?providers: Array[String],
|
11
|
+
?transforms: Array[String],
|
12
|
+
?extras: Hash[Symbol, untyped],
|
13
|
+
?stream: Proc
|
14
|
+
) -> Hash[String, untyped]
|
15
|
+
|
16
|
+
def models: () -> Array[Hash[String, untyped]]
|
17
|
+
|
18
|
+
def query_generation_stats: (generation_id: String) -> Hash[String, untyped]
|
19
|
+
end
|
20
|
+
end
|
metadata
ADDED
@@ -0,0 +1,89 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: open_router
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Obie Fernandez
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2024-03-19 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:
|
42
|
+
email:
|
43
|
+
- obiefernandez@gmail.com
|
44
|
+
executables: []
|
45
|
+
extensions: []
|
46
|
+
extra_rdoc_files: []
|
47
|
+
files:
|
48
|
+
- ".rspec"
|
49
|
+
- ".rubocop.yml"
|
50
|
+
- CHANGELOG.md
|
51
|
+
- CODE_OF_CONDUCT.md
|
52
|
+
- Gemfile
|
53
|
+
- Gemfile.lock
|
54
|
+
- LICENSE.txt
|
55
|
+
- README.md
|
56
|
+
- Rakefile
|
57
|
+
- lib/open_router.rb
|
58
|
+
- lib/open_router/client.rb
|
59
|
+
- lib/open_router/http.rb
|
60
|
+
- lib/open_router/version.rb
|
61
|
+
- open_router.gemspec
|
62
|
+
- sig/open_router.rbs
|
63
|
+
homepage: https://github.com/OlympiaAI/open_router
|
64
|
+
licenses:
|
65
|
+
- MIT
|
66
|
+
metadata:
|
67
|
+
homepage_uri: https://github.com/OlympiaAI/open_router
|
68
|
+
source_code_uri: https://github.com/OlympiaAI/open_router
|
69
|
+
changelog_uri: https://github.com/OlympiaAI/open_router/blob/main/CHANGELOG.md
|
70
|
+
post_install_message:
|
71
|
+
rdoc_options: []
|
72
|
+
require_paths:
|
73
|
+
- lib
|
74
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
75
|
+
requirements:
|
76
|
+
- - ">="
|
77
|
+
- !ruby/object:Gem::Version
|
78
|
+
version: 3.2.1
|
79
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
80
|
+
requirements:
|
81
|
+
- - ">="
|
82
|
+
- !ruby/object:Gem::Version
|
83
|
+
version: '0'
|
84
|
+
requirements: []
|
85
|
+
rubygems_version: 3.4.12
|
86
|
+
signing_key:
|
87
|
+
specification_version: 4
|
88
|
+
summary: Ruby library for OpenRouter API.
|
89
|
+
test_files: []
|