savvy_openrouter 0.2.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 +7 -0
- data/.rspec +3 -0
- data/.rubocop.yml +50 -0
- data/CHANGELOG.md +23 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE.txt +21 -0
- data/README.md +234 -0
- data/Rakefile +12 -0
- data/exe/savvy_openrouter +32 -0
- data/lib/generators/savvy_openrouter/install/install_generator.rb +17 -0
- data/lib/generators/savvy_openrouter/install/templates/savvy_openrouter.yml +53 -0
- data/lib/savvy_openrouter/api_call_logger.rb +93 -0
- data/lib/savvy_openrouter/client.rb +105 -0
- data/lib/savvy_openrouter/completion_retry_policy.rb +135 -0
- data/lib/savvy_openrouter/configuration.rb +156 -0
- data/lib/savvy_openrouter/connection.rb +316 -0
- data/lib/savvy_openrouter/connection_instrumentation.rb +133 -0
- data/lib/savvy_openrouter/errors.rb +35 -0
- data/lib/savvy_openrouter/resources/analytics.rb +13 -0
- data/lib/savvy_openrouter/resources/anthropic_messages.rb +14 -0
- data/lib/savvy_openrouter/resources/api_keys.rb +33 -0
- data/lib/savvy_openrouter/resources/audio.rb +19 -0
- data/lib/savvy_openrouter/resources/base.rb +23 -0
- data/lib/savvy_openrouter/resources/chat.rb +45 -0
- data/lib/savvy_openrouter/resources/credits.rb +13 -0
- data/lib/savvy_openrouter/resources/embeddings.rb +18 -0
- data/lib/savvy_openrouter/resources/endpoints.rb +13 -0
- data/lib/savvy_openrouter/resources/generations.rb +17 -0
- data/lib/savvy_openrouter/resources/guardrails.rb +61 -0
- data/lib/savvy_openrouter/resources/models.rb +57 -0
- data/lib/savvy_openrouter/resources/oauth.rb +17 -0
- data/lib/savvy_openrouter/resources/organization.rb +13 -0
- data/lib/savvy_openrouter/resources/providers.rb +13 -0
- data/lib/savvy_openrouter/resources/rerank.rb +14 -0
- data/lib/savvy_openrouter/resources/responses.rb +14 -0
- data/lib/savvy_openrouter/resources/videos.rb +53 -0
- data/lib/savvy_openrouter/resources/workspaces.rb +37 -0
- data/lib/savvy_openrouter/streaming.rb +32 -0
- data/lib/savvy_openrouter/version.rb +5 -0
- data/lib/savvy_openrouter.rb +13 -0
- data/savvy_openrouter-0.1.0.gem +0 -0
- data/sig/savvy_openrouter.rbs +150 -0
- metadata +165 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 5429c1ab8b5a4a777f1e95511f1ff54a6b4c409026637a1732f090bf919fc1fc
|
|
4
|
+
data.tar.gz: 40731fb4249d671e8ad33aaeab2de19708972cf75abc2a5d3d91e702d9e7dde4
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 73104149df96fcbbc61b33719d924865335c98f355ac37f5701b0083005e8dca9f7fc38d7740722d70524a207a485474cfe7a7e03383cde1bf2818dbe91a8eb6
|
|
7
|
+
data.tar.gz: 1d3f8011538f69c2e5e47aae61b7adbb28d262ab3e13c369214d7c6f442d347da1ce8ae36e05bdc36067624b732dc6b8d63d22c38df4e8d43de5d7334ae2854b
|
data/.rspec
ADDED
data/.rubocop.yml
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
AllCops:
|
|
2
|
+
TargetRubyVersion: 3.1
|
|
3
|
+
NewCops: enable
|
|
4
|
+
SuggestExtensions: false
|
|
5
|
+
Exclude:
|
|
6
|
+
- "vendor/**/*"
|
|
7
|
+
|
|
8
|
+
Style/Documentation:
|
|
9
|
+
Enabled: false
|
|
10
|
+
|
|
11
|
+
Metrics/MethodLength:
|
|
12
|
+
Max: 35
|
|
13
|
+
|
|
14
|
+
Metrics/ParameterLists:
|
|
15
|
+
Max: 8
|
|
16
|
+
|
|
17
|
+
Metrics/ClassLength:
|
|
18
|
+
Max: 300
|
|
19
|
+
|
|
20
|
+
Metrics/ModuleLength:
|
|
21
|
+
Max: 120
|
|
22
|
+
|
|
23
|
+
Metrics/AbcSize:
|
|
24
|
+
Max: 48
|
|
25
|
+
|
|
26
|
+
Metrics/CyclomaticComplexity:
|
|
27
|
+
Max: 20
|
|
28
|
+
|
|
29
|
+
Metrics/PerceivedComplexity:
|
|
30
|
+
Max: 20
|
|
31
|
+
|
|
32
|
+
Metrics/BlockLength:
|
|
33
|
+
Exclude:
|
|
34
|
+
- "spec/**/*_spec.rb"
|
|
35
|
+
- "*.gemspec"
|
|
36
|
+
|
|
37
|
+
Layout/LineLength:
|
|
38
|
+
Max: 130
|
|
39
|
+
|
|
40
|
+
Gemspec/DevelopmentDependencies:
|
|
41
|
+
Enabled: false
|
|
42
|
+
|
|
43
|
+
Style/YAMLFileRead:
|
|
44
|
+
Enabled: false
|
|
45
|
+
|
|
46
|
+
Style/StringLiterals:
|
|
47
|
+
EnforcedStyle: double_quotes
|
|
48
|
+
|
|
49
|
+
Style/StringLiteralsInInterpolation:
|
|
50
|
+
EnforcedStyle: double_quotes
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
## [Unreleased]
|
|
2
|
+
|
|
3
|
+
## [0.2.0] - 2026-05-09
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- **`Chat`:** configurable **`chat_retries`** / **`completion_retries`** for **`client.chat.completions`** — retries on empty assistant text, **`usage.completion_tokens == 0`**, and HTTP **429** / **502** / **500**/**501** / **503** with backoff (streaming unchanged).
|
|
8
|
+
- **`Models`:** `SavvyOpenrouter::Resources::Models#list` forwards keyword arguments as **`GET /models`** query parameters (`category`, `output_modalities`, `supported_parameters`, etc.).
|
|
9
|
+
- **`Models`:** `SavvyOpenrouter::Resources::Models#first_ranked_free_text_model(category:, output_modalities: "text")` returns the first model in the API response whose **`pricing.prompt`** and **`pricing.completion`** are both zero, preserving OpenRouter’s list order (used to mirror curated “top free” picks per category when combined with text modality filters).
|
|
10
|
+
- **`Configuration`:** `api_call_log` in YAML or `api_call_log:` on the client — optional persistence of each HTTP exchange to a model class (`create!`) with user-defined column mappings for debugging (JSON, raw, and streaming paths).
|
|
11
|
+
- **`Configuration`:** `responses_defaults` / `defaults_responses` in YAML or `responses_defaults:` on the client: merged only into **`POST /responses`**, so Responses-only fields (plugins, server tools, `max_output_tokens`, …) are not merged into chat, embeddings, rerank, audio, or Anthropic bodies.
|
|
12
|
+
|
|
13
|
+
### Documentation
|
|
14
|
+
|
|
15
|
+
- **README:** chat completion retries (`chat_retries`), API call logging (`api_call_log`), Models API, usage snippets, and integration test notes.
|
|
16
|
+
|
|
17
|
+
## [0.1.0] - 2026-05-09
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
- `SavvyOpenrouter::Client` with resources for chat (incl. SSE streaming), Responses beta, Anthropic `/messages`, embeddings, rerank, models, credits, providers, generations, endpoints (ZDR), analytics (`/activity`), audio (speech + transcription), video generation (create, poll, download, stream, `poll_until`), OAuth PKCE helpers, API keys, organization members, guardrails, and workspaces.
|
|
22
|
+
- YAML configuration discovery (`config/savvy_openrouter.yml`, `.savvy_openrouter.yml`) with merge defaults for chat and video requests.
|
|
23
|
+
- Rails generator `savvy_openrouter:install` and CLI `savvy_openrouter install`.
|
data/CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
|
2
|
+
|
|
3
|
+
## Our Pledge
|
|
4
|
+
|
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
|
10
|
+
identity and orientation.
|
|
11
|
+
|
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
|
13
|
+
diverse, inclusive, and healthy community.
|
|
14
|
+
|
|
15
|
+
## Our Standards
|
|
16
|
+
|
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
|
18
|
+
community include:
|
|
19
|
+
|
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
|
24
|
+
and learning from the experience
|
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
|
26
|
+
community
|
|
27
|
+
|
|
28
|
+
Examples of unacceptable behavior include:
|
|
29
|
+
|
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
|
31
|
+
any kind
|
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
|
33
|
+
* Public or private harassment
|
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
|
35
|
+
without their explicit permission
|
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
|
37
|
+
professional setting
|
|
38
|
+
|
|
39
|
+
## Enforcement Responsibilities
|
|
40
|
+
|
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
|
44
|
+
or harmful.
|
|
45
|
+
|
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
|
49
|
+
decisions when appropriate.
|
|
50
|
+
|
|
51
|
+
## Scope
|
|
52
|
+
|
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
|
54
|
+
an individual is officially representing the community in public spaces.
|
|
55
|
+
Examples of representing our community include using an official email address,
|
|
56
|
+
posting via an official social media account, or acting as an appointed
|
|
57
|
+
representative at an online or offline event.
|
|
58
|
+
|
|
59
|
+
## Enforcement
|
|
60
|
+
|
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
|
62
|
+
reported to the community leaders responsible for enforcement at
|
|
63
|
+
[INSERT CONTACT METHOD].
|
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
|
65
|
+
|
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
|
67
|
+
reporter of any incident.
|
|
68
|
+
|
|
69
|
+
## Enforcement Guidelines
|
|
70
|
+
|
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
|
73
|
+
|
|
74
|
+
### 1. Correction
|
|
75
|
+
|
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
|
77
|
+
unprofessional or unwelcome in the community.
|
|
78
|
+
|
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
|
82
|
+
|
|
83
|
+
### 2. Warning
|
|
84
|
+
|
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
|
86
|
+
actions.
|
|
87
|
+
|
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
|
93
|
+
ban.
|
|
94
|
+
|
|
95
|
+
### 3. Temporary Ban
|
|
96
|
+
|
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
|
98
|
+
sustained inappropriate behavior.
|
|
99
|
+
|
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
|
101
|
+
communication with the community for a specified period of time. No public or
|
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
|
104
|
+
Violating these terms may lead to a permanent ban.
|
|
105
|
+
|
|
106
|
+
### 4. Permanent Ban
|
|
107
|
+
|
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
|
111
|
+
|
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
|
113
|
+
community.
|
|
114
|
+
|
|
115
|
+
## Attribution
|
|
116
|
+
|
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
|
118
|
+
version 2.1, available at
|
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
|
120
|
+
|
|
121
|
+
Community Impact Guidelines were inspired by
|
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
|
123
|
+
|
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
|
127
|
+
|
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bryan Feller
|
|
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,234 @@
|
|
|
1
|
+
# Savvy OpenRouter
|
|
2
|
+
|
|
3
|
+
Ruby client for [OpenRouter](https://openrouter.ai/) — unified access to chat models, embeddings, reranking, speech, transcription, **video generation**, OAuth, API keys, guardrails, workspaces, and related REST endpoints.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
Add to your Gemfile:
|
|
8
|
+
|
|
9
|
+
```ruby
|
|
10
|
+
gem "savvy_openrouter"
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or install the gem directly:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
gem install savvy_openrouter
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Configuration
|
|
20
|
+
|
|
21
|
+
Precedence is **keyword arguments to `SavvyOpenrouter::Client`** (highest), then **YAML config**, then **environment variables** (lowest).
|
|
22
|
+
|
|
23
|
+
### Environment variables
|
|
24
|
+
|
|
25
|
+
| Variable | Purpose |
|
|
26
|
+
|----------|---------|
|
|
27
|
+
| `OPENROUTER_API_KEY` | Bearer token (required for requests) |
|
|
28
|
+
| `OPENROUTER_BASE_URL` | API base (default `https://openrouter.ai/api/v1`) |
|
|
29
|
+
| `OPENROUTER_DEFAULT_MODEL` | Default `model` when omitted in request bodies |
|
|
30
|
+
| `OPENROUTER_HTTP_REFERER` | `HTTP-Referer` header ([app attribution](https://openrouter.ai/docs/app-attribution.mdx)) |
|
|
31
|
+
| `OPENROUTER_APP_TITLE` | `X-Title` header |
|
|
32
|
+
|
|
33
|
+
### YAML config (optional)
|
|
34
|
+
|
|
35
|
+
If `config/savvy_openrouter.yml` or `.savvy_openrouter.yml` exists in the working directory, it is loaded automatically. Example:
|
|
36
|
+
|
|
37
|
+
```yaml
|
|
38
|
+
api_key: "sk-or-v1-..."
|
|
39
|
+
default_model: "openai/gpt-4o-mini"
|
|
40
|
+
defaults:
|
|
41
|
+
temperature: 0.7
|
|
42
|
+
max_tokens: 4096
|
|
43
|
+
video_defaults:
|
|
44
|
+
aspect_ratio: "16:9"
|
|
45
|
+
resolution: "720p"
|
|
46
|
+
http_referer: "https://your-app.example.com"
|
|
47
|
+
app_title: "Your App"
|
|
48
|
+
|
|
49
|
+
# Responses API only (POST /responses) — plugins, tools, max_output_tokens, x_search_filter, etc.
|
|
50
|
+
# Use this instead of putting `plugins` under global `defaults` (which would also merge into chat/embeddings).
|
|
51
|
+
# See https://openrouter.ai/docs/api/reference/responses/web-search
|
|
52
|
+
# responses_defaults:
|
|
53
|
+
# plugins:
|
|
54
|
+
# - id: web
|
|
55
|
+
# max_results: 5
|
|
56
|
+
# max_output_tokens: 4096
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### API call logging (`api_call_log`)
|
|
60
|
+
|
|
61
|
+
Optional persistence of **every outbound OpenRouter HTTP request** made through this gem (JSON clients, raw/binary downloads, and streaming chat). Configure **`api_call_log`** in YAML or pass **`api_call_log:`** when building **`SavvyOpenrouter::Client`**.
|
|
62
|
+
|
|
63
|
+
It depends on **Active Record** (or any Ruby class you configure) exposing **`create!(attributes)`** — the usual Rails pattern. Define a migration for whatever columns you map (strings / integers / booleans / text); avoid indexing huge raw payloads on Postgres without care.
|
|
64
|
+
|
|
65
|
+
```yaml
|
|
66
|
+
# Optional — persist each outbound HTTP exchange for debugging (Faraday JSON + raw + SSE streams)
|
|
67
|
+
api_call_log:
|
|
68
|
+
model: OpenRouterApiCallLog
|
|
69
|
+
max_body_bytes: 65536
|
|
70
|
+
columns:
|
|
71
|
+
method: http_method # GET, POST, …
|
|
72
|
+
path: request_url # full URL including query string when present
|
|
73
|
+
status: response_status # integer HTTP status (nil on transport failure before response)
|
|
74
|
+
duration_ms: duration_ms # float milliseconds
|
|
75
|
+
request_body: request_body # JSON-ish text; secrets redacted; truncated to max_body_bytes
|
|
76
|
+
response_body: response_body # same treatment
|
|
77
|
+
error_class: error_class # nil when Faraday returned a response
|
|
78
|
+
error_message: error_message # transport errors or truncated exception message
|
|
79
|
+
streaming: streaming # true for chat SSE streams
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Canonical keys on the **left** (`method`, `path`, …) are fixed by the gem; **right-hand** names are your database columns. Omit mappings you do not need. Set **`api_call_log: false`** (or omit `model` / `columns`) to disable.
|
|
83
|
+
|
|
84
|
+
Logging failures never raise into your app code. Large bodies are truncated; **`Authorization`** / **`sk-or-v1-*`** patterns in serialized bodies are redacted (still treat logs as sensitive).
|
|
85
|
+
|
|
86
|
+
### Chat completion retries (`chat_retries`)
|
|
87
|
+
|
|
88
|
+
For **`client.chat.completions`** only (not streaming), you can retry when OpenRouter returns a **successful HTTP 200** but the payload looks broken—common with **free tiers** (`usage.completion_tokens == 0`) or an **empty assistant `content`**—and on selected **HTTP errors** (`429`, `502`, `500`/`501`, `503`).
|
|
89
|
+
|
|
90
|
+
Configure **`chat_retries`** in YAML or pass **`chat_retries:`** / **`completion_retries:`** to **`SavvyOpenrouter::Client`**. Retries are off unless **`max_attempts`** is **greater than 1**.
|
|
91
|
+
|
|
92
|
+
```yaml
|
|
93
|
+
chat_retries:
|
|
94
|
+
max_attempts: 4
|
|
95
|
+
base_delay_ms: 400
|
|
96
|
+
max_delay_ms: 8000
|
|
97
|
+
exponential_backoff: true # default true; set false for fixed delay
|
|
98
|
+
jitter_ratio: 0.15 # 0–1, fraction of delay added randomly
|
|
99
|
+
on: # optional overrides (default true for each unless set false)
|
|
100
|
+
zero_completion_tokens: true
|
|
101
|
+
empty_assistant_content: true
|
|
102
|
+
rate_limit: true
|
|
103
|
+
bad_gateway: true
|
|
104
|
+
internal_server_error: true
|
|
105
|
+
service_unavailable: true
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
After the last attempt, the gem returns the **final response body** (for 200s) or **re-raises** the last API error. **`completions_stream`** does not use this policy—handle streaming retries in your own code if needed.
|
|
109
|
+
|
|
110
|
+
### Install templates
|
|
111
|
+
|
|
112
|
+
**Rails**
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
rails generate savvy_openrouter:install
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
**Plain Ruby / scripts**
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
bundle exec savvy_openrouter install
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Creates `config/savvy_openrouter.yml` from the bundled template.
|
|
125
|
+
|
|
126
|
+
### Responses API: web search and plugins
|
|
127
|
+
|
|
128
|
+
The [Responses API](https://openrouter.ai/docs/api/reference/responses/overview) accepts parameters such as [`plugins`](https://openrouter.ai/docs/api/reference/responses/web-search) (legacy web plugin), [`tools`](https://openrouter.ai/docs/guides/features/server-tools/web-search) (recommended `openrouter:web_search` server tool for Chat Completions and Responses), `max_output_tokens`, and `x_search_filter` (xAI).
|
|
129
|
+
|
|
130
|
+
**Do not put those keys in the global `defaults` hash**, because `defaults` is merged into **chat completions, embeddings, rerank, audio,** etc. Instead use **`responses_defaults`** in YAML (or `responses_defaults:` when constructing `SavvyOpenrouter::Client`). Those keys are merged **only** into `client.responses.create(...)`.
|
|
131
|
+
|
|
132
|
+
Example:
|
|
133
|
+
|
|
134
|
+
```yaml
|
|
135
|
+
responses_defaults:
|
|
136
|
+
plugins:
|
|
137
|
+
- id: web
|
|
138
|
+
max_results: 5
|
|
139
|
+
max_output_tokens: 9000
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Per-request arguments override the same keys from `responses_defaults`.
|
|
143
|
+
|
|
144
|
+
OpenRouter documents the legacy `plugins: [{ id: "web" }]` approach as deprecated in favor of the **`openrouter:web_search` server tool** via the `tools` array; you can still pass either shape through this gem as passthrough JSON.
|
|
145
|
+
|
|
146
|
+
### Models API (`GET /models`)
|
|
147
|
+
|
|
148
|
+
[`GET /api/v1/models`](https://openrouter.ai/docs/api/api-reference/models/get-models) supports optional **query parameters**, including `category` (for example `programming`, `roleplay`, `science`), `output_modalities` (for example `text`), and `supported_parameters`. Pass them as keywords to **`client.models.list`**:
|
|
149
|
+
|
|
150
|
+
```ruby
|
|
151
|
+
client.models.list(category: "programming", output_modalities: "text")
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
OpenRouter returns models in **curated rank order** within each filtered result set—that order is not “highest `context_length` wins.” To approximate the **top free text model** for a category, call **`first_ranked_free_text_model`**, which keeps API order and returns the **first** model whose **`pricing.prompt`** and **`pricing.completion`** both parse to zero:
|
|
155
|
+
|
|
156
|
+
```ruby
|
|
157
|
+
client.models.first_ranked_free_text_model(category: "programming")
|
|
158
|
+
client.models.first_ranked_free_text_model(category: "roleplay")
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
**Use a stored model id for normal traffic.** Resolving the free model calls **`GET /models`** (one request). Each chat turn is **`POST /chat/completions`** (another). If you call `first_ranked_free_text_model` (or `list` and pick) on **every** user message, you pay **two** API calls per turn—list plus chat. Instead, resolve **once** (at deploy, in a Rake task, or on a long TTL), **remember** the returned **`id`** (environment variable, database, cache, or `default_model` in `savvy_openrouter.yml`), and pass that string to **`client.chat.completions(model: ...)`** for ongoing requests. Refresh the stored id when you want to pick up a new “top free” model after OpenRouter changes their list.
|
|
162
|
+
|
|
163
|
+
That heuristic stays aligned with OpenRouter’s listing **as long as their ranking and pricing rows stay as they are**; it is not a separate benchmark score from the JSON (there is no `rating` field on each model). For chat-specific knobs such as **`tools`**, **`tool_choice`**, and **`response_format`** (including JSON schema), pass them on **`client.chat.completions`**; global YAML **`defaults`** also merge into embeddings and other resources, so prefer per-call args for tool and schema defaults unless you only use chat endpoints.
|
|
164
|
+
|
|
165
|
+
## Usage
|
|
166
|
+
|
|
167
|
+
```ruby
|
|
168
|
+
require "savvy_openrouter"
|
|
169
|
+
|
|
170
|
+
client = SavvyOpenrouter::Client.new(api_key: ENV.fetch("OPENROUTER_API_KEY"))
|
|
171
|
+
|
|
172
|
+
# Chat completion (defaults from YAML/env merged into body)
|
|
173
|
+
response = client.chat.completions(
|
|
174
|
+
messages: [{ role: "user", content: "Hello!" }]
|
|
175
|
+
)
|
|
176
|
+
puts response[:choices].first[:message][:content]
|
|
177
|
+
|
|
178
|
+
# Streaming (SSE); each yielded string is a JSON `data:` payload from OpenRouter
|
|
179
|
+
client.chat.completions_stream(messages: [{ role: "user", content: "Hi" }]) do |data_json|
|
|
180
|
+
chunk = JSON.parse(data_json)
|
|
181
|
+
print chunk.dig("choices", 0, "delta", "content")
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
# Embeddings
|
|
185
|
+
client.embeddings.create(model: "openai/text-embedding-3-small", input: "Hello world")
|
|
186
|
+
|
|
187
|
+
# Video: create (HTTP 202), poll, download binary
|
|
188
|
+
job = client.videos.create(model: "google/veo-3.1", prompt: "A calm ocean at dawn")
|
|
189
|
+
status = client.videos.poll_until(job[:id])
|
|
190
|
+
video_bytes = client.videos.download(job[:id]) if status[:status].to_s == "completed"
|
|
191
|
+
|
|
192
|
+
# Binary speech (TTS)
|
|
193
|
+
audio_bytes = client.audio.speech(model: "elevenlabs/...", input: "Hello")
|
|
194
|
+
|
|
195
|
+
# Responses API (beta)
|
|
196
|
+
client.responses.create(model: "openai/gpt-4o", input: "Hello")
|
|
197
|
+
|
|
198
|
+
# Discover top free model for a category (GET /models) — run rarely; persist the id, do not call per user message
|
|
199
|
+
top_free = client.models.first_ranked_free_text_model(category: "programming")
|
|
200
|
+
# e.g. save top_free[:id] to ENV or default_model, then:
|
|
201
|
+
client.chat.completions(model: top_free[:id], messages: [{ role: "user", content: "Hello!" }])
|
|
202
|
+
|
|
203
|
+
# Management APIs (typically require a management key)
|
|
204
|
+
client.api_keys.list
|
|
205
|
+
client.guardrails.list
|
|
206
|
+
client.workspaces.list
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
See the [OpenRouter API reference](https://openrouter.ai/docs/api/reference/overview) for request/response shapes.
|
|
210
|
+
|
|
211
|
+
## Errors
|
|
212
|
+
|
|
213
|
+
API failures raise subclasses of `SavvyOpenrouter::ApiError` (for example `AuthenticationError`, `PaymentRequiredError`, `RateLimitError`, `BadGatewayError`). Every error exposes `#status_code` and `#response_body` when available.
|
|
214
|
+
|
|
215
|
+
## Development
|
|
216
|
+
|
|
217
|
+
```bash
|
|
218
|
+
bin/setup
|
|
219
|
+
bundle exec rake # RSpec + RuboCop
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
Integration tests live in `spec/integration/` and are tagged `:integration`. When `OPENROUTER_API_KEY` is set, they call the live API (WebMock allows net connect only for those examples). Smoke chat examples use the free model `inclusionai/ring-2.6-1t:free`; **`spec/integration/free_model_rank_spec.rb`** asserts curated “first free” model ids for `programming` and `roleplay` against the live models list (these examples can fail if OpenRouter changes ordering or pricing).
|
|
223
|
+
|
|
224
|
+
## Contributing
|
|
225
|
+
|
|
226
|
+
Bug reports and pull requests are welcome on GitHub.
|
|
227
|
+
|
|
228
|
+
## License
|
|
229
|
+
|
|
230
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
|
231
|
+
|
|
232
|
+
## Code of Conduct
|
|
233
|
+
|
|
234
|
+
Everyone interacting in this project's repositories is expected to follow the [code of conduct](CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
#!/usr/bin/env ruby
|
|
2
|
+
# frozen_string_literal: true
|
|
3
|
+
|
|
4
|
+
require "fileutils"
|
|
5
|
+
|
|
6
|
+
gem_root = File.expand_path("..", __dir__)
|
|
7
|
+
template = File.join(gem_root, "lib/generators/savvy_openrouter/install/templates/savvy_openrouter.yml")
|
|
8
|
+
|
|
9
|
+
unless File.file?(template)
|
|
10
|
+
warn "Template missing: #{template}"
|
|
11
|
+
exit 1
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
case ARGV[0]
|
|
15
|
+
when "install"
|
|
16
|
+
dest_dir = File.join(Dir.pwd, "config")
|
|
17
|
+
dest = File.join(dest_dir, "savvy_openrouter.yml")
|
|
18
|
+
FileUtils.mkdir_p(dest_dir)
|
|
19
|
+
if File.file?(dest)
|
|
20
|
+
warn "Already exists: #{dest}"
|
|
21
|
+
exit 1
|
|
22
|
+
end
|
|
23
|
+
FileUtils.cp(template, dest)
|
|
24
|
+
puts "Created #{dest}"
|
|
25
|
+
when nil, "-h", "--help"
|
|
26
|
+
puts "Usage: savvy_openrouter install"
|
|
27
|
+
exit(ARGV[0] ? 0 : 1)
|
|
28
|
+
else
|
|
29
|
+
warn "Unknown command: #{ARGV[0].inspect}"
|
|
30
|
+
warn "Usage: savvy_openrouter install"
|
|
31
|
+
exit 1
|
|
32
|
+
end
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rails/generators/base"
|
|
4
|
+
|
|
5
|
+
module SavvyOpenrouter
|
|
6
|
+
module Generators
|
|
7
|
+
class InstallGenerator < Rails::Generators::Base
|
|
8
|
+
source_root File.expand_path("templates", __dir__)
|
|
9
|
+
|
|
10
|
+
desc "Creates config/savvy_openrouter.yml for OpenRouter defaults"
|
|
11
|
+
|
|
12
|
+
def copy_config
|
|
13
|
+
copy_file "savvy_openrouter.yml", "config/savvy_openrouter.yml"
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
end
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# OpenRouter defaults — loaded automatically when present at config/savvy_openrouter.yml
|
|
2
|
+
# or .savvy_openrouter.yml (see SavvyOpenrouter::Configuration).
|
|
3
|
+
#
|
|
4
|
+
# Precedence: keyword arguments to SavvyOpenrouter::Client > this file > ENV variables.
|
|
5
|
+
|
|
6
|
+
# api_key: "sk-or-v1-..."
|
|
7
|
+
# base_url: "https://openrouter.ai/api/v1"
|
|
8
|
+
|
|
9
|
+
# Default model merged into chat/embeddings/rerank/audio bodies when `model` is omitted:
|
|
10
|
+
# default_model: "openai/gpt-4o-mini"
|
|
11
|
+
|
|
12
|
+
# Optional app attribution headers (https://openrouter.ai/docs/app-attribution.mdx):
|
|
13
|
+
# http_referer: "https://your-app.example.com"
|
|
14
|
+
# app_title: "Your App Name"
|
|
15
|
+
|
|
16
|
+
# Keys merged into POST /chat/completions (and similar) bodies:
|
|
17
|
+
# defaults:
|
|
18
|
+
# temperature: 0.7
|
|
19
|
+
# max_tokens: 4096
|
|
20
|
+
|
|
21
|
+
# Keys merged into POST /videos bodies when creating video jobs:
|
|
22
|
+
# video_defaults:
|
|
23
|
+
# aspect_ratio: "16:9"
|
|
24
|
+
# resolution: "720p"
|
|
25
|
+
# duration: 8
|
|
26
|
+
|
|
27
|
+
# Keys merged only into POST /responses (Responses API beta) — not chat/embeddings:
|
|
28
|
+
# responses_defaults:
|
|
29
|
+
# plugins:
|
|
30
|
+
# - id: web
|
|
31
|
+
# max_results: 5
|
|
32
|
+
# max_output_tokens: 9000
|
|
33
|
+
#
|
|
34
|
+
# Optional: persist HTTP exchanges for debugging (Rails: migration + model with create!)
|
|
35
|
+
# api_call_log:
|
|
36
|
+
# model: OpenRouterApiCallLog
|
|
37
|
+
# max_body_bytes: 65536
|
|
38
|
+
# columns:
|
|
39
|
+
# method: http_method
|
|
40
|
+
# path: request_url
|
|
41
|
+
# status: response_status
|
|
42
|
+
# duration_ms: duration_ms
|
|
43
|
+
# request_body: request_body
|
|
44
|
+
# response_body: response_body
|
|
45
|
+
# error_class: error_class
|
|
46
|
+
# error_message: error_message
|
|
47
|
+
# streaming: streaming
|
|
48
|
+
#
|
|
49
|
+
# Optional: retry chat/completions (non-streaming) on empty output, zero completion tokens, or transient HTTP errors
|
|
50
|
+
# chat_retries:
|
|
51
|
+
# max_attempts: 4
|
|
52
|
+
# base_delay_ms: 400
|
|
53
|
+
# max_delay_ms: 8000
|