Skip to content

Troubleshooting

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

Troubleshooting Guide

Common Issues & Solutions

Authentication Issues

Invalid API Key

ChatGPT::AuthenticationError: Invalid Authentication

Solutions:

  1. Verify API key is correct:
# Check if API key is being loaded
puts ENV['OPENAI_API_KEY'].nil? ? "API key not found" : "API key length: #{ENV['OPENAI_API_KEY'].length}"
  1. Ensure proper configuration:
ChatGPT.configure do |config|
  config.api_key = ENV['OPENAI_API_KEY']
end
  1. Verify API key directly in client:
client = ChatGPT::Client.new(your_api_key)

Rate Limit Errors

Too Many Requests

ChatGPT::RateLimitError: Rate limit exceeded

Solutions:

  1. Implement exponential backoff:
def with_retry(max_attempts: 3)
  attempt = 0
  begin
    attempt += 1
    yield
  rescue ChatGPT::RateLimitError => e
    if attempt < max_attempts
      sleep(2 ** attempt)
      retry
    else
      raise
    end
  end
end
  1. Use in your code:
with_retry do
  client.chat(messages)
end

Timeout Issues

Request Timeout

ChatGPT::TimeoutError: Request timed out

Solutions:

  1. Increase timeout in configuration:
ChatGPT.configure do |config|
  config.request_timeout = 60  # Increase to 60 seconds
end
  1. Handle timeouts gracefully:
begin
  response = client.chat(messages)
rescue ChatGPT::TimeoutError => e
  # Log the error
  Rails.logger.error "Request timed out: #{e.message}"
  # Retry with increased timeout
  client.request_timeout = 60
  retry
end

Connection Issues

SSL/TLS Errors

OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0

Solutions:

  1. Update SSL certificates:
# Update system SSL certificates
ENV['SSL_CERT_FILE'] = '/path/to/cacert.pem'
  1. Force SSL verification:
require 'openssl'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE  # Use with caution

Response Parsing Issues

Invalid JSON Response

JSON::ParserError: unexpected token

Solutions:

  1. Check response content:
begin
  response = client.chat(messages)
rescue => e
  puts "Raw response: #{e.response.body}" if e.respond_to?(:response)
  raise
end

Debugging Tips

Enable Debug Logging

ChatGPT.configure do |config|
  config.debug = true  # Enable debug logging
end

Check Request Parameters

def debug_request(messages, params = {})
  puts "Messages: #{messages.inspect}"
  puts "Params: #{params.inspect}"
  
  response = client.chat(messages, params)
  puts "Response: #{response.inspect}"
rescue => e
  puts "Error: #{e.class} - #{e.message}"
  raise
end

Verify Configuration

def verify_configuration
  puts "API Key present: #{!ChatGPT.configuration.api_key.nil?}"
  puts "Timeout: #{ChatGPT.configuration.request_timeout}"
  puts "Max retries: #{ChatGPT.configuration.max_retries}"
end

Common Error Codes

Error Code Description Solution
401 Invalid Authentication Check API key
429 Rate Limit Exceeded Implement retries
500 Server Error Retry with backoff
503 Service Unavailable Retry later

Best Practices

Error Logging

def log_error(error)
  error_data = {
    class: error.class.name,
    message: error.message,
    backtrace: error.backtrace&.first(5)
  }
  
  Rails.logger.error("ChatGPT Error: #{error_data.to_json}")
end

Health Check

def health_check
  begin
    response = client.completions("test", max_tokens: 1)
    { status: "ok", message: "API responding" }
  rescue => e
    { status: "error", message: e.message }
  end
end

Environment Validation

def validate_environment
  missing_vars = []
  required_vars = ['OPENAI_API_KEY']
  
  required_vars.each do |var|
    missing_vars << var if ENV[var].nil?
  end
  
  raise "Missing environment variables: #{missing_vars.join(', ')}" if missing_vars.any?
end

Getting Help

If you're still experiencing issues:

  1. Check the GitHub Issues
  2. Create a new issue with:
    • Ruby version
    • Gem version
    • Error message
    • Minimal reproduction code
  3. Join the discussion in existing issues

Support Resources