Class: ChatGPT::Client
- Inherits:
-
Object
- Object
- ChatGPT::Client
- Defined in:
- lib/chatgpt/client.rb
Instance Method Summary collapse
-
#chat(messages, params = {}) ⇒ Hash
This method sends a chat message to the API.
-
#completions(prompt, params = {}) ⇒ Hash
Generate completions based on a given prompt.
-
#headers ⇒ Hash
Prepare headers for the API request.
-
#initialize(api_key) ⇒ Client
constructor
Initialize the client with the API key.
Constructor Details
#initialize(api_key) ⇒ Client
Initialize the client with the API key
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.
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(, 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: } # Make the API request and return the response. request_api(url, data) end |
#completions(prompt, params = {}) ⇒ Hash
Generate completions based on a given prompt
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 |
#headers ⇒ Hash
Prepare 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 |