Class: LlmGateway::Proxy::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/llm_gateway/proxy/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url:, target_provider:, target_config: {}, api_key: nil, path: "/agent/llm_proxy", **_options) ⇒ Client

Returns a new instance of Client.



12
13
14
15
16
17
18
# File 'lib/llm_gateway/proxy/client.rb', line 12

def initialize(url:, target_provider:, target_config: {}, api_key: nil, path: "/agent/llm_proxy", **_options)
  @url = url.to_s.sub(%r{/+\z}, "")
  @target_provider = target_provider.to_s
  @target_config = (target_config || {}).transform_keys(&:to_sym)
  @api_key = api_key
  @path = path.to_s.start_with?("/") ? path.to_s : "/#{path}"
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



10
11
12
# File 'lib/llm_gateway/proxy/client.rb', line 10

def path
  @path
end

#target_configObject (readonly)

Returns the value of attribute target_config.



10
11
12
# File 'lib/llm_gateway/proxy/client.rb', line 10

def target_config
  @target_config
end

#target_providerObject (readonly)

Returns the value of attribute target_provider.



10
11
12
# File 'lib/llm_gateway/proxy/client.rb', line 10

def target_provider
  @target_provider
end

#urlObject (readonly)

Returns the value of attribute url.



10
11
12
# File 'lib/llm_gateway/proxy/client.rb', line 10

def url
  @url
end

Instance Method Details

#stream(messages, tools: nil, system: nil, **options, &block) ⇒ Object



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
# File 'lib/llm_gateway/proxy/client.rb', line 20

def stream(messages, tools: nil, system: nil, **options, &block)
  uri = URI("#{url}#{path}")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == "https"
  http.read_timeout = 480
  http.open_timeout = 10

  request = Net::HTTP::Post.new(uri)
  request["content-type"] = "application/json"
  request["accept"] = "text/event-stream"
  request["accept-encoding"] = "identity"
  request["authorization"] = "Bearer #{@api_key}" if @api_key
  request.body = {
    provider: target_provider,
    config: target_config,
    messages: messages,
    system: system,
    tools: tools,
    options: options
  }.to_json

  http.request(request) do |response|
    unless response.code.to_i == 200
      body = +""
      response.read_body { |chunk| body << chunk }
      raise Errors::APIStatusError.new("Proxy request failed with status #{response.code}: #{body}", nil)
    end

    parse_sse_stream(response, &block)
  end
end