Skip to content

API Reference

Nagendra Dhanakeerthi edited this page Oct 31, 2024 · 2 revisions

API Reference

Client Methods

Initialization

ChatGPT::Client.new(api_key = nil)

Creates a new client instance. If api_key is nil, uses the configured global API key.

Chat API (Recommended)

Chat Completion

client.chat(messages, params = {})

Parameters:

  • messages: Array of message hashes with role and content
  • params: Optional parameters hash
# Example usage response = client.chat([ { role: "user", content: "What is Ruby?" } ]) puts response.dig("choices", 0, "message", "content") # With parameters response = client.chat([ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "What is Ruby?" } ], { model: 'gpt-3.5-turbo', # Optional, defaults to configured value temperature: 0.7, # Optional, defaults to 0.5 max_tokens: 100, # Optional, defaults to 16 top_p: 1.0, # Optional n: 1 # Optional, number of responses })

Streaming Chat

client.chat_stream(messages, params = {}) { |chunk| ... }

Same parameters as chat, but requires a block for handling chunks.

# Example usage client.chat_stream([ { role: "user", content: "Tell me a story" } ]) do |chunk| print chunk.dig("choices", 0, "delta", "content") end

Completions API

Text Completion

client.completions(prompt, params = {})

Parameters:

  • prompt: String prompt for completion
  • params: Optional parameters hash
# Example usage response = client.completions("Write a haiku about Ruby") puts response.dig("choices", 0, "text") # With parameters response = client.completions( "Write a haiku about Ruby", { engine: 'gpt-3.5-turbo-instruct', # Optional, defaults to configured value max_tokens: 50, # Optional temperature: 0.7, # Optional top_p: 0.9, # Optional n: 1 # Optional } )

Model Compatibility

API Method Compatible Models Response Access
Chat gpt-4, gpt-3.5-turbo response.dig("choices", 0, "message", "content")
Completions gpt-3.5-turbo-instruct response.dig("choices", 0, "text")

Configuration Options

# For Chat API (Recommended) ChatGPT.configure do |config| config.api_key = ENV['OPENAI_API_KEY'] config.api_version = 'v1' config.default_engine = 'gpt-3.5-turbo' # For chat config.request_timeout = 30 config.max_retries = 3 config.default_parameters = { max_tokens: 16, temperature: 0.5, top_p: 1.0, n: 1 } end # For Completions API ChatGPT.configure do |config| config.api_key = ENV['OPENAI_API_KEY'] config.api_version = 'v1' config.default_engine = 'gpt-3.5-turbo-instruct' # For completions # ... other config remains same end

Response Formats

Chat Response

{ "choices" => [{ "message" => { "role" => "assistant", "content" => "Response content here" } }] }

Completions Response

{ "choices" => [{ "text" => "Completion text here" }] }
Clone this wiki locally