Class: Gemini::Live::Connection
- Inherits:
-
Object
- Object
- Gemini::Live::Connection
- Defined in:
- lib/gemini/live/connection.rb
Overview
WebSocket connection manager for Live API
Constant Summary collapse
- WEBSOCKET_BASE_URL =
"wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent"
Instance Attribute Summary collapse
-
#connected ⇒ Object
readonly
Returns the value of attribute connected.
Instance Method Summary collapse
- #close ⇒ Object
- #connect ⇒ Object
- #connected? ⇒ Boolean
-
#initialize(api_key:, on_message:, on_open:, on_error:, on_close:) ⇒ Connection
constructor
A new instance of Connection.
- #send(data) ⇒ Object
Constructor Details
#initialize(api_key:, on_message:, on_open:, on_error:, on_close:) ⇒ Connection
Returns a new instance of Connection.
14 15 16 17 18 19 20 21 22 23 |
# File 'lib/gemini/live/connection.rb', line 14 def initialize(api_key:, on_message:, on_open:, on_error:, on_close:) @api_key = api_key @on_message = @on_open = on_open @on_error = on_error @on_close = on_close @ws = nil @connected = false @mutex = Mutex.new end |
Instance Attribute Details
#connected ⇒ Object (readonly)
Returns the value of attribute connected.
12 13 14 |
# File 'lib/gemini/live/connection.rb', line 12 def connected @connected end |
Instance Method Details
#close ⇒ Object
73 74 75 76 |
# File 'lib/gemini/live/connection.rb', line 73 def close @ws&.close @connected = false end |
#connect ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/gemini/live/connection.rb', line 25 def connect url = "#{WEBSOCKET_BASE_URL}?key=#{@api_key}" # Store callbacks in local variables for closure = @on_message on_open_callback = @on_open on_error_callback = @on_error on_close_callback = @on_close connection = self @ws = WebSocket::Client::Simple.connect(url) do |ws| ws.on :open do connection.instance_variable_set(:@connected, true) on_open_callback.call if on_open_callback end ws.on :message do |msg| .call(msg.data) if end ws.on :error do |e| on_error_callback.call(e) if on_error_callback end ws.on :close do |e| connection.instance_variable_set(:@connected, false) code = e.respond_to?(:code) ? e.code : nil reason = e.respond_to?(:reason) ? e.reason : nil on_close_callback.call(code, reason) if on_close_callback end end self end |
#connected? ⇒ Boolean
78 79 80 |
# File 'lib/gemini/live/connection.rb', line 78 def connected? @connected && @ws && !@ws.closed? end |
#send(data) ⇒ Object
60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/gemini/live/connection.rb', line 60 def send(data) return false unless @ws && @connected @mutex.synchronize do json_data = data.is_a?(String) ? data : data.to_json @ws.send(json_data) end true rescue StandardError => e @on_error&.call(e) false end |