Class: GroqRuby::Transport

Inherits:
Object
  • Object
show all
Defined in:
lib/groq_ruby/transport.rb

Overview

The single HTTP client used by every resource. Wraps Net::HTTP and exposes two operations: a buffered #call for ordinary requests and a streaming #stream for SSE (chat completions with ‘stream: true`).

Both methods return a Result. Internal control flow uses Do notation so the happy path stays linear; transport-level failures are wrapped in the appropriate APIError subclass.

Resources call ‘.value!` to surface the parsed response (raising on failure), preserving parity with the Python client’s exception model.

Constant Summary collapse

JSON_CONTENT_TYPE =
"application/json"

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ Transport

Returns a new instance of Transport.

Parameters:



23
24
25
# File 'lib/groq_ruby/transport.rb', line 23

def initialize(configuration)
  @config = configuration
end

Instance Method Details

#call(request, accept: :json) {|validate(response)| ... } ⇒ Dry::Monads::Result<Response, APIError>

Execute a buffered request.

Parameters:

  • request (Request)
  • accept (Symbol) (defaults to: :json)

    :json (decode body as JSON) or :binary (return raw String)

Yields:

  • (validate(response))

Returns:



32
33
34
35
36
37
# File 'lib/groq_ruby/transport.rb', line 32

def call(request, accept: :json)
  raw = yield execute(request)
  response = yield decode(raw, accept)
  yield validate(response)
  Success(response)
end

#stream(request) {|chunk| ... } ⇒ Dry::Monads::Result<Response, APIError>

Execute a streaming request, yielding each raw chunk to the block. The HTTP response is opened in chunked mode; the body is never buffered in full. Validates the status before streaming begins; error responses are read in full so the body can be parsed and surfaced via the mapped exception.

Yield Parameters:

  • chunk (String)

Returns:



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/groq_ruby/transport.rb', line 47

def stream(request, &on_chunk)
  uri = build_uri(request)
  http = build_http(uri)
  net_request = build_net_request(request, uri)

  with_translated_errors do
    outcome = nil
    http.start do |conn|
      conn.request(net_request) do |raw|
        outcome = stream_response(raw, &on_chunk)
      end
    end
    outcome
  end
end