ai-lite 1.0.0 → 1.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 +4 -4
- data/CHANGELOG.md +25 -4
- data/README.md +382 -24
- data/lib/ai_lite/gemini/chat.rb +8 -5
- data/lib/ai_lite/gemini/configuration.rb +11 -1
- data/lib/ai_lite/gemini/embeddings.rb +58 -0
- data/lib/ai_lite/gemini/images.rb +56 -0
- data/lib/ai_lite/gemini/models.rb +3 -1
- data/lib/ai_lite/gemini/speech.rb +108 -0
- data/lib/ai_lite/gemini/streaming.rb +34 -5
- data/lib/ai_lite/gemini/tokens.rb +53 -0
- data/lib/ai_lite/gemini/tool_calling.rb +66 -0
- data/lib/ai_lite/gemini/transcription.rb +66 -0
- data/lib/ai_lite/gemini.rb +38 -3
- data/lib/ai_lite/openai/streaming.rb +11 -7
- data/lib/ai_lite/openai/tokens.rb +38 -0
- data/lib/ai_lite/openai/tool_calling.rb +71 -0
- data/lib/ai_lite/openai.rb +22 -15
- data/lib/ai_lite/version.rb +1 -1
- data/test/ai_lite_test.rb +5 -5
- data/test/gemini_embeddings_test.rb +122 -0
- data/test/gemini_images_test.rb +154 -0
- data/test/gemini_models_test.rb +3 -2
- data/test/gemini_speech_test.rb +199 -0
- data/test/gemini_test.rb +1 -1
- data/test/gemini_transcription_test.rb +123 -0
- data/test/package_test.rb +51 -0
- data/test/token_counting_test.rb +173 -0
- data/test/tool_calling_test.rb +270 -0
- metadata +23 -6
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
class AiLite
|
|
2
|
+
class Gemini
|
|
3
|
+
module Images
|
|
4
|
+
def image(prompt, model: nil, output_path: nil, debug: false, options: {})
|
|
5
|
+
response = nil
|
|
6
|
+
raw = nil
|
|
7
|
+
response_id = nil
|
|
8
|
+
unless prompt.is_a?(String) && !prompt.strip.empty?
|
|
9
|
+
raise ArgumentError, "prompt must be a nonempty string"
|
|
10
|
+
end
|
|
11
|
+
payload = options.each_with_object({}) { |(key, value), result| result[key.to_s] = value }
|
|
12
|
+
if payload["stream"] || payload["background"]
|
|
13
|
+
raise ArgumentError, "image does not support streaming or background execution"
|
|
14
|
+
end
|
|
15
|
+
payload.merge!("model" => model || image_model, "input" => prompt)
|
|
16
|
+
response = post_interaction(payload)
|
|
17
|
+
raw = response.body
|
|
18
|
+
raw = JSON.parse(raw)
|
|
19
|
+
raise "Invalid Gemini image response: expected an object" unless raw.is_a?(Hash)
|
|
20
|
+
|
|
21
|
+
response_id = raw["id"]
|
|
22
|
+
if !response.code.to_i.between?(200, 299) || raw["error"]
|
|
23
|
+
return result_envelope(status: response.code.to_i, error: error_message(raw),
|
|
24
|
+
response_id: response_id, raw: raw, debug: debug)
|
|
25
|
+
end
|
|
26
|
+
unless raw["status"] == "completed"
|
|
27
|
+
raise "Gemini interaction #{raw['status'] || 'has no status'}; inspect raw with debug: true"
|
|
28
|
+
end
|
|
29
|
+
steps = raw["steps"]
|
|
30
|
+
raise "Invalid Gemini image response: expected steps" unless steps.is_a?(Array)
|
|
31
|
+
|
|
32
|
+
image = steps.flat_map do |step|
|
|
33
|
+
next [] unless step.is_a?(Hash) && step["type"] == "model_output"
|
|
34
|
+
|
|
35
|
+
step["content"].is_a?(Array) ? step["content"] : []
|
|
36
|
+
end.find { |part| part.is_a?(Hash) && part["type"] == "image" }
|
|
37
|
+
content = image && image["data"]
|
|
38
|
+
unless content.is_a?(String) && !content.empty?
|
|
39
|
+
raise "No inline image data returned; inspect raw with debug: true"
|
|
40
|
+
end
|
|
41
|
+
bytes = content.unpack1("m0")
|
|
42
|
+
raise "Empty image data returned" if bytes.empty?
|
|
43
|
+
|
|
44
|
+
File.binwrite(output_path, bytes) if output_path
|
|
45
|
+
result_envelope(status: response.code.to_i, content: content, response_id: response_id,
|
|
46
|
+
raw: raw, debug: debug)
|
|
47
|
+
rescue StandardError => e
|
|
48
|
+
result_envelope(status: response ? response.code.to_i : "unknown", error: e.message,
|
|
49
|
+
response_id: response_id, raw: raw, debug: debug)
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
include Images
|
|
54
|
+
private_constant :Images
|
|
55
|
+
end
|
|
56
|
+
end
|
|
@@ -2,7 +2,9 @@ class AiLite
|
|
|
2
2
|
class Gemini
|
|
3
3
|
module Models
|
|
4
4
|
def self.snapshot(source)
|
|
5
|
-
{ "chat" => source.model.
|
|
5
|
+
{ "chat" => source.model, "embedding" => source.embedding_model, "image" => source.image_model, "speech" => source.speech_model, "transcription" => source.transcription_model }.transform_values do |model|
|
|
6
|
+
model.is_a?(String) ? model.dup : model
|
|
7
|
+
end
|
|
6
8
|
end
|
|
7
9
|
|
|
8
10
|
def configured_models
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
class AiLite
|
|
2
|
+
class Gemini
|
|
3
|
+
module Speech
|
|
4
|
+
FORMATS = { "wav" => "audio/wav", "pcm" => "audio/l16",
|
|
5
|
+
"mulaw" => "audio/mulaw", "alaw" => "audio/alaw" }.freeze
|
|
6
|
+
|
|
7
|
+
def speak(text, model: nil, voice: nil, instructions: nil, response_format: nil,
|
|
8
|
+
output_path: nil, base64: false, debug: false, options: {})
|
|
9
|
+
response = nil
|
|
10
|
+
raw = nil
|
|
11
|
+
response_id = nil
|
|
12
|
+
unless text.is_a?(String) && !text.strip.empty?
|
|
13
|
+
raise ArgumentError, "text must be a nonempty string"
|
|
14
|
+
end
|
|
15
|
+
unless instructions.nil? || instructions.is_a?(String)
|
|
16
|
+
raise ArgumentError, "instructions must be a string"
|
|
17
|
+
end
|
|
18
|
+
if response_format && !FORMATS.key?(response_format)
|
|
19
|
+
raise ArgumentError, "response_format must be wav, pcm, mulaw, or alaw"
|
|
20
|
+
end
|
|
21
|
+
selected_voice = voice || speech_voice
|
|
22
|
+
unless selected_voice.is_a?(String) && !selected_voice.strip.empty?
|
|
23
|
+
raise ArgumentError, "voice must be a nonempty string"
|
|
24
|
+
end
|
|
25
|
+
payload = speech_hash(options, "options")
|
|
26
|
+
if payload["stream"] || payload["background"]
|
|
27
|
+
raise ArgumentError, "speak does not support streaming or background execution"
|
|
28
|
+
end
|
|
29
|
+
generation = speech_hash(payload.fetch("generation_config", {}), "generation_config")
|
|
30
|
+
# The helper deliberately owns single-speaker voice selection.
|
|
31
|
+
generation["speech_config"] = [{ "voice" => selected_voice }]
|
|
32
|
+
format = speech_hash(payload.fetch("response_format", {}), "response_format option")
|
|
33
|
+
format["type"] = "audio"
|
|
34
|
+
format["mime_type"] = FORMATS.fetch(response_format) if response_format
|
|
35
|
+
format["mime_type"] ||= FORMATS.fetch("wav")
|
|
36
|
+
unless FORMATS.value?(format["mime_type"])
|
|
37
|
+
raise ArgumentError, "Unsupported speech MIME type"
|
|
38
|
+
end
|
|
39
|
+
part = { "type" => "text", "text" => text }
|
|
40
|
+
part["annotations"] = [{ "type" => "speech_metadata", "style" => instructions }] if instructions
|
|
41
|
+
payload.merge!("model" => model || speech_model,
|
|
42
|
+
"input" => [{ "type" => "user_input", "content" => [part] }],
|
|
43
|
+
"response_format" => format, "generation_config" => generation)
|
|
44
|
+
response = post_interaction(payload)
|
|
45
|
+
raw = response.body
|
|
46
|
+
raw = JSON.parse(raw)
|
|
47
|
+
raise "Invalid Gemini speech response: expected an object" unless raw.is_a?(Hash)
|
|
48
|
+
|
|
49
|
+
response_id = raw["id"]
|
|
50
|
+
if !response.code.to_i.between?(200, 299) || raw["error"]
|
|
51
|
+
return result_envelope(status: response.code.to_i, error: error_message(raw),
|
|
52
|
+
response_id: response_id, raw: raw, debug: debug)
|
|
53
|
+
end
|
|
54
|
+
unless raw["status"] == "completed"
|
|
55
|
+
raise "Gemini interaction #{raw['status'] || 'has no status'}; inspect raw with debug: true"
|
|
56
|
+
end
|
|
57
|
+
raise "Invalid Gemini speech response: expected steps" unless raw["steps"].is_a?(Array)
|
|
58
|
+
|
|
59
|
+
blocks = raw["steps"].flat_map do |step|
|
|
60
|
+
next [] unless step.is_a?(Hash) && step["type"] == "model_output"
|
|
61
|
+
|
|
62
|
+
step["content"].is_a?(Array) ? step["content"] : []
|
|
63
|
+
end.select { |block| block.is_a?(Hash) && block["type"] == "audio" }
|
|
64
|
+
# Joining WAV containers or silently dropping speech would corrupt the result.
|
|
65
|
+
raise "Expected one audio block; inspect raw with debug: true" unless blocks.length == 1
|
|
66
|
+
|
|
67
|
+
block = blocks.first
|
|
68
|
+
encoded = block["data"]
|
|
69
|
+
unless encoded.is_a?(String) && !encoded.empty?
|
|
70
|
+
raise "No inline audio data returned; inspect raw with debug: true"
|
|
71
|
+
end
|
|
72
|
+
mime = block["mime_type"].to_s.split(";").first.to_s.strip.downcase
|
|
73
|
+
actual_format = FORMATS.key(mime)
|
|
74
|
+
raise "Unsupported or missing audio MIME type: #{mime}" unless actual_format
|
|
75
|
+
|
|
76
|
+
audio = encoded.unpack1("m0")
|
|
77
|
+
raise "Empty audio data returned" if audio.empty?
|
|
78
|
+
if actual_format == "wav" && !(audio.bytesize >= 12 && audio.start_with?("RIFF") && audio.byteslice(8, 4) == "WAVE")
|
|
79
|
+
raise "Invalid WAV audio returned"
|
|
80
|
+
end
|
|
81
|
+
File.binwrite(output_path, audio) if output_path
|
|
82
|
+
content = if base64
|
|
83
|
+
[audio].pack("m0")
|
|
84
|
+
elsif output_path
|
|
85
|
+
{ "path" => output_path, "bytes" => audio.bytesize, "format" => actual_format }
|
|
86
|
+
else
|
|
87
|
+
audio
|
|
88
|
+
end
|
|
89
|
+
result_envelope(status: response.code.to_i, content: content, response_id: response_id,
|
|
90
|
+
raw: raw, debug: debug)
|
|
91
|
+
rescue StandardError => e
|
|
92
|
+
result_envelope(status: response ? response.code.to_i : "unknown", error: e.message,
|
|
93
|
+
response_id: response_id, raw: raw, debug: debug)
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
private
|
|
97
|
+
|
|
98
|
+
def speech_hash(value, name)
|
|
99
|
+
raise ArgumentError, "#{name} must be a hash" unless value.is_a?(Hash)
|
|
100
|
+
|
|
101
|
+
value.each_with_object({}) { |(key, item), result| result[key.to_s] = item }
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
include Speech
|
|
106
|
+
private_constant :Speech
|
|
107
|
+
end
|
|
108
|
+
end
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
class AiLite
|
|
2
2
|
class Gemini
|
|
3
3
|
module Streaming
|
|
4
|
-
def chat_stream(message, model: nil, instructions: nil, previous_response_id: nil, max_output_tokens: nil, debug: false, options: {}, &block)
|
|
4
|
+
def chat_stream(message, model: nil, instructions: nil, previous_response_id: nil, max_output_tokens: nil, tools: nil, tool_results: nil, debug: false, options: {}, &block)
|
|
5
5
|
raise ArgumentError, "chat_stream requires a block" unless block
|
|
6
6
|
|
|
7
7
|
status = "unknown"
|
|
@@ -14,7 +14,7 @@ class AiLite
|
|
|
14
14
|
begin
|
|
15
15
|
payload = chat_payload(message, model: model, instructions: instructions,
|
|
16
16
|
previous_response_id: previous_response_id,
|
|
17
|
-
max_output_tokens: max_output_tokens, options: options, stream: true)
|
|
17
|
+
max_output_tokens: max_output_tokens, options: options, stream: true, tools: tools, tool_results: tool_results)
|
|
18
18
|
uri = URI.parse("#{API_BASE_URL}/interactions")
|
|
19
19
|
request = Net::HTTP::Post.new(uri)
|
|
20
20
|
headers.each { |key, value| request[key] = value }
|
|
@@ -22,6 +22,9 @@ class AiLite
|
|
|
22
22
|
request.body = JSON.generate(payload)
|
|
23
23
|
result = nil
|
|
24
24
|
step_types = {}
|
|
25
|
+
function_steps = {}
|
|
26
|
+
argument_fragments = {}
|
|
27
|
+
finished_functions = {}
|
|
25
28
|
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
|
|
26
29
|
http.open_timeout = timeout
|
|
27
30
|
http.read_timeout = timeout
|
|
@@ -43,9 +46,17 @@ class AiLite
|
|
|
43
46
|
interaction = event.fetch("interaction")
|
|
44
47
|
response_id = interaction["id"] || response_id
|
|
45
48
|
when "step.start"
|
|
46
|
-
|
|
49
|
+
index = event.fetch("index")
|
|
50
|
+
step = event.fetch("step")
|
|
51
|
+
step_types[index] = step.fetch("type")
|
|
52
|
+
function_steps[index] = step.dup if step["type"] == "function_call"
|
|
47
53
|
when "step.delta"
|
|
48
54
|
delta = event.fetch("delta")
|
|
55
|
+
if step_types[event["index"]] == "function_call" && delta["type"] == "arguments_delta"
|
|
56
|
+
index = event["index"]
|
|
57
|
+
argument_fragments[index] ||= +""
|
|
58
|
+
argument_fragments[index] << delta.fetch("arguments")
|
|
59
|
+
end
|
|
49
60
|
if step_types[event["index"]] == "model_output" && delta["type"] == "text"
|
|
50
61
|
chunk = delta.fetch("text")
|
|
51
62
|
text << chunk
|
|
@@ -56,9 +67,22 @@ class AiLite
|
|
|
56
67
|
raise
|
|
57
68
|
end
|
|
58
69
|
end
|
|
70
|
+
when "step.stop"
|
|
71
|
+
index = event["index"]
|
|
72
|
+
if function_steps.key?(index)
|
|
73
|
+
function_steps[index]["arguments"] = argument_fragments[index] if argument_fragments.key?(index)
|
|
74
|
+
finished_functions[index] = function_steps[index]
|
|
75
|
+
end
|
|
59
76
|
when "interaction.status_update"
|
|
60
77
|
response_id = event["interaction_id"] || response_id
|
|
61
|
-
if
|
|
78
|
+
if event["status"] == "requires_action"
|
|
79
|
+
raise "Gemini interaction requires_action before function calls completed" unless function_steps.size == finished_functions.size && !finished_functions.empty?
|
|
80
|
+
result = result_envelope(status: status, content: text.empty? ? nil : text,
|
|
81
|
+
response_id: response_id, raw: raw, debug: debug)
|
|
82
|
+
attach_tool_calls(result, { "steps" => finished_functions.values })
|
|
83
|
+
throw :ai_lite_gemini_finished
|
|
84
|
+
end
|
|
85
|
+
if %w[failed cancelled incomplete].include?(event["status"])
|
|
62
86
|
result = result_envelope(status: status, content: text.empty? ? nil : text,
|
|
63
87
|
response_id: response_id, error: "Gemini interaction #{event['status']}", raw: raw, debug: debug)
|
|
64
88
|
throw :ai_lite_gemini_finished
|
|
@@ -67,9 +91,10 @@ class AiLite
|
|
|
67
91
|
interaction = event.fetch("interaction")
|
|
68
92
|
response_id = interaction["id"] || response_id
|
|
69
93
|
raw = { "interaction" => interaction, "events" => events } if debug
|
|
94
|
+
tool_source = interaction.key?("steps") ? interaction : { "steps" => finished_functions.values }
|
|
70
95
|
error = if interaction["error"]
|
|
71
96
|
error_message(interaction)
|
|
72
|
-
elsif interaction["status"] != "completed"
|
|
97
|
+
elsif interaction["status"] != "completed" && !(interaction["status"] == "requires_action" && !extract_tool_calls(tool_source).empty?)
|
|
73
98
|
"Gemini interaction #{interaction['status'] || 'has no status'}"
|
|
74
99
|
end
|
|
75
100
|
content = text.empty? ? nil : text
|
|
@@ -82,6 +107,10 @@ class AiLite
|
|
|
82
107
|
end
|
|
83
108
|
result = result_envelope(status: status, content: content, response_id: response_id,
|
|
84
109
|
error: error, raw: raw, debug: debug)
|
|
110
|
+
unless error
|
|
111
|
+
raise "Gemini function call stream ended before step.stop" if !interaction.key?("steps") && function_steps.size != finished_functions.size
|
|
112
|
+
attach_tool_calls(result, tool_source)
|
|
113
|
+
end
|
|
85
114
|
throw :ai_lite_gemini_finished
|
|
86
115
|
when "error"
|
|
87
116
|
result = result_envelope(status: status, content: text.empty? ? nil : text,
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
class AiLite
|
|
2
|
+
class Gemini
|
|
3
|
+
module Tokens
|
|
4
|
+
def count_tokens(input, model: nil, instructions: nil, debug: false, options: {})
|
|
5
|
+
response = raw = nil
|
|
6
|
+
model_id = model || self.model
|
|
7
|
+
unless model_id.is_a?(String) && model_id.match?(%r{\A(?:models/)?[A-Za-z0-9._-]+\z})
|
|
8
|
+
raise ArgumentError, "model must be a Gemini model ID"
|
|
9
|
+
end
|
|
10
|
+
raise ArgumentError, "instructions must be a string" unless instructions.nil? || instructions.is_a?(String)
|
|
11
|
+
raise ArgumentError, "options must be a hash" unless options.is_a?(Hash)
|
|
12
|
+
|
|
13
|
+
contents = input.is_a?(String) ? [{ "parts" => [{ "text" => input }] }] : (input.is_a?(Hash) ? [input] : input)
|
|
14
|
+
unless contents.is_a?(Array) && contents.all? { |item| item.is_a?(Hash) && (item["parts"] || item[:parts]).is_a?(Array) }
|
|
15
|
+
raise ArgumentError, "input must be a string, a Gemini Content hash with parts, or an array of Content hashes"
|
|
16
|
+
end
|
|
17
|
+
resource = "models/#{model_id.delete_prefix('models/')}"
|
|
18
|
+
payload = options.each_with_object({}) { |(key, value), result| result[key.to_s] = value }
|
|
19
|
+
if payload.key?("previous_interaction_id") || payload.key?("previous_response_id")
|
|
20
|
+
raise ArgumentError, "Gemini token counting requires explicit conversation contents, not a previous interaction ID"
|
|
21
|
+
end
|
|
22
|
+
if payload.key?("generateContentRequest") || !instructions.nil?
|
|
23
|
+
request = payload.fetch("generateContentRequest", {})
|
|
24
|
+
raise ArgumentError, "generateContentRequest must be a hash" unless request.is_a?(Hash)
|
|
25
|
+
|
|
26
|
+
request = request.each_with_object({}) { |(key, value), result| result[key.to_s] = value }
|
|
27
|
+
request.merge!("model" => resource, "contents" => contents)
|
|
28
|
+
request["systemInstruction"] = { "parts" => [{ "text" => instructions }] } unless instructions.nil?
|
|
29
|
+
payload.delete("contents")
|
|
30
|
+
payload["generateContentRequest"] = request
|
|
31
|
+
else
|
|
32
|
+
payload["contents"] = contents
|
|
33
|
+
end
|
|
34
|
+
response = post_json(payload, endpoint: "#{API_BASE_URL}/#{resource}:countTokens")
|
|
35
|
+
raw = response.body
|
|
36
|
+
raw = JSON.parse(raw)
|
|
37
|
+
raise "Invalid Gemini token count response: expected an object" unless raw.is_a?(Hash)
|
|
38
|
+
unless response.code.to_i.between?(200, 299) && !raw["error"]
|
|
39
|
+
return result_envelope(status: response.code.to_i, error: error_message(raw), raw: raw, debug: debug)
|
|
40
|
+
end
|
|
41
|
+
count = raw["totalTokens"]
|
|
42
|
+
raise "Invalid Gemini token count: expected a nonnegative integer" unless count.is_a?(Integer) && count >= 0
|
|
43
|
+
|
|
44
|
+
result_envelope(status: response.code.to_i, content: count, raw: raw, debug: debug)
|
|
45
|
+
rescue StandardError => e
|
|
46
|
+
result_envelope(status: response ? response.code.to_i : "unknown", error: e.message, raw: raw, debug: debug)
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
include Tokens
|
|
51
|
+
private_constant :Tokens
|
|
52
|
+
end
|
|
53
|
+
end
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
class AiLite
|
|
2
|
+
class Gemini
|
|
3
|
+
module ToolCalling
|
|
4
|
+
private
|
|
5
|
+
|
|
6
|
+
def apply_chat_tools(payload, tools)
|
|
7
|
+
payload["tools"] = tools unless tools.nil?
|
|
8
|
+
if payload.key?("tools") && !(payload["tools"].is_a?(Array) && payload["tools"].all? { |tool| tool.is_a?(Hash) })
|
|
9
|
+
raise ArgumentError, "tools must be an array of provider tool definitions"
|
|
10
|
+
end
|
|
11
|
+
payload
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
def tool_result_input(message, results, previous_id)
|
|
15
|
+
return message if results.nil?
|
|
16
|
+
raise ArgumentError, "Use tool_results without a message" unless message.nil?
|
|
17
|
+
unless previous_id.is_a?(String) && !previous_id.strip.empty?
|
|
18
|
+
raise ArgumentError, "tool_results requires previous_response_id; use native input for stateless history"
|
|
19
|
+
end
|
|
20
|
+
unless results.is_a?(Array) && !results.empty?
|
|
21
|
+
raise ArgumentError, "tool_results must be a nonempty array"
|
|
22
|
+
end
|
|
23
|
+
ids = []
|
|
24
|
+
results.map do |item|
|
|
25
|
+
raise ArgumentError, "Each tool result must be a hash" unless item.is_a?(Hash)
|
|
26
|
+
entry = item.each_with_object({}) { |(key, value), hash| hash[key.to_s] = value }
|
|
27
|
+
unless %w[id name].all? { |key| entry[key].is_a?(String) && !entry[key].strip.empty? } && entry.key?("output")
|
|
28
|
+
raise ArgumentError, "Each tool result requires id, name, and output"
|
|
29
|
+
end
|
|
30
|
+
raise ArgumentError, "Duplicate tool result ID" if ids.include?(entry["id"])
|
|
31
|
+
ids << entry["id"]
|
|
32
|
+
output = entry["output"].is_a?(String) ? entry["output"] : JSON.generate(entry["output"])
|
|
33
|
+
{ "type" => "function_result", "call_id" => entry["id"], "name" => entry["name"],
|
|
34
|
+
"result" => [{ "type" => "text", "text" => output }] }
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def extract_tool_calls(raw)
|
|
39
|
+
calls = Array(raw["steps"]).select { |item| item.is_a?(Hash) && item["type"] == "function_call" }
|
|
40
|
+
ids = []
|
|
41
|
+
calls.map do |call|
|
|
42
|
+
id = call["id"]
|
|
43
|
+
name = call["name"]
|
|
44
|
+
arguments = call["arguments"]
|
|
45
|
+
arguments = JSON.parse(arguments) if arguments.is_a?(String)
|
|
46
|
+
unless id.is_a?(String) && !id.empty? && name.is_a?(String) && !name.empty? && arguments.is_a?(Hash)
|
|
47
|
+
raise "Invalid function call: expected ID, name, and object arguments"
|
|
48
|
+
end
|
|
49
|
+
raise "Invalid function call: duplicate ID" if ids.include?(id)
|
|
50
|
+
ids << id
|
|
51
|
+
{ "id" => id, "name" => name, "arguments" => arguments }
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def attach_tool_calls(result, raw)
|
|
56
|
+
return result if result["error"]
|
|
57
|
+
calls = extract_tool_calls(raw)
|
|
58
|
+
result["tool_calls"] = calls unless calls.empty?
|
|
59
|
+
result
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
include ToolCalling
|
|
64
|
+
private_constant :ToolCalling
|
|
65
|
+
end
|
|
66
|
+
end
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
class AiLite
|
|
2
|
+
class Gemini
|
|
3
|
+
module Transcription
|
|
4
|
+
MIME_TYPES = {
|
|
5
|
+
".wav" => "audio/wav", ".mp3" => "audio/mp3", ".aiff" => "audio/aiff",
|
|
6
|
+
".aif" => "audio/aiff", ".aac" => "audio/aac", ".ogg" => "audio/ogg",
|
|
7
|
+
".flac" => "audio/flac", ".mpeg" => "audio/mpeg", ".m4a" => "audio/m4a",
|
|
8
|
+
".l16" => "audio/l16", ".pcm" => "audio/l16", ".opus" => "audio/opus",
|
|
9
|
+
".alaw" => "audio/alaw", ".mulaw" => "audio/mulaw", ".webm" => "audio/webm"
|
|
10
|
+
}.freeze
|
|
11
|
+
MAX_REQUEST_BYTES = 20_000_000
|
|
12
|
+
|
|
13
|
+
def transcribe(file_path, model: nil, mime_type: nil, debug: false, options: {})
|
|
14
|
+
response = raw = response_id = nil
|
|
15
|
+
raise ArgumentError, "options must be a hash" unless options.is_a?(Hash)
|
|
16
|
+
|
|
17
|
+
payload = options.each_with_object({}) { |(key, value), result| result[key.to_s] = value }
|
|
18
|
+
raise ArgumentError, "Streaming and background transcription are not supported" if payload["stream"] || payload["background"]
|
|
19
|
+
unless file_path.is_a?(String) && File.file?(file_path)
|
|
20
|
+
raise ArgumentError, "file_path must point to an existing audio file"
|
|
21
|
+
end
|
|
22
|
+
mime = mime_type || MIME_TYPES[File.extname(file_path).downcase]
|
|
23
|
+
unless mime.is_a?(String) && MIME_TYPES.value?(mime.split(";", 2).first)
|
|
24
|
+
raise ArgumentError, "Unsupported audio format; supply a supported mime_type"
|
|
25
|
+
end
|
|
26
|
+
# Bound the read before allocating the base64 request, even if the file grows.
|
|
27
|
+
audio = File.binread(file_path, MAX_REQUEST_BYTES * 3 / 4)
|
|
28
|
+
raise ArgumentError, "Audio file is empty" if audio.empty?
|
|
29
|
+
|
|
30
|
+
payload.merge!("model" => model || transcription_model,
|
|
31
|
+
"input" => [{ "type" => "audio", "data" => [audio].pack("m0"), "mime_type" => mime }])
|
|
32
|
+
if JSON.generate(payload).bytesize >= MAX_REQUEST_BYTES
|
|
33
|
+
raise ArgumentError, "Inline transcription request must be under 20 MB; use a smaller audio file"
|
|
34
|
+
end
|
|
35
|
+
response = post_interaction(payload)
|
|
36
|
+
raw = response.body
|
|
37
|
+
raw = JSON.parse(raw)
|
|
38
|
+
raise "Invalid Gemini response: expected an object" unless raw.is_a?(Hash)
|
|
39
|
+
|
|
40
|
+
response_id = raw["id"]
|
|
41
|
+
unless response.code.to_i.between?(200, 299) && !raw["error"]
|
|
42
|
+
return result_envelope(status: response.code.to_i, error: error_message(raw),
|
|
43
|
+
response_id: response_id, raw: raw, debug: debug)
|
|
44
|
+
end
|
|
45
|
+
raise "Gemini interaction #{raw['status'] || 'has no status'}" unless raw["status"] == "completed"
|
|
46
|
+
raise "Invalid Gemini response: expected steps" unless raw["steps"].is_a?(Array)
|
|
47
|
+
|
|
48
|
+
parts = raw["steps"].flat_map do |step|
|
|
49
|
+
next [] unless step.is_a?(Hash) && step["type"] == "model_output" && step["content"].is_a?(Array)
|
|
50
|
+
|
|
51
|
+
step["content"].select { |part| part.is_a?(Hash) && part["type"] == "text" && part["text"].is_a?(String) }
|
|
52
|
+
end
|
|
53
|
+
raise "Gemini response did not include transcript text" if parts.empty?
|
|
54
|
+
|
|
55
|
+
result_envelope(status: response.code.to_i, content: parts.map { |part| part["text"] }.join,
|
|
56
|
+
response_id: response_id, raw: raw, debug: debug)
|
|
57
|
+
rescue StandardError => e
|
|
58
|
+
result_envelope(status: response ? response.code.to_i : "unknown", error: e.message,
|
|
59
|
+
response_id: response_id, raw: raw, debug: debug)
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
include Transcription
|
|
64
|
+
private_constant :Transcription
|
|
65
|
+
end
|
|
66
|
+
end
|
data/lib/ai_lite/gemini.rb
CHANGED
|
@@ -3,7 +3,13 @@ require "net/http"
|
|
|
3
3
|
require "uri"
|
|
4
4
|
require_relative "version"
|
|
5
5
|
require_relative "gemini/configuration"
|
|
6
|
+
require_relative "gemini/tokens"
|
|
7
|
+
require_relative "gemini/tool_calling"
|
|
6
8
|
require_relative "gemini/chat"
|
|
9
|
+
require_relative "gemini/embeddings"
|
|
10
|
+
require_relative "gemini/images"
|
|
11
|
+
require_relative "gemini/speech"
|
|
12
|
+
require_relative "gemini/transcription"
|
|
7
13
|
require_relative "gemini/streaming"
|
|
8
14
|
require_relative "gemini/youtube"
|
|
9
15
|
require_relative "gemini/models"
|
|
@@ -43,19 +49,44 @@ class AiLite
|
|
|
43
49
|
client.chat_stream(message, **kwargs, &block)
|
|
44
50
|
end
|
|
45
51
|
|
|
52
|
+
def transcribe(file_path, **kwargs)
|
|
53
|
+
client.transcribe(file_path, **kwargs)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def speak(text, **kwargs)
|
|
57
|
+
client.speak(text, **kwargs)
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def image(prompt, **kwargs)
|
|
61
|
+
client.image(prompt, **kwargs)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def embed(input, **kwargs)
|
|
65
|
+
client.embed(input, **kwargs)
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def count_tokens(input, **kwargs)
|
|
69
|
+
client.count_tokens(input, **kwargs)
|
|
70
|
+
end
|
|
71
|
+
|
|
46
72
|
def chat(message, **kwargs)
|
|
47
73
|
client.chat(message, **kwargs)
|
|
48
74
|
end
|
|
49
75
|
end
|
|
50
76
|
|
|
51
|
-
attr_reader :api_key, :model, :timeout, :max_output_tokens, :headers
|
|
77
|
+
attr_reader :api_key, :model, :embedding_model, :image_model, :speech_model, :speech_voice, :transcription_model, :timeout, :max_output_tokens, :headers
|
|
52
78
|
|
|
53
|
-
def initialize(api_key: nil, model: nil, timeout: nil, max_output_tokens: nil)
|
|
79
|
+
def initialize(api_key: nil, model: nil, embedding_model: nil, image_model: nil, speech_model: nil, speech_voice: nil, transcription_model: nil, timeout: nil, max_output_tokens: nil)
|
|
54
80
|
config = self.class.configuration
|
|
55
81
|
@api_key = api_key || config.api_key || ENV["GEMINI_API_KEY"]
|
|
56
82
|
raise ArgumentError, "Missing Gemini API key" if @api_key.to_s.strip.empty?
|
|
57
83
|
|
|
58
84
|
@model = model || config.model
|
|
85
|
+
@embedding_model = embedding_model || config.embedding_model
|
|
86
|
+
@image_model = image_model || config.image_model
|
|
87
|
+
@speech_model = speech_model || config.speech_model
|
|
88
|
+
@speech_voice = speech_voice || config.speech_voice
|
|
89
|
+
@transcription_model = transcription_model || config.transcription_model
|
|
59
90
|
@timeout = timeout || config.timeout
|
|
60
91
|
@max_output_tokens = max_output_tokens || config.max_output_tokens
|
|
61
92
|
@headers = { "x-goog-api-key" => @api_key, "Content-Type" => "application/json" }
|
|
@@ -64,7 +95,11 @@ class AiLite
|
|
|
64
95
|
private
|
|
65
96
|
|
|
66
97
|
def post_interaction(payload)
|
|
67
|
-
|
|
98
|
+
post_json(payload, endpoint: "#{API_BASE_URL}/interactions")
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def post_json(payload, endpoint:)
|
|
102
|
+
uri = URI.parse(endpoint)
|
|
68
103
|
request = Net::HTTP::Post.new(uri)
|
|
69
104
|
headers.each { |key, value| request[key] = value }
|
|
70
105
|
request.body = JSON.generate(payload)
|
|
@@ -2,7 +2,7 @@ class AiLite
|
|
|
2
2
|
class OpenAI
|
|
3
3
|
module Streaming
|
|
4
4
|
# Text deltas are yielded immediately; the return value is the final envelope.
|
|
5
|
-
def chat_stream(message, model: nil, instructions: nil, previous_response_id: nil, max_output_tokens: nil, debug: false, options: {}, &block)
|
|
5
|
+
def chat_stream(message, model: nil, instructions: nil, previous_response_id: nil, max_output_tokens: nil, tools: nil, tool_results: nil, debug: false, options: {}, &block)
|
|
6
6
|
raise ArgumentError, "chat_stream requires a block" unless block
|
|
7
7
|
|
|
8
8
|
status = "unknown"
|
|
@@ -11,12 +11,14 @@ class AiLite
|
|
|
11
11
|
raw = nil
|
|
12
12
|
callback_error = nil
|
|
13
13
|
begin
|
|
14
|
-
payload = options.
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
payload[
|
|
14
|
+
payload = options.each_with_object({}) { |(key, value), hash| hash[key.to_s] = value }
|
|
15
|
+
input = tool_result_input(message, tool_results, previous_response_id || payload["previous_response_id"])
|
|
16
|
+
raise ArgumentError, "Missing chat input" if input.nil?
|
|
17
|
+
payload.merge!("model" => model || self.model, "input" => input, "stream" => true,
|
|
18
|
+
"max_output_tokens" => max_output_tokens || self.max_output_tokens)
|
|
19
|
+
payload["instructions"] = instructions if instructions
|
|
20
|
+
payload["previous_response_id"] = previous_response_id if previous_response_id
|
|
21
|
+
apply_chat_tools(payload, tools)
|
|
20
22
|
uri = URI.parse(response_endpoint)
|
|
21
23
|
request = Net::HTTP::Post.new(uri)
|
|
22
24
|
headers.each { |key, value| request[key] = value }
|
|
@@ -61,9 +63,11 @@ class AiLite
|
|
|
61
63
|
when "response.incomplete"
|
|
62
64
|
"Response incomplete: #{raw.dig('incomplete_details', 'reason') || 'unknown reason'}"
|
|
63
65
|
end
|
|
66
|
+
error ||= error_message(raw) if raw["error"]
|
|
64
67
|
content = error ? text : parse_content(extract_output_text(raw))
|
|
65
68
|
result = prettify_data(status: status, content: content, error: error,
|
|
66
69
|
response_id: response_id, raw: raw, debug: debug)
|
|
70
|
+
attach_tool_calls(result, raw)
|
|
67
71
|
throw :ai_lite_stream_finished
|
|
68
72
|
when "error"
|
|
69
73
|
result = prettify_data(status: status, content: text, error: error_message(event),
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
class AiLite
|
|
2
|
+
class OpenAI
|
|
3
|
+
module Tokens
|
|
4
|
+
def count_tokens(input, model: nil, instructions: nil, previous_response_id: nil, debug: false, options: {})
|
|
5
|
+
response = raw = nil
|
|
6
|
+
unless input.is_a?(String) || (input.is_a?(Array) && input.all? { |item| item.is_a?(Hash) })
|
|
7
|
+
raise ArgumentError, "input must be a string or an array of OpenAI Responses input items"
|
|
8
|
+
end
|
|
9
|
+
raise ArgumentError, "options must be a hash" unless options.is_a?(Hash)
|
|
10
|
+
raise ArgumentError, "instructions must be a string" unless instructions.nil? || instructions.is_a?(String)
|
|
11
|
+
|
|
12
|
+
payload = options.each_with_object({}) { |(key, value), result| result[key.to_s] = value }
|
|
13
|
+
payload.merge!("model" => model || self.model, "input" => input)
|
|
14
|
+
payload["instructions"] = instructions unless instructions.nil?
|
|
15
|
+
payload["previous_response_id"] = previous_response_id unless previous_response_id.nil?
|
|
16
|
+
response = post(payload, endpoint: "#{API_BASE_URL}/responses/input_tokens")
|
|
17
|
+
raw = response.body
|
|
18
|
+
raw = JSON.parse(raw)
|
|
19
|
+
raise "Invalid OpenAI token count response: expected an object" unless raw.is_a?(Hash)
|
|
20
|
+
|
|
21
|
+
unless response.code.to_i.between?(200, 299) && !raw["error"]
|
|
22
|
+
error = raw["error"]
|
|
23
|
+
message = error.is_a?(Hash) ? (error["message"] || error.to_s) : (error || raw["message"] || raw.to_s)
|
|
24
|
+
return prettify_data(status: response.code.to_i, error: message, raw: raw, debug: debug)
|
|
25
|
+
end
|
|
26
|
+
count = raw["input_tokens"]
|
|
27
|
+
raise "Invalid OpenAI token count: expected a nonnegative integer" unless count.is_a?(Integer) && count >= 0
|
|
28
|
+
|
|
29
|
+
prettify_data(status: response.code.to_i, content: count, raw: raw, debug: debug)
|
|
30
|
+
rescue StandardError => e
|
|
31
|
+
prettify_data(status: response ? response.code.to_i : "unknown", error: e.message, raw: raw, debug: debug)
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
include Tokens
|
|
36
|
+
private_constant :Tokens
|
|
37
|
+
end
|
|
38
|
+
end
|