Class: ChatGPT::Client

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

Instance Method Summary collapse

Constructor Details

#initialize(api_key) ⇒ Client

Initialize the client with the API key

Parameters:

  • api_key (String)

    The API key for the GPT-3 service



9
10
11
12
13
# File 'lib/chatgpt/client.rb', line 9

def initialize(api_key)
  @api_key = api_key
  # Base endpoint for the OpenAI API
  @endpoint = 'https://api.openai.com/v1'
end

Instance Method Details

#chat(messages, params = {}) ⇒ Hash

This method sends a chat message to the API

Each message is a hash with a ‘role` and `content` key. The `role` key can be ’system’, ‘user’, or ‘assistant’, and the ‘content` key contains the text of the message.

the model to be used for the chat. If no ‘model’ key is provided, ‘gpt-3.5-turbo’ is used by default.

Parameters:

  • messages (Array<Hash>)

    The array of messages for the conversation.

  • params (Hash) (defaults to: {})

    Optional parameters for the chat request. This can include the ‘model’ key to specify

Returns:

  • (Hash)

    The response from the API.



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/chatgpt/client.rb', line 66

def chat(messages, params = {})
  # Set default parameters
  model = params[:model] || 'gpt-3.5-turbo'

  # Construct the URL for the chat request
  url = "#{@endpoint}/chat/completions"

  # Prepare the data for the request. The data is a hash with 'model' and 'messages' keys.
  data = {
    model: model,
    messages: messages
  }
  
  # Make the API request and return the response.
  request_api(url, data)
end

#completions(prompt, params = {}) ⇒ Hash

Generate completions based on a given prompt

Parameters:

  • prompt (String)

    The prompt to be completed

  • params (Hash) (defaults to: {})

    Additional parameters for the completion request

Returns:

  • (Hash)

    The completion results from the API



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/chatgpt/client.rb', line 31

def completions(prompt, params = {})
  # Set default parameters
  engine = params[:engine] || 'text-davinci-002'
  max_tokens = params[:max_tokens] || 16
  temperature = params[:temperature] || 0.5
  top_p = params[:top_p] || 1.0
  n = params[:n] || 1

  # Construct the URL for the completion request
  url = "#{@endpoint}/engines/#{engine}/completions"
  
  # Prepare the data for the request
  data = {
    prompt: prompt,
    max_tokens: max_tokens,
    temperature: temperature,
    top_p: top_p,
    n: n
  }
  
  # Make the request to the API
  request_api(url, data)
end

#headersHash

Prepare headers for the API request

Returns:

  • (Hash)

    The headers for the API request



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

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