ai-lite 1.1.0 → 1.3.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 -6
- data/README.md +392 -23
- data/lib/ai_lite/claude/chat.rb +73 -0
- data/lib/ai_lite/claude/configuration.rb +22 -0
- data/lib/ai_lite/claude.rb +82 -0
- data/lib/ai_lite/gemini/chat.rb +8 -5
- data/lib/ai_lite/gemini/configuration.rb +7 -1
- data/lib/ai_lite/gemini/images.rb +1 -1
- data/lib/ai_lite/gemini/models.rb +1 -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 +21 -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/lib/ai_lite.rb +1 -0
- data/test/ai_lite_test.rb +5 -5
- data/test/claude_test.rb +156 -0
- data/test/gemini_images_test.rb +6 -6
- data/test/gemini_models_test.rb +1 -1
- 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 +52 -0
- data/test/token_counting_test.rb +173 -0
- data/test/tool_calling_test.rb +270 -0
- metadata +26 -8
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
require "json"
|
|
2
|
+
require "net/http"
|
|
3
|
+
require "uri"
|
|
4
|
+
require_relative "version"
|
|
5
|
+
require_relative "claude/configuration"
|
|
6
|
+
require_relative "claude/chat"
|
|
7
|
+
|
|
8
|
+
class AiLite
|
|
9
|
+
class Claude
|
|
10
|
+
class << self
|
|
11
|
+
def configuration
|
|
12
|
+
@configuration ||= Configuration.new
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def configure
|
|
16
|
+
yield configuration
|
|
17
|
+
reset_client!
|
|
18
|
+
configuration
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def reset_configuration!
|
|
22
|
+
@configuration = Configuration.new
|
|
23
|
+
reset_client!
|
|
24
|
+
configuration
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def client
|
|
28
|
+
@client ||= new
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def reset_client!
|
|
32
|
+
@client = nil
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def chat(message, **kwargs)
|
|
36
|
+
client.chat(message, **kwargs)
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
attr_reader :api_key, :model, :api_version, :workspace_id, :timeout, :max_output_tokens, :headers
|
|
41
|
+
|
|
42
|
+
def initialize(api_key: nil, model: nil, api_version: nil, workspace_id: nil, timeout: nil, max_output_tokens: nil)
|
|
43
|
+
config = self.class.configuration
|
|
44
|
+
@api_key = api_key || config.api_key || ENV["ANTHROPIC_API_KEY"]
|
|
45
|
+
raise ArgumentError, "Missing Anthropic API key" if @api_key.to_s.strip.empty?
|
|
46
|
+
|
|
47
|
+
@model = model || config.model
|
|
48
|
+
@api_version = api_version || config.api_version
|
|
49
|
+
@workspace_id = workspace_id || config.workspace_id
|
|
50
|
+
@timeout = timeout || config.timeout
|
|
51
|
+
@max_output_tokens = max_output_tokens || config.max_output_tokens
|
|
52
|
+
@headers = { "Authorization" => "Bearer #{@api_key}", "anthropic-version" => @api_version,
|
|
53
|
+
"Content-Type" => "application/json" }
|
|
54
|
+
@headers["anthropic-workspace-id"] = @workspace_id if @workspace_id
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
private
|
|
58
|
+
|
|
59
|
+
def post_json(payload, endpoint:)
|
|
60
|
+
uri = URI.parse(endpoint)
|
|
61
|
+
request = Net::HTTP::Post.new(uri)
|
|
62
|
+
headers.each { |key, value| request[key] = value }
|
|
63
|
+
request.body = JSON.generate(payload)
|
|
64
|
+
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
|
|
65
|
+
http.open_timeout = timeout
|
|
66
|
+
http.read_timeout = timeout
|
|
67
|
+
http.request(request)
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def result_envelope(status:, content: nil, error: nil, response_id: nil, raw: nil, debug: false)
|
|
72
|
+
{ "content" => content, "response_id" => response_id, "status" => status,
|
|
73
|
+
"error" => error, "raw" => debug ? raw : nil }
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def error_message(raw)
|
|
77
|
+
return raw.to_s unless raw.is_a?(Hash)
|
|
78
|
+
error = raw["error"]
|
|
79
|
+
error.is_a?(Hash) ? (error["message"] || error["type"] || error.to_s) : (error || raw["message"] || raw.to_s)
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
end
|
data/lib/ai_lite/gemini/chat.rb
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
class AiLite
|
|
2
2
|
class Gemini
|
|
3
3
|
module Chat
|
|
4
|
-
def chat(message, model: nil, instructions: nil, previous_response_id: nil, max_output_tokens: nil, debug: false, options: {})
|
|
4
|
+
def chat(message, model: nil, instructions: nil, previous_response_id: nil, max_output_tokens: nil, tools: nil, tool_results: nil, debug: false, options: {})
|
|
5
5
|
response = nil
|
|
6
6
|
raw = nil
|
|
7
7
|
response_id = nil
|
|
8
8
|
payload = chat_payload(message, model: model, instructions: instructions,
|
|
9
9
|
previous_response_id: previous_response_id,
|
|
10
|
-
max_output_tokens: max_output_tokens, options: options)
|
|
10
|
+
max_output_tokens: max_output_tokens, options: options, tools: tools, tool_results: tool_results)
|
|
11
11
|
response = post_interaction(payload)
|
|
12
12
|
raw = response.body
|
|
13
13
|
raw = JSON.parse(raw)
|
|
@@ -21,7 +21,7 @@ class AiLite
|
|
|
21
21
|
|
|
22
22
|
error = if raw["error"]
|
|
23
23
|
error_message(raw)
|
|
24
|
-
elsif raw["status"] != "completed"
|
|
24
|
+
elsif raw["status"] != "completed" && !(raw["status"] == "requires_action" && !extract_tool_calls(raw).empty?)
|
|
25
25
|
"Gemini interaction #{raw['status'] || 'has no status'}; inspect raw with debug: true"
|
|
26
26
|
end
|
|
27
27
|
steps = raw["steps"]
|
|
@@ -43,16 +43,19 @@ class AiLite
|
|
|
43
43
|
text
|
|
44
44
|
end
|
|
45
45
|
end
|
|
46
|
-
result_envelope(status: response.code.to_i, content: content, error: error,
|
|
46
|
+
result = result_envelope(status: response.code.to_i, content: content, error: error,
|
|
47
47
|
response_id: response_id, raw: raw, debug: debug)
|
|
48
|
+
attach_tool_calls(result, raw)
|
|
48
49
|
rescue StandardError => e
|
|
49
50
|
result_envelope(status: response ? response.code.to_i : "unknown", error: e.message,
|
|
50
51
|
response_id: response_id, raw: raw, debug: debug)
|
|
51
52
|
end
|
|
52
53
|
private
|
|
53
54
|
|
|
54
|
-
def chat_payload(message, model:, instructions:, previous_response_id:, max_output_tokens:, options:, stream: false)
|
|
55
|
+
def chat_payload(message, model:, instructions:, previous_response_id:, max_output_tokens:, options:, stream: false, tools: nil, tool_results: nil)
|
|
55
56
|
payload = options.each_with_object({}) { |(key, value), result| result[key.to_s] = value }
|
|
57
|
+
message = tool_result_input(message, tool_results, previous_response_id || payload["previous_interaction_id"])
|
|
58
|
+
apply_chat_tools(payload, tools)
|
|
56
59
|
if (!stream && payload["stream"]) || payload["background"]
|
|
57
60
|
raise ArgumentError, "Use chat_stream for streaming; background execution is not supported"
|
|
58
61
|
end
|
|
@@ -4,17 +4,23 @@ class AiLite
|
|
|
4
4
|
DEFAULT_MODEL = "gemini-3.8-flash".freeze
|
|
5
5
|
DEFAULT_EMBEDDING_MODEL = "gemini-embedding-001".freeze
|
|
6
6
|
DEFAULT_IMAGE_MODEL = "gemini-nano-banana-2.1".freeze
|
|
7
|
+
DEFAULT_SPEECH_MODEL = "gemini-3.8-flash-tts".freeze
|
|
8
|
+
DEFAULT_SPEECH_VOICE = "Kore".freeze
|
|
9
|
+
DEFAULT_TRANSCRIPTION_MODEL = "gemini-3.5-transcribe".freeze
|
|
7
10
|
DEFAULT_TIMEOUT = 120
|
|
8
11
|
DEFAULT_MAX_OUTPUT_TOKENS = 2000
|
|
9
12
|
|
|
10
13
|
class Configuration
|
|
11
|
-
attr_accessor :api_key, :model, :embedding_model, :image_model, :timeout, :max_output_tokens
|
|
14
|
+
attr_accessor :api_key, :model, :embedding_model, :image_model, :speech_model, :speech_voice, :transcription_model, :timeout, :max_output_tokens
|
|
12
15
|
|
|
13
16
|
def initialize
|
|
14
17
|
@api_key = nil
|
|
15
18
|
@model = DEFAULT_MODEL
|
|
16
19
|
@embedding_model = DEFAULT_EMBEDDING_MODEL
|
|
17
20
|
@image_model = DEFAULT_IMAGE_MODEL
|
|
21
|
+
@speech_model = DEFAULT_SPEECH_MODEL
|
|
22
|
+
@speech_voice = DEFAULT_SPEECH_VOICE
|
|
23
|
+
@transcription_model = DEFAULT_TRANSCRIPTION_MODEL
|
|
18
24
|
@timeout = DEFAULT_TIMEOUT
|
|
19
25
|
@max_output_tokens = DEFAULT_MAX_OUTPUT_TOKENS
|
|
20
26
|
end
|
|
@@ -38,7 +38,7 @@ class AiLite
|
|
|
38
38
|
unless content.is_a?(String) && !content.empty?
|
|
39
39
|
raise "No inline image data returned; inspect raw with debug: true"
|
|
40
40
|
end
|
|
41
|
-
bytes =
|
|
41
|
+
bytes = content.unpack1("m0")
|
|
42
42
|
raise "Empty image data returned" if bytes.empty?
|
|
43
43
|
|
|
44
44
|
File.binwrite(output_path, bytes) if output_path
|
|
@@ -2,7 +2,7 @@ class AiLite
|
|
|
2
2
|
class Gemini
|
|
3
3
|
module Models
|
|
4
4
|
def self.snapshot(source)
|
|
5
|
-
{ "chat" => source.model, "embedding" => source.embedding_model, "image" => source.image_model }.transform_values do |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
6
|
model.is_a?(String) ? model.dup : model
|
|
7
7
|
end
|
|
8
8
|
end
|
|
@@ -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
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
require "json"
|
|
2
2
|
require "net/http"
|
|
3
3
|
require "uri"
|
|
4
|
-
require "base64"
|
|
5
4
|
require_relative "version"
|
|
6
5
|
require_relative "gemini/configuration"
|
|
6
|
+
require_relative "gemini/tokens"
|
|
7
|
+
require_relative "gemini/tool_calling"
|
|
7
8
|
require_relative "gemini/chat"
|
|
8
9
|
require_relative "gemini/embeddings"
|
|
9
10
|
require_relative "gemini/images"
|
|
11
|
+
require_relative "gemini/speech"
|
|
12
|
+
require_relative "gemini/transcription"
|
|
10
13
|
require_relative "gemini/streaming"
|
|
11
14
|
require_relative "gemini/youtube"
|
|
12
15
|
require_relative "gemini/models"
|
|
@@ -46,6 +49,14 @@ class AiLite
|
|
|
46
49
|
client.chat_stream(message, **kwargs, &block)
|
|
47
50
|
end
|
|
48
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
|
+
|
|
49
60
|
def image(prompt, **kwargs)
|
|
50
61
|
client.image(prompt, **kwargs)
|
|
51
62
|
end
|
|
@@ -54,14 +65,18 @@ class AiLite
|
|
|
54
65
|
client.embed(input, **kwargs)
|
|
55
66
|
end
|
|
56
67
|
|
|
68
|
+
def count_tokens(input, **kwargs)
|
|
69
|
+
client.count_tokens(input, **kwargs)
|
|
70
|
+
end
|
|
71
|
+
|
|
57
72
|
def chat(message, **kwargs)
|
|
58
73
|
client.chat(message, **kwargs)
|
|
59
74
|
end
|
|
60
75
|
end
|
|
61
76
|
|
|
62
|
-
attr_reader :api_key, :model, :embedding_model, :image_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
|
|
63
78
|
|
|
64
|
-
def initialize(api_key: nil, model: nil, embedding_model: nil, image_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)
|
|
65
80
|
config = self.class.configuration
|
|
66
81
|
@api_key = api_key || config.api_key || ENV["GEMINI_API_KEY"]
|
|
67
82
|
raise ArgumentError, "Missing Gemini API key" if @api_key.to_s.strip.empty?
|
|
@@ -69,6 +84,9 @@ class AiLite
|
|
|
69
84
|
@model = model || config.model
|
|
70
85
|
@embedding_model = embedding_model || config.embedding_model
|
|
71
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
|
|
72
90
|
@timeout = timeout || config.timeout
|
|
73
91
|
@max_output_tokens = max_output_tokens || config.max_output_tokens
|
|
74
92
|
@headers = { "x-goog-api-key" => @api_key, "Content-Type" => "application/json" }
|