Class: Dify::Client

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

Direct Known Subclasses

ChatClient, CompletionClient

Instance Method Summary collapse

Constructor Details

#initialize(api_key, base_url: "https://api.dify.ai/v1") ⇒ Client

Returns a new instance of Client.



8
9
10
11
# File 'lib/dify/client.rb', line 8

def initialize(api_key, base_url: "https://api.dify.ai/v1")
  @api_key = api_key
  @base_url = base_url.end_with?("/v1") ? base_url : "#{base_url}/v1"
end

Instance Method Details

#_send_request(method, endpoint, data = nil, params = nil, stream = false, &block) ⇒ Object



13
14
15
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
# File 'lib/dify/client.rb', line 13

def _send_request(method, endpoint, data = nil, params = nil, stream = false, &block)
  uri = URI.parse("#{@base_url}#{endpoint}")

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = (uri.scheme == "https")

  headers = {
    "Authorization" => "Bearer #{@api_key}",
    "Content-Type" => "application/json"
  }

  case method
  when "GET"
    uri.query = URI.encode_www_form(params) if params
    request = Net::HTTP::Get.new(uri.request_uri, headers)
  when "POST"
    request = Net::HTTP::Post.new(uri.request_uri, headers)
    request.body = data&.to_json
  else
    raise ArgumentError, "Unsupported HTTP method: #{method}"
  end

  if stream
    http.request(request) do |response|
      buffer = String.new
      response.read_body do |chunk|
        buffer << chunk
        while (line = buffer.slice!(/data: (.+)\n/))
          data = line.match(/data: (.+)\n/)[1]
          block.call(JSON.parse(data)) if block_given?
        end
      end
    end
  else
    http.request(request)
  end
end

#get_application_parameters(user) ⇒ Object



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

def get_application_parameters(user)
  params = { user: user }
  _send_request("GET", "/parameters", nil, params)
end

#message_feedback(message_id, rating, user) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/dify/client.rb', line 51

def message_feedback(message_id, rating, user)
  data = {
    rating: rating,
    user: user
  }
  _send_request("POST", "/messages/#{message_id}/feedbacks", data)
end