Skip to content

Usage Examples

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

Usage Examples

Chat Examples

Basic Chat

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

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

puts response.dig("choices", 0, "message", "content")

Conversation with Context

messages = [
  { role: "system", content: "You are a helpful assistant." },
  { role: "user", content: "What's Ruby?" },
  { role: "assistant", content: "Ruby is a programming language..." },
  { role: "user", content: "Tell me more!" }
]

response = client.chat(messages)

Streaming Chat

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

Completions Examples

Basic Completion

response = client.completions("Write a haiku about Ruby")

Advanced Parameters

response = client.completions(
  "Translate to French: Hello, world!",
  {
    engine: "gpt-3.5-turbo",
    max_tokens: 60,
    temperature: 0.7,
    top_p: 1.0,
    n: 2  # Get 2 different completions
  }
)

Rails Integration

Controller Example

# app/controllers/chat_controller.rb
class ChatController < ApplicationController
  def create
    client = ChatGPT::Client.new
    response = client.chat([
      { role: "user", content: params[:message] }
    ])
    
    render json: {
      message: response.dig("choices", 0, "message", "content")
    }
  rescue ChatGPT::Error => e
    render json: { error: e.message }, status: :unprocessable_entity
  end
end

Background Job Example

# app/jobs/chat_completion_job.rb
class ChatCompletionJob < ApplicationJob
  queue_as :default

  def perform(user_id, message)
    client = ChatGPT::Client.new
    response = client.chat([
      { role: "user", content: message }
    ])
    
    ChatResponse.create!(
      user_id: user_id,
      content: response.dig("choices", 0, "message", "content")
    )
  end
end

Error Handling Examples

Comprehensive Error Handling

begin
  response = client.chat(messages)
rescue ChatGPT::AuthenticationError => e
  # Handle authentication errors
  Rails.logger.error "Authentication failed: #{e.message}"
  raise
rescue ChatGPT::RateLimitError => e
  # Handle rate limit errors
  RetryJob.set(wait: 1.minute).perform_later(messages)
rescue ChatGPT::InvalidRequestError => e
  # Handle invalid requests
  Rails.logger.warn "Invalid request: #{e.message}"
  raise
rescue ChatGPT::APIError => e
  # Handle other API errors
  Bugsnag.notify(e)
  raise
end

Testing Examples

With RSpec

RSpec.describe ChatService do
  let(:client) { instance_double(ChatGPT::Client) }
  
  before do
    allow(ChatGPT::Client).to receive(:new).and_return(client)
  end
  
  it "handles chat responses" do
    expect(client).to receive(:chat)
      .with([{ role: "user", content: "Hello" }])
      .and_return({ "choices" => [{ "message" => { "content" => "Hi!" } }] })
      
    response = ChatService.new.send_message("Hello")
    expect(response).to eq "Hi!"
  end
end

With Minitest

require 'minitest/autorun'

class TestChatService < Minitest::Test
  def setup
    @client = ChatGPT::Client.new
  end
  
  def test_chat_response
    response = @client.chat([
      { role: "user", content: "Hello" }
    ])
    
    assert response["choices"].length > 0
    assert response["choices"][0]["message"]["content"]
  end
end