Skip to content

Quick Start

Nagendra Dhanakeerthi edited this page Oct 30, 2024 · 1 revision

Quick Start Guide

Basic Usage

Initialize Client

require 'chatgpt'

client = ChatGPT::Client.new(ENV['OPENAI_API_KEY'])

Chat Completion

# Simple chat
response = client.chat([
  { role: "user", content: "Hello!" }
])

puts response["choices"][0]["message"]["content"]

# With system message
messages = [
  { role: "system", content: "You are a helpful assistant." },
  { role: "user", content: "What's the weather like?" }
]

response = client.chat(messages)

Text Completion

# Simple completion
response = client.completions("Write a poem about Ruby")

# With parameters
response = client.completions(
  "Write a poem about Ruby",
  {
    engine: "text-davinci-002",
    max_tokens: 100,
    temperature: 0.7
  }
)

Streaming Responses

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

Error Handling

begin
  response = client.chat(messages)
rescue ChatGPT::AuthenticationError => e
  puts "Auth error: #{e.message}"
rescue ChatGPT::RateLimitError => e
  puts "Rate limit hit: #{e.message}"
rescue ChatGPT::APIError => e
  puts "API error: #{e.message}"
end

Next Steps

Clone this wiki locally