Class: Groq::Client

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

Defined Under Namespace

Classes: Error

Constant Summary collapse

CONFIG_KEYS =
%i[
  api_key
  api_url
  model_id
  max_tokens
  temperature
  request_timeout
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(config = {}, &faraday_middleware) ⇒ Client

Returns a new instance of Client.



16
17
18
19
20
21
22
23
# File 'lib/groq/client.rb', line 16

def initialize(config = {}, &faraday_middleware)
  CONFIG_KEYS.each do |key|
    # Set instance variables like api_key.
    # Fall back to global config if not present.
    instance_variable_set(:"@#{key}", config[key] || Groq.configuration.send(key))
  end
  @faraday_middleware = faraday_middleware
end

Instance Method Details

#chat(messages, model_id: nil, tools: nil, tool_choice: nil, max_tokens: nil, temperature: nil, json: false, stream: nil, &stream_chunk) ⇒ 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
# File 'lib/groq/client.rb', line 25

def chat(messages, model_id: nil, tools: nil, tool_choice: nil, max_tokens: nil, temperature: nil, json: false, stream: nil, &stream_chunk)
  unless messages.is_a?(Array) || messages.is_a?(String)
    raise ArgumentError, "require messages to be an Array or String"
  end

  if messages.is_a?(String)
    messages = [{role: "user", content: messages}]
  end

  model_id ||= @model_id

  if stream_chunk ||= stream
    require "event_stream_parser"
  end

  body = {
    model: model_id,
    messages: messages,
    tools: tools,
    tool_choice: tool_choice,
    max_tokens: max_tokens || @max_tokens,
    temperature: temperature || @temperature,
    response_format: json ? {type: "json_object"} : nil,
    stream_chunk: stream_chunk
  }.compact
  response = post(path: "/openai/v1/chat/completions", body: body)
  # Configured to raise exceptions on 4xx/5xx responses
  if response.body.is_a?(Hash)
    return response.body.dig("choices", 0, "message")
  end
  response.body
end

#clientObject



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/groq/client.rb', line 70

def client
  @client ||= begin
    connection = Faraday.new(url: @api_url) do |f|
      f.request :json # automatically encode the request body as JSON
      f.response :json # automatically decode JSON responses
      f.response :raise_error # raise exceptions on 4xx/5xx responses

      f.adapter Faraday.default_adapter
      f.options[:timeout] = request_timeout
    end
    @faraday_middleware&.call(connection)

    connection
  end
end

#get(path:) ⇒ Object



58
59
60
61
62
# File 'lib/groq/client.rb', line 58

def get(path:)
  client.get(path) do |req|
    req.headers = headers
  end
end

#post(path:, body:) ⇒ Object



64
65
66
67
68
# File 'lib/groq/client.rb', line 64

def post(path:, body:)
  client.post(path) do |req|
    configure_json_post_request(req, body)
  end
end