Class: VSM::Drivers::Gemini::AsyncDriver

Inherits:
Object
  • Object
show all
Defined in:
lib/vsm/drivers/gemini/async_driver.rb

Instance Method Summary collapse

Constructor Details

#initialize(api_key:, model:, base_url: "https://generativelanguage.googleapis.com/v1beta", streaming: true) ⇒ AsyncDriver

Returns a new instance of AsyncDriver.



12
13
14
# File 'lib/vsm/drivers/gemini/async_driver.rb', line 12

def initialize(api_key:, model:, base_url: "https://generativelanguage.googleapis.com/v1beta", streaming: true)
  @api_key, @model, @base, @streaming = api_key, model, base_url, streaming
end

Instance Method Details

#run!(conversation:, tools:, policy: {}, &emit) ⇒ Object



16
17
18
19
20
21
22
23
24
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/vsm/drivers/gemini/async_driver.rb', line 16

def run!(conversation:, tools:, policy: {}, &emit)
  contents = to_gemini_contents(conversation)
  fndecls  = normalize_gemini_tools(tools)
  if @streaming
    uri = URI.parse("#{@base}/models/#{@model}:streamGenerateContent?alt=sse&key=#{@api_key}")
    headers = { "content-type" => "application/json", "accept" => "text/event-stream" }
    body = JSON.dump({ contents: contents, system_instruction: (policy[:system_prompt] && { parts: [{ text: policy[:system_prompt] }], role: "user" }), tools: [{ functionDeclarations: fndecls }] })
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = (uri.scheme == "https")
    req = Net::HTTP::Post.new(uri.request_uri)
    headers.each { |k,v| req[k] = v }
    req.body = body
    http.request(req) do |res|
      if res.code.to_i != 200
        err = +""; res.read_body { |c| err << c }
        emit.call(:assistant_final, "Gemini HTTP #{res.code}: #{err.to_s.byteslice(0, 400)}")
        next
      end
      buffer = +""; text = +""; calls = []
      res.read_body do |chunk|
        buffer << chunk
        while (i = buffer.index("\n"))
          line = buffer.slice!(0..i)
          line.chomp!
          next unless line.start_with?("data:")
          data = line.sub("data:","").strip
          next if data.empty? || data == "[DONE]"
          obj = JSON.parse(data) rescue nil
          next unless obj
          parts = (obj.dig("candidates",0,"content","parts") || [])
          parts.each do |p|
            if (t = p["text"]) && !t.empty?
              text << t
              emit.call(:assistant_delta, t)
            end
            if (fc = p["functionCall"]) && fc["name"]
              calls << { id: SecureRandom.uuid, name: fc["name"], arguments: (fc["args"] || {}) }
            end
          end
        end
      end
      if calls.any?
        emit.call(:tool_calls, calls)
      else
        emit.call(:assistant_final, text)
      end
    end
  else
    uri = URI.parse("#{@base}/models/#{@model}:generateContent?key=#{@api_key}")
    headers = { "content-type" => "application/json" }
    body = JSON.dump({ contents: contents, system_instruction: (policy[:system_prompt] && { parts: [{ text: policy[:system_prompt] }], role: "user" }), tools: [{ functionDeclarations: fndecls }] })
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = (uri.scheme == "https")
    req = Net::HTTP::Post.new(uri.request_uri)
    headers.each { |k,v| req[k] = v }
    req.body = body
    res = http.request(req)
    if res.code.to_i != 200
      emit.call(:assistant_final, "Gemini HTTP #{res.code}")
    else
      data = JSON.parse(res.body) rescue {}
      parts = (data.dig("candidates",0,"content","parts") || [])
      calls = parts.filter_map { |p| fc = p["functionCall"]; fc && { id: SecureRandom.uuid, name: fc["name"], arguments: fc["args"] || {} } }
      if calls.any?
        emit.call(:tool_calls, calls)
      else
        text = parts.filter_map { |p| p["text"] }.join
        emit.call(:assistant_final, text.to_s)
      end
    end
  end
  :done
end