Class: TinyChatGpt
- Inherits:
-
Object
- Object
- TinyChatGpt
- Defined in:
- lib/tiny_chat_gpt.rb
Overview
the TinyChatGPT class is an API adapter for OpenAI’s GPT-3 based ChatGPT model. this class makes it easy to send prompts to the ChatGPT API and receive responses.
usage:
chatbot = ChatGPT.new("davinci", "your_api_key")
puts chatbot.ask("Hello, how are you today?")
if there is any non-200 HTTP response from the API then an instance of TinyChatGpt::APIError will be raised with a helpful error message.
NOTE: this version does not maintain any context from one prompt to the next, so having a longer conversation with ChatGPT via this client is not yet supported. every use of the #ask method is sent as a separate API request, and does not include the context of previous prompts and replies.
Defined Under Namespace
Classes: APIError
Constant Summary collapse
- API_URL =
"https://api.openai.com/v1/engines/davinci/jobs".freeze
Instance Method Summary collapse
- #_parse_response(response) ⇒ Object
- #_send_request(request) ⇒ Object
- #ask(prompt) ⇒ Object
-
#initialize(model, api_key) ⇒ TinyChatGpt
constructor
A new instance of TinyChatGpt.
Constructor Details
#initialize(model, api_key) ⇒ TinyChatGpt
Returns a new instance of TinyChatGpt.
22 23 24 25 |
# File 'lib/tiny_chat_gpt.rb', line 22 def initialize(model, api_key) @model = model @api_key = api_key end |
Instance Method Details
#_parse_response(response) ⇒ Object
55 56 57 58 |
# File 'lib/tiny_chat_gpt.rb', line 55 def _parse_response(response) response = JSON.parse(response) response["choices"].first["text"] end |
#_send_request(request) ⇒ Object
45 46 47 48 49 50 51 52 53 |
# File 'lib/tiny_chat_gpt.rb', line 45 def _send_request(request) uri = URI(API_URL) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json') request.basic_auth(@api_key, '') request.body = request.to_json http.request(request) end |
#ask(prompt) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/tiny_chat_gpt.rb', line 27 def ask(prompt) request = { prompt: prompt, max_tokens: 100, n: 1, stop: "", temperature: 0.5, model: @model } response = _send_request(request) if response.code == 200 _parse_response(response) else raise TinyChatGpt::APIError.new("ERR: non-200 HTTP status to ChatGPT: #{response.code}") end end |