ai-lite 1.1.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 +19 -6
- data/README.md +295 -14
- 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/test/ai_lite_test.rb +5 -5
- 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 +51 -0
- data/test/token_counting_test.rb +173 -0
- data/test/tool_calling_test.rb +270 -0
- metadata +19 -7
|
@@ -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" }
|
|
@@ -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
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
class AiLite
|
|
2
|
+
class OpenAI
|
|
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_call_output", "call_id" => entry["id"], "output" => output }
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def extract_tool_calls(raw)
|
|
38
|
+
calls = Array(raw["output"]).select { |item| item.is_a?(Hash) && item["type"] == "function_call" }
|
|
39
|
+
if !calls.empty? && raw["status"] && raw["status"] != "completed"
|
|
40
|
+
raise "Response #{raw['status']}: function calls are not complete"
|
|
41
|
+
end
|
|
42
|
+
ids = []
|
|
43
|
+
calls.map do |call|
|
|
44
|
+
if call["status"] && call["status"] != "completed"
|
|
45
|
+
raise "Function call #{call['status']}: arguments are not complete"
|
|
46
|
+
end
|
|
47
|
+
id = call["call_id"]
|
|
48
|
+
name = call["name"]
|
|
49
|
+
arguments = call["arguments"]
|
|
50
|
+
arguments = JSON.parse(arguments) if arguments.is_a?(String)
|
|
51
|
+
unless id.is_a?(String) && !id.empty? && name.is_a?(String) && !name.empty? && arguments.is_a?(Hash)
|
|
52
|
+
raise "Invalid function call: expected ID, name, and object arguments"
|
|
53
|
+
end
|
|
54
|
+
raise "Invalid function call: duplicate ID" if ids.include?(id)
|
|
55
|
+
ids << id
|
|
56
|
+
{ "id" => id, "name" => name, "arguments" => arguments }
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def attach_tool_calls(result, raw)
|
|
61
|
+
return result if result["error"]
|
|
62
|
+
calls = extract_tool_calls(raw)
|
|
63
|
+
result["tool_calls"] = calls unless calls.empty?
|
|
64
|
+
result
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
include ToolCalling
|
|
69
|
+
private_constant :ToolCalling
|
|
70
|
+
end
|
|
71
|
+
end
|
data/lib/ai_lite/openai.rb
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
require "base64"
|
|
2
1
|
require "json"
|
|
3
2
|
require "net/http"
|
|
4
3
|
require "securerandom"
|
|
5
4
|
require "uri"
|
|
6
5
|
require_relative "version"
|
|
7
6
|
require_relative "openai/configuration"
|
|
7
|
+
require_relative "openai/tokens"
|
|
8
|
+
require_relative "openai/tool_calling"
|
|
8
9
|
require_relative "openai/streaming"
|
|
9
10
|
require_relative "openai/models"
|
|
10
11
|
|
|
@@ -31,6 +32,10 @@ class AiLite
|
|
|
31
32
|
@client ||= new
|
|
32
33
|
end
|
|
33
34
|
|
|
35
|
+
def count_tokens(input, **kwargs)
|
|
36
|
+
client.count_tokens(input, **kwargs)
|
|
37
|
+
end
|
|
38
|
+
|
|
34
39
|
def chat(message, **kwargs)
|
|
35
40
|
client.chat(message, **kwargs)
|
|
36
41
|
end
|
|
@@ -85,15 +90,16 @@ class AiLite
|
|
|
85
90
|
}
|
|
86
91
|
end
|
|
87
92
|
|
|
88
|
-
def chat(message, model: nil, instructions: nil, previous_response_id: nil, max_output_tokens: nil, debug: false, options: {})
|
|
89
|
-
payload = options.
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
payload[
|
|
96
|
-
|
|
93
|
+
def chat(message, model: nil, instructions: nil, previous_response_id: nil, max_output_tokens: nil, tools: nil, tool_results: nil, debug: false, options: {})
|
|
94
|
+
payload = options.each_with_object({}) { |(key, value), hash| hash[key.to_s] = value }
|
|
95
|
+
previous_id = previous_response_id || payload["previous_response_id"]
|
|
96
|
+
input = tool_result_input(message, tool_results, previous_id)
|
|
97
|
+
raise ArgumentError, "Missing chat input" if input.nil?
|
|
98
|
+
payload.merge!("model" => model || self.model, "input" => input,
|
|
99
|
+
"max_output_tokens" => max_output_tokens || self.max_output_tokens)
|
|
100
|
+
payload["instructions"] = instructions if instructions
|
|
101
|
+
payload["previous_response_id"] = previous_response_id if previous_response_id
|
|
102
|
+
apply_chat_tools(payload, tools)
|
|
97
103
|
extract_content(post(payload), debug: debug)
|
|
98
104
|
rescue => e
|
|
99
105
|
prettify_data(status: "unknown", error: e.message, raw: nil, debug: debug)
|
|
@@ -257,7 +263,7 @@ class AiLite
|
|
|
257
263
|
reason = parsed_response.dig("incomplete_details", "reason")
|
|
258
264
|
["Response #{parsed_response['status']}", reason].compact.join(": ")
|
|
259
265
|
end
|
|
260
|
-
prettify_data(
|
|
266
|
+
result = prettify_data(
|
|
261
267
|
status: status,
|
|
262
268
|
content: content,
|
|
263
269
|
error: error,
|
|
@@ -265,10 +271,11 @@ class AiLite
|
|
|
265
271
|
raw: parsed_response,
|
|
266
272
|
debug: debug
|
|
267
273
|
)
|
|
274
|
+
attach_tool_calls(result, parsed_response)
|
|
268
275
|
rescue JSON::ParserError => e
|
|
269
276
|
prettify_data(status: response_status(response), error: e.message, raw: response&.body, debug: debug)
|
|
270
277
|
rescue => e
|
|
271
|
-
prettify_data(status: response_status(response), error: e.message, raw:
|
|
278
|
+
prettify_data(status: response_status(response), error: e.message, raw: parsed_response, debug: debug)
|
|
272
279
|
end
|
|
273
280
|
|
|
274
281
|
def extract_moderation(response, debug: false)
|
|
@@ -459,7 +466,7 @@ class AiLite
|
|
|
459
466
|
|
|
460
467
|
def image_data_url(path)
|
|
461
468
|
mime_type = image_mime_type(path)
|
|
462
|
-
"data:#{mime_type};base64,#{
|
|
469
|
+
"data:#{mime_type};base64,#{[File.binread(path)].pack("m0")}"
|
|
463
470
|
end
|
|
464
471
|
|
|
465
472
|
def image_mime_type(path)
|
|
@@ -509,11 +516,11 @@ class AiLite
|
|
|
509
516
|
def write_image_output(path, content)
|
|
510
517
|
raise "No image data returned" if content.to_s.empty?
|
|
511
518
|
|
|
512
|
-
File.binwrite(path,
|
|
519
|
+
File.binwrite(path, content.unpack1("m"))
|
|
513
520
|
end
|
|
514
521
|
|
|
515
522
|
def speech_content(audio, output_path:, base64:, response_format:)
|
|
516
|
-
return
|
|
523
|
+
return [audio].pack("m0") if base64
|
|
517
524
|
return audio unless output_path
|
|
518
525
|
|
|
519
526
|
{
|
data/lib/ai_lite/version.rb
CHANGED
data/test/ai_lite_test.rb
CHANGED
|
@@ -619,7 +619,7 @@ class AiLiteTest < Minitest::Test
|
|
|
619
619
|
|
|
620
620
|
def test_image_sends_post_to_images_with_default_payload
|
|
621
621
|
client = provider.new(api_key: "token-abc")
|
|
622
|
-
image_data =
|
|
622
|
+
image_data = ["fake image"].pack("m0")
|
|
623
623
|
|
|
624
624
|
with_stubbed_http(image_response(b64_json: image_data)) do |captured, _response|
|
|
625
625
|
result = client.image("A small ruby gem logo")
|
|
@@ -689,7 +689,7 @@ class AiLiteTest < Minitest::Test
|
|
|
689
689
|
|
|
690
690
|
def test_image_writes_decoded_content_to_output_path
|
|
691
691
|
client = provider.new(api_key: "token-abc")
|
|
692
|
-
image_data =
|
|
692
|
+
image_data = ["fake image"].pack("m0")
|
|
693
693
|
|
|
694
694
|
Tempfile.create(["generated", ".png"]) do |file|
|
|
695
695
|
with_stubbed_http(image_response(b64_json: image_data)) do |_captured, _response|
|
|
@@ -703,7 +703,7 @@ class AiLiteTest < Minitest::Test
|
|
|
703
703
|
|
|
704
704
|
def test_image_debug_true_returns_raw_usage
|
|
705
705
|
client = provider.new(api_key: "token-abc")
|
|
706
|
-
image_data =
|
|
706
|
+
image_data = ["fake image"].pack("m0")
|
|
707
707
|
|
|
708
708
|
with_stubbed_http(image_response(b64_json: image_data)) do |_captured, _response|
|
|
709
709
|
result = client.image("A debuggable image", debug: true)
|
|
@@ -825,7 +825,7 @@ class AiLiteTest < Minitest::Test
|
|
|
825
825
|
with_stubbed_http(speech_response("fake audio")) do |_captured, _response|
|
|
826
826
|
result = client.speak("Encode this", base64: true)
|
|
827
827
|
|
|
828
|
-
assert_equal
|
|
828
|
+
assert_equal ["fake audio"].pack("m0"), result["content"]
|
|
829
829
|
assert_nil result["raw"]
|
|
830
830
|
end
|
|
831
831
|
end
|
|
@@ -1155,7 +1155,7 @@ class AiLiteTest < Minitest::Test
|
|
|
1155
1155
|
FakeResponse.new("200", body)
|
|
1156
1156
|
end
|
|
1157
1157
|
|
|
1158
|
-
def image_response(b64_json:
|
|
1158
|
+
def image_response(b64_json: ["fake image"].pack("m0"))
|
|
1159
1159
|
image = {}
|
|
1160
1160
|
image["b64_json"] = b64_json if b64_json
|
|
1161
1161
|
|