lex-bedrock 0.1.2 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e12c7f82bdc05d53d867d8b29ae661f217fad0b4212d415fbae54688c004a80f
4
- data.tar.gz: 7ffd2df1e9b2a9578da793a7c890573537f08c27c3d0aaf7a19cc4d5df2f3088
3
+ metadata.gz: fba4162f800e8419912e30cc4ce1477b5f9894f0f282bd67d3eafa3b61e74d9a
4
+ data.tar.gz: 2c26974438c1758108c6006c14eba339ede7feb48d6a65c157c1156de2c4dd68
5
5
  SHA512:
6
- metadata.gz: d5a9f930e1a5f6f409bfd6e99effa0948f9a8a43234ec0c2be6e67c57cdf80d0712d5bdb27c60332f00555e1a73d28fb905cad21a9354593b77821d5adab766d
7
- data.tar.gz: 8da2d781f1572ab1e22e7658f5d7618c4820b57db8dcfe2e78e2d4dd403b00545687614d76f8a812191cccd3d3426fa791bb4270ecfe10f4d3691401c8a78c43
6
+ metadata.gz: 8e3d7990c6e40d37a7ee94a58f2a792ded501d015e318e6d953589a0fe7592e1648dd631e911dc5b37b3f84d1769f7895d0fa628fc652255acb102a8c091c70b
7
+ data.tar.gz: 4c643c663bbcac6110209a9dcb202e04962689fee2a2268321e91e6543d76476d7bc0d14eddc7efd71e5f76e597d66e8b37f3b97a940e4e41e897f7559bc6b07
@@ -0,0 +1,7 @@
1
+ # Auto-generated from team-config.yml
2
+ # Team: ai
3
+ #
4
+ # To apply: scripts/apply-codeowners.sh lex-bedrock
5
+
6
+ * @LegionIO/maintainers
7
+ * @LegionIO/ai
@@ -0,0 +1,18 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: bundler
4
+ directory: /
5
+ schedule:
6
+ interval: weekly
7
+ day: monday
8
+ open-pull-requests-limit: 5
9
+ labels:
10
+ - "type:dependencies"
11
+ - package-ecosystem: github-actions
12
+ directory: /
13
+ schedule:
14
+ interval: weekly
15
+ day: monday
16
+ open-pull-requests-limit: 5
17
+ labels:
18
+ - "type:dependencies"
@@ -3,13 +3,31 @@ on:
3
3
  push:
4
4
  branches: [main]
5
5
  pull_request:
6
+ schedule:
7
+ - cron: '0 9 * * 1'
6
8
 
7
9
  jobs:
8
10
  ci:
9
11
  uses: LegionIO/.github/.github/workflows/ci.yml@main
10
12
 
13
+ excluded-files:
14
+ uses: LegionIO/.github/.github/workflows/excluded-files.yml@main
15
+
16
+ security:
17
+ uses: LegionIO/.github/.github/workflows/security-scan.yml@main
18
+
19
+ version-changelog:
20
+ uses: LegionIO/.github/.github/workflows/version-changelog.yml@main
21
+
22
+ dependency-review:
23
+ uses: LegionIO/.github/.github/workflows/dependency-review.yml@main
24
+
25
+ stale:
26
+ if: github.event_name == 'schedule'
27
+ uses: LegionIO/.github/.github/workflows/stale.yml@main
28
+
11
29
  release:
12
- needs: ci
30
+ needs: [ci, excluded-files]
13
31
  if: github.event_name == 'push' && github.ref == 'refs/heads/main'
14
32
  uses: LegionIO/.github/.github/workflows/release.yml@main
15
33
  secrets:
data/.rubocop.yml CHANGED
@@ -1,51 +1,2 @@
1
- AllCops:
2
- TargetRubyVersion: 3.4
3
- NewCops: enable
4
- SuggestExtensions: false
5
-
6
- Layout/LineLength:
7
- Max: 160
8
-
9
- Layout/SpaceAroundEqualsInParameterDefault:
10
- EnforcedStyle: space
11
-
12
- Layout/HashAlignment:
13
- EnforcedHashRocketStyle: table
14
- EnforcedColonStyle: table
15
-
16
- Metrics/MethodLength:
17
- Max: 50
18
-
19
- Metrics/ClassLength:
20
- Max: 1500
21
-
22
- Metrics/ModuleLength:
23
- Max: 1500
24
-
25
- Metrics/BlockLength:
26
- Max: 40
27
- Exclude:
28
- - 'spec/**/*'
29
- - '*.gemspec'
30
-
31
- Metrics/AbcSize:
32
- Max: 60
33
-
34
- Metrics/CyclomaticComplexity:
35
- Max: 15
36
-
37
- Metrics/PerceivedComplexity:
38
- Max: 17
39
-
40
- Style/Documentation:
41
- Enabled: false
42
-
43
- Style/SymbolArray:
44
- Enabled: true
45
-
46
- Style/FrozenStringLiteralComment:
47
- Enabled: true
48
- EnforcedStyle: always
49
-
50
- Naming/FileName:
51
- Enabled: false
1
+ inherit_gem:
2
+ rubocop-legion: config/lex.yml
data/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.0] - 2026-03-31
4
+
5
+ ### Added
6
+ - `Helpers::Errors` — Bedrock exception classification (`ThrottlingException`, `AccessDeniedException`, `ModelNotReadyException`) with exponential backoff retry (`with_retry`)
7
+ - `Helpers::Credentials` — AWS credential caching with TTL-based refresh (3000s default); falls back to SDK default provider chain when no explicit keys given
8
+ - `Helpers::Thinking` — helpers to build `additional_model_request_fields` for extended thinking (`build_thinking_fields`, `sanitize_inference_config`)
9
+ - `Helpers::ModelRegistry` — canonical-to-Bedrock ID mapping for 11 Anthropic models, `resolve`/`known?`/`all` API
10
+ - `Runners::Converse#create_stream` — streaming Converse via `converse_stream` with per-event block callback and full accumulation fallback
11
+ - `Runners::Converse#create_with_thinking` — convenience method that wires thinking betas and config into a single call
12
+ - `Runners::Tokens#count_tokens` — token counting via `CountTokensCommand` with `anthropic_beta`/`thinking` body params
13
+ - `Runners::Profiles` — inference profile listing, lookup, and canonical model ID resolution via `ListInferenceProfiles`/`GetInferenceProfile`
14
+
15
+ ### Changed
16
+ - `Runners::Converse#create` now accepts `top_p`, `top_k`, `stop_sequences`, `tool_config`, `guardrail_config`, `additional_model_request_fields`
17
+ - `Helpers::Client` — `bedrock_runtime_client`/`bedrock_client` now accept a pre-built `credentials:` kwarg; `access_key_id` is now optional (nil triggers SDK default provider chain)
18
+ - `Helpers::Client` — added `region_for_model` for env-var and settings-driven per-model region routing
19
+ - All runner calls wrapped in `Helpers::Errors.with_retry` for production reliability
20
+ - `Legion::Extensions::Bedrock::Client` now includes `Runners::Tokens` and `Runners::Profiles`
21
+
22
+ ## [0.1.3] - 2026-03-30
23
+
24
+ ### Changed
25
+ - update to rubocop-legion 0.1.7, resolve all offenses
26
+
3
27
  ## [0.1.2] - 2026-03-22
4
28
 
5
29
  ### Changed
data/CLAUDE.md ADDED
@@ -0,0 +1,60 @@
1
+ # lex-bedrock: AWS Bedrock Integration for LegionIO
2
+
3
+ **Repository Level 3 Documentation**
4
+ - **Parent**: `/Users/miverso2/rubymine/legion/extensions-ai/CLAUDE.md`
5
+ - **Grandparent**: `/Users/miverso2/rubymine/legion/CLAUDE.md`
6
+
7
+ ## Purpose
8
+
9
+ Legion Extension that connects LegionIO to AWS Bedrock for foundation model inference. Provides runners for the Converse API, raw InvokeModel, and model listing using the AWS SDK (not Faraday).
10
+
11
+ **GitHub**: https://github.com/LegionIO/lex-bedrock
12
+ **License**: MIT
13
+ **Version**: 0.1.2
14
+ **Specs**: 38 examples
15
+
16
+ ## Architecture
17
+
18
+ ```
19
+ Legion::Extensions::Bedrock
20
+ ├── Runners/
21
+ │ ├── Converse # create(model_id:, messages:, access_key_id:, secret_access_key:, ...)
22
+ │ ├── Invoke # invoke_model(model_id:, body:, access_key_id:, secret_access_key:, ...)
23
+ │ └── Models # list(access_key_id:, secret_access_key:, ...), get(model_id:, ...)
24
+ ├── Helpers/
25
+ │ └── Client # AWS SDK client factories (module, not Faraday)
26
+ └── Client # Standalone client class (includes all runners, holds @config)
27
+ ```
28
+
29
+ `Helpers::Client` is a **module** with two factory methods:
30
+ - `bedrock_runtime_client(...)` — builds `Aws::BedrockRuntime::Client` (used by Converse and Invoke runners)
31
+ - `bedrock_client(...)` — builds `Aws::Bedrock::Client` (used by Models runner)
32
+
33
+ `DEFAULT_REGION` is `'us-east-2'`. All credential kwargs (`access_key_id:`, `secret_access_key:`, `region:`, `session_token:`) are passed through to the AWS SDK constructors. `session_token:` is optional and omitted if nil.
34
+
35
+ ## Key Design Decisions
36
+
37
+ - This is the only extension in extensions-ai that uses the AWS SDK instead of Faraday. There is no HTTP connection object — SDK clients handle transport.
38
+ - `Invoke#invoke_model` uses `::JSON.dump` and `::JSON.parse` (stdlib, explicit `::` prefix) to avoid namespace collision with `Legion::JSON`.
39
+ - `Converse#create` returns `{ result: response.output, usage: response.usage, stop_reason: response.stop_reason }` — three keys, unlike other runners which return only `{ result: ... }`.
40
+ - `Models#list` returns `{ models: response.model_summaries }` and `Models#get` returns `{ model: response.model_details }`.
41
+ - `include Legion::Extensions::Helpers::Lex` is guarded with `const_defined?` pattern.
42
+
43
+ ## Dependencies
44
+
45
+ | Gem | Purpose |
46
+ |-----|---------|
47
+ | `aws-sdk-bedrock` | Bedrock management API (model listing) |
48
+ | `aws-sdk-bedrockruntime` | Bedrock runtime API (inference) |
49
+
50
+ ## Testing
51
+
52
+ ```bash
53
+ bundle install
54
+ bundle exec rspec # 38 examples
55
+ bundle exec rubocop
56
+ ```
57
+
58
+ ---
59
+
60
+ **Maintained By**: Matthew Iverson (@Esity)
data/Gemfile CHANGED
@@ -5,3 +5,4 @@ gemspec
5
5
 
6
6
  gem 'rspec'
7
7
  gem 'rubocop'
8
+ gem 'rubocop-legion', '~> 0.1'
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2021 Esity
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -4,6 +4,8 @@ require 'legion/extensions/bedrock/helpers/client'
4
4
  require 'legion/extensions/bedrock/runners/models'
5
5
  require 'legion/extensions/bedrock/runners/converse'
6
6
  require 'legion/extensions/bedrock/runners/invoke'
7
+ require 'legion/extensions/bedrock/runners/tokens'
8
+ require 'legion/extensions/bedrock/runners/profiles'
7
9
 
8
10
  module Legion
9
11
  module Extensions
@@ -12,6 +14,8 @@ module Legion
12
14
  include Legion::Extensions::Bedrock::Runners::Models
13
15
  include Legion::Extensions::Bedrock::Runners::Converse
14
16
  include Legion::Extensions::Bedrock::Runners::Invoke
17
+ include Legion::Extensions::Bedrock::Runners::Tokens
18
+ include Legion::Extensions::Bedrock::Runners::Profiles
15
19
 
16
20
  attr_reader :config
17
21
 
@@ -12,29 +12,53 @@ module Legion
12
12
 
13
13
  module_function
14
14
 
15
- def bedrock_runtime_client(access_key_id:, secret_access_key:, region: DEFAULT_REGION,
16
- session_token: nil, **)
17
- opts = {
18
- access_key_id: access_key_id,
19
- secret_access_key: secret_access_key,
20
- region: region
21
- }
22
- opts[:session_token] = session_token if session_token
23
-
24
- Aws::BedrockRuntime::Client.new(**opts)
15
+ def bedrock_runtime_client(access_key_id: nil, secret_access_key: nil,
16
+ region: DEFAULT_REGION, session_token: nil,
17
+ credentials: nil, **)
18
+ Aws::BedrockRuntime::Client.new(
19
+ region:,
20
+ credentials: credentials || build_credentials(access_key_id:, secret_access_key:,
21
+ session_token:)
22
+ )
25
23
  end
26
24
 
27
- def bedrock_client(access_key_id:, secret_access_key:, region: DEFAULT_REGION,
28
- session_token: nil, **)
29
- opts = {
30
- access_key_id: access_key_id,
31
- secret_access_key: secret_access_key,
32
- region: region
33
- }
34
- opts[:session_token] = session_token if session_token
25
+ def bedrock_client(access_key_id: nil, secret_access_key: nil,
26
+ region: DEFAULT_REGION, session_token: nil,
27
+ credentials: nil, **)
28
+ Aws::Bedrock::Client.new(
29
+ region:,
30
+ credentials: credentials || build_credentials(access_key_id:, secret_access_key:,
31
+ session_token:)
32
+ )
33
+ end
34
+
35
+ def region_for_model(model_id:, region: nil)
36
+ return region if region
37
+
38
+ env_key = "BEDROCK_REGION_#{model_id.upcase.gsub(/[^A-Z0-9]/, '_')}"
39
+ env_val = ENV.fetch(env_key, nil)
40
+ return env_val if env_val
41
+
42
+ settings_region = begin
43
+ Legion::Settings[:bedrock]&.dig(:model_regions, model_id.to_sym)
44
+ rescue StandardError => _e
45
+ nil
46
+ end
35
47
 
36
- Aws::Bedrock::Client.new(**opts)
48
+ settings_region || DEFAULT_REGION
37
49
  end
50
+
51
+ def build_credentials(access_key_id:, secret_access_key:, session_token:)
52
+ return nil if access_key_id.nil?
53
+
54
+ if session_token
55
+ Aws::Credentials.new(access_key_id, secret_access_key, session_token)
56
+ else
57
+ Aws::Credentials.new(access_key_id, secret_access_key)
58
+ end
59
+ end
60
+
61
+ private_class_method :build_credentials
38
62
  end
39
63
  end
40
64
  end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Bedrock
6
+ module Helpers
7
+ module Credentials
8
+ CREDENTIAL_TTL = 3000 # seconds — refresh before the typical 1-hour STS TTL
9
+
10
+ @credential_cache = {} # rubocop:disable ThreadSafety/MutableClassInstanceVariable
11
+ @cache_mutex = ::Mutex.new
12
+
13
+ module_function
14
+
15
+ def resolve(access_key_id: nil, secret_access_key: nil,
16
+ session_token: nil, region: 'us-east-2', **)
17
+ return default_credentials if access_key_id.nil?
18
+
19
+ cache_key = "#{access_key_id}/#{region}"
20
+ @cache_mutex.synchronize do
21
+ entry = @credential_cache[cache_key]
22
+ if entry.nil? || stale?(entry)
23
+ @credential_cache[cache_key] = {
24
+ credentials: build_static(
25
+ access_key_id:,
26
+ secret_access_key:,
27
+ session_token:
28
+ ),
29
+ fetched_at: ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
30
+ }
31
+ end
32
+ @credential_cache[cache_key][:credentials]
33
+ end
34
+ end
35
+
36
+ def clear_cache!
37
+ @cache_mutex.synchronize { @credential_cache.clear }
38
+ end
39
+
40
+ def default_credentials
41
+ Aws::Credentials.new(nil, nil) # triggers SDK default chain
42
+ end
43
+
44
+ def build_static(access_key_id:, secret_access_key:, session_token:)
45
+ if session_token
46
+ Aws::Credentials.new(access_key_id, secret_access_key, session_token)
47
+ else
48
+ Aws::Credentials.new(access_key_id, secret_access_key)
49
+ end
50
+ end
51
+
52
+ def stale?(entry)
53
+ elapsed = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - entry[:fetched_at]
54
+ elapsed >= CREDENTIAL_TTL
55
+ end
56
+
57
+ private_class_method :default_credentials, :build_static, :stale?
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Bedrock
6
+ module Helpers
7
+ module Errors
8
+ THROTTLING_ERRORS = %w[
9
+ Aws::BedrockRuntime::Errors::ThrottlingException
10
+ Aws::BedrockRuntime::Errors::ServiceUnavailableException
11
+ Aws::Bedrock::Errors::ThrottlingException
12
+ Aws::Bedrock::Errors::ServiceUnavailableException
13
+ ].freeze
14
+
15
+ ACCESS_ERRORS = %w[
16
+ Aws::BedrockRuntime::Errors::AccessDeniedException
17
+ Aws::Bedrock::Errors::AccessDeniedException
18
+ ].freeze
19
+
20
+ MODEL_ERRORS = %w[
21
+ Aws::BedrockRuntime::Errors::ModelNotReadyException
22
+ Aws::BedrockRuntime::Errors::ModelTimeoutException
23
+ Aws::BedrockRuntime::Errors::ModelErrorException
24
+ ].freeze
25
+
26
+ MAX_RETRIES = 3
27
+ BASE_DELAY = 0.5 # seconds
28
+ MAX_DELAY = 16.0 # seconds
29
+
30
+ module_function
31
+
32
+ def throttling_error?(exception)
33
+ THROTTLING_ERRORS.include?(exception.class.name)
34
+ end
35
+
36
+ def access_error?(exception)
37
+ ACCESS_ERRORS.include?(exception.class.name)
38
+ end
39
+
40
+ def model_error?(exception)
41
+ MODEL_ERRORS.include?(exception.class.name)
42
+ end
43
+
44
+ def retryable?(exception)
45
+ throttling_error?(exception)
46
+ end
47
+
48
+ def with_retry(max_retries: MAX_RETRIES)
49
+ attempts = 0
50
+ begin
51
+ yield
52
+ rescue StandardError => e
53
+ attempts += 1
54
+ raise unless retryable?(e) && attempts <= max_retries
55
+
56
+ delay = [BASE_DELAY * (2**(attempts - 1)), MAX_DELAY].min
57
+ sleep(delay)
58
+ retry
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Bedrock
6
+ module Helpers
7
+ module ModelRegistry
8
+ # Maps canonical model names to their AWS Bedrock cross-region inference profile IDs.
9
+ # Use the us.* cross-region IDs for best availability.
10
+ MODELS = {
11
+ 'claude-3-5-haiku-20241022' => 'us.anthropic.claude-3-5-haiku-20241022-v1:0',
12
+ 'claude-haiku-4-5-20251001' => 'us.anthropic.claude-haiku-4-5-20251001-v1:0',
13
+ 'claude-3-5-sonnet-20241022' => 'anthropic.claude-3-5-sonnet-20241022-v2:0',
14
+ 'claude-3-7-sonnet-20250219' => 'us.anthropic.claude-3-7-sonnet-20250219-v1:0',
15
+ 'claude-sonnet-4-20250514' => 'us.anthropic.claude-sonnet-4-20250514-v1:0',
16
+ 'claude-sonnet-4-5-20250929' => 'us.anthropic.claude-sonnet-4-5-20250929-v1:0',
17
+ 'claude-sonnet-4-6' => 'us.anthropic.claude-sonnet-4-6',
18
+ 'claude-opus-4-20250514' => 'us.anthropic.claude-opus-4-20250514-v1:0',
19
+ 'claude-opus-4-1-20250805' => 'us.anthropic.claude-opus-4-1-20250805-v1:0',
20
+ 'claude-opus-4-5-20251101' => 'us.anthropic.claude-opus-4-5-20251101-v1:0',
21
+ 'claude-opus-4-6' => 'us.anthropic.claude-opus-4-6-v1'
22
+ }.freeze
23
+
24
+ module_function
25
+
26
+ def resolve(model_id)
27
+ return model_id if bedrock_id?(model_id)
28
+
29
+ MODELS.fetch(model_id, model_id)
30
+ end
31
+
32
+ def known?(model_id)
33
+ MODELS.key?(model_id)
34
+ end
35
+
36
+ def all
37
+ MODELS.dup
38
+ end
39
+
40
+ def bedrock_id?(model_id)
41
+ model_id.include?('.') || model_id.include?(':')
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Bedrock
6
+ module Helpers
7
+ module Thinking
8
+ THINKING_BETA = 'interleaved-thinking-2025-05-14'
9
+ CONTEXT_1M_BETA = 'context-1m-2025-08-07'
10
+ TOOL_SEARCH_BETA = 'tool-search-tool-2025-10-19'
11
+
12
+ module_function
13
+
14
+ def build_thinking_fields(budget_tokens: nil, adaptive: false, extra_betas: [])
15
+ betas = [THINKING_BETA] + Array(extra_betas)
16
+ fields = { anthropic_beta: betas }
17
+
18
+ thinking = if adaptive || budget_tokens.nil?
19
+ { type: 'adaptive' }
20
+ else
21
+ { type: 'enabled', budget_tokens: }
22
+ end
23
+
24
+ fields[:thinking] = thinking
25
+ fields
26
+ end
27
+
28
+ def sanitize_inference_config(inference_config:, thinking_enabled:)
29
+ return inference_config unless thinking_enabled
30
+
31
+ inference_config.except(:temperature)
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
37
+ end
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'legion/extensions/bedrock/helpers/client'
4
+ require 'legion/extensions/bedrock/helpers/errors'
5
+ require 'legion/extensions/bedrock/helpers/thinking'
4
6
 
5
7
  module Legion
6
8
  module Extensions
@@ -9,24 +11,23 @@ module Legion
9
11
  module Converse
10
12
  def create(model_id:, messages:, access_key_id:, secret_access_key:, # rubocop:disable Metrics/ParameterLists
11
13
  system: nil, max_tokens: 1024, temperature: nil,
14
+ top_p: nil, top_k: nil, stop_sequences: nil,
15
+ tool_config: nil, guardrail_config: nil,
16
+ additional_model_request_fields: nil,
12
17
  region: Helpers::Client::DEFAULT_REGION, **)
13
18
  client = Helpers::Client.bedrock_runtime_client(
14
- access_key_id: access_key_id,
15
- secret_access_key: secret_access_key,
16
- region: region
19
+ access_key_id:,
20
+ secret_access_key:,
21
+ region:
17
22
  )
18
23
 
19
- inference_config = { max_tokens: max_tokens }
20
- inference_config[:temperature] = temperature if temperature
21
-
22
- request = {
23
- model_id: model_id,
24
- messages: messages,
25
- inference_config: inference_config
26
- }
27
- request[:system] = [{ text: system }] if system
24
+ request = build_converse_request(
25
+ model_id:, messages:, system:, max_tokens:, temperature:,
26
+ top_p:, top_k:, stop_sequences:, tool_config:,
27
+ guardrail_config:, additional_model_request_fields:
28
+ )
28
29
 
29
- response = client.converse(**request)
30
+ response = Helpers::Errors.with_retry { client.converse(**request) }
30
31
  {
31
32
  result: response.output,
32
33
  usage: response.usage,
@@ -34,8 +35,114 @@ module Legion
34
35
  }
35
36
  end
36
37
 
37
- include Legion::Extensions::Helpers::Lex if Legion::Extensions.const_defined?(:Helpers) &&
38
- Legion::Extensions::Helpers.const_defined?(:Lex)
38
+ def create_stream(model_id:, messages:, access_key_id:, secret_access_key:, # rubocop:disable Metrics/ParameterLists
39
+ system: nil, max_tokens: 1024, temperature: nil,
40
+ top_p: nil, top_k: nil, stop_sequences: nil,
41
+ tool_config: nil, guardrail_config: nil,
42
+ additional_model_request_fields: nil,
43
+ region: Helpers::Client::DEFAULT_REGION, **,
44
+ &block)
45
+ client = Helpers::Client.bedrock_runtime_client(
46
+ access_key_id:,
47
+ secret_access_key:,
48
+ region:
49
+ )
50
+
51
+ request = build_converse_request(
52
+ model_id:, messages:, system:, max_tokens:, temperature:,
53
+ top_p:, top_k:, stop_sequences:, tool_config:,
54
+ guardrail_config:, additional_model_request_fields:
55
+ )
56
+
57
+ accumulated_text = +''
58
+ final_usage = nil
59
+ final_stop = nil
60
+
61
+ Helpers::Errors.with_retry do
62
+ client.converse_stream(**request) do |stream|
63
+ stream.on_content_block_delta_event do |event|
64
+ delta = event.delta
65
+ text = delta.respond_to?(:text) ? delta.text : nil
66
+ next if text.nil?
67
+
68
+ accumulated_text << text
69
+ block&.call(type: :delta, text:)
70
+ end
71
+
72
+ stream.on_message_stop_event do |event|
73
+ final_stop = event.stop_reason
74
+ block&.call(type: :stop, stop_reason: final_stop)
75
+ end
76
+
77
+ stream.on_metadata_event do |event|
78
+ final_usage = event.usage
79
+ block&.call(type: :usage, usage: final_usage)
80
+ end
81
+ end
82
+ end
83
+
84
+ {
85
+ result: accumulated_text,
86
+ usage: final_usage,
87
+ stop_reason: final_stop
88
+ }
89
+ end
90
+
91
+ def create_with_thinking(model_id:, messages:, access_key_id:, secret_access_key:, # rubocop:disable Metrics/ParameterLists
92
+ budget_tokens: nil, adaptive: false, extra_betas: [],
93
+ system: nil, max_tokens: 16_000,
94
+ region: Helpers::Client::DEFAULT_REGION, **opts)
95
+ thinking_fields = Helpers::Thinking.build_thinking_fields(
96
+ budget_tokens:, adaptive:, extra_betas:
97
+ )
98
+
99
+ # Merge with any caller-supplied additional_model_request_fields
100
+ amrf = opts.delete(:additional_model_request_fields) || {}
101
+ merged_amrf = thinking_fields.merge(amrf) do |_key, thinking_val, caller_val|
102
+ thinking_val.is_a?(Array) ? thinking_val | Array(caller_val) : caller_val
103
+ end
104
+
105
+ create(
106
+ model_id:, messages:, access_key_id:, secret_access_key:,
107
+ system:, max_tokens:, region:,
108
+ additional_model_request_fields: merged_amrf,
109
+ **opts
110
+ )
111
+ end
112
+
113
+ private
114
+
115
+ def build_converse_request(model_id:, messages:, system:, max_tokens:, # rubocop:disable Metrics/ParameterLists
116
+ temperature:, top_p:, top_k:, stop_sequences:,
117
+ tool_config:, guardrail_config:,
118
+ additional_model_request_fields:)
119
+ inference_config = { max_tokens: }
120
+ inference_config[:temperature] = temperature if temperature
121
+ inference_config[:top_p] = top_p if top_p
122
+ inference_config[:stop_sequences] = stop_sequences if stop_sequences
123
+
124
+ request = {
125
+ model_id:,
126
+ messages:,
127
+ inference_config:
128
+ }
129
+ request[:system] = [{ text: system }] if system
130
+ request[:tool_config] = tool_config if tool_config
131
+ request[:guardrail_config] = guardrail_config if guardrail_config
132
+ request[:additional_model_request_fields] = additional_model_request_fields \
133
+ if additional_model_request_fields
134
+
135
+ # top_k goes in additional_model_request_fields for Anthropic models
136
+ if top_k
137
+ request[:additional_model_request_fields] ||= {}
138
+ request[:additional_model_request_fields][:top_k] = top_k
139
+ end
140
+
141
+ request
142
+ end
143
+
144
+ include Legion::Extensions::Helpers::Lex if Legion::Extensions.const_defined?(:Helpers, false) &&
145
+ Legion::Extensions::Helpers.const_defined?(:Lex, false)
39
146
  end
40
147
  end
41
148
  end
@@ -8,7 +8,7 @@ module Legion
8
8
  module Bedrock
9
9
  module Runners
10
10
  module Invoke
11
- def invoke_model(model_id:, body:, access_key_id:, secret_access_key:, # rubocop:disable Metrics/ParameterLists
11
+ def invoke_model(model_id:, body:, access_key_id:, secret_access_key:,
12
12
  content_type: 'application/json', accept: 'application/json',
13
13
  region: Helpers::Client::DEFAULT_REGION, **)
14
14
  client = Helpers::Client.bedrock_runtime_client(
@@ -30,8 +30,8 @@ module Legion
30
30
  }
31
31
  end
32
32
 
33
- include Legion::Extensions::Helpers::Lex if Legion::Extensions.const_defined?(:Helpers) &&
34
- Legion::Extensions::Helpers.const_defined?(:Lex)
33
+ include Legion::Extensions::Helpers::Lex if Legion::Extensions.const_defined?(:Helpers, false) &&
34
+ Legion::Extensions::Helpers.const_defined?(:Lex, false)
35
35
  end
36
36
  end
37
37
  end
@@ -27,8 +27,8 @@ module Legion
27
27
  { model: response.model_details }
28
28
  end
29
29
 
30
- include Legion::Extensions::Helpers::Lex if Legion::Extensions.const_defined?(:Helpers) &&
31
- Legion::Extensions::Helpers.const_defined?(:Lex)
30
+ include Legion::Extensions::Helpers::Lex if Legion::Extensions.const_defined?(:Helpers, false) &&
31
+ Legion::Extensions::Helpers.const_defined?(:Lex, false)
32
32
  end
33
33
  end
34
34
  end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'legion/extensions/bedrock/helpers/client'
4
+ require 'legion/extensions/bedrock/helpers/errors'
5
+
6
+ module Legion
7
+ module Extensions
8
+ module Bedrock
9
+ module Runners
10
+ module Profiles
11
+ def list_inference_profiles(access_key_id:, secret_access_key:,
12
+ profile_type: 'SYSTEM_DEFINED',
13
+ region: Helpers::Client::DEFAULT_REGION, **)
14
+ client = Helpers::Client.bedrock_client(
15
+ access_key_id:,
16
+ secret_access_key:,
17
+ region:
18
+ )
19
+
20
+ response = Helpers::Errors.with_retry do
21
+ client.list_inference_profiles(type_equals: profile_type)
22
+ end
23
+
24
+ { inference_profiles: response.inference_profile_summaries }
25
+ end
26
+
27
+ def get_inference_profile(profile_id:, access_key_id:, secret_access_key:,
28
+ region: Helpers::Client::DEFAULT_REGION, **)
29
+ client = Helpers::Client.bedrock_client(
30
+ access_key_id:,
31
+ secret_access_key:,
32
+ region:
33
+ )
34
+
35
+ response = Helpers::Errors.with_retry do
36
+ client.get_inference_profile(inference_profile_identifier: profile_id)
37
+ end
38
+
39
+ { inference_profile: response }
40
+ end
41
+
42
+ def resolve_profile_id(canonical_model_id:, access_key_id:, secret_access_key:,
43
+ region: Helpers::Client::DEFAULT_REGION, **)
44
+ result = list_inference_profiles(
45
+ access_key_id:, secret_access_key:, region:
46
+ )
47
+ profiles = result[:inference_profiles]
48
+
49
+ matched = profiles.find do |p|
50
+ p.respond_to?(:models) &&
51
+ Array(p.models).any? { |m| m.model_arn.to_s.include?(canonical_model_id) }
52
+ end
53
+
54
+ matched ? matched.inference_profile_id : canonical_model_id
55
+ end
56
+
57
+ include Legion::Extensions::Helpers::Lex if Legion::Extensions.const_defined?(:Helpers, false) &&
58
+ Legion::Extensions::Helpers.const_defined?(:Lex, false)
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'legion/extensions/bedrock/helpers/client'
4
+ require 'legion/extensions/bedrock/helpers/errors'
5
+
6
+ module Legion
7
+ module Extensions
8
+ module Bedrock
9
+ module Runners
10
+ module Tokens
11
+ def count_tokens(model_id:, messages:, access_key_id:, secret_access_key:, # rubocop:disable Metrics/ParameterLists
12
+ system: nil, tools: nil, anthropic_version: 'bedrock-2023-05-31',
13
+ anthropic_beta: nil, thinking: nil,
14
+ region: Helpers::Client::DEFAULT_REGION, **)
15
+ client = Helpers::Client.bedrock_runtime_client(
16
+ access_key_id:,
17
+ secret_access_key:,
18
+ region:
19
+ )
20
+
21
+ request = build_count_tokens_request(
22
+ model_id:, messages:, system:, tools:,
23
+ anthropic_version:, anthropic_beta:, thinking:
24
+ )
25
+
26
+ response = Helpers::Errors.with_retry { client.count_tokens(**request) }
27
+ {
28
+ input_token_count: response.input_tokens
29
+ }
30
+ end
31
+
32
+ private
33
+
34
+ def build_count_tokens_request(model_id:, messages:, system:, tools:,
35
+ anthropic_version:, anthropic_beta:, thinking:)
36
+ body_fields = { anthropic_version: }
37
+ body_fields[:anthropic_beta] = anthropic_beta if anthropic_beta
38
+ body_fields[:thinking] = thinking if thinking
39
+
40
+ request = {
41
+ model_id:,
42
+ messages:,
43
+ system: system ? [{ text: system }] : nil,
44
+ additional_model_request_fields: body_fields
45
+ }
46
+ request[:tools] = tools if tools
47
+ request.compact
48
+ end
49
+
50
+ include Legion::Extensions::Helpers::Lex if Legion::Extensions.const_defined?(:Helpers, false) &&
51
+ Legion::Extensions::Helpers.const_defined?(:Lex, false)
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
@@ -3,7 +3,7 @@
3
3
  module Legion
4
4
  module Extensions
5
5
  module Bedrock
6
- VERSION = '0.1.2'
6
+ VERSION = '0.2.0'
7
7
  end
8
8
  end
9
9
  end
@@ -2,14 +2,20 @@
2
2
 
3
3
  require 'legion/extensions/bedrock/version'
4
4
  require 'legion/extensions/bedrock/helpers/client'
5
+ require 'legion/extensions/bedrock/helpers/errors'
6
+ require 'legion/extensions/bedrock/helpers/credentials'
7
+ require 'legion/extensions/bedrock/helpers/thinking'
8
+ require 'legion/extensions/bedrock/helpers/model_registry'
5
9
  require 'legion/extensions/bedrock/runners/models'
6
10
  require 'legion/extensions/bedrock/runners/converse'
7
11
  require 'legion/extensions/bedrock/runners/invoke'
12
+ require 'legion/extensions/bedrock/runners/tokens'
13
+ require 'legion/extensions/bedrock/runners/profiles'
8
14
 
9
15
  module Legion
10
16
  module Extensions
11
17
  module Bedrock
12
- extend Legion::Extensions::Core if Legion::Extensions.const_defined? :Core
18
+ extend Legion::Extensions::Core if Legion::Extensions.const_defined? :Core, false
13
19
  end
14
20
  end
15
21
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: lex-bedrock
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.2
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Esity
@@ -142,20 +142,30 @@ executables: []
142
142
  extensions: []
143
143
  extra_rdoc_files: []
144
144
  files:
145
+ - ".github/CODEOWNERS"
146
+ - ".github/dependabot.yml"
145
147
  - ".github/workflows/ci.yml"
146
148
  - ".gitignore"
147
149
  - ".rspec"
148
150
  - ".rubocop.yml"
149
151
  - CHANGELOG.md
152
+ - CLAUDE.md
150
153
  - Gemfile
154
+ - LICENSE
151
155
  - README.md
152
156
  - lex-bedrock.gemspec
153
157
  - lib/legion/extensions/bedrock.rb
154
158
  - lib/legion/extensions/bedrock/client.rb
155
159
  - lib/legion/extensions/bedrock/helpers/client.rb
160
+ - lib/legion/extensions/bedrock/helpers/credentials.rb
161
+ - lib/legion/extensions/bedrock/helpers/errors.rb
162
+ - lib/legion/extensions/bedrock/helpers/model_registry.rb
163
+ - lib/legion/extensions/bedrock/helpers/thinking.rb
156
164
  - lib/legion/extensions/bedrock/runners/converse.rb
157
165
  - lib/legion/extensions/bedrock/runners/invoke.rb
158
166
  - lib/legion/extensions/bedrock/runners/models.rb
167
+ - lib/legion/extensions/bedrock/runners/profiles.rb
168
+ - lib/legion/extensions/bedrock/runners/tokens.rb
159
169
  - lib/legion/extensions/bedrock/version.rb
160
170
  homepage: https://github.com/LegionIO/lex-bedrock
161
171
  licenses: