bedrock-datacircle 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/LICENSE.txt +21 -0
- data/README.md +116 -0
- data/lib/bedrock/datacircle/calls.rb +184 -0
- data/lib/bedrock/datacircle/client.rb +79 -0
- data/lib/bedrock/datacircle/collector.rb +189 -0
- data/lib/bedrock/datacircle/tools.rb +248 -0
- data/lib/bedrock/datacircle/version.rb +9 -0
- data/lib/bedrock/datacircle.rb +26 -0
- data/lib/bedrock-datacircle.rb +4 -0
- metadata +77 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 25c94cb8ef4a531a434e810294e3f2ae04e071db7836a8366a21a6d65947c762
|
|
4
|
+
data.tar.gz: 612bce9e2024555739ed89464fd88585e1289e69c8ed5013be95a423f1cf0a88
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 1dd2833c928aa59c7f29671e33ce425c443ebabaca857a9b0f01e710dc90aa45f106d336a2e6bd3974def9cf9946403d72765cb64e272b83222d889355130ea0
|
|
7
|
+
data.tar.gz: 3ea180fa41e8564df4d145729c2a88cb76b1910888a265145bf48d9a384970473b5b407963acff4ea0d8a0f4c16bddcae77e40328c60d2687e8f10563a17a15b
|
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Datacircle
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# Datacircle tools for Amazon Bedrock in the AWS SDK for Ruby
|
|
2
|
+
|
|
3
|
+
Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website.
|
|
4
|
+
|
|
5
|
+
Our website: https://datacircle.dev
|
|
6
|
+
|
|
7
|
+
This gem gives Amazon Bedrock's Converse API four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You pass the tools to `converse` or `converse_stream` of [aws-sdk-bedrockruntime](https://github.com/aws/aws-sdk-ruby). Bedrock does not run tools. This gem runs each call the model makes to a Datacircle tool. You get the answers to send back to the model. You need no key and no account.
|
|
8
|
+
|
|
9
|
+
| Tool | What the tool gives | Call |
|
|
10
|
+
| --- | --- | --- |
|
|
11
|
+
| `datacircle_list_apis` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
|
|
12
|
+
| `datacircle_best_plans` | One API's plans, sorted by score out of 100, best first. Each plan comes with a rank and a price per 1,000 calls | `GET /apis/{slug}/best` |
|
|
13
|
+
| `datacircle_search_plans` | Plans that match a provider or plan name, on all APIs or on one API. You can sort them by score, provider or price | `GET /plans` |
|
|
14
|
+
| `datacircle_provider` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
bundle add bedrock-datacircle
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The gem needs Ruby 3.2 or later and `aws-sdk-bedrockruntime` 1.9.0 or later. Reasoning blocks need `aws-sdk-bedrockruntime` 1.39.0 or later.
|
|
23
|
+
|
|
24
|
+
## Use the tools with converse
|
|
25
|
+
|
|
26
|
+
Put `tools` in `tool_config`. Add the model's message to `messages`, then the answers that `results` gives:
|
|
27
|
+
|
|
28
|
+
```ruby
|
|
29
|
+
require "bedrock/datacircle"
|
|
30
|
+
|
|
31
|
+
client = Aws::BedrockRuntime::Client.new(region: "us-east-1")
|
|
32
|
+
datacircle = Aws::BedrockRuntime::Datacircle::Tools.new
|
|
33
|
+
messages = [{role: "user", content: [{text: "Who are the 3 best providers for the email-finder API?"}]}]
|
|
34
|
+
|
|
35
|
+
loop do
|
|
36
|
+
response = client.converse(model_id: "amazon.nova-pro-v1:0", messages: messages, tool_config: {tools: datacircle.tools})
|
|
37
|
+
message = response.output.message.to_h
|
|
38
|
+
messages << message
|
|
39
|
+
answers = datacircle.results(message)
|
|
40
|
+
break puts(message[:content].filter_map { _1[:text] }.join) unless answers
|
|
41
|
+
|
|
42
|
+
messages << answers
|
|
43
|
+
end
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`results` gives one user message with a `tool_result` for each tool the model used, in order. You get `nil` when the model used no tool.
|
|
47
|
+
|
|
48
|
+
Add `response.output.message.to_h` to your messages, not `response.output.message`. `aws-sdk-core` before 3.201.2 refuses the SDK's own message when you send it back. A Hash works on every version.
|
|
49
|
+
|
|
50
|
+
## Use the tools with converse_stream
|
|
51
|
+
|
|
52
|
+
Give the stream to a `Collector` in the block of `converse_stream`. After the stream ends, `collector.message` gives the model's message:
|
|
53
|
+
|
|
54
|
+
```ruby
|
|
55
|
+
messages = [{role: "user", content: [{text: "Which provider ranks first for the SERP API?"}]}]
|
|
56
|
+
|
|
57
|
+
loop do
|
|
58
|
+
collector = Aws::BedrockRuntime::Datacircle::Collector.new
|
|
59
|
+
client.converse_stream(model_id: "amazon.nova-pro-v1:0", messages: messages, tool_config: {tools: datacircle.tools}) do |stream|
|
|
60
|
+
collector.listen(stream) { |text| print text }
|
|
61
|
+
end
|
|
62
|
+
message = collector.message
|
|
63
|
+
messages << message
|
|
64
|
+
answers = datacircle.results(message) or break
|
|
65
|
+
messages << answers
|
|
66
|
+
end
|
|
67
|
+
puts
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The collector builds the model's message from the events: the text, the reasoning and each tool input. The block of `listen` gets each piece of text as it comes. `listen` also takes an `event_stream_handler` of yours. When you read the stream after the call, use `Aws::BedrockRuntime::Datacircle::Collector.collect(response.stream)`. `collector.message` raises the stream's error event, such as a `ThrottlingException`.
|
|
71
|
+
|
|
72
|
+
## Your own tools
|
|
73
|
+
|
|
74
|
+
Bedrock needs an answer to each tool the model used in a turn. If you add tools of your own, give `results` a block. The block gets each use of one of your tools as an `Aws::BedrockRuntime::Types::ToolUseBlock`, with `tool_use_id`, `name` and `input`. The block returns the answer as a String, or as a Hash that the gem sends as JSON:
|
|
75
|
+
|
|
76
|
+
```ruby
|
|
77
|
+
get_time = {tool_spec: {name: "get_time", description: "The time now in a time zone, like +02:00",
|
|
78
|
+
input_schema: {json: {type: "object", properties: {zone: {type: "string"}}, required: ["zone"]}}}}
|
|
79
|
+
tool_config = {tools: [*datacircle.tools, get_time]}
|
|
80
|
+
|
|
81
|
+
answers = datacircle.results(message) { |use| {time: Time.now.getlocal(use.input["zone"]).strftime("%H:%M")} }
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
When the block raises, the model reads `{"error": "..."}` with the message. Leave out the block and the model reads an error for each use of your tools. `datacircle.handles?(name)` tells you if the tool named `name` is one of ours. `datacircle.result(tool_use)` answers one use of a Datacircle tool and gives `nil` for any other tool.
|
|
85
|
+
|
|
86
|
+
## Call a tool yourself
|
|
87
|
+
|
|
88
|
+
You can call a tool without a model. You get the tool's answer as a Hash:
|
|
89
|
+
|
|
90
|
+
```ruby
|
|
91
|
+
Aws::BedrockRuntime::Datacircle::Tools.new.run("datacircle_best_plans", {"slug" => "email-finder", "limit" => 3})
|
|
92
|
+
# => {"api" => "Employee email", "slug" => "email-finder", ..., "plans" => [{"api" => "Employee email", "rank" => 1, ...}]}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`Aws::BedrockRuntime::Datacircle::Calls.new` makes the same calls. The methods of `Calls` are `list_apis`, `best_plans`, `search_plans` and `provider`.
|
|
96
|
+
|
|
97
|
+
## What the model reads
|
|
98
|
+
|
|
99
|
+
Each tool gives the model a JSON object as the text of the `tool_result`. Each plan comes with a rank, provider, plan, score, price per 1,000 (`perThousand`, in dollars) and a page on datacircle.dev. That page lists every field. A tool also takes an API's name or a provider's name in place of a slug.
|
|
100
|
+
|
|
101
|
+
For an unknown slug, the model reads `{"error": "..."}` with the API's message and what to send instead. If the input does not fit the schema, the error names each wrong field. If the network fails, the error gives the network's message. The model can read the error, call the tool again and keep going. `run` gives the same errors as `{"error" => "..."}`. `Calls` raises a network error as `Aws::BedrockRuntime::Datacircle::Error`.
|
|
102
|
+
|
|
103
|
+
`Aws::BedrockRuntime::Datacircle::Tools.new(base_url: ...)` sets a new address for the tools, for example a proxy of yours. Leave `base_url` out and the tools call https://api.datacircle.dev/v1.
|
|
104
|
+
|
|
105
|
+
## Network
|
|
106
|
+
|
|
107
|
+
Each tool call sends HTTPS GET requests to https://api.datacircle.dev/v1 and nowhere else. Most calls send one request. A tool sends up to four when the model gives a name in place of a slug. The requests hold only the tool's input from the model: no key and nothing from your messages. The API takes up to 60 calls a minute from one IP address. A tool waits once, for a minute at most, when the API asks for a wait. The gem's one dependency is `aws-sdk-bedrockruntime`. The gem stores nothing.
|
|
108
|
+
|
|
109
|
+
## Links
|
|
110
|
+
|
|
111
|
+
- Datacircle: https://datacircle.dev
|
|
112
|
+
- The API: https://datacircle.dev/api
|
|
113
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
114
|
+
- What each key means: https://datacircle.dev/fields
|
|
115
|
+
|
|
116
|
+
MIT license.
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Aws
|
|
4
|
+
module BedrockRuntime
|
|
5
|
+
module Datacircle
|
|
6
|
+
# A plan holds about 90 keys (its terms of use, its aggregators...): these choose a plan, the rest is on its page.
|
|
7
|
+
PLAN_KEYS = %w[api rank provider plan score perThousand notFoundPerThousand billing pay currency units unit
|
|
8
|
+
strengths latencyMs page pricingPage docs].freeze
|
|
9
|
+
|
|
10
|
+
# Tells a model that sent a provider's name to an API's tool where a provider's plans are.
|
|
11
|
+
FOR_PROVIDER = "A provider's plans: datacircle_search_plans with its name as query, like bright data, " \
|
|
12
|
+
'or datacircle_provider.'
|
|
13
|
+
|
|
14
|
+
# Tells a model that sent an API's slug to the provider's tool where an API's best providers are.
|
|
15
|
+
FOR_API = "An API's best providers: datacircle_best_plans with the API's slug, like email-finder."
|
|
16
|
+
|
|
17
|
+
# A placeholder a small model copies from a prompt's example, like <api-slug>, sent in place of a slug.
|
|
18
|
+
PLACEHOLDER = /[<>{}]/
|
|
19
|
+
|
|
20
|
+
# The four calls of https://api.datacircle.dev/v1 behind the tools, each answering the Hash the model reads: an
|
|
21
|
+
# answer of 4xx (an unknown slug, a wrong argument) as {"error" => the API's words}. Error is raised when the API
|
|
22
|
+
# can't be reached or answers 5xx; Tools gives it to the model as {"error": ...} too.
|
|
23
|
+
class Calls
|
|
24
|
+
def initialize(base_url: Client::BASE)
|
|
25
|
+
@client = Client.new(base_url: base_url)
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# GET /apis, the APIs whose name or slug holds the most of the query's words first.
|
|
29
|
+
def list_apis(query: nil, limit: nil)
|
|
30
|
+
apis = objects(@client.get('/apis'))
|
|
31
|
+
words = query.to_s.downcase.tr('-', ' ').split
|
|
32
|
+
found = apis.each_with_index.filter_map do |api, order|
|
|
33
|
+
name = "#{api['api']} #{api['slug'].to_s.tr('-', ' ')}".downcase
|
|
34
|
+
matched = words.count { |word| name.include?(word) }
|
|
35
|
+
[-matched, order, api] if matched.positive? || words.empty?
|
|
36
|
+
end.sort_by { |matched, order, _| [matched, order] }
|
|
37
|
+
answer = { 'total' => found.size,
|
|
38
|
+
'apis' => found.first(bounded(limit, 200) || 20)
|
|
39
|
+
.map { |_, _, api| brief(api, %w[api slug plans providers best bestPage sheetPage]) } }
|
|
40
|
+
if words.any? && (found.empty? || -found.first.first < words.size)
|
|
41
|
+
# A provider's name sent as an API's, like Bright Data, whose data matches many APIs: where its plans are.
|
|
42
|
+
answer['note'] = "No API's name holds every word of #{query.to_s.to_json}. A provider's plans: " \
|
|
43
|
+
'datacircle_search_plans with its name as query, or datacircle_provider.'
|
|
44
|
+
end
|
|
45
|
+
answer
|
|
46
|
+
rescue Error => e
|
|
47
|
+
refusal(e)
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# GET /apis/{slug}/best
|
|
51
|
+
def best_plans(slug: nil, limit: nil)
|
|
52
|
+
if slug.to_s.match?(PLACEHOLDER)
|
|
53
|
+
return { 'error' => "#{slug.to_s.to_json} is a placeholder. Give the API's own slug, like email-finder: " \
|
|
54
|
+
'datacircle_list_apis gives every slug.' }
|
|
55
|
+
end
|
|
56
|
+
api = slugify(slug)
|
|
57
|
+
return { 'error' => "Give an API's slug, like email-finder: datacircle_list_apis gives every slug. #{FOR_PROVIDER}" } if api.empty?
|
|
58
|
+
|
|
59
|
+
begin
|
|
60
|
+
best(api, limit)
|
|
61
|
+
rescue Error => e
|
|
62
|
+
return refusal(e) unless e.status == 404
|
|
63
|
+
|
|
64
|
+
# The slug with "api" after it, like serp-api, as the sheet's address reads (/serp-api-pricing): the API's own.
|
|
65
|
+
bare = api.sub(/-api(-pricing)?\z/, '')
|
|
66
|
+
if bare != api && !bare.empty?
|
|
67
|
+
begin
|
|
68
|
+
return best(bare, limit).merge('note' => "No API has the slug #{api}: these are #{bare}'s plans.")
|
|
69
|
+
rescue Error
|
|
70
|
+
# The first answer stands.
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
# An API's name sent as its slug, like Employee email: the API of that name.
|
|
74
|
+
named = objects(@client.get('/apis')).find { |entry| slugify(entry['api']) == api }
|
|
75
|
+
return best(named['slug'], limit) if named
|
|
76
|
+
|
|
77
|
+
# A provider's name sent as the API's slug: the API's words, and where a provider's plans are.
|
|
78
|
+
{ 'error' => "#{e.message}. datacircle_list_apis gives every API's slug. #{FOR_PROVIDER}" }
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# GET /plans
|
|
83
|
+
def search_plans(api: nil, query: nil, sort: nil, limit: nil, offset: nil)
|
|
84
|
+
api = api.to_s
|
|
85
|
+
query = query.to_s
|
|
86
|
+
notes = []
|
|
87
|
+
search = lambda do |on, words|
|
|
88
|
+
@client.get('/plans', api: on.strip, query: words.strip, sort: sort, limit: bounded(limit, 50),
|
|
89
|
+
offset: (offset.to_i if offset && offset.to_i.positive?))
|
|
90
|
+
end
|
|
91
|
+
begin
|
|
92
|
+
answer = search.call(api, query)
|
|
93
|
+
rescue Error => e
|
|
94
|
+
raise unless e.status == 400 && e.message.include?('api must be') && query.strip.empty?
|
|
95
|
+
|
|
96
|
+
# A provider's name sent as the API: the plans whose provider or plan name holds it.
|
|
97
|
+
notes << "No API is named #{api.to_json}: these are the plans whose provider or plan name holds it."
|
|
98
|
+
api, query = '', api
|
|
99
|
+
answer = search.call(api, query)
|
|
100
|
+
end
|
|
101
|
+
if answer['total'].to_i.zero? && query.include?('-')
|
|
102
|
+
# A slug sent as a name, like bright-data, which no name holds: its words, like bright data. A name with a
|
|
103
|
+
# hyphen, like A-Leads, is found as it is first.
|
|
104
|
+
words = query.tr('-', ' ').split.join(' ')
|
|
105
|
+
begin
|
|
106
|
+
answer = search.call(api, words)
|
|
107
|
+
notes << "No provider's or plan's name holds #{query.to_json}: these are the plans whose name holds #{words.to_json}."
|
|
108
|
+
rescue Error
|
|
109
|
+
# The first answer stands.
|
|
110
|
+
end
|
|
111
|
+
end
|
|
112
|
+
answer = answer.merge('plans' => objects(answer['plans']).map { |plan| brief(plan) })
|
|
113
|
+
notes.empty? ? answer : answer.merge('note' => notes.join(' '))
|
|
114
|
+
rescue Error => e
|
|
115
|
+
refusal(e)
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# GET /providers/{slug}
|
|
119
|
+
def provider(slug: nil)
|
|
120
|
+
if slug.to_s.match?(PLACEHOLDER)
|
|
121
|
+
return { 'error' => "#{slug.to_s.to_json} is a placeholder. Give the provider's own slug or name, like " \
|
|
122
|
+
'bright-data or Bright Data.' }
|
|
123
|
+
end
|
|
124
|
+
name = slugify(slug)
|
|
125
|
+
return { 'error' => "Give a provider's slug or name, like bright-data or Bright Data" } if name.empty?
|
|
126
|
+
|
|
127
|
+
begin
|
|
128
|
+
answer = @client.get("/providers/#{name}")
|
|
129
|
+
rescue Error => e
|
|
130
|
+
# An API's slug sent as a provider's, like email-finder: the API's words, and where an API's best providers are.
|
|
131
|
+
return e.status == 404 ? { 'error' => "#{e.message}. #{FOR_API}" } : refusal(e)
|
|
132
|
+
end
|
|
133
|
+
apis = objects(answer['apis']).map do |entry|
|
|
134
|
+
plans = objects(entry['plans'])
|
|
135
|
+
kept = brief(entry, %w[api slug rank bestPage]).merge('plans' => plans.size)
|
|
136
|
+
top = best_plan(plans)
|
|
137
|
+
top ? kept.merge('best' => brief(top, %w[plan score perThousand page])) : kept
|
|
138
|
+
end
|
|
139
|
+
# Its best rank first, the APIs where it has none last, in the API's order.
|
|
140
|
+
apis = apis.each_with_index.sort_by { |entry, order| [entry['rank'].is_a?(Numeric) ? entry['rank'] : Float::INFINITY, order] }
|
|
141
|
+
.map(&:first)
|
|
142
|
+
answer.merge('apis' => apis, 'total' => apis.size, 'ranked' => apis.count { |entry| entry['rank'].is_a?(Numeric) })
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
private
|
|
146
|
+
|
|
147
|
+
def best(api, limit)
|
|
148
|
+
answer = @client.get("/apis/#{api}/best", limit: bounded(limit, 50))
|
|
149
|
+
answer.merge('plans' => objects(answer['plans']).map { |plan| brief(plan) })
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
# An answer of 4xx as the model reads it, the API's words; anything else raised.
|
|
153
|
+
def refusal(error)
|
|
154
|
+
raise error unless error.status && error.status >= 400 && error.status < 500
|
|
155
|
+
|
|
156
|
+
{ 'error' => error.message }
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def brief(item, keys = PLAN_KEYS)
|
|
160
|
+
keys.each_with_object({}) { |key, kept| kept[key] = item[key] unless item[key].nil? }
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
def objects(value)
|
|
164
|
+
value.is_a?(Array) ? value.select { |item| item.is_a?(Hash) } : []
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
# A limit the model sent, within the API's bounds, or nil for the API's default.
|
|
168
|
+
def bounded(value, high)
|
|
169
|
+
value.nil? || value < 1 ? nil : value.to_i.clamp(1, high)
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
# The API's rule for a slug: the name in lowercase letters and digits, the rest a hyphen.
|
|
173
|
+
def slugify(value)
|
|
174
|
+
value.to_s.unicode_normalize(:nfkd).gsub(/\p{Mn}/, '').downcase.gsub(/[^a-z0-9]+/, '-').gsub(/\A-+|-+\z/, '')
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
# A provider's best plan on an API: its lowest rank, the first when none has a rank.
|
|
178
|
+
def best_plan(plans)
|
|
179
|
+
plans.select { |plan| plan['rank'].is_a?(Numeric) }.min_by { |plan| plan['rank'] } || plans.first
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
end
|
|
183
|
+
end
|
|
184
|
+
end
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'json'
|
|
4
|
+
require 'net/http'
|
|
5
|
+
require 'openssl'
|
|
6
|
+
require 'uri'
|
|
7
|
+
|
|
8
|
+
module Aws
|
|
9
|
+
module BedrockRuntime
|
|
10
|
+
module Datacircle
|
|
11
|
+
# What Datacircle's API answered when it gave no data (its HTTP status in #status), or why it could not be reached.
|
|
12
|
+
class Error < StandardError
|
|
13
|
+
attr_reader :status
|
|
14
|
+
|
|
15
|
+
def initialize(message = nil, status: nil)
|
|
16
|
+
super(message)
|
|
17
|
+
@status = status
|
|
18
|
+
end
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
# One HTTPS GET to Datacircle's open API, with no key: its answer as a Hash or an Array.
|
|
22
|
+
class Client
|
|
23
|
+
BASE = 'https://api.datacircle.dev/v1'
|
|
24
|
+
|
|
25
|
+
def initialize(base_url: BASE)
|
|
26
|
+
@base = base_url.to_s.chomp('/')
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def get(path, params = {})
|
|
30
|
+
uri = URI("#{@base}#{path}")
|
|
31
|
+
query = params.reject { |_, value| value.nil? || value.to_s.strip.empty? }
|
|
32
|
+
uri.query = URI.encode_www_form(query) unless query.empty?
|
|
33
|
+
2.times do |attempt|
|
|
34
|
+
response = request(uri)
|
|
35
|
+
return parse(response) if response.is_a?(Net::HTTPSuccess)
|
|
36
|
+
|
|
37
|
+
if response.code == '429' && attempt.zero?
|
|
38
|
+
sleep(wait(response))
|
|
39
|
+
next
|
|
40
|
+
end
|
|
41
|
+
raise Error.new(words(response), status: response.code.to_i)
|
|
42
|
+
end
|
|
43
|
+
raise Error.new("Datacircle's API answered 429 twice: wait a minute and call again", status: 429)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
private
|
|
47
|
+
|
|
48
|
+
def request(uri)
|
|
49
|
+
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: 15, read_timeout: 30) do |http|
|
|
50
|
+
http.get(uri.request_uri, 'Accept' => 'application/json', 'User-Agent' => "bedrock-datacircle/#{VERSION}")
|
|
51
|
+
end
|
|
52
|
+
rescue SocketError, SystemCallError, Timeout::Error, OpenSSL::SSL::SSLError, Net::HTTPBadResponse, IOError => e
|
|
53
|
+
raise Error, "Datacircle's API could not be reached: #{e.message}"
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def parse(response)
|
|
57
|
+
JSON.parse(response.body.to_s)
|
|
58
|
+
rescue JSON::ParserError
|
|
59
|
+
raise Error.new("Datacircle's API answered #{response.code} with no JSON", status: response.code.to_i)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# The API asks to wait in Retry-After: its seconds, a minute at most.
|
|
63
|
+
def wait(response)
|
|
64
|
+
Integer(response['Retry-After'].to_s.strip, 10).clamp(1, 60)
|
|
65
|
+
rescue ArgumentError
|
|
66
|
+
60
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# The API's own words: its error of a 4xx, else its status.
|
|
70
|
+
def words(response)
|
|
71
|
+
parsed = JSON.parse(response.body.to_s)
|
|
72
|
+
parsed.is_a?(Hash) && parsed['error'].is_a?(String) && !parsed['error'].empty? ? parsed['error'] : "Datacircle's API answered #{response.code}"
|
|
73
|
+
rescue JSON::ParserError
|
|
74
|
+
"Datacircle's API answered #{response.code}"
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Aws
|
|
4
|
+
module BedrockRuntime
|
|
5
|
+
module Datacircle
|
|
6
|
+
# Gathers #converse_stream's events into the model's message, as #converse gives it in output.message: its text,
|
|
7
|
+
# its reasoning, with the signature Bedrock wants back beside a tool use, and each tool use, whose input comes in
|
|
8
|
+
# pieces of JSON. Other blocks (images, citations) are left out.
|
|
9
|
+
#
|
|
10
|
+
# collector = Aws::BedrockRuntime::Datacircle::Collector.new
|
|
11
|
+
# client.converse_stream(model_id: ..., messages: messages, tool_config: config) do |stream|
|
|
12
|
+
# collector.listen(stream) { |text| print text }
|
|
13
|
+
# end
|
|
14
|
+
# messages << collector.message
|
|
15
|
+
#
|
|
16
|
+
# or, once a stream read whole: Collector.collect(response.stream). One collector gathers one stream.
|
|
17
|
+
class Collector
|
|
18
|
+
# The SDK's events that carry an error of the stream, and the error each is raised as.
|
|
19
|
+
ERRORS = %i[internal_server_exception model_stream_error_exception validation_exception throttling_exception
|
|
20
|
+
service_unavailable_exception].freeze
|
|
21
|
+
|
|
22
|
+
# The stream's stop reason, from its message_stop event: "tool_use" when the model used tools.
|
|
23
|
+
attr_reader :stop_reason
|
|
24
|
+
# The stream's metadata event: its usage and metrics.
|
|
25
|
+
attr_reader :metadata
|
|
26
|
+
# The stream's error event (a throttling, a validation...), which #message raises: the SDK's own error, like
|
|
27
|
+
# Aws::BedrockRuntime::Errors::ThrottlingException, or the SDK's Aws::Errors::EventError.
|
|
28
|
+
attr_reader :error
|
|
29
|
+
|
|
30
|
+
# The model's message of a stream read whole (response.stream of #converse_stream with no block), as #message
|
|
31
|
+
# gives it, or its error event raised. Each piece of text goes to the block, for an app that shows it.
|
|
32
|
+
def self.collect(events, &on_text)
|
|
33
|
+
collector = new
|
|
34
|
+
Array(events).each do |event|
|
|
35
|
+
text = collector.add(event)
|
|
36
|
+
on_text&.call(text) unless text.empty?
|
|
37
|
+
end
|
|
38
|
+
collector.message
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def initialize
|
|
42
|
+
@blocks = {}
|
|
43
|
+
@stop_reason = @metadata = @error = nil
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# Has the stream of #converse_stream's block (an Aws::BedrockRuntime::EventStreams::ConverseStreamOutput) give
|
|
47
|
+
# this collector each event as it comes, and the block each piece of the answer's text. An error event is kept
|
|
48
|
+
# for #message to raise once #converse_stream is done: raised in the SDK's own callback, a throttling would
|
|
49
|
+
# make the SDK send the request again.
|
|
50
|
+
def listen(stream, &on_text)
|
|
51
|
+
stream.on_event do |event|
|
|
52
|
+
text = add(event)
|
|
53
|
+
on_text&.call(text) unless text.empty?
|
|
54
|
+
end
|
|
55
|
+
self
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# Takes the stream's next event and gives the text it adds to the model's answer, '' for none. An error event is
|
|
59
|
+
# kept in #error, for #message to raise. A message_start starts the message over: the SDK sends a request
|
|
60
|
+
# again after some failures, and its events come again from the start.
|
|
61
|
+
def add(event)
|
|
62
|
+
type = event.is_a?(Exception) ? :error : field(event, :event_type)&.to_sym
|
|
63
|
+
if type == :error || ERRORS.include?(type)
|
|
64
|
+
@error ||= event.is_a?(Exception) ? event : error(type, event)
|
|
65
|
+
return ''
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
case type
|
|
69
|
+
when :message_start then initialize
|
|
70
|
+
when :content_block_start then start(event)
|
|
71
|
+
when :content_block_delta then return delta(event)
|
|
72
|
+
when :message_stop then @stop_reason = field(event, :stop_reason)
|
|
73
|
+
when :metadata then @metadata = event
|
|
74
|
+
end
|
|
75
|
+
''
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# The model's message the events make, for the next request's messages and for Tools#results: a Hash of
|
|
79
|
+
# symbol keys, as #converse and #converse_stream take it. A tool use's input that is no JSON object, like none
|
|
80
|
+
# at all, is given as {}: Bedrock takes only an object. A blank text is left out, as Bedrock refuses it. Raises
|
|
81
|
+
# the stream's error event, if it had one.
|
|
82
|
+
def message
|
|
83
|
+
raise @error if @error
|
|
84
|
+
|
|
85
|
+
content = @blocks.sort_by(&:first).filter_map { |_, block| block_of(block) }
|
|
86
|
+
{ role: 'assistant', content: content }
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# The text of the model's answer so far.
|
|
90
|
+
def text
|
|
91
|
+
@blocks.sort_by(&:first).map { |_, block| block[:text] }.join
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
private
|
|
95
|
+
|
|
96
|
+
def block(index)
|
|
97
|
+
@blocks[index.to_i] ||= { text: +'', reasoning: +'', signature: +'', redacted: [], input: +'' }
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def start(event)
|
|
101
|
+
start = field(event, :start)
|
|
102
|
+
if (use = field(start, :tool_use))
|
|
103
|
+
block(field(event, :content_block_index))[:use] = { tool_use_id: field(use, :tool_use_id).to_s, name: field(use, :name).to_s,
|
|
104
|
+
type: field(use, :type) }
|
|
105
|
+
elsif (result = field(start, :tool_result))
|
|
106
|
+
block(field(event, :content_block_index))[:result] = { tool_use_id: field(result, :tool_use_id).to_s, type: field(result, :type),
|
|
107
|
+
status: field(result, :status), content: [] }
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def delta(event)
|
|
112
|
+
delta = field(event, :delta)
|
|
113
|
+
block = block(field(event, :content_block_index))
|
|
114
|
+
if (text = field(delta, :text)).is_a?(String)
|
|
115
|
+
block[:text] << text
|
|
116
|
+
return text
|
|
117
|
+
end
|
|
118
|
+
if (use = field(delta, :tool_use))
|
|
119
|
+
block[:input] << field(use, :input).to_s
|
|
120
|
+
end
|
|
121
|
+
if (reasoning = field(delta, :reasoning_content))
|
|
122
|
+
block[:reasoning] << field(reasoning, :text) if field(reasoning, :text).is_a?(String)
|
|
123
|
+
block[:signature] << field(reasoning, :signature) if field(reasoning, :signature).is_a?(String)
|
|
124
|
+
block[:redacted] << field(reasoning, :redacted_content) if field(reasoning, :redacted_content)
|
|
125
|
+
end
|
|
126
|
+
Array(field(delta, :tool_result)).each do |part|
|
|
127
|
+
block[:result] ||= { tool_use_id: '', content: [] }
|
|
128
|
+
parts = block[:result][:content]
|
|
129
|
+
if (piece = field(part, :text)).is_a?(String)
|
|
130
|
+
parts.last&.key?(:text) ? parts.last[:text] += piece : parts << { text: piece }
|
|
131
|
+
elsif !field(part, :json).nil?
|
|
132
|
+
parts << { json: field(part, :json) }
|
|
133
|
+
end
|
|
134
|
+
end
|
|
135
|
+
''
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
def block_of(block)
|
|
139
|
+
if block[:use]
|
|
140
|
+
use = { tool_use_id: block[:use][:tool_use_id], name: block[:use][:name], input: object(block[:input]) }
|
|
141
|
+
use[:type] = 'server_tool_use' if block[:use][:type].to_s == 'server_tool_use'
|
|
142
|
+
{ tool_use: use }
|
|
143
|
+
elsif block[:result]
|
|
144
|
+
result = block[:result]
|
|
145
|
+
return nil if result[:content].empty?
|
|
146
|
+
|
|
147
|
+
kept = { tool_use_id: result[:tool_use_id], content: result[:content] }
|
|
148
|
+
kept[:type] = result[:type] if result[:type]
|
|
149
|
+
kept[:status] = result[:status] if %w[success error].include?(result[:status].to_s)
|
|
150
|
+
{ tool_result: kept }
|
|
151
|
+
elsif block[:redacted].any?
|
|
152
|
+
{ reasoning_content: { redacted_content: block[:redacted].join } }
|
|
153
|
+
elsif !block[:reasoning].empty? || !block[:signature].empty?
|
|
154
|
+
text = { text: block[:reasoning] }
|
|
155
|
+
text[:signature] = block[:signature] unless block[:signature].empty?
|
|
156
|
+
{ reasoning_content: { reasoning_text: text } }
|
|
157
|
+
elsif !block[:text].strip.empty?
|
|
158
|
+
{ text: block[:text] }
|
|
159
|
+
end
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
# A tool use's input from its pieces: the JSON object they make, {} for none or for anything else.
|
|
163
|
+
def object(input)
|
|
164
|
+
parsed = JSON.parse(input)
|
|
165
|
+
parsed.is_a?(Hash) ? parsed : {}
|
|
166
|
+
rescue JSON::ParserError
|
|
167
|
+
{}
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
def error(type, event)
|
|
171
|
+
name = type.to_s.split('_').map(&:capitalize).join
|
|
172
|
+
message = field(event, :message)
|
|
173
|
+
if defined?(Errors) && Errors.const_defined?(name, false)
|
|
174
|
+
Errors.const_get(name, false).new(nil, message, event)
|
|
175
|
+
else
|
|
176
|
+
Aws::Errors::EventError.new(type, name, message)
|
|
177
|
+
end
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
def field(item, key)
|
|
181
|
+
case item
|
|
182
|
+
when Struct then item.members.include?(key) ? item[key] : nil
|
|
183
|
+
when Hash then item.key?(key) ? item[key] : item[key.to_s]
|
|
184
|
+
end
|
|
185
|
+
end
|
|
186
|
+
end
|
|
187
|
+
end
|
|
188
|
+
end
|
|
189
|
+
end
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Aws
|
|
4
|
+
module BedrockRuntime
|
|
5
|
+
module Datacircle
|
|
6
|
+
LIST_APIS = 'datacircle_list_apis'
|
|
7
|
+
BEST_PLANS = 'datacircle_best_plans'
|
|
8
|
+
SEARCH_PLANS = 'datacircle_search_plans'
|
|
9
|
+
PROVIDER = 'datacircle_provider'
|
|
10
|
+
|
|
11
|
+
# The four tools' names, in the order Tools#tools gives them. Their answers name each other by these names.
|
|
12
|
+
NAMES = [LIST_APIS, BEST_PLANS, SEARCH_PLANS, PROVIDER].freeze
|
|
13
|
+
|
|
14
|
+
PRICE = "perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency."
|
|
15
|
+
|
|
16
|
+
# The four tools for the tool_config of Aws::BedrockRuntime::Client#converse and #converse_stream, and the run of
|
|
17
|
+
# the tool uses the model makes.
|
|
18
|
+
#
|
|
19
|
+
# datacircle = Aws::BedrockRuntime::Datacircle::Tools.new
|
|
20
|
+
# response = client.converse(model_id: ..., messages: messages, tool_config: { tools: datacircle.tools })
|
|
21
|
+
# messages << response.output.message.to_h
|
|
22
|
+
# answer = datacircle.results(messages.last) and messages << answer
|
|
23
|
+
#
|
|
24
|
+
# It holds no state: one can serve many threads.
|
|
25
|
+
class Tools
|
|
26
|
+
ABOUT = {
|
|
27
|
+
LIST_APIS => "Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev). GTM means go-to-market. GTM " \
|
|
28
|
+
"APIs are the APIs sales and marketing teams use. Gives each API's slug, how many plans and " \
|
|
29
|
+
"providers it has and its best plan. Call it first to find an API's slug.",
|
|
30
|
+
BEST_PLANS => "Gives an API's plans best first by their score out of 100 on Datacircle's benchmark " \
|
|
31
|
+
'(https://datacircle.dev), each with its rank, provider, plan, $ per 1,000 calls and its page. ' \
|
|
32
|
+
"#{PRICE}",
|
|
33
|
+
SEARCH_PLANS => "Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by provider " \
|
|
34
|
+
'or plan name, sorted by score, provider or price. Gives how many were found and up to limit ' \
|
|
35
|
+
"of them. #{PRICE}",
|
|
36
|
+
PROVIDER => "Gives each API one provider sells and its rank on each on Datacircle's benchmark " \
|
|
37
|
+
'(https://datacircle.dev), with its best plan there, its best rank first. total is how many APIs ' \
|
|
38
|
+
'it sells, ranked on how many of them it has a rank. For an API\'s best providers, call ' \
|
|
39
|
+
'datacircle_best_plans.'
|
|
40
|
+
}.freeze
|
|
41
|
+
|
|
42
|
+
# Each tool's input: its keys in order, each [type, what the model is told, its bounds or choices, needed].
|
|
43
|
+
INPUTS = {
|
|
44
|
+
LIST_APIS => {
|
|
45
|
+
'query' => [:text, "Words of the API's name or slug, like email or linkedin profile: the APIs that hold " \
|
|
46
|
+
"the most of them come first. Left out, the sheet's order"],
|
|
47
|
+
'limit' => [:count, 'How many APIs to give, 1 to 200. 20 when left out: the sheet has about 150', [1, 200]]
|
|
48
|
+
},
|
|
49
|
+
BEST_PLANS => {
|
|
50
|
+
'slug' => [:text, "The API's slug, like email-finder or linkedin-profile, as datacircle_list_apis gives it",
|
|
51
|
+
nil, true],
|
|
52
|
+
'limit' => [:count, 'How many plans to give, 1 to 50. 10 when left out', [1, 50]]
|
|
53
|
+
},
|
|
54
|
+
SEARCH_PLANS => {
|
|
55
|
+
'api' => [:text, "Only this API's plans: its name or slug, like email-finder. A provider's name goes in " \
|
|
56
|
+
'query, never here. Left out, every API'],
|
|
57
|
+
'query' => [:text, "Words that must all appear in the provider's or plan's name, like bright data. Left " \
|
|
58
|
+
'out, every plan'],
|
|
59
|
+
'sort' => [:choice, 'score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first)',
|
|
60
|
+
%w[score provider price]],
|
|
61
|
+
'limit' => [:count, 'How many plans to give, 1 to 50. 10 when left out', [1, 50]],
|
|
62
|
+
'offset' => [:count, 'How many found plans to skip first. 0 when left out', [0, nil]]
|
|
63
|
+
},
|
|
64
|
+
PROVIDER => {
|
|
65
|
+
'slug' => [:text, "The provider's slug, like bright-data, or its name, like Bright Data: the name is made " \
|
|
66
|
+
'a slug', nil, true]
|
|
67
|
+
}
|
|
68
|
+
}.freeze
|
|
69
|
+
|
|
70
|
+
# base_url: where the tools call, https://api.datacircle.dev/v1 when left out.
|
|
71
|
+
def initialize(base_url: nil)
|
|
72
|
+
@base_url = base_url || Client::BASE
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# The four tools for tool_config: { tools: [...] } of #converse and #converse_stream, each a tool_spec Hash. A new
|
|
76
|
+
# copy at each call: they can go beside the app's own tools.
|
|
77
|
+
def tools
|
|
78
|
+
NAMES.map do |name|
|
|
79
|
+
{ tool_spec: { name: name, description: ABOUT[name], input_schema: { json: schema(name) } } }
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# Whether name is one of the four tools'.
|
|
84
|
+
def handles?(name)
|
|
85
|
+
NAMES.include?(name.to_s)
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
# The tool uses of the model's message that the app answers, in order, each an
|
|
89
|
+
# Aws::BedrockRuntime::Types::ToolUseBlock: every tool_use block but a system tool's, which Bedrock runs itself
|
|
90
|
+
# (its type server_tool_use, or answered by a tool_result block of the same message). The message is
|
|
91
|
+
# response.output.message of #converse, or a Hash like Collector#message's.
|
|
92
|
+
def tool_uses(message)
|
|
93
|
+
blocks = Array(field(message, :content))
|
|
94
|
+
answered = blocks.filter_map { |block| field(field(block, :tool_result), :tool_use_id) }
|
|
95
|
+
blocks.filter_map do |block|
|
|
96
|
+
use = field(block, :tool_use)
|
|
97
|
+
next if use.nil? || field(use, :type).to_s == 'server_tool_use' || answered.include?(field(use, :tool_use_id))
|
|
98
|
+
|
|
99
|
+
Types::ToolUseBlock.new(tool_use_id: field(use, :tool_use_id).to_s, name: field(use, :name).to_s, input: field(use, :input))
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# The tool_result block that answers one tool use of the four tools', its text the tool's answer as JSON; nil
|
|
104
|
+
# for a use of another tool, which the app runs itself. Never raises: an answer of 4xx, an input that doesn't
|
|
105
|
+
# fit or a failed network is the model's to read, as {"error": "..."}.
|
|
106
|
+
def result(tool_use)
|
|
107
|
+
name = field(tool_use, :name).to_s
|
|
108
|
+
return nil unless handles?(name)
|
|
109
|
+
|
|
110
|
+
text_result(field(tool_use, :tool_use_id), JSON.generate(answer(name, field(tool_use, :input))))
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# Answers each tool use of the model's message, in order, in one user message of tool_result blocks, for the
|
|
114
|
+
# next request's messages: the four tools' uses by #result, the others by the block, which gets each as an
|
|
115
|
+
# Aws::BedrockRuntime::Types::ToolUseBlock. What the block gives is the answer: text as it is, nil as {}, any
|
|
116
|
+
# other value as JSON; what it raises, the model reads as {"error": "..."}. Bedrock wants every tool use of a turn
|
|
117
|
+
# answered: with no block, the model reads {"error": "No tool is named ... here."} for each other tool's.
|
|
118
|
+
# Gives nil when the message has no tool use to answer: it is the model's answer.
|
|
119
|
+
def results(message, &own)
|
|
120
|
+
uses = tool_uses(message)
|
|
121
|
+
return nil if uses.empty?
|
|
122
|
+
|
|
123
|
+
{ role: 'user', content: uses.map { |use| result(use) || text_result(use.tool_use_id, own_answer(use, own)) } }
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# The answer one tool gives the model, as a Hash: the input is a Hash (string or symbol keys), JSON text or nil.
|
|
127
|
+
# An answer of 4xx, an input that doesn't fit the tool's schema or a failed network is {"error" => "..."}.
|
|
128
|
+
# Raises ArgumentError when name is not one of the four tools'.
|
|
129
|
+
def run(name, input = nil)
|
|
130
|
+
raise ArgumentError, "No tool is named #{name.to_s.inspect}: the tools are #{NAMES.join(', ')}" unless handles?(name)
|
|
131
|
+
|
|
132
|
+
answer(name.to_s, input)
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
private
|
|
136
|
+
|
|
137
|
+
def schema(name)
|
|
138
|
+
fields = INPUTS[name]
|
|
139
|
+
properties = fields.to_h do |key, (type, about, rule)|
|
|
140
|
+
property = { 'type' => type == :count ? 'integer' : 'string', 'description' => about }
|
|
141
|
+
property['enum'] = rule.dup if type == :choice
|
|
142
|
+
if type == :count
|
|
143
|
+
property['minimum'] = rule[0]
|
|
144
|
+
property['maximum'] = rule[1] if rule[1]
|
|
145
|
+
end
|
|
146
|
+
[key, property]
|
|
147
|
+
end
|
|
148
|
+
needed = fields.select { |_, (_, _, _, need)| need }.keys
|
|
149
|
+
# No required list when none is needed, and no additionalProperties: the JSON schema every Bedrock model takes.
|
|
150
|
+
needed.empty? ? { 'type' => 'object', 'properties' => properties } : { 'type' => 'object', 'properties' => properties, 'required' => needed }
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
def answer(name, input)
|
|
154
|
+
arguments = check(name, read(input)).transform_keys(&:to_sym)
|
|
155
|
+
calls = Calls.new(base_url: @base_url)
|
|
156
|
+
case name
|
|
157
|
+
when LIST_APIS then calls.list_apis(**arguments)
|
|
158
|
+
when BEST_PLANS then calls.best_plans(**arguments)
|
|
159
|
+
when SEARCH_PLANS then calls.search_plans(**arguments)
|
|
160
|
+
when PROVIDER then calls.provider(**arguments)
|
|
161
|
+
end
|
|
162
|
+
rescue Error => e
|
|
163
|
+
{ 'error' => e.message }
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
# The tool use's input as a Hash of string keys: Converse gives a Hash; JSON text, as an app's own code may hold
|
|
167
|
+
# it, is read as one; none is {}.
|
|
168
|
+
def read(input)
|
|
169
|
+
input = input.strip.empty? ? {} : JSON.parse(input) if input.is_a?(String)
|
|
170
|
+
input = {} if input.nil?
|
|
171
|
+
raise Error, "The input does not fit the tool's input schema: expected an object, got #{shown(input)}" unless input.is_a?(Hash)
|
|
172
|
+
|
|
173
|
+
input.to_h { |key, value| [key.to_s, value] }
|
|
174
|
+
rescue JSON::ParserError => e
|
|
175
|
+
raise Error, "The input is not JSON: #{e.message}"
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
# The input checked against the tool's schema, looser than it so that a small model that strays is understood
|
|
179
|
+
# where it can be: null is a key left out, a key of its own is dropped, a number sent as text is read as one, a
|
|
180
|
+
# fraction cut to its whole part. What it refuses, the model reads why, each key, so that it can call again.
|
|
181
|
+
def check(name, given)
|
|
182
|
+
kept = {}
|
|
183
|
+
refused = []
|
|
184
|
+
INPUTS[name].each do |key, (type, _, rule, need)|
|
|
185
|
+
value = given[key]
|
|
186
|
+
if value.nil?
|
|
187
|
+
refused << "#{key}: expected text, got nothing" if need
|
|
188
|
+
next
|
|
189
|
+
end
|
|
190
|
+
case type
|
|
191
|
+
when :text
|
|
192
|
+
value.is_a?(String) ? kept[key] = value : refused << "#{key}: expected text, got #{shown(value)}"
|
|
193
|
+
when :choice
|
|
194
|
+
rule.include?(value) ? kept[key] = value : refused << "#{key}: expected one of #{rule.join(', ')}, got #{shown(value)}"
|
|
195
|
+
when :count
|
|
196
|
+
number = count(value)
|
|
197
|
+
number ? kept[key] = number : refused << "#{key}: expected a number, got #{shown(value)}"
|
|
198
|
+
end
|
|
199
|
+
end
|
|
200
|
+
raise Error, "The input does not fit the tool's input schema: #{refused.join('; ')}" unless refused.empty?
|
|
201
|
+
|
|
202
|
+
kept
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
# A number, or one sent as text, as an Integer or a Float; nil for anything else.
|
|
206
|
+
def count(value)
|
|
207
|
+
value = Float(value.strip) if value.is_a?(String) && !value.strip.empty?
|
|
208
|
+
value.is_a?(Numeric) && value.finite? ? value : nil
|
|
209
|
+
rescue ArgumentError
|
|
210
|
+
nil
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
def shown(value)
|
|
214
|
+
value.nil? ? 'nothing' : JSON.generate(value)
|
|
215
|
+
rescue JSON::GeneratorError, ::Encoding::UndefinedConversionError
|
|
216
|
+
value.inspect
|
|
217
|
+
end
|
|
218
|
+
|
|
219
|
+
# The app's own answer to a use of another tool, as text.
|
|
220
|
+
def own_answer(use, own)
|
|
221
|
+
return error_text("No tool is named #{use.name.to_json} here.") unless own
|
|
222
|
+
|
|
223
|
+
value = own.call(use)
|
|
224
|
+
value.is_a?(String) ? value : value.nil? ? '{}' : JSON.generate(value)
|
|
225
|
+
rescue StandardError => e
|
|
226
|
+
error_text(e.message)
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
# A tool_result of one text block. A blank text is sent as {}: Bedrock refuses a blank one.
|
|
230
|
+
def text_result(tool_use_id, text)
|
|
231
|
+
{ tool_result: { tool_use_id: tool_use_id.to_s, content: [{ text: text.strip.empty? ? '{}' : text }] } }
|
|
232
|
+
end
|
|
233
|
+
|
|
234
|
+
def error_text(message)
|
|
235
|
+
JSON.generate('error' => message.to_s)
|
|
236
|
+
end
|
|
237
|
+
|
|
238
|
+
# A key of an SDK struct, or of a Hash as an app writes it (symbols) or holds it from JSON (strings).
|
|
239
|
+
def field(item, key)
|
|
240
|
+
case item
|
|
241
|
+
when Struct then item.members.include?(key) ? item[key] : nil
|
|
242
|
+
when Hash then item.key?(key) ? item[key] : item[key.to_s]
|
|
243
|
+
end
|
|
244
|
+
end
|
|
245
|
+
end
|
|
246
|
+
end
|
|
247
|
+
end
|
|
248
|
+
end
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'json'
|
|
4
|
+
require 'aws-sdk-bedrockruntime'
|
|
5
|
+
require_relative 'datacircle/version'
|
|
6
|
+
require_relative 'datacircle/client'
|
|
7
|
+
require_relative 'datacircle/calls'
|
|
8
|
+
require_relative 'datacircle/tools'
|
|
9
|
+
require_relative 'datacircle/collector'
|
|
10
|
+
|
|
11
|
+
module Aws
|
|
12
|
+
module BedrockRuntime
|
|
13
|
+
# Datacircle's open API as four tools for Amazon Bedrock's Converse API, with no key: find the best GTM APIs. We
|
|
14
|
+
# benchmark all the GTM APIs and we put the results on our website, https://datacircle.dev
|
|
15
|
+
#
|
|
16
|
+
# datacircle = Aws::BedrockRuntime::Datacircle::Tools.new
|
|
17
|
+
# client.converse(model_id: ..., messages: messages, tool_config: { tools: datacircle.tools })
|
|
18
|
+
#
|
|
19
|
+
# datacircle_list_apis, datacircle_best_plans, datacircle_search_plans and datacircle_provider make one GET of
|
|
20
|
+
# https://api.datacircle.dev/v1 each. Tools#results answers the model's tool uses in one user message of tool_result
|
|
21
|
+
# blocks; Collector gathers #converse_stream's events into the model's message. The API's error, or why it could
|
|
22
|
+
# not be reached, goes to the model as {"error": ...}.
|
|
23
|
+
module Datacircle
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: bedrock-datacircle
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Wayne Hamadi
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies:
|
|
12
|
+
- !ruby/object:Gem::Dependency
|
|
13
|
+
name: aws-sdk-bedrockruntime
|
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
|
15
|
+
requirements:
|
|
16
|
+
- - ">="
|
|
17
|
+
- !ruby/object:Gem::Version
|
|
18
|
+
version: 1.9.0
|
|
19
|
+
- - "<"
|
|
20
|
+
- !ruby/object:Gem::Version
|
|
21
|
+
version: '2'
|
|
22
|
+
type: :runtime
|
|
23
|
+
prerelease: false
|
|
24
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
25
|
+
requirements:
|
|
26
|
+
- - ">="
|
|
27
|
+
- !ruby/object:Gem::Version
|
|
28
|
+
version: 1.9.0
|
|
29
|
+
- - "<"
|
|
30
|
+
- !ruby/object:Gem::Version
|
|
31
|
+
version: '2'
|
|
32
|
+
description: 'Four tools for the Converse API of aws-sdk-bedrockruntime call Datacircle''s
|
|
33
|
+
open API with no key. List the GTM APIs and each API''s best plans. Search every
|
|
34
|
+
plan, or see where one provider ranks in our benchmarks. We benchmark all the GTM
|
|
35
|
+
APIs and we put the results on our website: https://datacircle.dev'
|
|
36
|
+
email:
|
|
37
|
+
- wayne@datacircle.dev
|
|
38
|
+
executables: []
|
|
39
|
+
extensions: []
|
|
40
|
+
extra_rdoc_files: []
|
|
41
|
+
files:
|
|
42
|
+
- LICENSE.txt
|
|
43
|
+
- README.md
|
|
44
|
+
- lib/bedrock-datacircle.rb
|
|
45
|
+
- lib/bedrock/datacircle.rb
|
|
46
|
+
- lib/bedrock/datacircle/calls.rb
|
|
47
|
+
- lib/bedrock/datacircle/client.rb
|
|
48
|
+
- lib/bedrock/datacircle/collector.rb
|
|
49
|
+
- lib/bedrock/datacircle/tools.rb
|
|
50
|
+
- lib/bedrock/datacircle/version.rb
|
|
51
|
+
homepage: https://datacircle.dev
|
|
52
|
+
licenses:
|
|
53
|
+
- MIT
|
|
54
|
+
metadata:
|
|
55
|
+
homepage_uri: https://datacircle.dev
|
|
56
|
+
source_code_uri: https://github.com/waynehamadi/bedrock-ruby-datacircle
|
|
57
|
+
documentation_uri: https://github.com/waynehamadi/bedrock-ruby-datacircle#readme
|
|
58
|
+
bug_tracker_uri: https://github.com/waynehamadi/bedrock-ruby-datacircle/issues
|
|
59
|
+
rdoc_options: []
|
|
60
|
+
require_paths:
|
|
61
|
+
- lib
|
|
62
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
63
|
+
requirements:
|
|
64
|
+
- - ">="
|
|
65
|
+
- !ruby/object:Gem::Version
|
|
66
|
+
version: 3.2.0
|
|
67
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
68
|
+
requirements:
|
|
69
|
+
- - ">="
|
|
70
|
+
- !ruby/object:Gem::Version
|
|
71
|
+
version: '0'
|
|
72
|
+
requirements: []
|
|
73
|
+
rubygems_version: 3.6.9
|
|
74
|
+
specification_version: 4
|
|
75
|
+
summary: Amazon Bedrock Converse tools that find the best GTM APIs, for the AWS SDK
|
|
76
|
+
for Ruby.
|
|
77
|
+
test_files: []
|