omniai-google 3.25.0 → 3.27.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 +4 -4
- data/README.md +45 -0
- data/lib/omniai/google/cache.rb +150 -0
- data/lib/omniai/google/cache_registry.rb +125 -0
- data/lib/omniai/google/cache_store.rb +46 -0
- data/lib/omniai/google/caches.rb +46 -0
- data/lib/omniai/google/chat.rb +183 -10
- data/lib/omniai/google/client.rb +41 -1
- data/lib/omniai/google/config.rb +17 -0
- data/lib/omniai/google/transcribe/transcription.rb +18 -0
- data/lib/omniai/google/transcribe.rb +43 -4
- data/lib/omniai/google/transcribe_helpers.rb +17 -7
- data/lib/omniai/google/version.rb +1 -1
- data/lib/omniai/google.rb +3 -0
- metadata +6 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: ddaf939fe461b95ab895b1591cfc015171adfc06fd123facd3c46ddc3b7add13
|
|
4
|
+
data.tar.gz: b9423a258395b539611c59425d76ed9423088035188830d0b950fa385d7adbe2
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: bd9c1040b3fbbb83119c75ef89f3e28bbb229499242eaee0dedd826b3671dcb643abbb26d6ad91663371630b0d7a7d53045ead37e253f4d2e167540135743ace
|
|
7
|
+
data.tar.gz: 1fbe2130b8f361e2d595e44462cb30702db4b385e128f27b00c15496e43a50e89d85d79dc0f5d9eaf6b9b6a5c4f3cf0a53064a2e24e05aba842e08e813b73e2a
|
data/README.md
CHANGED
|
@@ -213,6 +213,41 @@ client.chat("What are the prime factors of 1234567?", model: OmniAI::Google::Cha
|
|
|
213
213
|
|
|
214
214
|
[Google API Reference `thinking`](https://ai.google.dev/gemini-api/docs/thinking)
|
|
215
215
|
|
|
216
|
+
#### Context Caching
|
|
217
|
+
|
|
218
|
+
Explicit context caching (`cachedContents`) is opt-in. Cached input tokens are billed at a discount, but a cache must hold at least 4,096 tokens, not every model supports it (the Gemini 4 models don't yet), and storage is billed per hour while it lives. The gem's default TTL is 300 seconds, not Google's 60 minutes.
|
|
219
|
+
|
|
220
|
+
Manage a cache yourself with `client.caches`, and pass it (or its name) as `cached_content:`. A `Cache` is checked against the request's model, location and tools; a name can only be checked against the location. A cached request can't send a system message, tools or a tool config: those live in the cache, and the prompt holds only what follows it. Tools passed to `chat` still run locally.
|
|
221
|
+
|
|
222
|
+
```ruby
|
|
223
|
+
cache = client.caches.create(model: "gemini-3.8-flash", ttl: 600, tools: [weather]) do |prompt|
|
|
224
|
+
prompt.system("...")
|
|
225
|
+
prompt.user("...") # a shared prefix
|
|
226
|
+
end
|
|
227
|
+
client.chat("...", model: "gemini-3.8-flash", cached_content: cache, tools: [weather])
|
|
228
|
+
cache.update(ttl: 600)
|
|
229
|
+
cache.delete
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Or let the gem manage caches with `cache:`:
|
|
233
|
+
|
|
234
|
+
```ruby
|
|
235
|
+
client.chat(prompt, cache: :system) # the system prompt and tools
|
|
236
|
+
client.chat(prompt, cache: true) # also every message before the last one
|
|
237
|
+
client.chat(prompt, cache: { ttl: 600 }) # as `true`, with a TTL (seconds)
|
|
238
|
+
client.chat(prompt, cache: { ttl: 600, scope: :system }) # as `:system`, with a TTL
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Caches are keyed on the model, location and cached content, and kept in `config.cache_store` (per process by default; set it to `Rails.cache` or similar to share caches across processes). Only one create per key runs at a time within a process; with a shared store, processes that miss at the same time each create a cache, and the extras are billed until their TTL ends. A cache's TTL is extended when it's used with less than half left. The chat falls back to an uncached request when the create fails, when it takes longer than `config.cache_wait` (default 10 seconds; the create carries on in the background), or when the cache is gone (404, `NOT_FOUND` or `FAILED_PRECONDITION`, or a 400 `INVALID_ARGUMENT` when a `get` of the cache then returns 404; retried once). A tool-call loop reuses the first round's cache.
|
|
242
|
+
|
|
243
|
+
Any change to the cached part is a new cache, so put what varies (per-request values, earlier turns that change) after it. The cached part is stored by Google for the TTL: with `cache: true` that is every message before the last one. Keeping data you can't store with Google, such as PHI under your agreements, out of it is the caller's job. Cached tokens are reported in `usageMetadata.cachedContentTokenCount`:
|
|
244
|
+
|
|
245
|
+
```ruby
|
|
246
|
+
response.response_chain.sum { |r| r.data.dig("usageMetadata", "cachedContentTokenCount").to_i }
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
[Google API Reference `cachedContents`](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview)
|
|
250
|
+
|
|
216
251
|
### Upload
|
|
217
252
|
|
|
218
253
|
An upload is especially useful when processing audio / image / video / text files. To use:
|
|
@@ -366,6 +401,16 @@ client.transcribe("audio.mp3", model: OmniAI::Google::Transcribe::Model::CHIRP)
|
|
|
366
401
|
- Clear error messages for common issues
|
|
367
402
|
- Graceful handling of network timeouts
|
|
368
403
|
|
|
404
|
+
#### Batch Wait
|
|
405
|
+
|
|
406
|
+
A batch operation is polled every 15 seconds for an estimate from the file size (600 to 10,800 seconds). Google's queue time doesn't scale with audio length, so pass `max_wait:` (seconds) to wait longer. Past it, `OmniAI::Google::Transcribe::TimeoutError` (an `OmniAI::Error`) is raised with the `operation_name` and `wait`; Google may still finish and bill the operation.
|
|
407
|
+
|
|
408
|
+
```ruby
|
|
409
|
+
transcription = client.transcribe("gs://bucket/audio.wav", model: "chirp_3", max_wait: 1800)
|
|
410
|
+
transcription.operation_name # => "projects/.../operations/..." (nil for a sync request)
|
|
411
|
+
transcription.billed_duration # => 300.0 (seconds Google billed; nil when not reported)
|
|
412
|
+
```
|
|
413
|
+
|
|
369
414
|
[Google Speech-to-Text API Reference](https://cloud.google.com/speech-to-text/docs)
|
|
370
415
|
|
|
371
416
|
#### Gemini Transcribe
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module OmniAI
|
|
4
|
+
module Google
|
|
5
|
+
# An explicit context cache (`cachedContents`). Usage:
|
|
6
|
+
#
|
|
7
|
+
# cache = client.caches.create(model: "gemini-3.8-flash", ttl: 600) do |prompt|
|
|
8
|
+
# prompt.system("...")
|
|
9
|
+
# prompt.user("...")
|
|
10
|
+
# end
|
|
11
|
+
# client.chat("...", model: "gemini-3.8-flash", cached_content: cache.name)
|
|
12
|
+
# cache.delete
|
|
13
|
+
class Cache
|
|
14
|
+
DEFAULT_TTL = 300
|
|
15
|
+
|
|
16
|
+
# @!attribute [r] data
|
|
17
|
+
# @return [Hash] the raw `cachedContents` resource
|
|
18
|
+
attr_reader :data
|
|
19
|
+
|
|
20
|
+
# @param prompt [OmniAI::Chat::Prompt, String, nil] optional
|
|
21
|
+
# @param client [Client] required - already located for the model
|
|
22
|
+
# @param model [String] required
|
|
23
|
+
# @param ttl [Integer] optional - seconds
|
|
24
|
+
# @param tools [Array<OmniAI::Tool>, nil] optional
|
|
25
|
+
#
|
|
26
|
+
# @yield [prompt] optional
|
|
27
|
+
# @yieldparam prompt [OmniAI::Chat::Prompt]
|
|
28
|
+
#
|
|
29
|
+
# @raise [HTTPError]
|
|
30
|
+
#
|
|
31
|
+
# @return [Cache]
|
|
32
|
+
def self.create(prompt = nil, client:, model:, ttl: DEFAULT_TTL, tools: nil, &block)
|
|
33
|
+
prompt = prompt ? OmniAI::Chat::Prompt.parse(prompt) : OmniAI::Chat::Prompt.new
|
|
34
|
+
block&.call(prompt)
|
|
35
|
+
|
|
36
|
+
data = request!(client, :post, client.cache_path, payload(client:, model:, prompt:, tools:, ttl:))
|
|
37
|
+
new(client:, data:, tool_names: Array(tools).grep(OmniAI::Tool).map(&:name))
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# @param name [String]
|
|
41
|
+
# @param client [Client]
|
|
42
|
+
#
|
|
43
|
+
# @raise [HTTPError]
|
|
44
|
+
#
|
|
45
|
+
# @return [Cache]
|
|
46
|
+
def self.get(name, client:)
|
|
47
|
+
new(client:, data: request!(client, :get, client.cache_path(name)))
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# @param name [String]
|
|
51
|
+
# @param client [Client]
|
|
52
|
+
#
|
|
53
|
+
# @raise [HTTPError]
|
|
54
|
+
def self.delete(name, client:)
|
|
55
|
+
request!(client, :delete, client.cache_path(name))
|
|
56
|
+
nil
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# @param name [String]
|
|
60
|
+
#
|
|
61
|
+
# @return [String, nil] e.g. "us" for "projects/P/locations/us/cachedContents/123"
|
|
62
|
+
def self.location_id(name)
|
|
63
|
+
name[%r{\Aprojects/[^/]+/locations/([^/]+)/}, 1]
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# Serialized with the chat CONTEXT, so the cached part is byte-identical to what chat would send.
|
|
67
|
+
#
|
|
68
|
+
# @return [Hash]
|
|
69
|
+
def self.payload(client:, model:, prompt:, tools:, ttl:)
|
|
70
|
+
system = prompt.messages.find(&:system?)
|
|
71
|
+
contents = prompt.messages.reject(&:system?).map { |message| message.serialize(context: Chat::CONTEXT) }
|
|
72
|
+
|
|
73
|
+
{
|
|
74
|
+
model: client.model_name(model),
|
|
75
|
+
systemInstruction: system&.serialize(context: Chat::CONTEXT),
|
|
76
|
+
contents: (contents unless contents.empty?),
|
|
77
|
+
tools: Chat.serialize_tools(tools),
|
|
78
|
+
ttl: "#{Integer(ttl)}s",
|
|
79
|
+
}.compact
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# @raise [HTTPError]
|
|
83
|
+
#
|
|
84
|
+
# @return [Hash]
|
|
85
|
+
def self.request!(client, method, path, json = nil, params: {})
|
|
86
|
+
params = params.merge(key: (client.api_key unless client.credentials?)).compact
|
|
87
|
+
response = client.connection.accept(:json).request(method, path, params:, json:)
|
|
88
|
+
|
|
89
|
+
raise HTTPError, response.flush unless response.status.ok?
|
|
90
|
+
|
|
91
|
+
body = response.body.to_s
|
|
92
|
+
body.strip.empty? ? {} : JSON.parse(body)
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
# @!attribute [r] tool_names
|
|
96
|
+
# @return [Array<String>, nil] the tools the cache was created with; nil when unknown (e.g. from `get`)
|
|
97
|
+
attr_reader :tool_names
|
|
98
|
+
|
|
99
|
+
# @param client [Client]
|
|
100
|
+
# @param data [Hash]
|
|
101
|
+
# @param tool_names [Array<String>, nil]
|
|
102
|
+
def initialize(client:, data:, tool_names: nil)
|
|
103
|
+
@client = client
|
|
104
|
+
@data = data
|
|
105
|
+
@tool_names = tool_names
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# @return [String] e.g. "projects/P/locations/L/cachedContents/123" or "cachedContents/123"
|
|
109
|
+
def name
|
|
110
|
+
@data["name"]
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# @return [String]
|
|
114
|
+
def model
|
|
115
|
+
@data["model"]
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# @return [Time, nil]
|
|
119
|
+
def expire_time
|
|
120
|
+
Time.parse(@data["expireTime"]) if @data["expireTime"]
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
# @return [String, nil]
|
|
124
|
+
def location_id
|
|
125
|
+
self.class.location_id(name)
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# @return [Integer, nil]
|
|
129
|
+
def token_count
|
|
130
|
+
@data.dig("usageMetadata", "totalTokenCount")
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
# @param ttl [Integer] seconds from now
|
|
134
|
+
#
|
|
135
|
+
# @raise [HTTPError]
|
|
136
|
+
#
|
|
137
|
+
# @return [Cache]
|
|
138
|
+
def update(ttl:)
|
|
139
|
+
@data = self.class.request!(@client, :patch, @client.cache_path(name), { ttl: "#{Integer(ttl)}s" },
|
|
140
|
+
params: { updateMask: "ttl" })
|
|
141
|
+
self
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
# @raise [HTTPError]
|
|
145
|
+
def delete
|
|
146
|
+
self.class.delete(name, client: @client)
|
|
147
|
+
end
|
|
148
|
+
end
|
|
149
|
+
end
|
|
150
|
+
end
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module OmniAI
|
|
4
|
+
module Google
|
|
5
|
+
# Per-process bookkeeping for `cache:`. Creates and TTL refreshes run on a background thread, one per key, so a
|
|
6
|
+
# slow create (the first one in a project has taken ~2 min) never blocks a chat for longer than `wait`.
|
|
7
|
+
class CacheRegistry
|
|
8
|
+
PREFIX = "omniai-google/cache/"
|
|
9
|
+
|
|
10
|
+
# A store entry expires this many seconds before the cache itself, so a hit always has time left.
|
|
11
|
+
MARGIN = 30
|
|
12
|
+
|
|
13
|
+
# 4xx statuses that are worth retrying later; any other 4xx on create marks the key uncacheable for the TTL.
|
|
14
|
+
TRANSIENT = [408, 429].freeze
|
|
15
|
+
|
|
16
|
+
# @return [CacheRegistry]
|
|
17
|
+
def self.instance
|
|
18
|
+
INSTANCE
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def initialize
|
|
22
|
+
@mutex = Mutex.new
|
|
23
|
+
@pending = {}
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# @param key [String]
|
|
27
|
+
# @param client [Client] located for the model; used to refresh the TTL
|
|
28
|
+
# @param ttl [Integer] seconds
|
|
29
|
+
# @param wait [Numeric] seconds
|
|
30
|
+
#
|
|
31
|
+
# @yieldreturn [Cache] creates the cache
|
|
32
|
+
#
|
|
33
|
+
# @return [String, nil] a cache name, or nil to send uncached
|
|
34
|
+
def fetch(key, client:, ttl:, wait:, &create)
|
|
35
|
+
entry = store.read(PREFIX + key)
|
|
36
|
+
return hit(key, entry, client:) if entry.is_a?(Hash) && entry["name"]
|
|
37
|
+
return if entry
|
|
38
|
+
|
|
39
|
+
thread = background(key) { create!(key, ttl:, logger: client.logger, &create) }
|
|
40
|
+
thread.value if thread.join(wait)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# @param key [String]
|
|
44
|
+
def evict(key)
|
|
45
|
+
store.delete(PREFIX + key)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
private
|
|
49
|
+
|
|
50
|
+
# @return [#read, #write, #delete]
|
|
51
|
+
def store
|
|
52
|
+
OmniAI::Google.config.cache_store
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# @return [Float]
|
|
56
|
+
def now
|
|
57
|
+
Time.now.to_f
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Starts the block on a thread unless one is already running for the key; either way returns that thread.
|
|
61
|
+
# A thread inherited across a fork is dead and its `ensure` never runs in the child, so it is replaced.
|
|
62
|
+
#
|
|
63
|
+
# @return [Thread]
|
|
64
|
+
def background(key, &block)
|
|
65
|
+
@mutex.synchronize do
|
|
66
|
+
@pending.delete(key) unless @pending[key]&.alive?
|
|
67
|
+
@pending[key] ||= Thread.new do
|
|
68
|
+
block.call
|
|
69
|
+
ensure
|
|
70
|
+
@mutex.synchronize { @pending.delete(key) }
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# @return [String, nil]
|
|
76
|
+
def create!(key, ttl:, logger:)
|
|
77
|
+
cache = yield
|
|
78
|
+
write(key, cache.name, ttl)
|
|
79
|
+
cache.name
|
|
80
|
+
rescue HTTPError => e
|
|
81
|
+
status = e.response.status.to_i
|
|
82
|
+
if status.between?(400, 499) && !TRANSIENT.include?(status)
|
|
83
|
+
store.write(PREFIX + key, { "uncacheable" => status }, expires_in: ttl)
|
|
84
|
+
end
|
|
85
|
+
logger&.warn("OmniAI::Google cache create failed status=#{status}")
|
|
86
|
+
nil
|
|
87
|
+
rescue StandardError => e
|
|
88
|
+
logger&.warn("OmniAI::Google cache create failed error=#{e.class}")
|
|
89
|
+
nil
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# Extends the TTL in the background once less than half of it is left.
|
|
93
|
+
#
|
|
94
|
+
# @return [String]
|
|
95
|
+
def hit(key, entry, client:)
|
|
96
|
+
name = entry["name"]
|
|
97
|
+
ttl = entry["ttl"]
|
|
98
|
+
background("refresh/#{key}") { refresh!(key, name, ttl, client:) } if entry["expires_at"] - now < ttl / 2.0
|
|
99
|
+
name
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# A refresh that fails with a 4xx evicts the key, so the next chat creates a new cache.
|
|
103
|
+
def refresh!(key, name, ttl, client:)
|
|
104
|
+
Cache.new(client:, data: { "name" => name }).update(ttl:)
|
|
105
|
+
write(key, name, ttl)
|
|
106
|
+
rescue HTTPError => e
|
|
107
|
+
evict(key) if e.response.status.client_error?
|
|
108
|
+
client.logger&.warn("OmniAI::Google cache refresh failed status=#{e.response.status.to_i}")
|
|
109
|
+
rescue StandardError => e
|
|
110
|
+
client.logger&.warn("OmniAI::Google cache refresh failed error=#{e.class}")
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# @param key [String]
|
|
114
|
+
# @param name [String]
|
|
115
|
+
# @param ttl [Integer]
|
|
116
|
+
def write(key, name, ttl)
|
|
117
|
+
store.write(PREFIX + key, { "name" => name, "ttl" => ttl, "expires_at" => now + ttl },
|
|
118
|
+
expires_in: [ttl - MARGIN, 1].max)
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
INSTANCE = new
|
|
122
|
+
private_constant :INSTANCE
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
end
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module OmniAI
|
|
4
|
+
module Google
|
|
5
|
+
# The default per-process store for `cache:`. Any object with `read(key)`, `write(key, value, expires_in:)` and
|
|
6
|
+
# `delete(key)` can replace it via `config.cache_store` (e.g. `Rails.cache`).
|
|
7
|
+
class CacheStore
|
|
8
|
+
def initialize
|
|
9
|
+
@entries = {}
|
|
10
|
+
@mutex = Mutex.new
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
# @param key [String]
|
|
14
|
+
#
|
|
15
|
+
# @return [Object, nil]
|
|
16
|
+
def read(key)
|
|
17
|
+
@mutex.synchronize do
|
|
18
|
+
value, expires_at = @entries[key]
|
|
19
|
+
next value if expires_at && expires_at > now
|
|
20
|
+
|
|
21
|
+
@entries.delete(key)
|
|
22
|
+
nil
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# @param key [String]
|
|
27
|
+
# @param value [Object]
|
|
28
|
+
# @param expires_in [Numeric] seconds
|
|
29
|
+
def write(key, value, expires_in:)
|
|
30
|
+
@mutex.synchronize { @entries[key] = [value, now + expires_in] }
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# @param key [String]
|
|
34
|
+
def delete(key)
|
|
35
|
+
@mutex.synchronize { @entries.delete(key) }
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
private
|
|
39
|
+
|
|
40
|
+
# @return [Float]
|
|
41
|
+
def now
|
|
42
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module OmniAI
|
|
4
|
+
module Google
|
|
5
|
+
# `client.caches`: create, get and delete explicit context caches.
|
|
6
|
+
class Caches
|
|
7
|
+
# @param client [Client]
|
|
8
|
+
def initialize(client:)
|
|
9
|
+
@client = client
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
# The cache is created at the model's location, the same host `client.chat` uses for that model.
|
|
13
|
+
#
|
|
14
|
+
# @param prompt [OmniAI::Chat::Prompt, String, nil] optional
|
|
15
|
+
# @param model [String] required
|
|
16
|
+
# @param ttl [Integer] optional - seconds
|
|
17
|
+
# @param tools [Array<OmniAI::Tool>, nil] optional - declarations live in the cache; a cached chat can't send them
|
|
18
|
+
#
|
|
19
|
+
# @yield [prompt] optional
|
|
20
|
+
# @yieldparam prompt [OmniAI::Chat::Prompt]
|
|
21
|
+
#
|
|
22
|
+
# @raise [HTTPError]
|
|
23
|
+
#
|
|
24
|
+
# @return [Cache]
|
|
25
|
+
def create(prompt = nil, model:, ttl: Cache::DEFAULT_TTL, tools: nil, &)
|
|
26
|
+
Cache.create(prompt, client: @client.for_model(model), model:, ttl:, tools:, &)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# @param name [String]
|
|
30
|
+
#
|
|
31
|
+
# @raise [HTTPError]
|
|
32
|
+
#
|
|
33
|
+
# @return [Cache]
|
|
34
|
+
def get(name)
|
|
35
|
+
Cache.get(name, client: @client.for_cache(name))
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# @param name [String]
|
|
39
|
+
#
|
|
40
|
+
# @raise [HTTPError]
|
|
41
|
+
def delete(name)
|
|
42
|
+
Cache.delete(name, client: @client.for_cache(name))
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
data/lib/omniai/google/chat.rb
CHANGED
|
@@ -79,13 +79,61 @@ module OmniAI
|
|
|
79
79
|
context.deserializers[:thinking] = ThinkingSerializer.method(:deserialize)
|
|
80
80
|
end
|
|
81
81
|
|
|
82
|
+
# Google rejects these on a request that uses `cachedContent`; they must live in the cache.
|
|
83
|
+
CACHE_EXCLUDED_KEYS = %i[system_instruction systemInstruction tools tool_config toolConfig].freeze
|
|
84
|
+
|
|
85
|
+
# A cached request that gets one of these, or a 404, is retried once uncached (`cache:` only).
|
|
86
|
+
CACHE_GONE_STATUSES = %w[NOT_FOUND FAILED_PRECONDITION].freeze
|
|
87
|
+
|
|
88
|
+
# Vertex answers a request against a deleted cache with 400 INVALID_ARGUMENT, the same status as a bad prompt,
|
|
89
|
+
# so this one is retried only when a `get` of the cache then returns 404.
|
|
90
|
+
CACHE_CHECK_STATUS = "INVALID_ARGUMENT"
|
|
91
|
+
|
|
92
|
+
# @param tools [Array<OmniAI::Tool, Symbol, String>, nil]
|
|
93
|
+
#
|
|
94
|
+
# @return [Array<Hash>, nil]
|
|
95
|
+
def self.serialize_tools(tools)
|
|
96
|
+
return if tools.nil? || tools.empty?
|
|
97
|
+
|
|
98
|
+
[
|
|
99
|
+
{ function_declarations: tools.grep(OmniAI::Tool).map { |tool| tool.serialize(context: CONTEXT) } },
|
|
100
|
+
].concat(tools.filter { |tool| tool.is_a?(Symbol) || tool.is_a?(String) }.map { |name| { name => {} } })
|
|
101
|
+
end
|
|
102
|
+
|
|
82
103
|
# `client` is swapped for `client.for_model(model)`, so `locations` routes the request.
|
|
104
|
+
#
|
|
105
|
+
# Caching (Gemini explicit context caching, off by default):
|
|
106
|
+
# - `cached_content:` a `Cache` or cache name made with `client.caches`; the prompt holds only what follows it
|
|
107
|
+
# - `cache: :system` caches the system prompt and tools
|
|
108
|
+
# - `cache: true` also caches every message before the last one
|
|
109
|
+
# - `cache: { ttl: 600 }` as `true`, with a TTL in seconds (default 300); add `scope: :system` for `:system`
|
|
110
|
+
#
|
|
111
|
+
# @raise [ArgumentError] for an invalid cache option, or a `cached_content:` that doesn't fit the request
|
|
83
112
|
def initialize(prompt = nil, client:, model:, **, &)
|
|
84
113
|
super(prompt, client: client.for_model(model), model:, **, &)
|
|
114
|
+
@cache = cache_option
|
|
115
|
+
@cache_use = explicit_cache_use
|
|
85
116
|
end
|
|
86
117
|
|
|
87
118
|
protected
|
|
88
119
|
|
|
120
|
+
# Rounds of a tool-call loop reuse the first round's cache, so a loop doesn't create one cache per round.
|
|
121
|
+
#
|
|
122
|
+
# @param prompt [OmniAI::Chat::Prompt]
|
|
123
|
+
#
|
|
124
|
+
# @return [Chat]
|
|
125
|
+
def spawn!(prompt)
|
|
126
|
+
super.tap { |chat| chat.inherit_cache(@cache_use, @cache_key) if @cache }
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
# @param cache_use [Hash, nil]
|
|
130
|
+
# @param cache_key [String, nil]
|
|
131
|
+
def inherit_cache(cache_use, cache_key)
|
|
132
|
+
@cache_use = cache_use
|
|
133
|
+
@cache_key = cache_key
|
|
134
|
+
@cache_resolved = true
|
|
135
|
+
end
|
|
136
|
+
|
|
89
137
|
# @return [Context]
|
|
90
138
|
def context
|
|
91
139
|
CONTEXT
|
|
@@ -93,6 +141,17 @@ module OmniAI
|
|
|
93
141
|
|
|
94
142
|
# @return [HTTP::Response]
|
|
95
143
|
def request!
|
|
144
|
+
resolve_cache! if @cache && !@cache_resolved
|
|
145
|
+
response = post!
|
|
146
|
+
return response unless @cache && @cache_use && cache_gone?(response)
|
|
147
|
+
|
|
148
|
+
CacheRegistry.instance.evict(@cache_key)
|
|
149
|
+
@cache_use = nil
|
|
150
|
+
post!
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# @return [HTTP::Response]
|
|
154
|
+
def post!
|
|
96
155
|
@client
|
|
97
156
|
.connection
|
|
98
157
|
.accept(:json)
|
|
@@ -110,6 +169,8 @@ module OmniAI
|
|
|
110
169
|
#
|
|
111
170
|
# @return [Hash]
|
|
112
171
|
def payload
|
|
172
|
+
return cached_payload if @cache_use
|
|
173
|
+
|
|
113
174
|
OmniAI::Google.config.chat_options.except(:max_tokens).merge({
|
|
114
175
|
system_instruction: @prompt.messages.find(&:system?)&.serialize(context:),
|
|
115
176
|
contents: @prompt.messages.reject(&:system?).map { |message| message.serialize(context:) },
|
|
@@ -118,23 +179,135 @@ module OmniAI
|
|
|
118
179
|
}).compact
|
|
119
180
|
end
|
|
120
181
|
|
|
182
|
+
# The system prompt and tools live in the cache, so neither is sent; tools still run locally.
|
|
183
|
+
#
|
|
184
|
+
# @return [Hash]
|
|
185
|
+
def cached_payload
|
|
186
|
+
OmniAI::Google.config.chat_options.except(:max_tokens, *CACHE_EXCLUDED_KEYS).merge({
|
|
187
|
+
cachedContent: @cache_use[:name],
|
|
188
|
+
contents: @prompt.messages.reject(&:system?).drop(@cache_use[:skip]).map do |message|
|
|
189
|
+
message.serialize(context:)
|
|
190
|
+
end,
|
|
191
|
+
generationConfig: generation_config,
|
|
192
|
+
}).compact
|
|
193
|
+
end
|
|
194
|
+
|
|
121
195
|
# @return [Hash]
|
|
122
196
|
def tools
|
|
123
|
-
|
|
197
|
+
self.class.serialize_tools(@tools)
|
|
198
|
+
end
|
|
124
199
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
200
|
+
# @return [Hash, nil] `{ scope: :system | :all, ttl: Integer }`
|
|
201
|
+
def cache_option
|
|
202
|
+
cache = @options[:cache]
|
|
203
|
+
return unless cache
|
|
204
|
+
|
|
205
|
+
raise ArgumentError, "pass `cache:` or `cached_content:`, not both" if @options[:cached_content]
|
|
206
|
+
|
|
207
|
+
option =
|
|
208
|
+
case cache
|
|
209
|
+
when true then { scope: :all }
|
|
210
|
+
when :system then { scope: :system }
|
|
211
|
+
when Hash then { scope: :all }.merge(cache.slice(:scope, :ttl))
|
|
212
|
+
else raise ArgumentError, "unsupported cache=#{cache.inspect}"
|
|
213
|
+
end
|
|
214
|
+
option[:ttl] = Integer(option[:ttl] || Cache::DEFAULT_TTL)
|
|
215
|
+
scope = option[:scope]
|
|
216
|
+
raise ArgumentError, "unsupported cache scope=#{scope.inspect}" unless %i[all system].include?(scope)
|
|
217
|
+
|
|
218
|
+
option
|
|
219
|
+
end
|
|
220
|
+
|
|
221
|
+
# @raise [ArgumentError]
|
|
222
|
+
#
|
|
223
|
+
# @return [Hash, nil]
|
|
224
|
+
def explicit_cache_use
|
|
225
|
+
cached = @options[:cached_content]
|
|
226
|
+
return unless cached
|
|
227
|
+
|
|
228
|
+
if @prompt.messages.any?(&:system?)
|
|
229
|
+
raise ArgumentError, "a cached chat can't send a system message; put it in the cache"
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
name = cached.is_a?(Cache) ? cached.name : cached
|
|
233
|
+
check_cache_location!(name)
|
|
234
|
+
check_cache!(cached) if cached.is_a?(Cache)
|
|
235
|
+
|
|
236
|
+
{ name:, skip: 0 }
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
# @param name [String]
|
|
240
|
+
#
|
|
241
|
+
# @raise [ArgumentError]
|
|
242
|
+
def check_cache_location!(name)
|
|
243
|
+
location_id = Cache.location_id(name)
|
|
244
|
+
return if location_id.nil? || location_id.eql?(@client.location_id)
|
|
245
|
+
|
|
246
|
+
raise ArgumentError, "cache location=#{location_id} doesn't match the request location=#{@client.location_id}"
|
|
128
247
|
end
|
|
129
248
|
|
|
130
|
-
# @
|
|
131
|
-
|
|
132
|
-
|
|
249
|
+
# @param cache [Cache]
|
|
250
|
+
#
|
|
251
|
+
# @raise [ArgumentError]
|
|
252
|
+
def check_cache!(cache)
|
|
253
|
+
if cache.model && !cache.model.split("/").last.eql?(@model)
|
|
254
|
+
raise ArgumentError, "cache model=#{cache.model} doesn't match model=#{@model}"
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
return if cache.tool_names.nil?
|
|
258
|
+
|
|
259
|
+
missing = Array(@tools).grep(OmniAI::Tool).map(&:name) - cache.tool_names
|
|
260
|
+
raise ArgumentError, "tools #{missing.join(', ')} are not declared in the cache" if missing.any?
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
# Finds or creates the cache for this prompt's cacheable part (`cache:`). Sends uncached when there is nothing
|
|
264
|
+
# to cache, the model or prompt can't be cached, or a create is still pending after `config.cache_wait`.
|
|
265
|
+
def resolve_cache!
|
|
266
|
+
@cache_resolved = true
|
|
267
|
+
messages = @prompt.messages.reject(&:system?)
|
|
268
|
+
cached = @cache[:scope].eql?(:system) ? [] : messages[0...-1]
|
|
269
|
+
prompt = OmniAI::Chat::Prompt.new(messages: [@prompt.messages.find(&:system?), *cached].compact)
|
|
270
|
+
return if prompt.messages.empty? && !tools?
|
|
271
|
+
|
|
272
|
+
ttl = @cache[:ttl]
|
|
273
|
+
body = Cache.payload(client: @client, model: @model, prompt:, tools: @tools, ttl:).except(:ttl)
|
|
274
|
+
@cache_key = Digest::SHA256.hexdigest(JSON.generate([@client.host, body]))
|
|
275
|
+
|
|
276
|
+
name = CacheRegistry.instance.fetch(@cache_key, client: @client, ttl:,
|
|
277
|
+
wait: OmniAI::Google.config.cache_wait) do
|
|
278
|
+
Cache.create(prompt, client: @client, model: @model, ttl:, tools: @tools)
|
|
279
|
+
end
|
|
280
|
+
@cache_use = { name:, skip: cached.length } if name
|
|
281
|
+
end
|
|
282
|
+
|
|
283
|
+
# @param response [HTTP::Response]
|
|
284
|
+
#
|
|
285
|
+
# @return [Boolean]
|
|
286
|
+
def cache_gone?(response)
|
|
287
|
+
return true if response.status.not_found?
|
|
288
|
+
return false unless response.status.client_error?
|
|
289
|
+
|
|
290
|
+
status = error_status(response)
|
|
291
|
+
CACHE_GONE_STATUSES.include?(status) || (status.eql?(CACHE_CHECK_STATUS) && cache_missing?)
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
# @param response [HTTP::Response]
|
|
295
|
+
#
|
|
296
|
+
# @return [String, nil] e.g. "NOT_FOUND"
|
|
297
|
+
def error_status(response)
|
|
298
|
+
JSON.parse(response.body.to_s).dig("error", "status")
|
|
299
|
+
rescue JSON::ParserError
|
|
300
|
+
nil
|
|
133
301
|
end
|
|
134
302
|
|
|
135
|
-
# @return [
|
|
136
|
-
def
|
|
137
|
-
|
|
303
|
+
# @return [Boolean] true when a `get` of the cache in use returns 404
|
|
304
|
+
def cache_missing?
|
|
305
|
+
Cache.get(@cache_use[:name], client: @client)
|
|
306
|
+
false
|
|
307
|
+
rescue HTTPError => e
|
|
308
|
+
e.response.status.not_found?
|
|
309
|
+
rescue StandardError
|
|
310
|
+
false
|
|
138
311
|
end
|
|
139
312
|
|
|
140
313
|
# @return [Hash]
|
data/lib/omniai/google/client.rb
CHANGED
|
@@ -81,6 +81,45 @@ module OmniAI
|
|
|
81
81
|
dup.tap { |client| client.locate!(location_id) }
|
|
82
82
|
end
|
|
83
83
|
|
|
84
|
+
# A copy of this client pointed at a cache's location in `locations` mode, or this client otherwise.
|
|
85
|
+
#
|
|
86
|
+
# @param name [String] e.g. "projects/P/locations/us/cachedContents/123"
|
|
87
|
+
#
|
|
88
|
+
# @return [Client]
|
|
89
|
+
def for_cache(name)
|
|
90
|
+
return self if @locations.nil?
|
|
91
|
+
|
|
92
|
+
location_id = Cache.location_id(name) || raise(ArgumentError, "no location in cache name=#{name.inspect}")
|
|
93
|
+
dup.tap { |client| client.locate!(location_id) }
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# @return [String, nil]
|
|
97
|
+
attr_reader :location_id
|
|
98
|
+
|
|
99
|
+
# @return [Caches] create, get and delete explicit context caches
|
|
100
|
+
def caches
|
|
101
|
+
Caches.new(client: self)
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# @return [String, nil] e.g. "projects/P/locations/us" on Vertex, nil on the Gemini API
|
|
105
|
+
def parent
|
|
106
|
+
"projects/#{@project_id}/locations/#{@location_id}" if @project_id && @location_id
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# @param model [String]
|
|
110
|
+
#
|
|
111
|
+
# @return [String] the model's resource name, as `cachedContents` expects it
|
|
112
|
+
def model_name(model)
|
|
113
|
+
parent ? "#{parent}/publishers/google/models/#{model}" : "models/#{model}"
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
# @param name [String, nil] a cache name; nil for the collection
|
|
117
|
+
#
|
|
118
|
+
# @return [String]
|
|
119
|
+
def cache_path(name = nil)
|
|
120
|
+
"/#{@version}/#{name || [parent, 'cachedContents'].compact.join('/')}"
|
|
121
|
+
end
|
|
122
|
+
|
|
84
123
|
# @return [Boolean] true for a client returned by `#for_model`
|
|
85
124
|
def located?
|
|
86
125
|
@located || false
|
|
@@ -128,7 +167,8 @@ module OmniAI
|
|
|
128
167
|
# @param model [String] optional
|
|
129
168
|
# @param language [String, Array<String>] optional - language codes for transcription
|
|
130
169
|
# @param format [Symbol] optional - :json or :verbose_json
|
|
131
|
-
# @param options [Hash] Gemini transcribe models only: `diarization:`, `word_timestamps:`, `vocabulary
|
|
170
|
+
# @param options [Hash] Gemini transcribe models only: `diarization:`, `word_timestamps:`, `vocabulary:`;
|
|
171
|
+
# Speech-to-Text models only: `max_wait:` (seconds to wait for a batch operation)
|
|
132
172
|
def transcribe(input, model: Transcribe::DEFAULT_MODEL, language: nil, format: nil, **)
|
|
133
173
|
Transcribe.process!(input, model:, language:, format:, client: self, **)
|
|
134
174
|
end
|
data/lib/omniai/google/config.rb
CHANGED
|
@@ -25,6 +25,17 @@ module OmniAI
|
|
|
25
25
|
# @return [Hash{String => String}, nil]
|
|
26
26
|
attr_accessor :locations
|
|
27
27
|
|
|
28
|
+
# @!attribute [rw] cache_wait
|
|
29
|
+
# Seconds a chat with `cache:` waits for a cache create before sending uncached. The create carries on in the
|
|
30
|
+
# background either way.
|
|
31
|
+
# @return [Numeric]
|
|
32
|
+
attr_accessor :cache_wait
|
|
33
|
+
|
|
34
|
+
# @!attribute [w] cache_store
|
|
35
|
+
# Where `cache:` keeps cache names: anything with `read`, `write(key, value, expires_in:)` and `delete`
|
|
36
|
+
# (e.g. `Rails.cache`, so processes share caches). Defaults to a per-process store.
|
|
37
|
+
attr_writer :cache_store
|
|
38
|
+
|
|
28
39
|
# @param api_key [String, nil] optional - defaults to `ENV['GOOGLE_API_KEY']`
|
|
29
40
|
# @param project_id [String, nil] optional - defaults to `ENV['GOOGLE_PROJECT_ID']`
|
|
30
41
|
# @param location_id [String, nil] optional - defaults to `ENV['GOOGLE_LOCATION_ID']`
|
|
@@ -43,6 +54,12 @@ module OmniAI
|
|
|
43
54
|
super(api_key:, host:, logger:, timeout:)
|
|
44
55
|
@project_id = project_id
|
|
45
56
|
@location_id = location_id
|
|
57
|
+
@cache_wait = 10
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# @return [#read, #write, #delete]
|
|
61
|
+
def cache_store
|
|
62
|
+
@cache_store ||= CacheStore.new
|
|
46
63
|
end
|
|
47
64
|
|
|
48
65
|
# @return [String]
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module OmniAI
|
|
4
|
+
module Google
|
|
5
|
+
class Transcribe
|
|
6
|
+
# A Speech-to-Text (Chirp) transcription, with the details Google reports for billing.
|
|
7
|
+
class Transcription < OmniAI::Transcribe::Transcription
|
|
8
|
+
# @!attribute [rw] operation_name
|
|
9
|
+
# @return [String, nil] the batch operation, e.g. "projects/P/locations/us/operations/123"; nil when sync
|
|
10
|
+
attr_accessor :operation_name
|
|
11
|
+
|
|
12
|
+
# @!attribute [rw] billed_duration
|
|
13
|
+
# @return [Float, nil] seconds Google billed (`totalBilledDuration`); nil when not reported
|
|
14
|
+
attr_accessor :billed_duration
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
end
|
|
@@ -11,6 +11,25 @@ module OmniAI
|
|
|
11
11
|
class Transcribe < OmniAI::Transcribe
|
|
12
12
|
include TranscribeHelpers
|
|
13
13
|
|
|
14
|
+
# Raised when a batch operation isn't done within `max_wait`. Google may still finish (and bill) it.
|
|
15
|
+
class TimeoutError < OmniAI::Error
|
|
16
|
+
# @!attribute [r] operation_name
|
|
17
|
+
# @return [String]
|
|
18
|
+
attr_reader :operation_name
|
|
19
|
+
|
|
20
|
+
# @!attribute [r] wait
|
|
21
|
+
# @return [Numeric] seconds
|
|
22
|
+
attr_reader :wait
|
|
23
|
+
|
|
24
|
+
# @param operation_name [String]
|
|
25
|
+
# @param wait [Numeric] seconds
|
|
26
|
+
def initialize(operation_name:, wait:)
|
|
27
|
+
super("operation=#{operation_name} not done after #{wait}s")
|
|
28
|
+
@operation_name = operation_name
|
|
29
|
+
@wait = wait
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
|
|
14
33
|
module Model
|
|
15
34
|
GEMINI_3_5_TRANSCRIBE = "gemini-3.5-transcribe"
|
|
16
35
|
CHIRP_3 = "chirp_3"
|
|
@@ -39,7 +58,11 @@ module OmniAI
|
|
|
39
58
|
#
|
|
40
59
|
# @return [OmniAI::Transcribe::Transcription]
|
|
41
60
|
def self.process!(io, model:, **options)
|
|
42
|
-
|
|
61
|
+
if Gemini.model?(model)
|
|
62
|
+
raise ArgumentError, "max_wait is not supported by Gemini transcribe models" if options.key?(:max_wait)
|
|
63
|
+
|
|
64
|
+
return Gemini.process!(io, model:, **options)
|
|
65
|
+
end
|
|
43
66
|
|
|
44
67
|
unsupported = options.keys & GEMINI_OPTIONS
|
|
45
68
|
if unsupported.any?
|
|
@@ -50,8 +73,18 @@ module OmniAI
|
|
|
50
73
|
end
|
|
51
74
|
|
|
52
75
|
# `client` is swapped for `client.for_model(model)`, so `locations` routes the request.
|
|
53
|
-
|
|
76
|
+
#
|
|
77
|
+
# @param max_wait [Numeric, nil] optional - seconds to wait for a batch operation; defaults to an estimate from
|
|
78
|
+
# the file size (600 to 10,800 seconds)
|
|
79
|
+
#
|
|
80
|
+
# @raise [ArgumentError] when `max_wait` isn't a positive number
|
|
81
|
+
def initialize(io, client:, model:, max_wait: nil, **)
|
|
82
|
+
unless max_wait.nil? || (max_wait.is_a?(Numeric) && max_wait.positive?)
|
|
83
|
+
raise ArgumentError, "max_wait must be a positive number of seconds, got #{max_wait.inspect}"
|
|
84
|
+
end
|
|
85
|
+
|
|
54
86
|
super(io, client: client.for_model(model), model:, **)
|
|
87
|
+
@max_wait = max_wait
|
|
55
88
|
end
|
|
56
89
|
|
|
57
90
|
# @raise [HTTPError]
|
|
@@ -84,7 +117,9 @@ module OmniAI
|
|
|
84
117
|
transcript = data.dig("results", 0, "alternatives", 0, "transcript") || ""
|
|
85
118
|
|
|
86
119
|
transformed_data = build_sync_response_data(data, transcript)
|
|
87
|
-
Transcription.parse(model: @model, format: @format, data: transformed_data)
|
|
120
|
+
Transcription.parse(model: @model, format: @format, data: transformed_data).tap do |transcription|
|
|
121
|
+
transcription.billed_duration = parse_duration(data.dig("metadata", "totalBilledDuration"))
|
|
122
|
+
end
|
|
88
123
|
end
|
|
89
124
|
|
|
90
125
|
# @raise [HTTPError]
|
|
@@ -107,7 +142,11 @@ module OmniAI
|
|
|
107
142
|
# Extract transcript from completed operation
|
|
108
143
|
transcript_data = extract_batch_transcript(result)
|
|
109
144
|
|
|
110
|
-
Transcription.parse(model: @model, format: @format, data: transcript_data)
|
|
145
|
+
Transcription.parse(model: @model, format: @format, data: transcript_data).tap do |transcription|
|
|
146
|
+
transcription.operation_name = operation_name
|
|
147
|
+
file_result = (result.dig("response", "results") || {}).values.first
|
|
148
|
+
transcription.billed_duration = parse_duration(file_result&.dig("metadata", "totalBilledDuration"))
|
|
149
|
+
end
|
|
111
150
|
ensure
|
|
112
151
|
# Delete our upload even when the request fails or polling times out
|
|
113
152
|
cleanup_gcs_file(@uploaded_gcs_uri) if @uploaded_gcs_uri
|
|
@@ -4,6 +4,9 @@ module OmniAI
|
|
|
4
4
|
module Google
|
|
5
5
|
# Helper methods for transcription functionality
|
|
6
6
|
module TranscribeHelpers # rubocop:disable Metrics/ModuleLength
|
|
7
|
+
# Seconds between polls of a batch operation.
|
|
8
|
+
POLL_INTERVAL = 15
|
|
9
|
+
|
|
7
10
|
private
|
|
8
11
|
|
|
9
12
|
# @return [String]
|
|
@@ -224,13 +227,14 @@ module OmniAI
|
|
|
224
227
|
# Add authentication if using credentials
|
|
225
228
|
connection = connection.auth("Bearer #{@client.send(:auth).split.last}") if @client.credentials?
|
|
226
229
|
|
|
227
|
-
|
|
230
|
+
wait = max_wait
|
|
231
|
+
max_attempts = (wait / POLL_INTERVAL.to_f).ceil
|
|
228
232
|
attempt = 0
|
|
229
233
|
|
|
230
234
|
loop do
|
|
231
235
|
attempt += 1
|
|
232
236
|
|
|
233
|
-
raise
|
|
237
|
+
raise Transcribe::TimeoutError.new(operation_name:, wait:) if attempt > max_attempts
|
|
234
238
|
|
|
235
239
|
operation_response = connection.get("/v2/#{operation_name}", params: operation_params)
|
|
236
240
|
|
|
@@ -248,7 +252,7 @@ module OmniAI
|
|
|
248
252
|
return operation_data if operation_data["done"]
|
|
249
253
|
|
|
250
254
|
# Wait before polling again
|
|
251
|
-
sleep(
|
|
255
|
+
sleep(POLL_INTERVAL)
|
|
252
256
|
end
|
|
253
257
|
end
|
|
254
258
|
|
|
@@ -494,16 +498,22 @@ module OmniAI
|
|
|
494
498
|
::Google::Cloud::Storage.new(project_id:, credentials:)
|
|
495
499
|
end
|
|
496
500
|
|
|
497
|
-
#
|
|
498
|
-
|
|
501
|
+
# Seconds to poll a batch operation: `max_wait:` when given, else an estimate from the file size.
|
|
502
|
+
#
|
|
503
|
+
# @return [Numeric]
|
|
504
|
+
def max_wait
|
|
505
|
+
@max_wait || default_max_wait
|
|
506
|
+
end
|
|
507
|
+
|
|
508
|
+
# @return [Numeric]
|
|
509
|
+
def default_max_wait
|
|
499
510
|
file_size_bytes = calculate_file_size
|
|
500
511
|
assumed_bitrate_bps = 48_000
|
|
501
512
|
estimated_duration_seconds = (file_size_bytes * 8.0) / assumed_bitrate_bps
|
|
502
513
|
estimated_processing_seconds = estimated_duration_seconds * 0.3
|
|
503
514
|
total_wait_seconds = estimated_processing_seconds + 90
|
|
504
515
|
# Batch jobs can queue for minutes regardless of audio length
|
|
505
|
-
|
|
506
|
-
(final_wait_seconds / 15).ceil
|
|
516
|
+
total_wait_seconds.clamp(600, 10_800)
|
|
507
517
|
end
|
|
508
518
|
end
|
|
509
519
|
end
|
data/lib/omniai/google.rb
CHANGED
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: omniai-google
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 3.
|
|
4
|
+
version: 3.27.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Kevin Sylvestre
|
|
@@ -118,6 +118,10 @@ files:
|
|
|
118
118
|
- README.md
|
|
119
119
|
- lib/omniai/google.rb
|
|
120
120
|
- lib/omniai/google/bucket.rb
|
|
121
|
+
- lib/omniai/google/cache.rb
|
|
122
|
+
- lib/omniai/google/cache_registry.rb
|
|
123
|
+
- lib/omniai/google/cache_store.rb
|
|
124
|
+
- lib/omniai/google/caches.rb
|
|
121
125
|
- lib/omniai/google/chat.rb
|
|
122
126
|
- lib/omniai/google/chat/choice_serializer.rb
|
|
123
127
|
- lib/omniai/google/chat/content_serializer.rb
|
|
@@ -143,6 +147,7 @@ files:
|
|
|
143
147
|
- lib/omniai/google/stream_error.rb
|
|
144
148
|
- lib/omniai/google/transcribe.rb
|
|
145
149
|
- lib/omniai/google/transcribe/gemini.rb
|
|
150
|
+
- lib/omniai/google/transcribe/transcription.rb
|
|
146
151
|
- lib/omniai/google/transcribe_helpers.rb
|
|
147
152
|
- lib/omniai/google/unknown_location_error.rb
|
|
148
153
|
- lib/omniai/google/upload.rb
|